Refactor HDPath pattern matching to be safer. (#5046)

* Refactor hd path pattern matching to be safer. Also avoids warnings in scala3

* Allow single element bip32 path
This commit is contained in:
Chris Stewart 2023-04-19 08:41:10 -05:00 committed by GitHub
parent 51429a7d68
commit 3728b9a9d9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 15 deletions

View file

@ -130,21 +130,26 @@ object BIP32Path extends Factory[BIP32Path] with StringFactory[BIP32Path] {
// and without (https://wiki.trezor.io/Standard_derivation_paths)
.map(_.trim)
val head +: rest = parts
require(head == "m",
"""The first element in a BIP32 path string must be "m"""")
if (parts.isEmpty) {
sys.error(s"Cannot have bip32 path empty bip32 path, got=$string")
} else {
val head = parts.head
val rest = parts.tail
require(head == "m",
"""The first element in a BIP32 path string must be "m"""")
val path = rest.map { str =>
val (index: String, hardened: Boolean) =
if (str.endsWith("'") || str.endsWith("h")) {
(str.dropRight(1), true)
} else {
(str, false)
}
BIP32Node(index.toInt, hardened)
val path = rest.map { str =>
val (index: String, hardened: Boolean) =
if (str.endsWith("'") || str.endsWith("h")) {
(str.dropRight(1), true)
} else {
(str, false)
}
BIP32Node(index.toInt, hardened)
}
BIP32PathImpl(path)
}
BIP32PathImpl(path)
}
/** Takes in a BIP32 Path and verifies all paths are hardened

View file

@ -61,8 +61,11 @@ private[hd] trait HDPathFactory[PathType <: BIP32Path]
require(children.length == 5,
s"A $pathName path string must have five elements")
val _ :+ coinChild :+ accountChild :+ chainChild :+ addressChild =
children
val (coinChild, accountChild, chainChild, addressChild) = {
require(children.length == 5,
s"Must have 5 elements in HDPath, got=$children")
(children(1), children(2), children(3), children(4))
}
require(coinChild.hardened, "The coin type child must be hardened!")
require(accountChild.hardened, "The account child must be hardened!")