Created
July 19, 2017 20:33
-
-
Save ghadishayban/dda219dcab112b84ceb6ff736c524a7a to your computer and use it in GitHub Desktop.
sawtooth / bitcoin compact signature generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment