Implement BIP32Path.fromHardenedString(). (#2886)

* Implement BIP32Path.fromHardenedString(). This will throw exceptions a non hardened path in the string exists

* Do what ben says rather than re-implementing BIP32Path.fromString
This commit is contained in:
Chris Stewart 2021-04-09 13:19:11 -05:00 committed by GitHub
parent bb379ecfcf
commit 85fb931cba
3 changed files with 41 additions and 1 deletions

View File

@ -232,4 +232,34 @@ class BIP32PathTest extends BitcoinSUnitTest {
}
}
it must "ensure that all paths are hardened when using BIP32.fromHardenedString" in {
val string = "m/1'/2'/3'/4'/5'"
val bip32Path = BIP32Path.fromHardenedString(string)
assert(bip32Path.toString == string)
//bad paths
val badPath1 = "m/1/2'/3'/4'/5'"
assertThrows[IllegalArgumentException] {
BIP32Path.fromHardenedString(badPath1)
}
val badPath2 = "m/1'/2'/3'/4'/5"
assertThrows[IllegalArgumentException] {
BIP32Path.fromHardenedString(badPath2)
}
val badPath3 = "m/1'/2'/3/4'/5"
assertThrows[IllegalArgumentException] {
BIP32Path.fromHardenedString(badPath3)
}
val badPath4 = "m/1/2/3/4/5"
assertThrows[IllegalArgumentException] {
BIP32Path.fromHardenedString(badPath4)
}
}
}

View File

@ -146,6 +146,16 @@ object BIP32Path extends Factory[BIP32Path] with StringFactory[BIP32Path] {
BIP32PathImpl(path)
}
/** Takes in a BIP32 Path and verifies all paths are hardened
* @throws RuntimeException is a non hardened path is found
*/
def fromHardenedString(string: String): BIP32Path = {
val path = BIP32Path.fromString(string)
require(path.forall(_.hardened),
s"Found non hardened path in string=$string")
path
}
private def fromBytes(bytes: ByteVector, littleEndian: Boolean): BIP32Path = {
require(bytes.size % 4 == 0,
s"ByteVector is not suited for KeyPath, got=${bytes.length}")

View File

@ -54,7 +54,7 @@ class DLCOracle(private[this] val extPrivateKey: ExtPrivateKeyHardened)(implicit
val chain = HDChainType.External
val index = 0
val path = BIP32Path.fromString(
val path = BIP32Path.fromHardenedString(
s"m/${purpose.constant}'/${coin.coinType.toInt}'/${account.index}'/${chain.index}'/$index'")
extPrivateKey.deriveChildPrivKey(path).key