derive method

HDKey derive(
  1. int index
)

Derives a key at index returning the same type of key: either public or private. The index can inlcude the hardenBit to specify that it is hardened.

Implementation

HDKey derive(int index) {

  if (index > HDKey.maxIndex || index < 0) {
    throw ArgumentError.value(
      index, "index", "Can only derive 32-bit indicies",
    );
  }

  final hardened = index >= hardenBit;

  Uint8List data = Uint8List(37);
  if (hardened) {
    if (privateKey == null) {
      throw ArgumentError("Unabled to derive hardened key from public key");
    }
    data[0] = 0x00;
    data.setRange(1, 33, privateKey!.data);
  } else {
    data.setRange(0, 33, publicKey.data);
  }
  data.buffer.asByteData().setUint32(33, index);

  final i = hmacSha512(_chaincode, data);
  final il = i.sublist(0, 32);
  final ir = i.sublist(32);

  if (privateKey != null) {
    final newKey = privateKey!.tweak(il);
    if (newKey == null) return derive(index+1);
    return HDPrivateKey(
      privateKey: newKey,
      chaincode: ir,
      depth: depth+1,
      index: index,
      parentFingerprint: fingerprint,
    );
  }

  // Public key
  final newKey = publicKey.tweak(il);
  if (newKey == null) return derive(index+1);
  return HDPublicKey(
    publicKey: newKey,
    chaincode: ir,
    depth: depth+1,
    index: index,
    parentFingerprint: fingerprint,
  );

}