HD Private Keys (Bip32)
Hierarchical Deterministic Keys(HD Keys) form a key component of how one manages Private keys within a Bitcoin Wallet. If you are not familiar with HD Keys, be sure to read more about them in the Developer Guide Appendix
The following classes are used for working with HD keys.
class | description |
---|---|
DeterministicHierarchy | A tree data structure of deterministically derived ECC keypairs |
DeterministicKey | A node in the deterministic hierarchy. This class extends ECKey. |
HDKeyDerivation | Implementation of BIP32 wallet child key generation algorithm |
Initialise a new HD Private key from a master “seed”
import org.twostack.bitcoin4j.Utils.HEX
import org.twostack.bitcoin4j.crypto.*
//the root node in our hierarchy.
//The seedbytes should be at least 64 bits long
var seedBytes = HEX.decode("000102030405060708090a0b0c0d0e0f");
//deterministically derive a master private key from a seed value
val rootKey: DeterministicKey = HDKeyDerivation.createMasterPrivateKey(seedBytes)
Derive a child key at a specific path
import org.twostack.bitcoin4j.crypto.*
//initialise a deterministic hierarchy
val dh = DeterministicHierarchy(rootKey)
//create a hardened path to a node
val pathOneString = "m/44H/0H/0H/6"
val pathOne = HDPath.parsePath(pathOneString)
//retrieve deterministic private key at specified path,
//specifying that the path is relative, and to create key if it does not exist
val dkOne: DeterministicKey = dh[pathOne.subList(0, pathOne.size), true, true]
//export our deterministic key to WiF,
//and wrap using with a PrivateKey instance
val pkOne : PrivateKey = PrivateKey.fromWIF(dkOne.getPrivateKeyAsWiF(NetworkType.MAIN))