|
| 1 | +package ckdutil |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/hmac" |
| 5 | + "crypto/sha512" |
| 6 | + "encoding/binary" |
| 7 | + "encoding/hex" |
| 8 | + "fmt" |
| 9 | + "math/big" |
| 10 | + |
| 11 | + "github.com/btcsuite/btcd/btcec/v2" |
| 12 | + "github.com/decred/dcrd/dcrec/edwards/v2" |
| 13 | +) |
| 14 | + |
| 15 | +const ( |
| 16 | + hardenedKeyStart = 0x80000000 |
| 17 | + // Compressed pubkey: 1-byte prefix (02/03) + 32-byte X coordinate. |
| 18 | + pubKeyBytesLenCompressed = 33 |
| 19 | + // BIP32 specifies child index serialized as 4-byte big-endian (ser32). |
| 20 | + childIndexBytes = 4 |
| 21 | + pubKeyCompressedEven byte = 0x2 |
| 22 | + pubKeyCompressedOdd byte = 0x3 |
| 23 | +) |
| 24 | + |
| 25 | +// DeriveEd25519ChildCompressed derives a non-hardened child public key on ed25519 and returns the 32-byte compressed key. |
| 26 | +func DeriveEd25519ChildCompressed(masterPubKey []byte, chainCodeHex string, path []uint32) ([]byte, error) { |
| 27 | + if len(masterPubKey) == 0 { |
| 28 | + return nil, fmt.Errorf("master public key is empty") |
| 29 | + } |
| 30 | + |
| 31 | + pubKey, err := edwards.ParsePubKey(masterPubKey) |
| 32 | + if err != nil { |
| 33 | + return nil, fmt.Errorf("decode master pubkey: %w", err) |
| 34 | + } |
| 35 | + |
| 36 | + return deriveEd25519ChildCompressed(pubKey, chainCodeHex, path) |
| 37 | +} |
| 38 | + |
| 39 | +// DeriveSecp256k1ChildCompressed derives a non-hardened child public key on secp256k1 and returns the 33-byte compressed key. |
| 40 | +func DeriveSecp256k1ChildCompressed(masterPubKey []byte, chainCodeHex string, path []uint32) ([]byte, error) { |
| 41 | + if len(masterPubKey) != 33 { |
| 42 | + return nil, fmt.Errorf("invalid master pubkey length: %d", len(masterPubKey)) |
| 43 | + } |
| 44 | + |
| 45 | + curve := btcec.S256() |
| 46 | + pubKey, err := btcec.ParsePubKey(masterPubKey) |
| 47 | + if err != nil { |
| 48 | + return nil, fmt.Errorf("decode master pubkey: %w", err) |
| 49 | + } |
| 50 | + |
| 51 | + chainCode, err := hex.DecodeString(chainCodeHex) |
| 52 | + if err != nil { |
| 53 | + return nil, fmt.Errorf("decode chain code: %w", err) |
| 54 | + } |
| 55 | + if len(chainCode) != 32 { |
| 56 | + return nil, fmt.Errorf("invalid chain code length: %d", len(chainCode)) |
| 57 | + } |
| 58 | + |
| 59 | + currentX := new(big.Int).Set(pubKey.X()) |
| 60 | + currentY := new(big.Int).Set(pubKey.Y()) |
| 61 | + currentChainCode := append([]byte(nil), chainCode...) |
| 62 | + |
| 63 | + for _, index := range path { |
| 64 | + if index >= hardenedKeyStart { |
| 65 | + return nil, fmt.Errorf("hardened derivation not supported: %d", index) |
| 66 | + } |
| 67 | + |
| 68 | + data := make([]byte, pubKeyBytesLenCompressed+childIndexBytes) |
| 69 | + copy(data, serializeCompressed(currentX, currentY)) |
| 70 | + binary.BigEndian.PutUint32(data[pubKeyBytesLenCompressed:], index) |
| 71 | + |
| 72 | + mac := hmac.New(sha512.New, currentChainCode) |
| 73 | + mac.Write(data) |
| 74 | + ilr := mac.Sum(nil) |
| 75 | + il := ilr[:32] |
| 76 | + ir := ilr[32:] |
| 77 | + |
| 78 | + ilNum := new(big.Int).SetBytes(il) |
| 79 | + if ilNum.Sign() == 0 || ilNum.Cmp(curve.Params().N) >= 0 { |
| 80 | + return nil, fmt.Errorf("invalid IL for index %d", index) |
| 81 | + } |
| 82 | + |
| 83 | + deltaX, deltaY := curve.ScalarBaseMult(ilNum.Bytes()) |
| 84 | + childX, childY := curve.Add(currentX, currentY, deltaX, deltaY) |
| 85 | + if childX == nil || childY == nil || childX.Sign() == 0 || childY.Sign() == 0 { |
| 86 | + return nil, fmt.Errorf("invalid child point at index %d", index) |
| 87 | + } |
| 88 | + |
| 89 | + currentX, currentY = childX, childY |
| 90 | + currentChainCode = ir |
| 91 | + } |
| 92 | + |
| 93 | + return serializeCompressed(currentX, currentY), nil |
| 94 | +} |
| 95 | + |
| 96 | +// --- shared helpers (non-hardened) --- |
| 97 | + |
| 98 | +func deriveEd25519ChildCompressed(masterPub *edwards.PublicKey, chainCodeHex string, path []uint32) ([]byte, error) { |
| 99 | + if masterPub == nil || masterPub.X == nil || masterPub.Y == nil { |
| 100 | + return nil, fmt.Errorf("invalid master public key") |
| 101 | + } |
| 102 | + |
| 103 | + chainCode, err := hex.DecodeString(chainCodeHex) |
| 104 | + if err != nil { |
| 105 | + return nil, fmt.Errorf("decode chain code: %w", err) |
| 106 | + } |
| 107 | + if len(chainCode) != 32 { |
| 108 | + return nil, fmt.Errorf("invalid chain code length: %d", len(chainCode)) |
| 109 | + } |
| 110 | + |
| 111 | + curve := edwards.Edwards() |
| 112 | + currentX := new(big.Int).Set(masterPub.X) |
| 113 | + currentY := new(big.Int).Set(masterPub.Y) |
| 114 | + currentChainCode := append([]byte(nil), chainCode...) |
| 115 | + |
| 116 | + for _, index := range path { |
| 117 | + if index >= hardenedKeyStart { |
| 118 | + return nil, fmt.Errorf("hardened derivation not supported: %d", index) |
| 119 | + } |
| 120 | + |
| 121 | + data := make([]byte, pubKeyBytesLenCompressed+childIndexBytes) |
| 122 | + copy(data, serializeCompressed(currentX, currentY)) |
| 123 | + binary.BigEndian.PutUint32(data[pubKeyBytesLenCompressed:], index) |
| 124 | + |
| 125 | + mac := hmac.New(sha512.New, currentChainCode) |
| 126 | + mac.Write(data) |
| 127 | + ilr := mac.Sum(nil) |
| 128 | + il := ilr[:32] |
| 129 | + ir := ilr[32:] |
| 130 | + |
| 131 | + ilNum := new(big.Int).SetBytes(il) |
| 132 | + ilNum.Mod(ilNum, curve.Params().N) |
| 133 | + if ilNum.Sign() == 0 || ilNum.Cmp(curve.Params().N) >= 0 { |
| 134 | + return nil, fmt.Errorf("invalid IL for index %d", index) |
| 135 | + } |
| 136 | + |
| 137 | + deltaX, deltaY := curve.ScalarBaseMult(ilNum.Bytes()) |
| 138 | + childX, childY := curve.Add(currentX, currentY, deltaX, deltaY) |
| 139 | + if childX == nil || childY == nil || childX.Sign() == 0 || childY.Sign() == 0 { |
| 140 | + return nil, fmt.Errorf("invalid child point at index %d", index) |
| 141 | + } |
| 142 | + |
| 143 | + currentX, currentY = childX, childY |
| 144 | + currentChainCode = ir |
| 145 | + } |
| 146 | + |
| 147 | + childPub := edwards.PublicKey{ |
| 148 | + Curve: curve, |
| 149 | + X: currentX, |
| 150 | + Y: currentY, |
| 151 | + } |
| 152 | + |
| 153 | + return childPub.SerializeCompressed(), nil |
| 154 | +} |
| 155 | + |
| 156 | +// serializeCompressed matches the node compression (33 bytes). |
| 157 | +func serializeCompressed(x, y *big.Int) []byte { |
| 158 | + b := make([]byte, 0, pubKeyBytesLenCompressed) |
| 159 | + format := pubKeyCompressedEven |
| 160 | + if isOdd(y) { |
| 161 | + format = pubKeyCompressedOdd |
| 162 | + } |
| 163 | + b = append(b, format) |
| 164 | + return paddedAppend(b, 32, x.Bytes()) |
| 165 | +} |
| 166 | + |
| 167 | +func isOdd(a *big.Int) bool { |
| 168 | + return a.Bit(0) == 1 |
| 169 | +} |
| 170 | + |
| 171 | +func paddedAppend(dst []byte, srcPaddedSize int, src []byte) []byte { |
| 172 | + return append(dst, paddedBytes(srcPaddedSize, src)...) |
| 173 | +} |
| 174 | + |
| 175 | +func paddedBytes(size int, src []byte) []byte { |
| 176 | + offset := size - len(src) |
| 177 | + tmp := src |
| 178 | + if offset > 0 { |
| 179 | + tmp = make([]byte, size) |
| 180 | + copy(tmp[offset:], src) |
| 181 | + } |
| 182 | + return tmp |
| 183 | +} |
0 commit comments