1// Copyright (c) 2014-2016 The btcsuite developers 2// Use of this source code is governed by an ISC 3// license that can be found in the LICENSE file. 4 5package hdkeychain 6 7// References: 8// [BIP32]: BIP0032 - Hierarchical Deterministic Wallets 9// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki 10 11import ( 12 "bytes" 13 "crypto/hmac" 14 "crypto/rand" 15 "crypto/sha512" 16 "encoding/binary" 17 "errors" 18 "fmt" 19 "math/big" 20 21 "github.com/btcsuite/btcd/btcec" 22 "github.com/btcsuite/btcd/chaincfg" 23 "github.com/btcsuite/btcd/chaincfg/chainhash" 24 "github.com/btcsuite/btcutil" 25 "github.com/btcsuite/btcutil/base58" 26) 27 28const ( 29 // RecommendedSeedLen is the recommended length in bytes for a seed 30 // to a master node. 31 RecommendedSeedLen = 32 // 256 bits 32 33 // HardenedKeyStart is the index at which a hardened key starts. Each 34 // extended key has 2^31 normal child keys and 2^31 hardened child keys. 35 // Thus the range for normal child keys is [0, 2^31 - 1] and the range 36 // for hardened child keys is [2^31, 2^32 - 1]. 37 HardenedKeyStart = 0x80000000 // 2^31 38 39 // MinSeedBytes is the minimum number of bytes allowed for a seed to 40 // a master node. 41 MinSeedBytes = 16 // 128 bits 42 43 // MaxSeedBytes is the maximum number of bytes allowed for a seed to 44 // a master node. 45 MaxSeedBytes = 64 // 512 bits 46 47 // serializedKeyLen is the length of a serialized public or private 48 // extended key. It consists of 4 bytes version, 1 byte depth, 4 bytes 49 // fingerprint, 4 bytes child number, 32 bytes chain code, and 33 bytes 50 // public/private key data. 51 serializedKeyLen = 4 + 1 + 4 + 4 + 32 + 33 // 78 bytes 52 53 // maxUint8 is the max positive integer which can be serialized in a uint8 54 maxUint8 = 1<<8 - 1 55) 56 57var ( 58 // ErrDeriveHardFromPublic describes an error in which the caller 59 // attempted to derive a hardened extended key from a public key. 60 ErrDeriveHardFromPublic = errors.New("cannot derive a hardened key " + 61 "from a public key") 62 63 // ErrDeriveBeyondMaxDepth describes an error in which the caller 64 // has attempted to derive more than 255 keys from a root key. 65 ErrDeriveBeyondMaxDepth = errors.New("cannot derive a key with more than " + 66 "255 indices in its path") 67 68 // ErrNotPrivExtKey describes an error in which the caller attempted 69 // to extract a private key from a public extended key. 70 ErrNotPrivExtKey = errors.New("unable to create private keys from a " + 71 "public extended key") 72 73 // ErrInvalidChild describes an error in which the child at a specific 74 // index is invalid due to the derived key falling outside of the valid 75 // range for secp256k1 private keys. This error indicates the caller 76 // should simply ignore the invalid child extended key at this index and 77 // increment to the next index. 78 ErrInvalidChild = errors.New("the extended key at this index is invalid") 79 80 // ErrUnusableSeed describes an error in which the provided seed is not 81 // usable due to the derived key falling outside of the valid range for 82 // secp256k1 private keys. This error indicates the caller must choose 83 // another seed. 84 ErrUnusableSeed = errors.New("unusable seed") 85 86 // ErrInvalidSeedLen describes an error in which the provided seed or 87 // seed length is not in the allowed range. 88 ErrInvalidSeedLen = fmt.Errorf("seed length must be between %d and %d "+ 89 "bits", MinSeedBytes*8, MaxSeedBytes*8) 90 91 // ErrBadChecksum describes an error in which the checksum encoded with 92 // a serialized extended key does not match the calculated value. 93 ErrBadChecksum = errors.New("bad extended key checksum") 94 95 // ErrInvalidKeyLen describes an error in which the provided serialized 96 // key is not the expected length. 97 ErrInvalidKeyLen = errors.New("the provided serialized extended key " + 98 "length is invalid") 99) 100 101// masterKey is the master key used along with a random seed used to generate 102// the master node in the hierarchical tree. 103var masterKey = []byte("Bitcoin seed") 104 105// ExtendedKey houses all the information needed to support a hierarchical 106// deterministic extended key. See the package overview documentation for 107// more details on how to use extended keys. 108type ExtendedKey struct { 109 key []byte // This will be the pubkey for extended pub keys 110 pubKey []byte // This will only be set for extended priv keys 111 chainCode []byte 112 depth uint8 113 parentFP []byte 114 childNum uint32 115 version []byte 116 isPrivate bool 117} 118 119// NewExtendedKey returns a new instance of an extended key with the given 120// fields. No error checking is performed here as it's only intended to be a 121// convenience method used to create a populated struct. This function should 122// only be used by applications that need to create custom ExtendedKeys. All 123// other applications should just use NewMaster, Derive, or Neuter. 124func NewExtendedKey(version, key, chainCode, parentFP []byte, depth uint8, 125 childNum uint32, isPrivate bool) *ExtendedKey { 126 127 // NOTE: The pubKey field is intentionally left nil so it is only 128 // computed and memoized as required. 129 return &ExtendedKey{ 130 key: key, 131 chainCode: chainCode, 132 depth: depth, 133 parentFP: parentFP, 134 childNum: childNum, 135 version: version, 136 isPrivate: isPrivate, 137 } 138} 139 140// pubKeyBytes returns bytes for the serialized compressed public key associated 141// with this extended key in an efficient manner including memoization as 142// necessary. 143// 144// When the extended key is already a public key, the key is simply returned as 145// is since it's already in the correct form. However, when the extended key is 146// a private key, the public key will be calculated and memoized so future 147// accesses can simply return the cached result. 148func (k *ExtendedKey) pubKeyBytes() []byte { 149 // Just return the key if it's already an extended public key. 150 if !k.isPrivate { 151 return k.key 152 } 153 154 // This is a private extended key, so calculate and memoize the public 155 // key if needed. 156 if len(k.pubKey) == 0 { 157 pkx, pky := btcec.S256().ScalarBaseMult(k.key) 158 pubKey := btcec.PublicKey{Curve: btcec.S256(), X: pkx, Y: pky} 159 k.pubKey = pubKey.SerializeCompressed() 160 } 161 162 return k.pubKey 163} 164 165// IsPrivate returns whether or not the extended key is a private extended key. 166// 167// A private extended key can be used to derive both hardened and non-hardened 168// child private and public extended keys. A public extended key can only be 169// used to derive non-hardened child public extended keys. 170func (k *ExtendedKey) IsPrivate() bool { 171 return k.isPrivate 172} 173 174// Depth returns the current derivation level with respect to the root. 175// 176// The root key has depth zero, and the field has a maximum of 255 due to 177// how depth is serialized. 178func (k *ExtendedKey) Depth() uint8 { 179 return k.depth 180} 181 182// Version returns the extended key's hardened derivation version. This can be 183// used to identify the extended key's type. 184func (k *ExtendedKey) Version() []byte { 185 return k.version 186} 187 188// ParentFingerprint returns a fingerprint of the parent extended key from which 189// this one was derived. 190func (k *ExtendedKey) ParentFingerprint() uint32 { 191 return binary.BigEndian.Uint32(k.parentFP) 192} 193 194// ChainCode returns the chain code part of this extended key. 195// 196// It is identical for both public and private extended keys. 197func (k *ExtendedKey) ChainCode() []byte { 198 return append([]byte{}, k.chainCode...) 199} 200 201// Derive returns a derived child extended key at the given index. 202// 203// IMPORTANT: if you were previously using the Child method, this method is incompatible. 204// The Child method had a BIP-32 standard compatibility issue. You have to check whether 205// any hardened derivations in your derivation path are affected by this issue, via the 206// IsAffectedByIssue172 method and migrate the wallet if so. This method does conform 207// to the standard. If you need the old behavior, use DeriveNonStandard. 208// 209// When this extended key is a private extended key (as determined by the IsPrivate 210// function), a private extended key will be derived. Otherwise, the derived 211// extended key will be also be a public extended key. 212// 213// When the index is greater to or equal than the HardenedKeyStart constant, the 214// derived extended key will be a hardened extended key. It is only possible to 215// derive a hardened extended key from a private extended key. Consequently, 216// this function will return ErrDeriveHardFromPublic if a hardened child 217// extended key is requested from a public extended key. 218// 219// A hardened extended key is useful since, as previously mentioned, it requires 220// a parent private extended key to derive. In other words, normal child 221// extended public keys can be derived from a parent public extended key (no 222// knowledge of the parent private key) whereas hardened extended keys may not 223// be. 224// 225// NOTE: There is an extremely small chance (< 1 in 2^127) the specific child 226// index does not derive to a usable child. The ErrInvalidChild error will be 227// returned if this should occur, and the caller is expected to ignore the 228// invalid child and simply increment to the next index. 229func (k *ExtendedKey) Derive(i uint32) (*ExtendedKey, error) { 230 // Prevent derivation of children beyond the max allowed depth. 231 if k.depth == maxUint8 { 232 return nil, ErrDeriveBeyondMaxDepth 233 } 234 235 // There are four scenarios that could happen here: 236 // 1) Private extended key -> Hardened child private extended key 237 // 2) Private extended key -> Non-hardened child private extended key 238 // 3) Public extended key -> Non-hardened child public extended key 239 // 4) Public extended key -> Hardened child public extended key (INVALID!) 240 241 // Case #4 is invalid, so error out early. 242 // A hardened child extended key may not be created from a public 243 // extended key. 244 isChildHardened := i >= HardenedKeyStart 245 if !k.isPrivate && isChildHardened { 246 return nil, ErrDeriveHardFromPublic 247 } 248 249 // The data used to derive the child key depends on whether or not the 250 // child is hardened per [BIP32]. 251 // 252 // For hardened children: 253 // 0x00 || ser256(parentKey) || ser32(i) 254 // 255 // For normal children: 256 // serP(parentPubKey) || ser32(i) 257 keyLen := 33 258 data := make([]byte, keyLen+4) 259 if isChildHardened { 260 // Case #1. 261 // When the child is a hardened child, the key is known to be a 262 // private key due to the above early return. Pad it with a 263 // leading zero as required by [BIP32] for deriving the child. 264 // Additionally, right align it if it's shorter than 32 bytes. 265 offset := 33 - len(k.key) 266 copy(data[offset:], k.key) 267 } else { 268 // Case #2 or #3. 269 // This is either a public or private extended key, but in 270 // either case, the data which is used to derive the child key 271 // starts with the secp256k1 compressed public key bytes. 272 copy(data, k.pubKeyBytes()) 273 } 274 binary.BigEndian.PutUint32(data[keyLen:], i) 275 276 // Take the HMAC-SHA512 of the current key's chain code and the derived 277 // data: 278 // I = HMAC-SHA512(Key = chainCode, Data = data) 279 hmac512 := hmac.New(sha512.New, k.chainCode) 280 hmac512.Write(data) 281 ilr := hmac512.Sum(nil) 282 283 // Split "I" into two 32-byte sequences Il and Ir where: 284 // Il = intermediate key used to derive the child 285 // Ir = child chain code 286 il := ilr[:len(ilr)/2] 287 childChainCode := ilr[len(ilr)/2:] 288 289 // Both derived public or private keys rely on treating the left 32-byte 290 // sequence calculated above (Il) as a 256-bit integer that must be 291 // within the valid range for a secp256k1 private key. There is a small 292 // chance (< 1 in 2^127) this condition will not hold, and in that case, 293 // a child extended key can't be created for this index and the caller 294 // should simply increment to the next index. 295 ilNum := new(big.Int).SetBytes(il) 296 if ilNum.Cmp(btcec.S256().N) >= 0 || ilNum.Sign() == 0 { 297 return nil, ErrInvalidChild 298 } 299 300 // The algorithm used to derive the child key depends on whether or not 301 // a private or public child is being derived. 302 // 303 // For private children: 304 // childKey = parse256(Il) + parentKey 305 // 306 // For public children: 307 // childKey = serP(point(parse256(Il)) + parentKey) 308 var isPrivate bool 309 var childKey []byte 310 if k.isPrivate { 311 // Case #1 or #2. 312 // Add the parent private key to the intermediate private key to 313 // derive the final child key. 314 // 315 // childKey = parse256(Il) + parenKey 316 keyNum := new(big.Int).SetBytes(k.key) 317 ilNum.Add(ilNum, keyNum) 318 ilNum.Mod(ilNum, btcec.S256().N) 319 childKey = ilNum.Bytes() 320 isPrivate = true 321 } else { 322 // Case #3. 323 // Calculate the corresponding intermediate public key for 324 // intermediate private key. 325 ilx, ily := btcec.S256().ScalarBaseMult(il) 326 if ilx.Sign() == 0 || ily.Sign() == 0 { 327 return nil, ErrInvalidChild 328 } 329 330 // Convert the serialized compressed parent public key into X 331 // and Y coordinates so it can be added to the intermediate 332 // public key. 333 pubKey, err := btcec.ParsePubKey(k.key, btcec.S256()) 334 if err != nil { 335 return nil, err 336 } 337 338 // Add the intermediate public key to the parent public key to 339 // derive the final child key. 340 // 341 // childKey = serP(point(parse256(Il)) + parentKey) 342 childX, childY := btcec.S256().Add(ilx, ily, pubKey.X, pubKey.Y) 343 pk := btcec.PublicKey{Curve: btcec.S256(), X: childX, Y: childY} 344 childKey = pk.SerializeCompressed() 345 } 346 347 // The fingerprint of the parent for the derived child is the first 4 348 // bytes of the RIPEMD160(SHA256(parentPubKey)). 349 parentFP := btcutil.Hash160(k.pubKeyBytes())[:4] 350 return NewExtendedKey(k.version, childKey, childChainCode, parentFP, 351 k.depth+1, i, isPrivate), nil 352} 353 354// Returns true if this key was affected by the BIP-32 issue in the Child 355// method (since renamed to DeriveNonStandard). 356func (k *ExtendedKey) IsAffectedByIssue172() bool { 357 return len(k.key) < 32 358} 359 360// Deprecated: This is a non-standard derivation that is affected by issue #172. 361// 1-of-256 hardened derivations will be wrong. See note in the Derive method 362// and IsAffectedByIssue172. 363func (k *ExtendedKey) DeriveNonStandard(i uint32) (*ExtendedKey, error) { 364 if k.depth == maxUint8 { 365 return nil, ErrDeriveBeyondMaxDepth 366 } 367 368 isChildHardened := i >= HardenedKeyStart 369 if !k.isPrivate && isChildHardened { 370 return nil, ErrDeriveHardFromPublic 371 } 372 373 keyLen := 33 374 data := make([]byte, keyLen+4) 375 if isChildHardened { 376 copy(data[1:], k.key) 377 } else { 378 copy(data, k.pubKeyBytes()) 379 } 380 binary.BigEndian.PutUint32(data[keyLen:], i) 381 382 hmac512 := hmac.New(sha512.New, k.chainCode) 383 hmac512.Write(data) 384 ilr := hmac512.Sum(nil) 385 386 il := ilr[:len(ilr)/2] 387 childChainCode := ilr[len(ilr)/2:] 388 389 ilNum := new(big.Int).SetBytes(il) 390 if ilNum.Cmp(btcec.S256().N) >= 0 || ilNum.Sign() == 0 { 391 return nil, ErrInvalidChild 392 } 393 394 var isPrivate bool 395 var childKey []byte 396 if k.isPrivate { 397 keyNum := new(big.Int).SetBytes(k.key) 398 ilNum.Add(ilNum, keyNum) 399 ilNum.Mod(ilNum, btcec.S256().N) 400 childKey = ilNum.Bytes() 401 isPrivate = true 402 } else { 403 ilx, ily := btcec.S256().ScalarBaseMult(il) 404 if ilx.Sign() == 0 || ily.Sign() == 0 { 405 return nil, ErrInvalidChild 406 } 407 408 pubKey, err := btcec.ParsePubKey(k.key, btcec.S256()) 409 if err != nil { 410 return nil, err 411 } 412 413 childX, childY := btcec.S256().Add(ilx, ily, pubKey.X, pubKey.Y) 414 pk := btcec.PublicKey{Curve: btcec.S256(), X: childX, Y: childY} 415 childKey = pk.SerializeCompressed() 416 } 417 418 parentFP := btcutil.Hash160(k.pubKeyBytes())[:4] 419 return NewExtendedKey(k.version, childKey, childChainCode, parentFP, 420 k.depth+1, i, isPrivate), nil 421} 422 423// ChildNum returns the index at which the child extended key was derived. 424// 425// Extended keys with ChildNum value between 0 and 2^31-1 are normal child 426// keys, and those with a value between 2^31 and 2^32-1 are hardened keys. 427func (k *ExtendedKey) ChildIndex() uint32 { 428 return k.childNum 429} 430 431// Neuter returns a new extended public key from this extended private key. The 432// same extended key will be returned unaltered if it is already an extended 433// public key. 434// 435// As the name implies, an extended public key does not have access to the 436// private key, so it is not capable of signing transactions or deriving 437// child extended private keys. However, it is capable of deriving further 438// child extended public keys. 439func (k *ExtendedKey) Neuter() (*ExtendedKey, error) { 440 // Already an extended public key. 441 if !k.isPrivate { 442 return k, nil 443 } 444 445 // Get the associated public extended key version bytes. 446 version, err := chaincfg.HDPrivateKeyToPublicKeyID(k.version) 447 if err != nil { 448 return nil, err 449 } 450 451 // Convert it to an extended public key. The key for the new extended 452 // key will simply be the pubkey of the current extended private key. 453 // 454 // This is the function N((k,c)) -> (K, c) from [BIP32]. 455 return NewExtendedKey(version, k.pubKeyBytes(), k.chainCode, k.parentFP, 456 k.depth, k.childNum, false), nil 457} 458 459// CloneWithVersion returns a new extended key cloned from this extended key, 460// but using the provided HD version bytes. The version must be a private HD 461// key ID for an extended private key, and a public HD key ID for an extended 462// public key. 463// 464// This method creates a new copy and therefore does not mutate the original 465// extended key instance. 466// 467// Unlike Neuter(), this does NOT convert an extended private key to an 468// extended public key. It is particularly useful for converting between 469// standard BIP0032 extended keys (serializable to xprv/xpub) and keys based 470// on the SLIP132 standard (serializable to yprv/ypub, zprv/zpub, etc.). 471// 472// References: 473// [SLIP132]: SLIP-0132 - Registered HD version bytes for BIP-0032 474// https://github.com/satoshilabs/slips/blob/master/slip-0132.md 475func (k *ExtendedKey) CloneWithVersion(version []byte) (*ExtendedKey, error) { 476 if len(version) != 4 { 477 // TODO: The semantically correct error to return here is 478 // ErrInvalidHDKeyID (introduced in btcsuite/btcd#1617). Update the 479 // error type once available in a stable btcd / chaincfg release. 480 return nil, chaincfg.ErrUnknownHDKeyID 481 } 482 483 // Initialize a new extended key instance with the same fields as the 484 // current extended private/public key and the provided HD version bytes. 485 return NewExtendedKey(version, k.key, k.chainCode, k.parentFP, 486 k.depth, k.childNum, k.isPrivate), nil 487} 488 489// ECPubKey converts the extended key to a btcec public key and returns it. 490func (k *ExtendedKey) ECPubKey() (*btcec.PublicKey, error) { 491 return btcec.ParsePubKey(k.pubKeyBytes(), btcec.S256()) 492} 493 494// ECPrivKey converts the extended key to a btcec private key and returns it. 495// As you might imagine this is only possible if the extended key is a private 496// extended key (as determined by the IsPrivate function). The ErrNotPrivExtKey 497// error will be returned if this function is called on a public extended key. 498func (k *ExtendedKey) ECPrivKey() (*btcec.PrivateKey, error) { 499 if !k.isPrivate { 500 return nil, ErrNotPrivExtKey 501 } 502 503 privKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), k.key) 504 return privKey, nil 505} 506 507// Address converts the extended key to a standard bitcoin pay-to-pubkey-hash 508// address for the passed network. 509func (k *ExtendedKey) Address(net *chaincfg.Params) (*btcutil.AddressPubKeyHash, error) { 510 pkHash := btcutil.Hash160(k.pubKeyBytes()) 511 return btcutil.NewAddressPubKeyHash(pkHash, net) 512} 513 514// paddedAppend appends the src byte slice to dst, returning the new slice. 515// If the length of the source is smaller than the passed size, leading zero 516// bytes are appended to the dst slice before appending src. 517func paddedAppend(size uint, dst, src []byte) []byte { 518 for i := 0; i < int(size)-len(src); i++ { 519 dst = append(dst, 0) 520 } 521 return append(dst, src...) 522} 523 524// String returns the extended key as a human-readable base58-encoded string. 525func (k *ExtendedKey) String() string { 526 if len(k.key) == 0 { 527 return "zeroed extended key" 528 } 529 530 var childNumBytes [4]byte 531 binary.BigEndian.PutUint32(childNumBytes[:], k.childNum) 532 533 // The serialized format is: 534 // version (4) || depth (1) || parent fingerprint (4)) || 535 // child num (4) || chain code (32) || key data (33) || checksum (4) 536 serializedBytes := make([]byte, 0, serializedKeyLen+4) 537 serializedBytes = append(serializedBytes, k.version...) 538 serializedBytes = append(serializedBytes, k.depth) 539 serializedBytes = append(serializedBytes, k.parentFP...) 540 serializedBytes = append(serializedBytes, childNumBytes[:]...) 541 serializedBytes = append(serializedBytes, k.chainCode...) 542 if k.isPrivate { 543 serializedBytes = append(serializedBytes, 0x00) 544 serializedBytes = paddedAppend(32, serializedBytes, k.key) 545 } else { 546 serializedBytes = append(serializedBytes, k.pubKeyBytes()...) 547 } 548 549 checkSum := chainhash.DoubleHashB(serializedBytes)[:4] 550 serializedBytes = append(serializedBytes, checkSum...) 551 return base58.Encode(serializedBytes) 552} 553 554// IsForNet returns whether or not the extended key is associated with the 555// passed bitcoin network. 556func (k *ExtendedKey) IsForNet(net *chaincfg.Params) bool { 557 return bytes.Equal(k.version, net.HDPrivateKeyID[:]) || 558 bytes.Equal(k.version, net.HDPublicKeyID[:]) 559} 560 561// SetNet associates the extended key, and any child keys yet to be derived from 562// it, with the passed network. 563func (k *ExtendedKey) SetNet(net *chaincfg.Params) { 564 if k.isPrivate { 565 k.version = net.HDPrivateKeyID[:] 566 } else { 567 k.version = net.HDPublicKeyID[:] 568 } 569} 570 571// zero sets all bytes in the passed slice to zero. This is used to 572// explicitly clear private key material from memory. 573func zero(b []byte) { 574 lenb := len(b) 575 for i := 0; i < lenb; i++ { 576 b[i] = 0 577 } 578} 579 580// Zero manually clears all fields and bytes in the extended key. This can be 581// used to explicitly clear key material from memory for enhanced security 582// against memory scraping. This function only clears this particular key and 583// not any children that have already been derived. 584func (k *ExtendedKey) Zero() { 585 zero(k.key) 586 zero(k.pubKey) 587 zero(k.chainCode) 588 zero(k.parentFP) 589 k.version = nil 590 k.key = nil 591 k.depth = 0 592 k.childNum = 0 593 k.isPrivate = false 594} 595 596// NewMaster creates a new master node for use in creating a hierarchical 597// deterministic key chain. The seed must be between 128 and 512 bits and 598// should be generated by a cryptographically secure random generation source. 599// 600// NOTE: There is an extremely small chance (< 1 in 2^127) the provided seed 601// will derive to an unusable secret key. The ErrUnusable error will be 602// returned if this should occur, so the caller must check for it and generate a 603// new seed accordingly. 604func NewMaster(seed []byte, net *chaincfg.Params) (*ExtendedKey, error) { 605 // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. 606 if len(seed) < MinSeedBytes || len(seed) > MaxSeedBytes { 607 return nil, ErrInvalidSeedLen 608 } 609 610 // First take the HMAC-SHA512 of the master key and the seed data: 611 // I = HMAC-SHA512(Key = "Bitcoin seed", Data = S) 612 hmac512 := hmac.New(sha512.New, masterKey) 613 hmac512.Write(seed) 614 lr := hmac512.Sum(nil) 615 616 // Split "I" into two 32-byte sequences Il and Ir where: 617 // Il = master secret key 618 // Ir = master chain code 619 secretKey := lr[:len(lr)/2] 620 chainCode := lr[len(lr)/2:] 621 622 // Ensure the key in usable. 623 secretKeyNum := new(big.Int).SetBytes(secretKey) 624 if secretKeyNum.Cmp(btcec.S256().N) >= 0 || secretKeyNum.Sign() == 0 { 625 return nil, ErrUnusableSeed 626 } 627 628 parentFP := []byte{0x00, 0x00, 0x00, 0x00} 629 return NewExtendedKey(net.HDPrivateKeyID[:], secretKey, chainCode, 630 parentFP, 0, 0, true), nil 631} 632 633// NewKeyFromString returns a new extended key instance from a base58-encoded 634// extended key. 635func NewKeyFromString(key string) (*ExtendedKey, error) { 636 // The base58-decoded extended key must consist of a serialized payload 637 // plus an additional 4 bytes for the checksum. 638 decoded := base58.Decode(key) 639 if len(decoded) != serializedKeyLen+4 { 640 return nil, ErrInvalidKeyLen 641 } 642 643 // The serialized format is: 644 // version (4) || depth (1) || parent fingerprint (4)) || 645 // child num (4) || chain code (32) || key data (33) || checksum (4) 646 647 // Split the payload and checksum up and ensure the checksum matches. 648 payload := decoded[:len(decoded)-4] 649 checkSum := decoded[len(decoded)-4:] 650 expectedCheckSum := chainhash.DoubleHashB(payload)[:4] 651 if !bytes.Equal(checkSum, expectedCheckSum) { 652 return nil, ErrBadChecksum 653 } 654 655 // Deserialize each of the payload fields. 656 version := payload[:4] 657 depth := payload[4:5][0] 658 parentFP := payload[5:9] 659 childNum := binary.BigEndian.Uint32(payload[9:13]) 660 chainCode := payload[13:45] 661 keyData := payload[45:78] 662 663 // The key data is a private key if it starts with 0x00. Serialized 664 // compressed pubkeys either start with 0x02 or 0x03. 665 isPrivate := keyData[0] == 0x00 666 if isPrivate { 667 // Ensure the private key is valid. It must be within the range 668 // of the order of the secp256k1 curve and not be 0. 669 keyData = keyData[1:] 670 keyNum := new(big.Int).SetBytes(keyData) 671 if keyNum.Cmp(btcec.S256().N) >= 0 || keyNum.Sign() == 0 { 672 return nil, ErrUnusableSeed 673 } 674 } else { 675 // Ensure the public key parses correctly and is actually on the 676 // secp256k1 curve. 677 _, err := btcec.ParsePubKey(keyData, btcec.S256()) 678 if err != nil { 679 return nil, err 680 } 681 } 682 683 return NewExtendedKey(version, keyData, chainCode, parentFP, depth, 684 childNum, isPrivate), nil 685} 686 687// GenerateSeed returns a cryptographically secure random seed that can be used 688// as the input for the NewMaster function to generate a new master node. 689// 690// The length is in bytes and it must be between 16 and 64 (128 to 512 bits). 691// The recommended length is 32 (256 bits) as defined by the RecommendedSeedLen 692// constant. 693func GenerateSeed(length uint8) ([]byte, error) { 694 // Per [BIP32], the seed must be in range [MinSeedBytes, MaxSeedBytes]. 695 if length < MinSeedBytes || length > MaxSeedBytes { 696 return nil, ErrInvalidSeedLen 697 } 698 699 buf := make([]byte, length) 700 _, err := rand.Read(buf) 701 if err != nil { 702 return nil, err 703 } 704 705 return buf, nil 706} 707