Package org.bitcoinj.crypto
Class DeterministicKey
- java.lang.Object
-
- org.bitcoinj.crypto.ECKey
-
- org.bitcoinj.crypto.DeterministicKey
-
- All Implemented Interfaces:
EncryptableItem
public class DeterministicKey extends ECKey
A deterministic key is a node in aDeterministicHierarchy
. As per the BIP 32 specification it is a pair (key, chaincode). If you know its path in the tree and its chain code you can derive more keys from this. To obtain one of these, you can callHDKeyDerivation.createMasterPrivateKey(byte[])
.
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class org.bitcoinj.crypto.ECKey
ECKey.ECDSASignature, ECKey.KeyIsEncryptedException, ECKey.MissingPrivateKeyException
-
-
Field Summary
Fields Modifier and Type Field Description static java.util.Comparator<ECKey>
CHILDNUM_ORDER
Sorts deterministic keys in the order of their child number.-
Fields inherited from class org.bitcoinj.crypto.ECKey
AGE_COMPARATOR, creationTime, CURVE, encryptedPrivateKey, HALF_CURVE_ORDER, keyCrypter, priv, pub, PUBKEY_COMPARATOR
-
-
Constructor Summary
Constructors Constructor Description DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, java.math.BigInteger priv, DeterministicKey parent, int depth, int parentFingerprint)
Constructs a key from its components, including its private key data and possibly-redundant information about its parent key.DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, KeyCrypter crypter, LazyECPoint pub, EncryptedData priv, DeterministicKey parent)
Constructs a key from its components.DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, LazyECPoint publicAsPoint, java.math.BigInteger priv, DeterministicKey parent)
Constructs a key from its components.DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, LazyECPoint publicAsPoint, DeterministicKey parent, int depth, int parentFingerprint)
Constructs a key from its components, including its public key data and possibly-redundant information about its parent key.DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, org.bouncycastle.math.ec.ECPoint publicAsPoint, boolean compressed, java.math.BigInteger priv, DeterministicKey parent)
DeterministicKey(DeterministicKey keyToClone, DeterministicKey newParent)
Clones the keyDeterministicKey(HDPath hdPath, byte[] chainCode, java.math.BigInteger priv, DeterministicKey parent)
Constructs a key from its components.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description void
clearCreationTime()
Clears the creation time of this key.java.util.Optional<java.time.Instant>
creationTime()
The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree in which case the time is stored alongside the key as per normal, seeECKey.creationTime()
.DeterministicKey
decrypt(AesKey aesKey)
Create a decrypted private key with AES key.DeterministicKey
decrypt(KeyCrypter keyCrypter, AesKey aesKey)
Create a decrypted private key with the keyCrypter and AES key supplied.DeterministicKey
derive(int child)
Derives a child at the given index using hardened derivation.static DeterministicKey
deserialize(Network network, byte[] serializedKey)
Deserialize an HD Key with no parentstatic DeterministicKey
deserialize(Network network, byte[] serializedKey, DeterministicKey parent)
Deserialize an HD Key.static DeterministicKey
deserialize(NetworkParameters params, byte[] serializedKey)
Deprecated.static DeterministicKey
deserialize(NetworkParameters params, byte[] serializedKey, DeterministicKey parent)
Deprecated.static DeterministicKey
deserializeB58(java.lang.String base58, Network network)
Deserialize a base-58-encoded HD Key with no parentstatic DeterministicKey
deserializeB58(java.lang.String base58, NetworkParameters params)
Deprecated.static DeterministicKey
deserializeB58(DeterministicKey parent, java.lang.String base58, Network network)
Deserialize a base-58-encoded HD Key.static DeterministicKey
deserializeB58(DeterministicKey parent, java.lang.String base58, NetworkParameters params)
Deprecated.DeterministicKey
dropParent()
Returns the same key with the parent pointer removed (it still knows its own path and the parent fingerprint).DeterministicKey
dropPrivateBytes()
Returns the same key with the private bytes removed.DeterministicKey
encrypt(KeyCrypter keyCrypter, AesKey aesKey)
Create an encrypted private key with the keyCrypter and the AES key supplied.DeterministicKey
encrypt(KeyCrypter keyCrypter, AesKey aesKey, DeterministicKey newParent)
boolean
equals(java.lang.Object o)
Verifies equality of all fields but NOT the parent pointer (thus the same key derived in two separate hierarchy objects will equal each other.void
formatKeyWithAddress(boolean includePrivateKeys, AesKey aesKey, java.lang.StringBuilder builder, Network network, ScriptType outputScriptType, java.lang.String comment)
void
formatKeyWithAddress(boolean includePrivateKeys, AesKey aesKey, java.lang.StringBuilder builder, NetworkParameters params, ScriptType outputScriptType, java.lang.String comment)
byte[]
getChainCode()
Returns the chain code associated with this key.ChildNumber
getChildNumber()
Returns the last element of the path returned bygetPath()
int
getDepth()
Return this key's depth in the hierarchy, where the root node is at depth zero.int
getFingerprint()
Returns the first 32 bits of the result ofgetIdentifier()
.byte[]
getIdentifier()
Returns RIPE-MD160(SHA256(pub key bytes)).KeyCrypter
getKeyCrypter()
Returns this keysKeyCrypter
or the keycrypter of its parent key.DeterministicKey
getParent()
int
getParentFingerprint()
Return the fingerprint of the key from which this key was derived, if this is a child key, or else an array of four zero-value bytes.HDPath
getPath()
Returns the path through someDeterministicHierarchy
which reaches this keys position in the tree.java.lang.String
getPathAsString()
Returns the path of this key as a human-readable string starting with M or m to indicate the master key.java.math.BigInteger
getPrivKey()
Returns the private key of this deterministic key.byte[]
getPrivKeyBytes33()
Returns private key bytes, padded with zeros to 33 bytes.byte[]
getSecretBytes()
A wrapper forECKey.getPrivKeyBytes()
that returns null if the private key bytes are missing or would have to be derived (for the HD key case).int
hashCode()
boolean
hasPrivKey()
Returns true if this key has unencrypted access to private key bytes.boolean
isEncrypted()
A deterministic key is considered to be encrypted if it has access to encrypted private key bytes, OR if its parent does.boolean
isPubKeyOnly()
A deterministic key is considered to be 'public key only' if it hasn't got a private key part and it cannot be rederived.java.lang.String
serializePrivB58(Network network)
Serialize private key to Base58 (either "xprv" or "tprv")java.lang.String
serializePrivB58(Network network, ScriptType outputScriptType)
Deprecated.Use aserializePrivB58(Network)
or a descriptor if you need output type informationjava.lang.String
serializePrivB58(NetworkParameters params)
Deprecated.java.lang.String
serializePrivB58(NetworkParameters params, ScriptType outputScriptType)
Deprecated.java.lang.String
serializePubB58(Network network)
Serialize public key to Base58 (either "xpub" or "tpub")java.lang.String
serializePubB58(Network network, ScriptType outputScriptType)
Deprecated.Use aserializePubB58(Network)
or a descriptor if you need output type informationjava.lang.String
serializePubB58(NetworkParameters params)
Deprecated.java.lang.String
serializePubB58(NetworkParameters params, ScriptType outputScriptType)
Deprecated.void
setCreationTime(java.time.Instant creationTime)
The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree.void
setCreationTimeSeconds(long creationTimeSecs)
Deprecated.ECKey.ECDSASignature
sign(Sha256Hash input, AesKey aesKey)
Signs the given hash and returns the R and S components as BigIntegers.java.lang.String
toString()
-
Methods inherited from class org.bitcoinj.crypto.ECKey
decompress, doSign, encryptionIsReversible, findRecoveryId, fromASN1, fromEncrypted, fromPrivate, fromPrivate, fromPrivate, fromPrivate, fromPrivateAndPrecalculatedPublic, fromPrivateAndPrecalculatedPublic, fromPublicOnly, fromPublicOnly, fromPublicOnly, getEncryptedData, getEncryptedPrivateKey, getEncryptionType, getPrivateKeyAsHex, getPrivateKeyAsWiF, getPrivateKeyAsWiF, getPrivateKeyEncoded, getPrivateKeyEncoded, getPrivKeyBytes, getPubKey, getPubKeyHash, getPubKeyPoint, getPublicKeyAsHex, isCompressed, isPubKeyCanonical, isPubKeyCompressed, isWatching, maybeDecrypt, publicKeyFromPrivate, publicPointFromPrivate, recoverFromSignature, sign, signedMessageToKey, signMessage, signMessage, signMessage, signMessage, toAddress, toASN1, toStringWithPrivate, toStringWithPrivate, verify, verify, verify, verify, verifyMessage, verifyOrThrow, verifyOrThrow
-
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface org.bitcoinj.crypto.EncryptableItem
getCreationTimeSeconds
-
-
-
-
Field Detail
-
CHILDNUM_ORDER
public static final java.util.Comparator<ECKey> CHILDNUM_ORDER
Sorts deterministic keys in the order of their child number. That's usually the order used to derive them.
-
-
Constructor Detail
-
DeterministicKey
public DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, LazyECPoint publicAsPoint, @Nullable java.math.BigInteger priv, @Nullable DeterministicKey parent)
Constructs a key from its components. This is not normally something you should use.
-
DeterministicKey
public DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, org.bouncycastle.math.ec.ECPoint publicAsPoint, boolean compressed, @Nullable java.math.BigInteger priv, @Nullable DeterministicKey parent)
-
DeterministicKey
public DeterministicKey(HDPath hdPath, byte[] chainCode, java.math.BigInteger priv, @Nullable DeterministicKey parent)
Constructs a key from its components. This is not normally something you should use.
-
DeterministicKey
public DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, KeyCrypter crypter, LazyECPoint pub, EncryptedData priv, @Nullable DeterministicKey parent)
Constructs a key from its components. This is not normally something you should use.
-
DeterministicKey
public DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, LazyECPoint publicAsPoint, @Nullable DeterministicKey parent, int depth, int parentFingerprint)
Constructs a key from its components, including its public key data and possibly-redundant information about its parent key. Invoked when deserializing, but otherwise not something that you normally should use.
-
DeterministicKey
public DeterministicKey(java.util.List<ChildNumber> childNumberPath, byte[] chainCode, java.math.BigInteger priv, @Nullable DeterministicKey parent, int depth, int parentFingerprint)
Constructs a key from its components, including its private key data and possibly-redundant information about its parent key. Invoked when deserializing, but otherwise not something that you normally should use.
-
DeterministicKey
public DeterministicKey(DeterministicKey keyToClone, DeterministicKey newParent)
Clones the key
-
-
Method Detail
-
getPath
public HDPath getPath()
Returns the path through someDeterministicHierarchy
which reaches this keys position in the tree. A path can be written as 0/1/0 which means the first child of the root, the second child of that node, then the first child of that node.
-
getPathAsString
public java.lang.String getPathAsString()
Returns the path of this key as a human-readable string starting with M or m to indicate the master key.
-
getDepth
public int getDepth()
Return this key's depth in the hierarchy, where the root node is at depth zero. This may be different than the number of segments in the path if this key was deserialized without access to its parent.
-
getChildNumber
public ChildNumber getChildNumber()
Returns the last element of the path returned bygetPath()
-
getChainCode
public byte[] getChainCode()
Returns the chain code associated with this key. See the specification to learn more about chain codes.
-
getIdentifier
public byte[] getIdentifier()
Returns RIPE-MD160(SHA256(pub key bytes)).
-
getFingerprint
public int getFingerprint()
Returns the first 32 bits of the result ofgetIdentifier()
.
-
getParent
@Nullable public DeterministicKey getParent()
-
getParentFingerprint
public int getParentFingerprint()
Return the fingerprint of the key from which this key was derived, if this is a child key, or else an array of four zero-value bytes.
-
getPrivKeyBytes33
public byte[] getPrivKeyBytes33()
Returns private key bytes, padded with zeros to 33 bytes.- Throws:
java.lang.IllegalStateException
- if the private key bytes are missing.
-
dropPrivateBytes
public DeterministicKey dropPrivateBytes()
Returns the same key with the private bytes removed. May return the same instance. The purpose of this is to save memory: the private key can always be very efficiently rederived from a parent that a private key, so storing all the private keys in RAM is a poor tradeoff especially on constrained devices. This means that the returned key may still be usable for signing and so on, so don't expect it to be a true pubkey-only object! If you want that then you should follow this call with a call todropParent()
.
-
dropParent
public DeterministicKey dropParent()
Returns the same key with the parent pointer removed (it still knows its own path and the parent fingerprint).
If this key doesn't have private key bytes stored/cached itself, but could rederive them from the parent, then the new key returned by this method won't be able to do that. Thus, using dropPrivateBytes().dropParent() on a regular DeterministicKey will yield a new DeterministicKey that cannot sign or do other things involving the private key at all.
-
encrypt
public DeterministicKey encrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException
Description copied from class:ECKey
Create an encrypted private key with the keyCrypter and the AES key supplied. This method returns a new encrypted key and leaves the original unchanged.- Overrides:
encrypt
in classECKey
- Parameters:
keyCrypter
- The keyCrypter that specifies exactly how the encrypted bytes are created.aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached as it is slow to create).- Returns:
- encryptedKey
- Throws:
KeyCrypterException
-
encrypt
public DeterministicKey encrypt(KeyCrypter keyCrypter, AesKey aesKey, @Nullable DeterministicKey newParent) throws KeyCrypterException
- Throws:
KeyCrypterException
-
isPubKeyOnly
public boolean isPubKeyOnly()
A deterministic key is considered to be 'public key only' if it hasn't got a private key part and it cannot be rederived. If the hierarchy is encrypted this returns true.- Overrides:
isPubKeyOnly
in classECKey
-
hasPrivKey
public boolean hasPrivKey()
Description copied from class:ECKey
Returns true if this key has unencrypted access to private key bytes. Does the opposite ofECKey.isPubKeyOnly()
.- Overrides:
hasPrivKey
in classECKey
-
getSecretBytes
@Nullable public byte[] getSecretBytes()
Description copied from class:ECKey
A wrapper forECKey.getPrivKeyBytes()
that returns null if the private key bytes are missing or would have to be derived (for the HD key case).- Specified by:
getSecretBytes
in interfaceEncryptableItem
- Overrides:
getSecretBytes
in classECKey
-
isEncrypted
public boolean isEncrypted()
A deterministic key is considered to be encrypted if it has access to encrypted private key bytes, OR if its parent does. The reason is because the parent would be encrypted under the same key and this key knows how to rederive its own private key bytes from the parent, if needed.- Specified by:
isEncrypted
in interfaceEncryptableItem
- Overrides:
isEncrypted
in classECKey
-
getKeyCrypter
@Nullable public KeyCrypter getKeyCrypter()
Returns this keysKeyCrypter
or the keycrypter of its parent key.- Overrides:
getKeyCrypter
in classECKey
-
sign
public ECKey.ECDSASignature sign(Sha256Hash input, @Nullable AesKey aesKey) throws KeyCrypterException
Description copied from class:ECKey
Signs the given hash and returns the R and S components as BigIntegers. In the Bitcoin protocol, they are usually encoded using DER format, so you wantECKey.ECDSASignature.encodeToDER()
instead. However sometimes the independent components can be useful, for instance, if you're doing to do further EC maths on them.- Overrides:
sign
in classECKey
aesKey
- The AES key to use for decryption of the private key. If null then no decryption is required.- Throws:
KeyCrypterException
- if there's something wrong with aesKey.
-
decrypt
public DeterministicKey decrypt(KeyCrypter keyCrypter, AesKey aesKey) throws KeyCrypterException
Description copied from class:ECKey
Create a decrypted private key with the keyCrypter and AES key supplied. Note that if the aesKey is wrong, this has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also just yield a garbage key.- Overrides:
decrypt
in classECKey
- Parameters:
keyCrypter
- The keyCrypter that specifies exactly how the decrypted bytes are created.aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).- Throws:
KeyCrypterException
-
decrypt
public DeterministicKey decrypt(AesKey aesKey) throws KeyCrypterException
Description copied from class:ECKey
Create a decrypted private key with AES key. Note that if the AES key is wrong, this has some chance of throwing KeyCrypterException due to the corrupted padding that will result, but it can also just yield a garbage key.- Overrides:
decrypt
in classECKey
- Parameters:
aesKey
- The KeyParameter with the AES encryption key (usually constructed with keyCrypter#deriveKey and cached).- Throws:
KeyCrypterException
-
derive
public DeterministicKey derive(int child)
Derives a child at the given index using hardened derivation. Note:index
is not the "i" value. If you want the softened derivation, then use insteadHDKeyDerivation.deriveChildKey(this, new ChildNumber(child, false))
.
-
getPrivKey
public java.math.BigInteger getPrivKey()
Returns the private key of this deterministic key. Even if this object isn't storing the private key, it can be re-derived by walking up to the parents if necessary and this is what will happen.- Overrides:
getPrivKey
in classECKey
- Throws:
java.lang.IllegalStateException
- if the parents are encrypted or a watching chain.
-
serializePubB58
public java.lang.String serializePubB58(Network network, ScriptType outputScriptType)
Deprecated.Use aserializePubB58(Network)
or a descriptor if you need output type informationSerialize public key to Base58outputScriptType should not be used in generating "xpub" format. (and "ypub", "zpub", etc. should not be used)
- Parameters:
network
- which network to serialize key foroutputScriptType
- output script type- Returns:
- the key serialized as a Base58 address
- See Also:
- Why does importmulti not support zpub and ypub?
-
serializePubB58
@Deprecated public java.lang.String serializePubB58(NetworkParameters params, ScriptType outputScriptType)
Deprecated.
-
serializePrivB58
public java.lang.String serializePrivB58(Network network, ScriptType outputScriptType)
Deprecated.Use aserializePrivB58(Network)
or a descriptor if you need output type informationSerialize private key to Base58outputScriptType should not be used in generating "xprv" format. (and "zprv", "vprv", etc. should not be used)
- Parameters:
network
- which network to serialize key foroutputScriptType
- output script type- Returns:
- the key serialized as a Base58 address
- See Also:
- Why does importmulti not support zpub and ypub?
-
serializePrivB58
@Deprecated public java.lang.String serializePrivB58(NetworkParameters params, ScriptType outputScriptType)
Deprecated.
-
serializePubB58
public java.lang.String serializePubB58(Network network)
Serialize public key to Base58 (either "xpub" or "tpub")- Parameters:
network
- which network to serialize key for- Returns:
- the key serialized as a Base58 address
-
serializePubB58
@Deprecated public java.lang.String serializePubB58(NetworkParameters params)
Deprecated.
-
serializePrivB58
public java.lang.String serializePrivB58(Network network)
Serialize private key to Base58 (either "xprv" or "tprv")- Parameters:
network
- which network to serialize key for- Returns:
- the key serialized as a Base58 address
-
serializePrivB58
@Deprecated public java.lang.String serializePrivB58(NetworkParameters params)
Deprecated.
-
deserializeB58
public static DeterministicKey deserializeB58(java.lang.String base58, Network network)
Deserialize a base-58-encoded HD Key with no parent
-
deserializeB58
@Deprecated public static DeterministicKey deserializeB58(java.lang.String base58, NetworkParameters params)
Deprecated.
-
deserializeB58
public static DeterministicKey deserializeB58(@Nullable DeterministicKey parent, java.lang.String base58, Network network)
Deserialize a base-58-encoded HD Key.- Parameters:
parent
- The parent node in the given key's deterministic hierarchy.- Throws:
java.lang.IllegalArgumentException
- if the base58 encoded key could not be parsed.
-
deserializeB58
@Deprecated public static DeterministicKey deserializeB58(@Nullable DeterministicKey parent, java.lang.String base58, NetworkParameters params)
Deprecated.
-
deserialize
public static DeterministicKey deserialize(Network network, byte[] serializedKey)
Deserialize an HD Key with no parent
-
deserialize
@Deprecated public static DeterministicKey deserialize(NetworkParameters params, byte[] serializedKey)
Deprecated.Deserialize an HD Key with no parent
-
deserialize
public static DeterministicKey deserialize(Network network, byte[] serializedKey, @Nullable DeterministicKey parent)
Deserialize an HD Key.- Parameters:
parent
- The parent node in the given key's deterministic hierarchy.
-
deserialize
@Deprecated public static DeterministicKey deserialize(NetworkParameters params, byte[] serializedKey, @Nullable DeterministicKey parent)
Deprecated.Deserialize an HD Key.
-
creationTime
public java.util.Optional<java.time.Instant> creationTime()
The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree in which case the time is stored alongside the key as per normal, seeECKey.creationTime()
.- Specified by:
creationTime
in interfaceEncryptableItem
- Overrides:
creationTime
in classECKey
-
setCreationTime
public void setCreationTime(java.time.Instant creationTime)
The creation time of a deterministic key is equal to that of its parent, unless this key is the root of a tree. Thus, setting the creation time on a leaf is forbidden.- Overrides:
setCreationTime
in classECKey
- Parameters:
creationTime
- creation time of this key
-
clearCreationTime
public void clearCreationTime()
Clears the creation time of this key. This is mainly used deserialization and cloning. Normally you should not need to use this, as keys should have proper creation times whenever possible.- Overrides:
clearCreationTime
in classECKey
-
setCreationTimeSeconds
@Deprecated public void setCreationTimeSeconds(long creationTimeSecs)
Deprecated.- Overrides:
setCreationTimeSeconds
in classECKey
-
equals
public boolean equals(java.lang.Object o)
Verifies equality of all fields but NOT the parent pointer (thus the same key derived in two separate hierarchy objects will equal each other.
-
formatKeyWithAddress
public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, java.lang.StringBuilder builder, Network network, ScriptType outputScriptType, @Nullable java.lang.String comment)
- Overrides:
formatKeyWithAddress
in classECKey
-
formatKeyWithAddress
@Deprecated public void formatKeyWithAddress(boolean includePrivateKeys, @Nullable AesKey aesKey, java.lang.StringBuilder builder, NetworkParameters params, ScriptType outputScriptType, @Nullable java.lang.String comment)
- Overrides:
formatKeyWithAddress
in classECKey
-
-