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:

VET_EXTERNAL_PATH

Prefix of path for the VET.

Classes:

HDNode

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_MAINNET_PUBLIC

Version bytes for public main network.

VERSION_MAINNET_PRIVATE

Version bytes for private main network.

DEPTH_MASTER_NODE

Depth for master node.

FINGER_PRINT_MASTER_KEY

Fingerprint of a master key.

CHILD_NUMBER_MASTER_KEY

Child number of a master key.

public_key

Get current node's public key in uncompressed format bytes.

private_key

Get current node's private key in bytes format.

chain_code

Get the chain code of current HD node.

address

Get the common address format.

finger_print

Get the finger print of current HD Node public key.

Methods:

from_seed

Construct an HD Node from a seed (64 bytes).

from_mnemonic

Construct an HD Node from a mnemonic (set of words).

from_public_key

Construct an HD Node from an uncompressed public key.

from_private_key

Construct an HD Node from a private key.

derive

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.

DEPTH_MASTER_NODE: bytes = b'\x00'

Depth for master node.

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.

bip32_ctx: bip_utils.bip.bip32.bip32_secp256k1.Bip32Secp256k1
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
Returns

A new HDNode.

Return type

HDNode

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

HDNode

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.

Parameters
  • pub (bytes) – An uncompressed public key in bytes (starts with 0x04 as first byte).

  • chain_code (bytes) – 32 bytes

Returns

A new HDNode.

Return type

HDNode

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.

Parameters
  • priv (bytes) – The private key in bytes.

  • chain_code (bytes) – 32 bytes of random number you choose.

Returns

A new HDNode.

Return type

HDNode

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!)

Parameters

index (int) – Which key index (0 <= index < 2**32) to derive.

Returns

A New HDNode.

Return type

HDNode

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

bytes

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

bytes

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

bytes

property address: bytes

Get the common address format.

Changed in version 2.0.0: Regular method turned into property.

Returns

The address in bytes. (without 0x prefix)

Return type

bytes

property finger_print: bytes

Get the finger print of current HD Node public key.

Changed in version 2.0.0: Regular method turned into property.

Returns

finger print in bytes.

Return type

bytes

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

Encrypt a private key to a key store.

decrypt

Decrypt a keystore into a private key (bytes).

validate

Validate if the key store is in good shape (roughly).

is_valid

Validate if the key store is in good shape (roughly).

Type or structure checkers:

AES128CTRCipherParamsT

Parameters for AES-128-CTR cipher.

PBKDF2ParamsT

Parameters for PBKDF2 key derivation function.

ScryptParamsT

Parameters for scrypt key derivation function.

CryptoParamsT

Type of crypto parameter of key store.

KeyStoreT

Type of key store body dictionary.

AES128CTR_CIPHER_PARAMS

Validation Schema for AES-128-CTR cipher parameters.

PBKDF2_PARAMS

Validation Schema for PBKDF2 key derivation function parameters.

SCRYPT_PARAMS

Validation Schema for scrypt key derivation function parameters.

CRYPTO_PARAMS

Validation Schema for crypto certificate parameter.

KEYSTORE

Validation Schema for key store body.

Deprecated:

well_formed

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.

Parameters
  • private_key (bytes) – A private key in bytes.

  • password (bytes or str) – A password.

Returns

A key store json-style dictionary.

Return type

KeyStoreT

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).

Parameters
Returns

A private key in bytes.

Return type

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).

Parameters

keystore (KeyStoreT) – A key store dict.

Returns

Whether key store dict is well-formed.

Return type

bool

class thor_devkit.cry.keystore.AES128CTRCipherParamsT[source]

Bases: TypedDict

Parameters for AES-128-CTR cipher.

New in version 2.0.0.

Attributes:

iv

Internal parameter.

iv: str

Internal parameter.

class thor_devkit.cry.keystore.PBKDF2ParamsT[source]

Bases: TypedDict

Parameters for PBKDF2 key derivation function.

New in version 2.0.0.

Attributes:

c

Work factor.

dklen

Derived key length.

prf

Hash function to calculate HMAC.

salt

Salt to use, hex string.

c: int

Work factor.

dklen: int

Derived key length.

prf: Literal['hmac-sha256']

Hash function to calculate HMAC.

salt: str

Salt to use, hex string.

class thor_devkit.cry.keystore.ScryptParamsT[source]

Bases: TypedDict

Parameters for scrypt key derivation function.

New in version 2.0.0.

Attributes:

dklen

Derived key length.

n

Work factor.

r

Block size.

p

Parallelism factor.

salt

Salt to use, hex string.

dklen: int

Derived key length.

n: int

Work factor.

r: int

Block size.

p: int

Parallelism factor.

salt: str

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

Cipher used.

cipherparams

Parameters of used cipher.

ciphertext

Encoded data, 64 characters long (32 bytes).

kdf

Key derivation function (other are not supported).

kdfparams

Parameters of key derivation function.

mac

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.

ciphertext: str

Encoded data, 64 characters long (32 bytes).

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.

mac: str

MAC (checksum variant), 64 characters long (32 bytes).

class thor_devkit.cry.keystore.KeyStoreT[source]

Bases: TypedDict

Type of key store body dictionary.

New in version 2.0.0.

Attributes:

address

Address used.

id

36 chars, x{8}-x{4}-x{4}-x{4}-x{12}, x is any hex digit.

version

Version used.

crypto

Cryptography parameters.

address: str

Address used.

id: str

36 chars, x{8}-x{4}-x{4}-x{4}-x{12}, x is any hex digit.

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 for AES-128-CTR cipher parameters.

New in version 2.0.0.

thor_devkit.cry.keystore.PBKDF2_PARAMS(data): Final

Validation Schema for PBKDF2 key derivation function parameters.

New in version 2.0.0.

thor_devkit.cry.keystore.SCRYPT_PARAMS(data): Final

Validation Schema for scrypt key derivation function parameters.

New in version 2.0.0.

thor_devkit.cry.keystore.CRYPTO_PARAMS(data): Final

Validation Schema for crypto 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. Use validate() or is_valid() instead.

thor_devkit.certificate

User signed certificate.

Implemented according to VIP192

Classes:

Certificate

User signed certificate.

Type or structure checkers:

PayloadT

Type of Certificate payload parameter.

CertificateT

Type of Certificate body dictionary.

PAYLOAD

Validation Schema for certificate payload.

CERTIFICATE

Validation Schema for certificate payload.

Deprecated:

encode

Encode a certificate into json.

verify

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:

to_dict

Export certificate body as dictionary.

encode

Encode a certificate into json.

verify

Verify the signature of certificate.

is_valid

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

str

verify() Literal[True][source]

Verify the signature of certificate.

New in version 2.0.0.

Raises
Returns

Always True.

Return type

Literal[True]

is_valid() bool[source]

Check if the signature of certificate is valid.

New in version 2.0.0.

Returns

Whether signature is valid.

Return type

bool

class thor_devkit.certificate.PayloadT[source]

Bases: TypedDict

Type of Certificate payload parameter.

New in version 2.0.0.

Attributes:

type

Payload type.

content

Payload content.

type: str

Payload type.

content: str

Payload content.

class thor_devkit.certificate.CertificateT[source]

Bases: TypedDict

Type of Certificate body dictionary.

New in version 2.0.0.

Attributes:

purpose

Purpose of certificate, can be identification or agreement.

payload

Certificate payload.

domain

Domain for which certificate was issued.

timestamp

Issue time.

signer

Signer address, in 0x... format.

signature

Signature in 0x... format, 65 bytes (as from cry.secp256k1.secp256k1.sign()).

purpose: Literal['identification', 'agreement']

Purpose of certificate, can be identification or agreement.

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.

domain: str

Domain for which certificate was issued.

timestamp: int

Issue time.

signer: str

Signer address, in 0x... format.

signature: typing_extensions.NotRequired[str]

Signature in 0x... format, 65 bytes (as from cry.secp256k1.secp256k1.sign()).

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 by Certificate.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 by Certificate.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:

public_key_to_address

Derive an address from a public key.

is_address

Check if a text string is valid address.

to_checksum_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.

Parameters

key_bytes (bytes) – public key (uncompressed, starts with 0x04).

Returns

bytes that represents the address.

Return type

bytes

thor_devkit.cry.address.is_address(address: str) bool[source]

Check if a text string is valid address.

Parameters

address (str) – The address string to be checked. Should begin with 0x.

Returns

Whether given address is valid.

Return type

bool

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

str

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

Generate BIP39 mnemonic words.

is_valid

Check if the words form a valid BIP39 mnemonic words.

derive_seed

Derive a seed from a word list.

derive_private_key

Get a private key from the mnemonic wallet.

Type or structure checkers:

AllowedStrengthsT

Allowed mnemonic strength literal type.

Data:

ALLOWED_STRENGTHS

Allowed mnemonic strength options.

Deprecated:

validate

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

bool

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

bytes

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.

Parameters
  • words (Iterable of str) – A list of english words.

  • index (int, default: 0) – The private key index, starting from zero.

Returns

Private key.

Return type

bytes

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. Use is_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

Bloom filter.

class thor_devkit.bloom.Bloom(k: int, bits: Optional[bytes] = None)[source]

Bases: object

Bloom filter.

Construct a bloom filter.

Parameters
  • k (int) – The number of different hash functions to use.

  • bits (Optional[bytes], optional) – Bits of previous bloom filter to inherit. Leave it None to create an empty bloom filter.

Attributes:

MAX_K

Maximal amount of hash functions to use.

BITS_LENGTH

Filter size in bits.

k

The number of different hash functions used.

bits

Actual storage.

Methods:

estimate_k

Estimate the k based on expected elements count.

add

Add an element to the bloom filter.

test

Test if element is inside the bloom filter.

__contains__

Test if element is inside the bloom filter.

MAX_K: int = 16

Maximal amount of hash functions to use.

BITS_LENGTH: int = 2048

Filter size in bits.

classmethod estimate_k(count: int) int[source]

