derivePath method

HDKey derivePath(
  1. String path
)

Derives a child key in a path format akin to "m/15/3'/4" where the optional "m" specifies that this key is a master key and "'" specifies that an index is a hardened key.

Implementation

HDKey derivePath(String path) {

  final regex = RegExp(r"^(m\/)?(\d+'?\/)*\d+'?$");
  if (!regex.hasMatch(path)) throw ArgumentError("Expected BIP32 Path");

  List<String> splitPath = path.split("/");

  if (splitPath[0] == "m") {
    if (parentFingerprint != 0) {
      throw ArgumentError("Expected master, got child");
    }
    splitPath = splitPath.sublist(1);
  }

  return splitPath.fold(this, (HDKey prev, String indexStr) {
    if (indexStr.substring(indexStr.length - 1) == "'") {
      return prev.deriveHardened(
        int.parse(indexStr.substring(0, indexStr.length - 1)),
      );
    } else {
      final index = int.parse(indexStr);
      if (index >= hardenBit) {
        throw ArgumentError.value(path, "path", "out-of-range index");
      }
      return prev.derive(index);
    }
  });

}