Skip to content

Instantly share code, notes, and snippets.

@ghadishayban
Created July 19, 2017 20:33
Show Gist options
  • Select an option

  • Save ghadishayban/dda219dcab112b84ceb6ff736c524a7a to your computer and use it in GitHub Desktop.

Select an option

Save ghadishayban/dda219dcab112b84ceb6ff736c524a7a to your computer and use it in GitHub Desktop.

Revisions

  1. ghadishayban created this gist Jul 19, 2017.
    32 changes: 32 additions & 0 deletions sawtooth_signing.clj
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    (ns sawtooth-signing
    (:import org.bitcoinj.core.ECKey
    org.bitcoinj.core.DumpedPrivateKey
    org.bitcoinj.core.Sha256Hash
    org.bitcoinj.core.Utils
    org.bitcoinj.params.MainNetParams))

    (def ^{:doc "generates an in-memory priv key representation from the .wif"}
    wif->key
    (let [MAINNET (MainNetParams/get)]
    (fn [s]
    (-> (DumpedPrivateKey/fromBase58 MAINNET s)
    (.getKey)))))

    ;; https://bitcoin.stackexchange.com/a/19539
    (defn priv->pub
    "Returns the compressed format public key (65 bytes) from the uncompressed hex (130 bytes)"
    [^ECKey private-key]
    (let [uncompressed (.getPublicKeyAsHex private-key)]
    (str "03" (subs uncompressed 2 66))))

    ;; https://stackoverflow.com/q/34063694/1422711
    (defn sign
    "sign a byte array and return a hex representation of the bitcoin 'compact signature'"
    [^ECKey pk ^bytes data]
    (let [h (Sha256Hash/of data)
    sig (.sign pk h)
    arr (byte-array 64)]
    (System/arraycopy (Utils/bigIntegerToBytes (.-r sig) 32) 0 arr 0 32)
    (System/arraycopy (Utils/bigIntegerToBytes (.-s sig) 32) 0 arr 32 32)

    (.encode Utils/HEX arr)))