bip32DerivePrivateKey function
Derives a secp256k1 private key from a master seed following BIP32,
using a derivation path such as m/44'/637'/0'/0/0.
Implementation
Uint8List bip32DerivePrivateKey(Uint8List seed, String path) {
if (!_bip32PathRegex.hasMatch(path)) {
throw ArgumentError('Invalid BIP32 derivation path: $path');
}
final domain = ECCurve_secp256k1();
final n = domain.n;
final master = deriveKey('Bitcoin seed', seed);
var key = _bytesToBigInt(master.key);
var chainCode = master.chainCode;
if (key == BigInt.zero || key >= n) {
throw StateError('Invalid BIP32 master key derived from seed');
}
final segments = path.split('/').sublist(1);
for (final segment in segments) {
final hardened = segment.endsWith("'");
final index = int.parse(
hardened ? segment.substring(0, segment.length - 1) : segment);
final childIndex = hardened ? index + hardenedOffset : index;
final Uint8List data;
if (childIndex >= hardenedOffset) {
// Hardened child: 0x00 || ser256(k_par) || ser32(i)
data = Uint8List(37);
data.setRange(1, 33, _bigIntTo32Bytes(key));
} else {
// Normal child: serP(point(k_par)) || ser32(i)
final publicPoint = (domain.G * key)!;
data = Uint8List(37);
data.setRange(0, 33, publicPoint.getEncoded(true));
}
ByteData.sublistView(data).setUint32(33, childIndex);
final i = _hmacSha512(chainCode, data);
final il = _bytesToBigInt(Uint8List.sublistView(i, 0, 32));
final childKey = (il + key) % n;
if (il >= n || childKey == BigInt.zero) {
// Probability < 2^-127; BIP32 says to proceed with the next index, but
// like most implementations we simply reject.
throw StateError('Invalid BIP32 child key at segment $segment');
}
key = childKey;
chainCode = Uint8List.sublistView(i, 32);
}
return _bigIntTo32Bytes(key);
}