Mastering Bitcoin chapter 4 - 02 Deriving a WIF private key from an int

{:deps {org.clojure/clojure {:mvn/version "1.11.1"}
        base58 {:git/url "https://github.com/fjsousa/base58"
                :sha "807fba7f9f38175531be81c4f4c4a682fc380433"}
        buddy/buddy-core {:mvn/version "1.10.413"}
        ;; complient is used for autocompletion
        ;; add your libs here (and restart the runtime to pick up changes)
        compliment/compliment {:mvn/version "0.3.9"}}}
Extensible Data Notation
(ns play-with-addresses
  (:require
   [buddy.core.hash :as hash]
   [buddy.core.codecs :as codecs]
   [base58.core :as base58])
  (:import java.math.BigInteger))
2.1s

1 - Private key

;;key as decimal
(def key (BigInteger. "13840170145645816737842251482747434280357113762558403558088249138233286766301"))
0.1s
;;hex of a private key
(def key-hex (.toString key 16))
0.0s

2 - Base 58 Check Encoding

;; Base58check encoding from Mastering Bitcoin
;; https://github.com/bitcoinbook/bitcoinbook/blob/develop/ch04.asciidoc#base58check_encoding
0.0s
(def key-bytes (codecs/hex->bytes key-hex))
(count key-bytes) ;;32 bytes, 256 bits
0.0s
;;private key WIF version hex
(def version-hex "80")
0.0s
(def payload key-hex)
(def checksum-bytes
  (->> (str version-hex payload)
    codecs/hex->bytes
    hash/sha256
    hash/sha256
    (take 4)))
0.0s
(def private-key-wif
  (base58/encode (concat (codecs/hex->bytes version-hex) key-bytes checksum-bytes)))
0.0s

3 - Compressed private key

;; hex of a "compressed" private key - appending 01 to the Hex of the private key above
;; "The term "compressed private key" really means "private key from which only compressed 
;; public keys should be derived"
;; "version prefix is the same (0x80) for both WIF and WIF-compressed formats"
(def key-hex-compressed (str key-hex "01"))
0.0s
;; getting the checksum the same way as above
(def checksum-bytes-compressed
  (->> (str version-hex key-hex-compressed)
    codecs/hex->bytes
    hash/sha256
    hash/sha256
    (take 4)))
(def private-key-wif-compressed
  (base58/encode (concat
                   (codecs/hex->bytes version-hex)
                   (codecs/hex->bytes key-hex-compressed)
                   checksum-bytes-compressed)))
0.0s

Comparing with the keys in the book to make sure we did everything right:

Runtimes (1)