drivePath static method
Drives and returns a hierarchical wallet (BIP32HWallet) along the specified BIP32 derivation path.
masterWallet
is the master hierarchical wallet from which the path is derived.
path
is the BIP32 derivation path string to follow.
Returns a new hierarchical wallet derived from the master wallet following the provided path.
Throws ArgumentError if the provided BIP32 path is invalid. Throws ArgumentError if attempting to derive a hardened path from a public wallet. Throws ArgumentError if the path contains an invalid index or exceeds maximum index value.
Implementation
static BIP32HWallet drivePath(BIP32HWallet masterWallet, String path) {
/// Check if the provided BIP32 path is valid.
if (!isValidPath(path)) {
throw ArgumentError("Invalid BIP32 Path");
}
/// Split the path into individual segments and remove the leading "m" or "M" if present.
List<String> splitPath = path.split("/");
if (splitPath[0] == "m" || splitPath[0] == "M") {
splitPath = splitPath.sublist(1);
}
/// Use fold to iteratively drive the hierarchical wallet along the path.
return splitPath.fold(masterWallet, (BIP32HWallet prevHd, String indexStr) {
int index;
if (indexStr.endsWith("'")) {
/// Handle hardened path segment.
if (masterWallet._fromXpub) {
throw ArgumentError(
"Cannot drive hardened path from a public wallet");
}
index = int.parse(indexStr.substring(0, indexStr.length - 1));
if (index > _maxUint31 || index < 0) {
throw ArgumentError("Invalid index");
}
/// Derive a new hierarchical wallet with a hardened index.
final newDrive = prevHd._addDrive(index + _highBit);
return newDrive;
} else {
/// Handle non-hardened path segment.
index = int.parse(indexStr);
/// Derive a new hierarchical wallet with a non-hardened index.
final newDrive = prevHd._addDrive(index);
return newDrive;
}
});
}