extendedKey.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. package hd
  2. // References:
  3. // [BIP32]: BIP0032 - Hierarchical Deterministic Wallets
  4. // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
  5. import (
  6. "bytes"
  7. "crypto/hmac"
  8. "crypto/sha512"
  9. "encoding/binary"
  10. "errors"
  11. "fmt"
  12. "math/big"
  13. "github.com/btcsuite/btcd/btcec"
  14. "github.com/btcsuite/btcd/chaincfg"
  15. "github.com/btcsuite/btcd/chaincfg/chainhash"
  16. "github.com/btcsuite/btcutil"
  17. "github.com/btcsuite/btcutil/base58"
  18. )
  19. const (
  20. // RecommendedSeedLen is the recommended length in bytes for a seed
  21. // to a master node.
  22. RecommendedSeedLen = 32 // 256 bits
  23. // HardenedKeyStart is the index at which a hardended key starts. Each
  24. // extended key has 2^31 normal child keys and 2^31 hardned child keys.
  25. // Thus the range for normal child keys is [0, 2^31 - 1] and the range
  26. // for hardened child keys is [2^31, 2^32 - 1].
  27. HardenedKeyStart = 0x80000000 // 2^31
  28. // MinSeedBytes is the minimum number of bytes allowed for a seed to
  29. // a master node.
  30. MinSeedBytes = 16 // 128 bits
  31. // MaxSeedBytes is the maximum number of bytes allowed for a seed to
  32. // a master node.
  33. MaxSeedBytes = 64 // 512 bits
  34. // serializedKeyLen is the length of a serialized public or private
  35. // extended key. It consists of 4 bytes version, 1 byte depth, 4 bytes
  36. // fingerprint, 4 bytes child number, 32 bytes chain code, and 33 bytes
  37. // public/private key data.
  38. serializedKeyLen = 4 + 1 + 4 + 4 + 32 + 33 // 78 bytes
  39. // maxUint8 is the max positive integer which can be serialized in a uint8
  40. maxUint8 = 1<<8 - 1
  41. )
  42. var (
  43. // ErrDeriveHardFromPublic describes an error in which the caller
  44. // attempted to derive a hardened extended key from a public key.
  45. ErrDeriveHardFromPublic = errors.New("cannot derive a hardened key " +
  46. "from a public key")
  47. // ErrDeriveBeyondMaxDepth describes an error in which the caller
  48. // has attempted to derive more than 255 keys from a root key.
  49. ErrDeriveBeyondMaxDepth = errors.New("cannot derive a key with more than " +
  50. "255 indices in its path")
  51. // ErrNotPrivExtKey describes an error in which the caller attempted
  52. // to extract a private key from a public extended key.
  53. ErrNotPrivExtKey = errors.New("unable to create private keys from a " +
  54. "public extended key")
  55. // ErrInvalidChild describes an error in which the child at a specific
  56. // index is invalid due to the derived key falling outside of the valid
  57. // range for secp256k1 private keys. This error indicates the caller
  58. // should simply ignore the invalid child extended key at this index and
  59. // increment to the next index.
  60. ErrInvalidChild = errors.New("the extended key at this index is invalid")
  61. // ErrUnusableSeed describes an error in which the provided seed is not
  62. // usable due to the derived key falling outside of the valid range for
  63. // secp256k1 private keys. This error indicates the caller must choose
  64. // another seed.
  65. ErrUnusableSeed = errors.New("unusable seed")
  66. // ErrInvalidSeedLen describes an error in which the provided seed or
  67. // seed length is not in the allowed range.
  68. ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+
  69. "bits", MinSeedBytes*8, MaxSeedBytes*8)
  70. // ErrBadChecksum describes an error in which the checksum encoded with
  71. // a serialized extended key does not match the calculated value.
  72. ErrBadChecksum = errors.New("bad extended key checksum")
  73. // ErrInvalidKeyLen describes an error in which the provided serialized
  74. // key is not the expected length.
  75. ErrInvalidKeyLen = errors.New("the provided serialized extended key " +
  76. "length is invalid")
  77. )
  78. // masterKey is the master key used along with a random seed used to generate
  79. // the master node in the hierarchical tree.
  80. var masterKey = []byte("Bitcoin seed")
  81. // ExtendedKey houses all the information needed to support a hierarchical
  82. // deterministic extended key. See the package overview documentation for
  83. // more details on how to use extended keys.
  84. type ExtendedKey struct {
  85. key []byte // This will be the pubkey for extended pub keys
  86. pubKey []byte // This will only be set for extended priv keys
  87. chainCode []byte
  88. depth uint8
  89. parentFP []byte
  90. childNum uint32
  91. isPrivate bool
  92. }
  93. // NewExtendedKey returns a new instance of an extended key with the given
  94. // fields. No error checking is performed here as it's only intended to be a
  95. // convenience method used to create a populated struct. This function should
  96. // only by used by applications that need to create custom ExtendedKeys. All
  97. // other applications should just use NewMaster, Child, or Neuter.
  98. func NewExtendedKey(key, chainCode, parentFP []byte, depth uint8,
  99. childNum uint32, isPrivate bool) *ExtendedKey {
  100. // NOTE: The pubKey field is intentionally left nil so it is only
  101. // computed and memoized as required.
  102. return &ExtendedKey{
  103. key: key,
  104. chainCode: chainCode,
  105. depth: depth,
  106. parentFP: parentFP,
  107. childNum: childNum,
  108. isPrivate: isPrivate,
  109. }
  110. }
  111. // pubKeyBytes returns bytes for the serialized compressed public key associated
  112. // with this extended key in an efficient manner including memoization as
  113. // necessary.
  114. //
  115. // When the extended key is already a public key, the key is simply returned as
  116. // is since it's already in the correct form. However, when the extended key is
  117. // a private key, the public key will be calculated and memoized so future
  118. // accesses can simply return the cached result.
  119. func (k *ExtendedKey) pubKeyBytes() []byte {
  120. // Just return the key if it's already an extended public key.
  121. if !k.isPrivate {
  122. return k.key
  123. }
  124. // This is a private extended key, so calculate and memoize the public
  125. // key if needed.
  126. if len(k.pubKey) == 0 {
  127. pkx, pky := btcec.S256().ScalarBaseMult(k.key)
  128. pubKey := btcec.PublicKey{Curve: btcec.S256(), X: pkx, Y: pky}
  129. k.pubKey = pubKey.SerializeCompressed()
  130. }
  131. return k.pubKey
  132. }
  133. // IsPrivate returns whether or not the extended key is a private extended key.
  134. //
  135. // A private extended key can be used to derive both hardened and non-hardened
  136. // child private and public extended keys. A public extended key can only be
  137. // used to derive non-hardened child public extended keys.
  138. func (k *ExtendedKey) IsPrivate() bool {
  139. return k.isPrivate
  140. }
  141. // Depth returns the current derivation level with respect to the root.
  142. //
  143. // The root key has depth zero, and the field has a maximum of 255 due to
  144. // how depth is serialized.
  145. func (k *ExtendedKey) Depth() uint8 {
  146. return k.depth
  147. }
  148. // ParentFingerprint returns a fingerprint of the parent extended key from which
  149. // this one was derived.
  150. func (k *ExtendedKey) ParentFingerprint() uint32 {
  151. return binary.BigEndian.Uint32(k.parentFP)
  152. }
  153. // Child returns a derived child extended key at the given index. When this
  154. // extended key is a private extended key (as determined by the IsPrivate
  155. // function), a private extended key will be derived. Otherwise, the derived
  156. // extended key will be also be a public extended key.
  157. //
  158. // When the index is greater to or equal than the HardenedKeyStart constant, the
  159. // derived extended key will be a hardened extended key. It is only possible to
  160. // derive a hardended extended key from a private extended key. Consequently,
  161. // this function will return ErrDeriveHardFromPublic if a hardened child
  162. // extended key is requested from a public extended key.
  163. //
  164. // A hardened extended key is useful since, as previously mentioned, it requires
  165. // a parent private extended key to derive. In other words, normal child
  166. // extended public keys can be derived from a parent public extended key (no
  167. // knowledge of the parent private key) whereas hardened extended keys may not
  168. // be.
  169. //
  170. // NOTE: There is an extremely small chance (< 1 in 2^127) the specific child
  171. // index does not derive to a usable child. The ErrInvalidChild error will be
  172. // returned if this should occur, and the caller is expected to ignore the
  173. // invalid child and simply increment to the next index.
  174. func (k *ExtendedKey) Child(i uint32) (*ExtendedKey, error) {
  175. // Prevent derivation of children beyond the max allowed depth.
  176. if k.depth == maxUint8 {
  177. return nil, ErrDeriveBeyondMaxDepth
  178. }
  179. // There are four scenarios that could happen here:
  180. // 1) Private extended key -> Hardened child private extended key
  181. // 2) Private extended key -> Non-hardened child private extended key
  182. // 3) Public extended key -> Non-hardened child public extended key
  183. // 4) Public extended key -> Hardened child public extended key (INVALID!)
  184. // Case #4 is invalid, so error out early.
  185. // A hardened child extended key may not be created from a public
  186. // extended key.
  187. isChildHardened := i >= HardenedKeyStart
  188. if !k.isPrivate && isChildHardened {
  189. return nil, ErrDeriveHardFromPublic
  190. }
  191. // The data used to derive the child key depends on whether or not the
  192. // child is hardened per [BIP32].
  193. //
  194. // For hardened children:
  195. // 0x00 || ser256(parentKey) || ser32(i)
  196. //
  197. // For normal children:
  198. // serP(parentPubKey) || ser32(i)
  199. keyLen := 33
  200. data := make([]byte, keyLen+4)
  201. if isChildHardened {
  202. // Case #1.
  203. // When the child is a hardened child, the key is known to be a
  204. // private key due to the above early return. Pad it with a
  205. // leading zero as required by [BIP32] for deriving the child.
  206. copy(data[1:], k.key)
  207. } else {
  208. // Case #2 or #3.
  209. // This is either a public or private extended key, but in
  210. // either case, the data which is used to derive the child key
  211. // starts with the secp256k1 compressed public key bytes.
  212. copy(data, k.pubKeyBytes())
  213. }
  214. binary.BigEndian.PutUint32(data[keyLen:], i)
  215. // Take the HMAC-SHA512 of the current key's chain code and the derived
  216. // data:
  217. // I = HMAC-SHA512(Key = chainCode, Data = data)
  218. hmac512 := hmac.New(sha512.New, k.chainCode)
  219. hmac512.Write(data)
  220. ilr := hmac512.Sum(nil)
  221. // Split "I" into two 32-byte sequences Il and Ir where:
  222. // Il = intermediate key used to derive the child
  223. // Ir = child chain code
  224. il := ilr[:len(ilr)/2]
  225. childChainCode := ilr[len(ilr)/2:]
  226. // Both derived public or private keys rely on treating the left 32-byte
  227. // sequence calculated above (Il) as a 256-bit integer that must be
  228. // within the valid range for a secp256k1 private key. There is a small
  229. // chance (< 1 in 2^127) this condition will not hold, and in that case,
  230. // a child extended key can't be created for this index and the caller
  231. // should simply increment to the next index.
  232. ilNum := new(big.Int).SetBytes(il)
  233. if ilNum.Cmp(btcec.S256().N) >= 0 || ilNum.Sign() == 0 {
  234. return nil, ErrInvalidChild
  235. }
  236. // The algorithm used to derive the child key depends on whether or not
  237. // a private or public child is being derived.
  238. //
  239. // For private children:
  240. // childKey = parse256(Il) + parentKey
  241. //
  242. // For public children:
  243. // childKey = serP(point(parse256(Il)) + parentKey)
  244. var isPrivate bool
  245. var childKey []byte
  246. if k.isPrivate {
  247. // Case #1 or #2.
  248. // Add the parent private key to the intermediate private key to
  249. // derive the final child key.
  250. //
  251. // childKey = parse256(Il) + parenKey
  252. keyNum := new(big.Int).SetBytes(k.key)
  253. ilNum.Add(ilNum, keyNum)
  254. ilNum.Mod(ilNum, btcec.S256().N)
  255. childKey = ilNum.Bytes()
  256. isPrivate = true
  257. } else {
  258. // Case #3.
  259. // Calculate the corresponding intermediate public key for
  260. // intermediate private key.
  261. ilx, ily := btcec.S256().ScalarBaseMult(il)
  262. if ilx.Sign() == 0 || ily.Sign() == 0 {
  263. return nil, ErrInvalidChild
  264. }
  265. // Convert the serialized compressed parent public key into X
  266. // and Y coordinates so it can be added to the intermediate
  267. // public key.
  268. pubKey, err := btcec.ParsePubKey(k.key, btcec.S256())
  269. if err != nil {
  270. return nil, err
  271. }
  272. // Add the intermediate public key to the parent public key to
  273. // derive the final child key.
  274. //
  275. // childKey = serP(point(parse256(Il)) + parentKey)
  276. childX, childY := btcec.S256().Add(ilx, ily, pubKey.X, pubKey.Y)
  277. pk := btcec.PublicKey{Curve: btcec.S256(), X: childX, Y: childY}
  278. childKey = pk.SerializeCompressed()
  279. }
  280. // The fingerprint of the parent for the derived child is the first 4
  281. // bytes of the RIPEMD160(SHA256(parentPubKey)).
  282. parentFP := btcutil.Hash160(k.pubKeyBytes())[:4]
  283. return NewExtendedKey(childKey, childChainCode, parentFP,
  284. k.depth+1, i, isPrivate), nil
  285. }
  286. // Neuter returns a new extended public key from this extended private key. The
  287. // same extended key will be returned unaltered if it is already an extended
  288. // public key.
  289. //
  290. // As the name implies, an extended public key does not have access to the
  291. // private key, so it is not capable of signing transactions or deriving
  292. // child extended private keys. However, it is capable of deriving further
  293. // child extended public keys.
  294. func (k *ExtendedKey) Neuter() (*ExtendedKey, error) {
  295. // Already an extended public key.
  296. if !k.isPrivate {
  297. return k, nil
  298. }
  299. // Convert it to an extended public key. The key for the new extended
  300. // key will simply be the pubkey of the current extended private key.
  301. //
  302. // This is the function N((k,c)) -> (K, c) from [BIP32].
  303. return NewExtendedKey(k.pubKeyBytes(), k.chainCode, k.parentFP,
  304. k.depth, k.childNum, false), nil
  305. }
  306. // ECPubKey converts the extended key to a btcec public key and returns it.
  307. func (k *ExtendedKey) ECPubKey() (*btcec.PublicKey, error) {
  308. return btcec.ParsePubKey(k.pubKeyBytes(), btcec.S256())
  309. }
  310. // ECPrivKey converts the extended key to a btcec private key and returns it.
  311. // As you might imagine this is only possible if the extended key is a private
  312. // extended key (as determined by the IsPrivate function). The ErrNotPrivExtKey
  313. // error will be returned if this function is called on a public extended key.
  314. func (k *ExtendedKey) ECPrivKey() (*btcec.PrivateKey, error) {
  315. if !k.isPrivate {
  316. return nil, ErrNotPrivExtKey
  317. }
  318. privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), k.key)
  319. return privKey, nil
  320. }
  321. // Address converts the extended key to a standard bitcoin pay-to-pubkey-hash
  322. // address for the passed network.
  323. func (k *ExtendedKey) Address(net *chaincfg.Params) (*btcutil.AddressPubKeyHash, error) {
  324. pkHash := btcutil.Hash160(k.pubKeyBytes())
  325. return btcutil.NewAddressPubKeyHash(pkHash, net)
  326. }
  327. // paddedAppend appends the src byte slice to dst, returning the new slice.
  328. // If the length of the source is smaller than the passed size, leading zero
  329. // bytes are appended to the dst slice before appending src.
  330. func paddedAppend(size uint, dst, src []byte) []byte {
  331. for i := 0; i < int(size)-len(src); i++ {
  332. dst = append(dst, 0)
  333. }
  334. return append(dst, src...)
  335. }
  336. // String returns the extended key as a human-readable base58-encoded string.
  337. func (k *ExtendedKey) String() string {
  338. if len(k.key) == 0 {
  339. return "zeroed extended key"
  340. }
  341. var childNumBytes [4]byte
  342. binary.BigEndian.PutUint32(childNumBytes[:], k.childNum)
  343. // The serialized format is:
  344. // version (4) || depth (1) || parent fingerprint (4)) ||
  345. // child num (4) || chain code (32) || key data (33) || checksum (4)
  346. serializedBytes := make([]byte, 0, serializedKeyLen+4)
  347. serializedBytes = append(serializedBytes, k.depth)
  348. serializedBytes = append(serializedBytes, k.parentFP...)
  349. serializedBytes = append(serializedBytes, childNumBytes[:]...)
  350. serializedBytes = append(serializedBytes, k.chainCode...)
  351. if k.isPrivate {
  352. serializedBytes = append(serializedBytes, 0x00)
  353. serializedBytes = paddedAppend(32, serializedBytes, k.key)
  354. } else {
  355. serializedBytes = append(serializedBytes, k.pubKeyBytes()...)
  356. }
  357. checkSum := chainhash.DoubleHashB(serializedBytes)[:4]
  358. serializedBytes = append(serializedBytes, checkSum...)
  359. return base58.Encode(serializedBytes)
  360. }
  361. // zero sets all bytes in the passed slice to zero. This is used to
  362. // explicitly clear private key material from memory.
  363. func zero(b []byte) {
  364. lenb := len(b)
  365. for i := 0; i < lenb; i++ {
  366. b[i] = 0
  367. }
  368. }
  369. // Zero manually clears all fields and bytes in the extended key. This can be
  370. // used to explicitly clear key material from memory for enhanced security
  371. // against memory scraping. This function only clears this particular key and
  372. // not any children that have already been derived.
  373. func (k *ExtendedKey) Zero() {
  374. zero(k.key)
  375. zero(k.pubKey)
  376. zero(k.chainCode)
  377. zero(k.parentFP)
  378. k.key = nil
  379. k.depth = 0
  380. k.childNum = 0
  381. k.isPrivate = false
  382. }
  383. // NewMaster creates a new master node for use in creating a hierarchical
  384. // deterministic key chain. The seed must be between 128 and 512 bits and
  385. // should be generated by a cryptographically secure random generation source.
  386. //
  387. // NOTE: There is an extremely small chance (< 1 in 2^127) the provided seed
  388. // will derive to an unusable secret key. The ErrUnusable error will be
  389. // returned if this should occur, so the caller must check for it and generate a
  390. // new seed accordingly.
  391. func NewMaster(seed []byte) (*ExtendedKey, error) {
  392. // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes].
  393. if len(seed) < MinSeedBytes || len(seed) > MaxSeedBytes {
  394. return nil, ErrInvalidSeedLen
  395. }
  396. // First take the HMAC-SHA512 of the master key and the seed data:
  397. // I = HMAC-SHA512(Key = "Bitcoin seed", Data = S)
  398. hmac512 := hmac.New(sha512.New, masterKey)
  399. hmac512.Write(seed)
  400. lr := hmac512.Sum(nil)
  401. // Split "I" into two 32-byte sequences Il and Ir where:
  402. // Il = master secret key
  403. // Ir = master chain code
  404. secretKey := lr[:len(lr)/2]
  405. chainCode := lr[len(lr)/2:]
  406. // Ensure the key in usable.
  407. secretKeyNum := new(big.Int).SetBytes(secretKey)
  408. if secretKeyNum.Cmp(btcec.S256().N) >= 0 || secretKeyNum.Sign() == 0 {
  409. return nil, ErrUnusableSeed
  410. }
  411. parentFP := []byte{0x00, 0x00, 0x00, 0x00}
  412. return NewExtendedKey(secretKey, chainCode,
  413. parentFP, 0, 0, true), nil
  414. }
  415. // NewKeyFromString returns a new extended key instance from a base58-encoded
  416. // extended key.
  417. func NewKeyFromString(key string) (*ExtendedKey, error) {
  418. // The base58-decoded extended key must consist of a serialized payload
  419. // plus an additional 4 bytes for the checksum.
  420. decoded := base58.Decode(key)
  421. if len(decoded) != serializedKeyLen+4 {
  422. return nil, ErrInvalidKeyLen
  423. }
  424. // The serialized format is:
  425. // version (4) || depth (1) || parent fingerprint (4)) ||
  426. // child num (4) || chain code (32) || key data (33) || checksum (4)
  427. // Split the payload and checksum up and ensure the checksum matches.
  428. payload := decoded[:len(decoded)-4]
  429. checkSum := decoded[len(decoded)-4:]
  430. expectedCheckSum := chainhash.DoubleHashB(payload)[:4]
  431. if !bytes.Equal(checkSum, expectedCheckSum) {
  432. return nil, ErrBadChecksum
  433. }
  434. // Deserialize each of the payload fields.
  435. depth := payload[4:5][0]
  436. parentFP := payload[5:9]
  437. childNum := binary.BigEndian.Uint32(payload[9:13])
  438. chainCode := payload[13:45]
  439. keyData := payload[45:78]
  440. // The key data is a private key if it starts with 0x00. Serialized
  441. // compressed pubkeys either start with 0x02 or 0x03.
  442. isPrivate := keyData[0] == 0x00
  443. if isPrivate {
  444. // Ensure the private key is valid. It must be within the range
  445. // of the order of the secp256k1 curve and not be 0.
  446. keyData = keyData[1:]
  447. keyNum := new(big.Int).SetBytes(keyData)
  448. if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 {
  449. return nil, ErrUnusableSeed
  450. }
  451. } else {
  452. // Ensure the public key parses correctly and is actually on the
  453. // secp256k1 curve.
  454. _, err := btcec.ParsePubKey(keyData, btcec.S256())
  455. if err != nil {
  456. return nil, err
  457. }
  458. }
  459. return NewExtendedKey(keyData, chainCode, parentFP, depth,
  460. childNum, isPrivate), nil
  461. }