Useful models
thor_devkit.cry.hdnode
Hierarchically deterministic wallets for VeChain.
Relevant information: BIP32 and BIP44.
BIP-44 specified path notation:
m / purpose' / coin_type' / account' / change / address_index
Derive path for the VET:
m / 44' / 818' / 0' / 0 / address_index
So the following is the root of the “external” node chain for VET:
m / 44' / 818' / 0' / 0
m
is the master key, which shall be generated from a seed.
The following is the “first” key pair on the “external” node chain:
m / 44' / 818' / 0' / 0 / 0
Data:
Prefix of path for the VET. |
Classes:
Hierarchically deterministic (HD) node that is able to derive child HD Node. |
- thor_devkit.cry.hdnode.VET_EXTERNAL_PATH: Final = "m/44'/818'/0'/0"
Prefix of path for the VET.
address_index
is appended to this string for derivation
- class thor_devkit.cry.hdnode.HDNode(bip32_ctx: bip_utils.bip.bip32.bip32_secp256k1.Bip32Secp256k1)[source]
Bases:
object
Hierarchically deterministic (HD) node that is able to derive child HD Node.
Note
Please use static methods provided in this class to construct new instances rather than instantiate one by hand.
Class constructor, it is not recommended to use this directly.
To construct an HDNode, use staticmethods below instead.
- Parameters
bip32_ctx (Bip32) – Context to build node from.
Attributes:
Version bytes for public main network.
Version bytes for private main network.
Depth for master node.
Fingerprint of a master key.
Child number of a master key.
Get current node's public key in uncompressed format bytes.
Get current node's private key in bytes format.
Get the chain code of current HD node.
Get the common address format.
Get the finger print of current HD Node public key.
Methods:
Construct an HD Node from a seed (64 bytes).
Construct an HD Node from a mnemonic (set of words).
Construct an HD Node from an uncompressed public key.
Construct an HD Node from a private key.
Derive the child HD Node from current HD Node.
- VERSION_MAINNET_PUBLIC: bytes = b'\x04\x88\xb2\x1e'
Version bytes for public main network.
New in version 2.0.0.
- VERSION_MAINNET_PRIVATE: bytes = b'\x04\x88\xad\xe4'
Version bytes for private main network.
New in version 2.0.0.
- FINGER_PRINT_MASTER_KEY: bytes = b'\x00\x00\x00\x00'
Fingerprint of a master key.
New in version 2.0.0.
- CHILD_NUMBER_MASTER_KEY: bytes = b'\x00\x00\x00\x00'
Child number of a master key.
New in version 2.0.0.
- classmethod from_seed(seed: bytes, init_path: str = "m/44'/818'/0'/0") thor_devkit.cry.hdnode._Self [source]
Construct an HD Node from a seed (64 bytes).
The seed will be further developed into an “m” secret key and “chain code”.
Changed in version 2.0.0: Is
classmethod
now.- Parameters
seed (bytes) – Seed itself.
init_path (str, default:
VET_EXTERNAL_PATH
) – The initial derivation path
- Returns
A new HDNode.
- Return type
- classmethod from_mnemonic(words: Iterable[str], init_path: str = "m/44'/818'/0'/0") thor_devkit.cry.hdnode._Self [source]
Construct an HD Node from a mnemonic (set of words).
The words will generate a seed, which will be further developed into an “m” secret key and “chain code”.
Changed in version 2.0.0: Is
classmethod
now.- Parameters
words (Iterable of str) – Mnemonic words, usually 12 words.
init_path (str, default:
VET_EXTERNAL_PATH
) – The initial derivation path
- Returns
A new HDNode.
- Return type
- classmethod from_public_key(pub: bytes, chain_code: bytes) thor_devkit.cry.hdnode._Self [source]
Construct an HD Node from an uncompressed public key.
Changed in version 2.0.0: Is
classmethod
now.
- classmethod from_private_key(priv: bytes, chain_code: bytes) thor_devkit.cry.hdnode._Self [source]
Construct an HD Node from a private key.
Changed in version 2.0.0: Is
classmethod
now.
- derive(index: int) thor_devkit.cry.hdnode.HDNode [source]
Derive the child HD Node from current HD Node.
- Possible derivation paths:
private key -> private key
private key -> public key
public key -> public key
public key -> private key (impossible!)
- property public_key: bytes
Get current node’s public key in uncompressed format bytes.
Changed in version 2.0.0: Regular method turned into property.
- Returns
The uncompressed public key (starts with
0x04
)- Return type
- property private_key: bytes
Get current node’s private key in bytes format.
Changed in version 2.0.0: Regular method turned into property.
- Returns
The private key in bytes.
- Return type
- Raises
Bip32KeyError – If node was publicly derived
- property chain_code: bytes
Get the chain code of current HD node.
Changed in version 2.0.0: Regular method turned into property.
- Returns
32 bytes of chain code.
- Return type
thor_devkit.cry.keystore
Key store module.
Encrypt, decrypt and verify a key store.
The “keystore” dict should contain following format:
{
address: string
crypto: object
id: string
version: number
}
Functions:
Encrypt a private key to a key store. |
|
Decrypt a keystore into a private key (bytes). |
|
Validate if the key store is in good shape (roughly). |
|
Validate if the key store is in good shape (roughly). |
Type or structure checkers:
Parameters for |
|
Parameters for |
|
Parameters for |
|
Type of |
|
Type of key store body dictionary. |
|
Validation |
|
Validation |
|
Validation |
|
Validation |
|
Validation |
Deprecated:
Validate if the key store is in good shape (roughly). |
- thor_devkit.cry.keystore.encrypt(private_key: bytes, password: Union[str, bytes]) thor_devkit.cry.keystore.KeyStoreT [source]
Encrypt a private key to a key store.
- thor_devkit.cry.keystore.decrypt(keystore: thor_devkit.cry.keystore.KeyStoreT, password: Union[str, bytes]) bytes [source]
Decrypt a keystore into a private key (bytes).
- thor_devkit.cry.keystore.validate(keystore: thor_devkit.cry.keystore.KeyStoreT) Literal[True] [source]
Validate if the key store is in good shape (roughly).
- Parameters
keystore (KeyStoreT) – A key store dict.
- Returns
Always
True
for valid key store, raises otherwise.- Return type
Literal[True]
- Raises
voluptuous.error.Invalid – If data not in good shape.
- thor_devkit.cry.keystore.is_valid(keystore: thor_devkit.cry.keystore.KeyStoreT) bool [source]
Validate if the key store is in good shape (roughly).
- class thor_devkit.cry.keystore.AES128CTRCipherParamsT[source]
Bases:
TypedDict
Parameters for
AES-128-CTR
cipher.New in version 2.0.0.
Attributes:
Internal parameter.
- class thor_devkit.cry.keystore.PBKDF2ParamsT[source]
Bases:
TypedDict
Parameters for
PBKDF2
key derivation function.New in version 2.0.0.
Attributes:
Work factor.
Derived key length.
Hash function to calculate HMAC.
Salt to use, hex string.
- prf: Literal['hmac-sha256']
Hash function to calculate HMAC.
- class thor_devkit.cry.keystore.ScryptParamsT[source]
Bases:
TypedDict
Parameters for
scrypt
key derivation function.New in version 2.0.0.
Attributes:
Derived key length.
Work factor.
Block size.
Parallelism factor.
Salt to use, hex string.
- class thor_devkit.cry.keystore.CryptoParamsT[source]
Bases:
TypedDict
Type of
crypto
parameter of key store.New in version 2.0.0.
Attributes:
Cipher used.
Parameters of used cipher.
Encoded data, 64 characters long (32 bytes).
Key derivation function (other are not supported).
Parameters of key derivation function.
MAC (checksum variant), 64 characters long (32 bytes).
- cipher: Literal['aes-128-ctr']
Cipher used.
aes-128-ctr
is the only supported.
- cipherparams: thor_devkit.cry.keystore.AES128CTRCipherParamsT
Parameters of used cipher.
- kdf: Literal['pbkdf2', 'scrypt']
Key derivation function (other are not supported).
- kdfparams: Union[thor_devkit.cry.keystore.PBKDF2ParamsT, thor_devkit.cry.keystore.ScryptParamsT]
Parameters of key derivation function.
- class thor_devkit.cry.keystore.KeyStoreT[source]
Bases:
TypedDict
Type of key store body dictionary.
New in version 2.0.0.
Attributes:
Address used.
36 chars,
x{8}-x{4}-x{4}-x{4}-x{12}
,x
is any hex digit.Version used.
Cryptography parameters.
- version: Literal[3]
Version used. Other are not supported.
- crypto: thor_devkit.cry.keystore.CryptoParamsT
Cryptography parameters.
- thor_devkit.cry.keystore.AES128CTR_CIPHER_PARAMS(data): Final
Validation
Schema
forAES-128-CTR
cipher parameters.New in version 2.0.0.
- thor_devkit.cry.keystore.PBKDF2_PARAMS(data): Final
Validation
Schema
forPBKDF2
key derivation function parameters.New in version 2.0.0.
- thor_devkit.cry.keystore.SCRYPT_PARAMS(data): Final
Validation
Schema
forscrypt
key derivation function parameters.New in version 2.0.0.
- thor_devkit.cry.keystore.CRYPTO_PARAMS(data): Final
Validation
Schema
forcrypto
certificate parameter.New in version 2.0.0.
- thor_devkit.cry.keystore.KEYSTORE(data): Final
Validation
Schema
for key store body.New in version 2.0.0.
- thor_devkit.cry.keystore.well_formed(keystore: thor_devkit.cry.keystore.KeyStoreT) Literal[True] [source]
Validate if the key store is in good shape (roughly).
Deprecated since version 2.0.0: Function
well_formed()
is deprecated for naming consistency. Usevalidate()
oris_valid()
instead.
thor_devkit.certificate
User signed certificate.
Implemented according to VIP192
Classes:
User signed certificate. |
Type or structure checkers:
Type of Certificate |
|
Type of Certificate body dictionary. |
|
Validation |
|
Validation |
Deprecated:
Encode a certificate into json. |
|
Verify certificate signature. |
- class thor_devkit.certificate.Certificate(purpose: Literal['identification', 'agreement'], payload: thor_devkit.certificate.PayloadT, domain: str, timestamp: int, signer: str, signature: Optional[str] = None)[source]
Bases:
object
User signed certificate.
Instantiate certificate from parameters.
Changed in version 2.0.0:
ValueError
not raised anymore,Invalid
is used instead.- Parameters
purpose (str) – Certificate purpose.
payload (PayloadT) – Dictionary of style { “type”: str, “content”: str}
domain (str) – Certificate domain.
timestamp (int) – Integer Unix timestamp.
signer (str) – The signer address with
0x
prefix.signature (Optional[str], optional, default: None) – A
secp256k1
signed bytes, but turned into a'0x' + bytes.hex()
format.
- Raises
Invalid – When
payload
dictionary is malformed or parameters given are invalid.
Methods:
Export certificate body as dictionary.
Encode a certificate into json.
Verify the signature of certificate.
Check if the signature of certificate is valid.
- to_dict() thor_devkit.certificate.CertificateT [source]
Export certificate body as dictionary.
- encode() str [source]
Encode a certificate into json.
New in version 2.0.0.
- Returns
The encoded string.
- Return type
- verify() Literal[True] [source]
Verify the signature of certificate.
New in version 2.0.0.
- Raises
BadSignature – Signature does not match.
ValueError – Signature is absent or malformed.
- Returns
Always True.
- Return type
Literal[True]
- class thor_devkit.certificate.PayloadT[source]
Bases:
TypedDict
Type of Certificate
payload
parameter.New in version 2.0.0.
Attributes:
Payload type.
Payload content.
- class thor_devkit.certificate.CertificateT[source]
Bases:
TypedDict
Type of Certificate body dictionary.
New in version 2.0.0.
Attributes:
Purpose of certificate, can be
identification
oragreement
.Certificate payload.
Domain for which certificate was issued.
Issue time.
Signer address, in
0x...
format.Signature in
0x...
format, 65 bytes (as fromcry.secp256k1.secp256k1.sign()
).- purpose: Literal['identification', 'agreement']
Purpose of certificate, can be
identification
oragreement
.Usage scenarios:
- Identification
Request user to proof that he/she is the private key holder.
In this scenario payload is not essential to the user.
- Agreement
Request user to agree with an agreement by using user’s private key to sign.
In this scenario payload should contain the content such as Privacy policy and it is essential to the user.
Use cases may be extended in future, see VIP192 for details.
- payload: thor_devkit.certificate.PayloadT
Certificate payload.
- thor_devkit.certificate.PAYLOAD(data): Final
Validation
Schema
for certificate payload.New in version 2.0.0.
- thor_devkit.certificate.CERTIFICATE(data): Final
Validation
Schema
for certificate payload.New in version 2.0.0.
- thor_devkit.certificate.encode(cert: thor_devkit.certificate.Certificate) str [source]
Encode a certificate into json.
Deprecated since version 2.0.0:
encode()
module-level function is replaced byCertificate.encode()
method to conform with OOP standards.
- thor_devkit.certificate.verify(cert: thor_devkit.certificate.Certificate) Literal[True] [source]
Verify certificate signature.
Deprecated since version 2.0.0:
verify()
module-level function is replaced byCertificate.verify()
method to conform with OOP standards.
Various utilities and primitives
thor_devkit.cry.address
VeChain “public key” and “address” related operations and verifications.
Functions:
Derive an address from a public key. |
|
Check if a text string is valid address. |
|
Turn an address to a checksum address that is compatible with eip-55. |
- thor_devkit.cry.address.public_key_to_address(key_bytes: bytes) bytes [source]
Derive an address from a public key.
- thor_devkit.cry.address.is_address(address: str) bool [source]
Check if a text string is valid address.
- thor_devkit.cry.address.to_checksum_address(address: str) str [source]
Turn an address to a checksum address that is compatible with eip-55.
- Parameters
address (str) – The address string. Should begin with
0x
.- Returns
The address that is properly capitalized.
- Return type
- Raises
ValueError – If the address is not valid.
thor_devkit.cry.mnemonic
Mnemonic-related utilities.
Generate/validate a words used for mnemonic wallet.
Derive the first private key from words.
Derive the correct seed for BIP32.
Documentation:
Functions:
Generate BIP39 mnemonic words. |
|
Check if the words form a valid BIP39 mnemonic words. |
|
Derive a seed from a word list. |
|
Get a private key from the mnemonic wallet. |
Type or structure checkers:
Allowed mnemonic strength literal type. |
Data:
Allowed mnemonic strength options. |
Deprecated:
Check if the words form a valid BIP39 mnemonic phrase. |
- thor_devkit.cry.mnemonic.generate(strength: Literal[128, 160, 192, 224, 256] = 128) List[str] [source]
Generate BIP39 mnemonic words.
- Parameters
strength (int, default: 128) – Any of [128, 160, 192, 224, 256] (
ALLOWED_STRENGTHS
)- Returns
A list of words.
- Return type
List[str]
- Raises
ValueError – If the strength is not allowed.
- thor_devkit.cry.mnemonic.is_valid(words: Iterable[str]) bool [source]
Check if the words form a valid BIP39 mnemonic words.
New in version 2.0.0.
- Parameters
words (Iterable of str) – A list of english words.
- Returns
Whether mnemonic is valid.
- Return type
- thor_devkit.cry.mnemonic.derive_seed(words: Iterable[str]) bytes [source]
Derive a seed from a word list.
- Parameters
words (Iterable of str) – A list of english words.
- Returns
64 bytes
- Return type
- Raises
ValueError – Seed phrase is malformed.
- thor_devkit.cry.mnemonic.derive_private_key(words: Iterable[str], index: int = 0) bytes [source]
Get a private key from the mnemonic wallet.
- thor_devkit.cry.mnemonic.AllowedStrengthsT(*args, **kwargs)
Allowed mnemonic strength literal type.
alias of
Literal
[128, 160, 192, 224, 256]
- thor_devkit.cry.mnemonic.ALLOWED_STRENGTHS: Final[Tuple[Literal[128, 160, 192, 224, 256], ...]] = (128, 160, 192, 224, 256)
Allowed mnemonic strength options.
- thor_devkit.cry.mnemonic.validate(words: Iterable[str]) bool [source]
Check if the words form a valid BIP39 mnemonic phrase.
Deprecated since version 2.0.0: Function
validate()
is deprecated for naming consistency. Useis_valid()
instead. There is no raising equivalent.
thor_devkit.cry.bloom
Bloom filter implementation.
Bloom filter is a probabilistic data structure that is used to check whether the element definitely is not in set or may be in the set.
Instead of a traditional hash-based set, that takes up too much memory, this structure permits less memory with a tolerable false positive rate.
Used variables:
m
Total bits of the filter.
k
How many different hash functions to use.
n
Number of elements to be added to the filter.
This implementation uses 2048 bits / 256 bytes of storage. You can override it in a subclass.
Classes:
Bloom filter. |
- class thor_devkit.bloom.Bloom(k: int, bits: Optional[bytes] = None)[source]
Bases:
object
Bloom filter.
Construct a bloom filter.
- Parameters
Attributes:
Maximal amount of hash functions to use.
Filter size in bits.
The number of different hash functions used.
Actual storage.
Methods:
Estimate the k based on expected elements count.
Add an element to the bloom filter.
Test if element is inside the bloom filter.
Test if element is inside the bloom filter.
- add(element: bytes) Literal[True] [source]
Add an element to the bloom filter.
- Parameters
element (bytes) – The element in bytes.
- Returns
Always
True
- Return type
Literal[True]
- test(element: bytes) bool [source]
Test if element is inside the bloom filter.
- Parameters
element (bytes) – The element in bytes.
- Returns
True
if inside,False
if not inside.- Return type
Warning
If
False
is returned, then element is sure not in filter.If
True
is returned, then element may be in filter, there is no way to determine it surely.
- __contains__(element: bytes) bool [source]
Test if element is inside the bloom filter.
- Parameters
element (bytes) – The element in bytes.
- Returns
True
if inside,False
if not inside.- Return type
Warning
If
False
is returned, then element is sure not in filter.If
True
is returned, then element may be in filter, there is no way to determine it surely.
Hash and cryptography utilities
thor_devkit.cry.blake2b
Blake2b hash function.
Functions:
Compute a hash in black2b flavor. |
thor_devkit.cry.keccak
Keccak hash function.
Functions:
Compute the sha3_256 flavor hash. |
thor_devkit.cry.secp256k1
Elliptic curve secp256k1
related functions.
Generate a private key.
Derive uncompressed public key from private key.
Sign a message hash using the private key, generate signature.
Given the message hash and signature, recover the uncompressed public key.
Functions:
Verify if a private key is well-formed. |
|
Create a random number (32 bytes) as private key. |
|
Derive public key from a private key(uncompressed). |
|
Sign the message hash. |
|
Recover the uncompressed public key from signature. |
Deprecated:
Create a random number (32 bytes) as public key. |
|
Create a random number (32 bytes) as private key. |
- thor_devkit.cry.secp256k1.is_valid_private_key(priv_key: bytes) bool [source]
Verify if a private key is well-formed.
New in version 2.0.0.
- thor_devkit.cry.secp256k1.generate_private_key() bytes [source]
Create a random number (32 bytes) as private key.
New in version 2.0.0.
- Returns
The private key in 32 bytes format.
- Return type
- thor_devkit.cry.secp256k1.derive_public_key(priv_key: bytes) bytes [source]
Derive public key from a private key(uncompressed).
New in version 2.0.0.
- Parameters
priv_key (bytes) – The private key in bytes.
- Returns
The public key(uncompressed) in bytes, which starts with 04.
- Return type
- Raises
ValueError – If the private key is not valid.
- thor_devkit.cry.secp256k1.sign(msg_hash: bytes, priv_key: bytes) bytes [source]
Sign the message hash.
Note
It signs message hash, not the message itself!
- Parameters
- Returns
The signing result.
- Return type
- Raises
ValueError – If the input is malformed.
- thor_devkit.cry.secp256k1.recover(msg_hash: bytes, sig: bytes) bytes [source]
Recover the uncompressed public key from signature.
- Parameters
- Returns
public key in uncompressed format.
- Return type
- Raises
ValueError – If the signature is bad, or recovery bit is bad, or cannot recover(sig and msg_hash doesn’t match).
- thor_devkit.cry.secp256k1.derive_publicKey(priv_key: bytes) bytes [source]
Create a random number (32 bytes) as public key.
Deprecated since version 2.0.0: Use
derive_public_key()
instead for naming consistency.
- thor_devkit.cry.secp256k1.generate_privateKey() bytes [source]
Create a random number (32 bytes) as private key.
Deprecated since version 2.0.0: Use
generate_private_key()
instead for naming consistency.
Implementation details
thor_devkit.exceptions
Custom exceptions.
DeserializationError
and SerializationError
are aliases for
rlp.exception.DeserializationError
and
rlp.exception.SerializationError
(they aren’t listed on their
documentation page).
Exceptions:
Exception raised if deserialization fails. |
|
Exception raised if serialization fails. |
|
The signature of certificate does not match with the signer. |
|
The decoded transaction is invalid. |
- exception thor_devkit.exceptions.DeserializationError(message, serial)[source]
Bases:
rlp.exceptions.RLPException
Exception raised if deserialization fails.
- Variables
serial – the decoded RLP string that could not be deserialized
- exception thor_devkit.exceptions.SerializationError(message, obj)[source]
Bases:
rlp.exceptions.RLPException
Exception raised if serialization fails.
- Variables
obj – the object that could not be serialized
thor_devkit.cry.utils
Utils helping with hex <-> string
conversion and stripping.
Functions:
Strip the |
|
Remove the |
|
Check if bytes is the uncompressed public key. |
|
Check if bytes is the uncompressed public key. |
|
Lowercase input if it is string, return unchanged otherwise. |
Deprecated:
Check if bytes is the uncompressed public key. |
- thor_devkit.cry.utils.izip(*args, **kwargs)
Implements
python3.10+
zip strict mode.In python 3.10 and higher it is an alias for
partial(zip, strict=True)
.- Parameters
*iterables (Iterable[Any]) – Iterables to zip together.
- Yields
Tuple[Any, …] – Tuples of values like standard
zip()
generates.- Raises
ValueError – If not all iterables had equal length.
- thor_devkit.cry.utils.strip_0x04(p: bytes) bytes [source]
Strip the
0x04
off the starting of a byte sequence 65 bytes long.
- thor_devkit.cry.utils.validate_uncompressed_public_key(key_bytes: bytes) Literal[True] [source]
Check if bytes is the uncompressed public key.
- Parameters
key_bytes (bytes) – Address in bytes.
- Returns
Always
True
if public key is valid, raises otherwise.- Return type
Literal[True]
- Raises
ValueError – If address doesn’t begin with
04
as first byte.
- thor_devkit.cry.utils.is_valid_uncompressed_public_key(key_bytes: bytes) bool [source]
Check if bytes is the uncompressed public key.
- thor_devkit.cry.utils.is_uncompressed_public_key(key_bytes: bytes) Literal[True] [source]
Check if bytes is the uncompressed public key.
Deprecated since version 2.0.0: Use
is_valid_uncompressed_public_key()
orvalidate_uncompressed_public_key()
instead.
thor_devkit.validation
Helper functions for voluptuous
validation.
Functions:
Validate and normalize hex representation of number. |
|
Validate and normalize hex representation of bytes (like |
|
Validate and normalize address (40 bytes, with or without prefix). |
- thor_devkit.validation.hex_integer(length: Optional[int] = None, *, to_int: Literal[False] = False, require_prefix: bool = True, allow_empty: bool = 'False') Callable[[str], str] [source]
- thor_devkit.validation.hex_integer(length: Optional[int] = None, *, to_int: Literal[True], require_prefix: bool = 'True', allow_empty: bool = 'False') Callable[[str], int]
Validate and normalize hex representation of number.
Normalized form:
0x{val}
,val
is in lower case.- Parameters
- Returns
Validator callable.
- Return type
- thor_devkit.validation.hex_string(length: Optional[int] = None, *, to_bytes: Literal[False] = False, allow_empty: bool = 'False', allow_prefix: bool = False) Callable[[str], str] [source]
- thor_devkit.validation.hex_string(length: Optional[int] = None, *, to_bytes: Literal[True], allow_empty: bool = 'False', allow_prefix: bool = 'True') Callable[[str], bytes]
Validate and normalize hex representation of bytes (like
bytes.hex()
).Normalized form: without
0x
prefix, in lower case.