Skip to content

Commit

Permalink
Statically return HDPrivateKey from HDPrivateKeys
Browse files Browse the repository at this point in the history
  • Loading branch information
MatthewLM committed Aug 9, 2023
1 parent a2e73e2 commit 2fa9cf5
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
10 changes: 8 additions & 2 deletions coinlib/lib/src/crypto/hd_key.dart
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,13 @@ abstract class HDKey {

/// Derives a hardened key at [index] which only applies to private keys. The
/// [index] must not include the left-bit to specify that it is hardened.
HDKey deriveHardened(int index) {
HDPrivateKey deriveHardened(int index) {
if (index < 0 || index >= hardenBit) {
throw ArgumentError.value(
index, "index", "should be below hardered index",
);
}
return derive(index + hardenBit);
return derive(index + hardenBit) as HDPrivateKey;
}

/// Derives a child key in a [path] format akin to "m/15/3'/4" where the
Expand Down Expand Up @@ -280,6 +280,12 @@ class HDPrivateKey extends HDKey {
throw InvalidHDKey();
}

@override
HDPrivateKey derive(int index) => super.derive(index) as HDPrivateKey;

@override
HDPrivateKey derivePath(String path) => super.derivePath(path) as HDPrivateKey;

HDPublicKey get hdPublicKey => HDPublicKey(
publicKey: publicKey,
chaincode: chaincode,
Expand Down
8 changes: 4 additions & 4 deletions coinlib/test/crypto/hd_key_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ void main() {
forEachHDVector((parent, vec) {
if (parent != null) {

final derivedPriv = HDKey.decode(parent.privEncoded).derive(vec.index);
final derivedPriv = HDPrivateKey.decode(parent.privEncoded).derive(vec.index);
expectPriv(derivedPriv);
vec.expectHDKey(derivedPriv);
vec.expectHDPrivateKey(derivedPriv);

if (!vec.hardened) {
final derivedPub = HDKey.decode(parent.pubEncoded).derive(vec.index);
Expand All @@ -191,7 +191,7 @@ void main() {
final derivedHardened = HDKey.decode(parent.privEncoded)
.deriveHardened(vec.index - 0x80000000);
expectPriv(derivedHardened);
vec.expectHDKey(derivedHardened);
vec.expectHDPrivateKey(derivedHardened);
}
});
});
Expand All @@ -201,7 +201,7 @@ void main() {
final derived = masterHDKey.derivePath("m/0'/1/2'/2/1000000000");

expectPriv(derived);
hdVectors[0][5].expectHDKey(derived);
hdVectors[0][5].expectHDPrivateKey(derived);

final pubDerived = HDPublicKey.decode(hdVectors[0][3].pubEncoded, pubPrefix)
.derivePath("2/1000000000");
Expand Down
3 changes: 3 additions & 0 deletions coinlib/test/vectors/hd_keys.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ class HDVector {

}

// Adds a static check to the key type
expectHDPrivateKey(HDPrivateKey key) => expectHDKey(key);

}

final hdVectors = [
Expand Down

0 comments on commit 2fa9cf5

Please sign in to comment.