Estimate the k based on expected elements count.

Parameters

count (int) – The number of elements to be inserted.

Returns

The estimated k.

Return type

int

k: int

The number of different hash functions used.

bits: bytes

Actual storage.

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

bool

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

bool

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:

blake2b256

Compute a hash in black2b flavor.

thor_devkit.cry.blake2b.blake2b256(list_of_bytes: Iterable[bytes]) Tuple[bytes, int][source]

Compute a hash in black2b flavor.

Parameters

list_of_bytes (Iterable of bytes) – The iterable of bytes or bytearray’s to be hashed.

Returns

Hash result in bytes (32 bytes) and the length of bytes (32).

Return type

Tuple[bytes, int]

Raises

TypeError – If argument type is wrong.

thor_devkit.cry.keccak

Keccak hash function.

Functions:

keccak256

Compute the sha3_256 flavor hash.

thor_devkit.cry.keccak.keccak256(list_of_bytes: Iterable[bytes]) Tuple[bytes, int][source]

Compute the sha3_256 flavor hash.

Parameters

list_of_bytes (Iterable of bytes) – A list of bytes to be hashed.

Returns

Hash value in bytes (32 bytes) and length of bytes.

Return type

Tuple[bytes, int]

Raises

TypeError – If bytes or bytearray is used instead of sequence as input.

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:

is_valid_private_key

Verify if a private key is well-formed.

generate_private_key

Create a random number (32 bytes) as private key.

derive_public_key

Derive public key from a private key(uncompressed).

sign

Sign the message hash.

recover

Recover the uncompressed public key from signature.

Deprecated:

derive_publicKey

Create a random number (32 bytes) as public key.

generate_privateKey

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.

Parameters

priv_key (bytes) – Private key to check.

Returns

True if the private key is valid.

Return type

bool

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

bytes

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

bytes

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
  • msg_hash (bytes) – The message hash.

  • priv_key (bytes) – The private key in bytes.

Returns

The signing result.

Return type

bytes

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
  • msg_hash (bytes) – The message hash.

  • sig (bytes) – The signature.

Returns

public key in uncompressed format.

Return type

bytes

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:

DeserializationError

Exception raised if deserialization fails.

SerializationError

Exception raised if serialization fails.

BadSignature

The signature of certificate does not match with the signer.

BadTransaction

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

exception thor_devkit.exceptions.BadSignature(message: Optional[str] = None, *args: Any, **kwargs: Any)[source]

Bases: thor_devkit.exceptions._DefaultTextExceptionMixin, Exception

The signature of certificate does not match with the signer.

exception thor_devkit.exceptions.BadTransaction(message: Optional[str] = None, *args: Any, **kwargs: Any)[source]

Bases: thor_devkit.exceptions._DefaultTextExceptionMixin, ValueError

The decoded transaction is invalid.

thor_devkit.cry.utils

Utils helping with hex <-> string conversion and stripping.

Functions:

strip_0x04

Strip the 0x04 off the starting of a byte sequence 65 bytes long.

remove_0x

Remove the 0x prefix if any.

validate_uncompressed_public_key

Check if bytes is the uncompressed public key.

is_valid_uncompressed_public_key

Check if bytes is the uncompressed public key.

safe_tolowercase

Lowercase input if it is string, return unchanged otherwise.

Deprecated:

is_uncompressed_public_key

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.remove_0x(address: str) str[source]

Remove the 0x prefix if any.

Parameters

address (str) – Address string, like 0xabc

Returns

Address string without prefix 0x

Return type

str

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.

Parameters

key_bytes (bytes) – Address in bytes.

Returns

Whether input is uncompressed public key.

Return type

bool

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() or validate_uncompressed_public_key() instead.

thor_devkit.cry.utils.safe_tolowercase(s: thor_devkit.cry.utils._T) thor_devkit.cry.utils._T[source]

Lowercase input if it is string, return unchanged otherwise.

Parameters

s (str or Any) – Value to process.

Returns

Lowercase value if it is a string, value unchanged otherwise.

Return type

str or Any

thor_devkit.validation

Helper functions for voluptuous validation.

Functions:

hex_integer

Validate and normalize hex representation of number.

hex_string

Validate and normalize hex representation of bytes (like bytes.hex()).

address_type

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
  • length (Optional[int]) – Expected length of string, excluding prefix.

  • to_int (bool, default: False) – Normalize given string to integer.

  • require_prefix (bool, default: True) – Require 0x prefix.

  • allow_empty (bool, default: False) – Allow empty string (or 0x if require_prefix=True)

Returns

Validator callable.

Return type

Callable[[str], str]

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.

Parameters
  • length (Optional[int]) – Expected length of string.

  • allow_empty (bool, default: False) – Allow empty string.

  • allow_prefix (bool, default: True) – Allow 0x prefix in input.

Returns

Validator callable.

Return type

Callable[[str], str]

thor_devkit.validation.address_type() Callable[[str], str][source]

Validate and normalize address (40 bytes, with or without prefix).

Returns

Validator callable.

Return type

Callable[[str], str]