zpywallet.utils package

Submodules

zpywallet.utils.aes module

decrypt(enc: bytes, passphrase: bytes) bytes[source]

Decrypt encrypted binary data with the passphrase

Parameters:
  • enc (bytes) – data to decrypt

  • passphrase (bytes) – Decryption password

Returns:

The original text

Return type:

bytes

decrypt_str(enc: bytes, passphrase: str) str[source]

A wrapper around decrypt() for str objects

encrypt(raw: bytes, passphrase: bytes) bytes[source]

Encrypt binary data with the passphrase

Parameters:
  • raw (bytes) – data to encrypt

  • passphrase (bytes) – Encryption password. It is recommended to use a strong password.

Returns:

The encrypted text

Return type:

bytes

encrypt_str(raw: str, passphrase: str) str[source]

A wrapper around encyrpt() for str objects

hash_password_pbkdf2(password: bytes, salt: bytes, iterations=600000, key_length=44)[source]

zpywallet.utils.base58 module

Base58 encoding

Implementations of Base58 and Base58Check encodings that are compatible with the Bitcoin network.

b58decode(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', *, autofix: bool = False) bytes[source]

Decode a Base58 encoded string

b58decode_check(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', *, autofix: bool = False) bytes[source]

Decode and verify the checksum of a Base58 encoded string

b58decode_int(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', *, autofix: bool = False) int[source]

Decode a Base58 encoded string as an integer

b58encode(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz') bytes[source]

Encode a string using Base58

b58encode_check(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz') bytes[source]

Encode a string using Base58 with a 4 character checksum

b58encode_int(i: int, default_one: bool = True, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz') bytes[source]

Encode an integer using Base58

is_b58check(v: str | bytes, alphabet: bytes = b'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz', *, autofix: bool = False) bool[source]

Check if a string is valid Base58Check

scrub_input(v: str | bytes) bytes[source]

zpywallet.utils.bech32 module

Reference implementation for Bech32/Bech32m and segwit addresses.

class Encoding(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)[source]

Bases: Enum

Enumeration type to list the various supported encodings.

BECH32 = 1
BECH32M = 2
bech32_create_checksum(hrp, data, spec)[source]
bech32_decode(hrp, addr)[source]

Decode a segwit address.

bech32_encode(hrp, witver, witprog)[source]

Encode a segwit address.

bech32_hrp_expand(hrp)[source]
bech32_polymod(values)[source]
bech32_verify_checksum(hrp, data)[source]

Verify a checksum given HRP and converted data characters.

convertbits(data, frombits, tobits, pad=True)[source]

zpywallet.utils.bip32 module

Module for generating Heirarchical Deterministic (HD) keys for supported networks.

class HDWallet(chain_code, depth=0, parent_fingerprint=0, child_number=0, private_exponent=None, private_key=None, public_pair=None, public_key=None, mnemonic=None, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Bases: object

A BIP32 wallet is made up of Wallet nodes.

A Private node contains both a public and private key, while a public node contains only a public key.

WARNING:

When creating a NEW wallet this way, you MUST back up the private key. If you don’t then any coins sent to your address will be LOST FOREVER.

You need to save the private key somewhere. It is OK to just write it down on a piece of paper! Don’t share this key with anyone!

>>> my_wallet = Wallet.from_mnemonic(
...     key='correct horse battery staple')
>>> private = my_wallet.dump_xkey(private=True)
>>> private  
u'xprv9s21ZrQH143K2mDJW8vDeFwbyDbFv868mM2Zr87rJSTj8q16Unkaq1pryiV...'

If you want to use this wallet on your website to accept bitcoin or altcoin payments, you should first create a primary child.

BIP32 Hierarchical Deterministic Wallets are described in this BIP: https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki

__init__(chain_code, depth=0, parent_fingerprint=0, child_number=0, private_exponent=None, private_key=None, public_pair=None, public_key=None, mnemonic=None, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Construct a new BIP32 compliant wallet.

You probably don’t want to use this init methd. Instead use one of the class methods for creating a wallet.

In particular, the mnemonic is not used to generate the wallet in this constructor and its only purpose here is for storage. The Wallet object deals with master private keys for creating things, which are generated in the class methods.

address(compressed: bool = True, witness_version: int = 0)[source]

Create a public address from this Wallet.

Public addresses can accept payments.

https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses

Parameters:
  • compressed (bool) – Whether or not the compressed key should be used.

  • witness_version (int) – Used only when creating Bech32 addresses. Allowed values are 0 (segwit) and 1 (Taproot).

Returns:

An encoded address

Return type:

str

bitcoin_seed = b'Bitcoin seed'
crack_private_key(child_private_key)[source]

Crack the parent private key given a child private key.

BIP32 has a vulnerability/feature that allows you to recover the master private key if you’re given a master public key and any of its publicly-derived child private keys. This is a pretty serious security vulnerability that looks as innocuous as this:

>>> w = Wallet.new_random_wallet()
>>> child = w.get_child(0, is_prime=False)
>>> w_pub = w.public_copy()
>>> assert w_pub.private_key is None
>>> master_public_key = w_pub.serialize_b58(private=False)
>>> # Now you put master_public_key on your website
>>> # and give somebody a private key
>>> public_master = HDWallet.load_str_xkey(master_public_key)
>>> cracked_private_master = public_master.crack_private_key(child)
>>> assert w == cracked_private_master  # :(
Implementation details from:

http://bitcoinmagazine.com/8396/deterministic-wallets-advantages-flaw/

create_new_address_for_user(user_id)[source]

Create a new bitcoin address to accept payments for a User.

This is a convenience wrapper around get_child that helps you do the right thing. This method always creates a public, non-prime address that can be generated from a BIP32 public key on an insecure server.

dump_str_xkey(private=True, segwit=False) str[source]

Encode the serialized node in base58.

dump_xkey(private: bool = True, segwit: bool = False)[source]

Serialize this key.

Parameters:
  • private (bool) – Whether or not the serialized key should contain private information. Set to False for a public-only representation that cannot spend funds but can create children. You want private=False if you are, for example, running an e-commerce website and want to accept bitcoin payments. See the README for more information. Default is True.

  • segwit (bool) – Whether to use segwit extended version bytes instead of legacy extended version bytes. Only for networks which support Segwit, therefore the default value is False.

See the spec in load_xkey for more details.

property fingerprint

The first 32 bits of the identifier are called the fingerprint.

classmethod from_brainwallet(password: str, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generate a new key from a password using 50,000 rounds of HMAC-SHA256.

This should generate the same result as bip32.org.

WARNING: The security of this method has not been evaluated.

Parameters:

password (str) – The value to hash for generating the wallet. It may be a long string. Do not use a phrase from a book or song, as that will be guessed and is not secure. network: The network to use. Defaults to Bitcoin mainnet.

Returns:

A Wallet object.

Return type:

Wallet

classmethod from_master_seed(seed: bytes, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generate a new PrivateKey from a seed (byte string).

Parameters:
  • seed (bytes) – The bytes sequence to use to generate this wallet. The seed length should be at least 128 bits, no longer than 256 bits, and be divisible by 32.

  • network – The network to use. Defaults to Bitcoin mainnet.

See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format

classmethod from_mnemonic(mnemonic, passphrase='', network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generate a new PrivateKey from a secret key.

Parameters:
  • mnemonic – The key to use to generate this wallet.

  • passphrase – An optional passphrase for this mnemonic.

  • network – The network to use. Defaults to Bitcoin mainnet.

See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#Serialization_format

classmethod from_random(passphrase: str = '', strength: int = 128, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates a master key from system entropy.

Parameters:
  • strength (int) – Amount of entropy desired, in bits. This should be a multiple of 32 between 128 and 256. It directly affects the length of the mnemonic exported (each additional 32 bits adds an extra three words at the end).

  • passphrase (str) – An optional passphrase for the generated mnemonic string.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

The wallet object created.

Return type:

Wallet

get_child(child_number: int, is_prime: bool = False, as_private: bool = True)[source]

Derive a child key.

Parameters:
  • child_number (int) – The number of the child key to compute

  • is_prime (book) – If True, the child is calculated via private derivation. If False, then public derivation is used. If None, then it is figured out from the value of child_number.

  • as_private – If True, strips private key from the result. Defaults to False. If there is no private key present, this is ignored.

Child numbers should be less than 2,147,483,648 (2<<32).

This derivation is fully described at https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-functions

get_child_for_path(path: str)[source]

Get a child for a given path.

Rather than repeated calls to get_child, children can be found by a derivation path. Paths look like:

m/0/1’/10

Which is the same as

self.get_child(0).get_child(1, is_prime=True).get_child(10)

Or, in other words, the 10th publicly derived child of the 1st privately derived child of the 0th publicly derived child of master.

You can use either ‘ or p to denote a prime (that is, privately derived) child.

A child that has had its private key stripped can be requested by either passing a capital M or appending ‘.pub’ to the end of the path. These three paths all give the same child that has had its private key scrubbed:

M/0/1 m/0/1.pub M/0/1.pub

get_private_key_hex()[source]

Get the hex-encoded (I guess SEC1?) representation of the private key.

DO NOT share this private key with anyone.

get_public_key_hex(compressed=True) bytes[source]

Get the sec1 representation of the public key.

property identifier

Get the identifier for this node.

Extended keys can be identified by the Hash160 (RIPEMD160 after SHA256) of the public key’s key. This corresponds exactly to the data used in traditional Bitcoin addresses. It is not advised to represent this data in base58 format though, as it may be interpreted as an address that way (and wallet software is not required to accept payment to the chain key itself).

legacy_child()[source]

Equivalent to get_child(44, is_prime=True)

classmethod load_str_xkey(key: str, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Load an extended BIP32 key from a base58 or hex-encoded string.

Parameters:

key (str) – the extended key to generate an HDWallet from.

classmethod load_xkey(key: bytes, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Load an extended BIP32 key from a byte string.

Parameters:

key (bytes) – the extended key to generate an HDWallet from.

The key consists of

  • 4 byte version bytes (network key)

  • 1 byte depth:
    • 0x00 for master nodes,

    • 0x01 for level-1 descendants, ….

  • 4 byte fingerprint of the parent’s key (0x00000000 if master key)

  • 4 byte child number. This is the number i in x_i = x_{par}/i,

    with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key)

  • 32 bytes: the chain code

  • 33 bytes: the public key or private key data

    (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won’t even generate such data.)

property mnemonic_phrase

Returns the mnemonic phrase for this wallet, if specified.

WARNING: Never share your mnemonic phrase with anyone. They can use it to steal your assets.

classmethod new_random_wallet(user_entropy: bytes = None, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generate a new wallet using a randomly generated 512 bit seed.

Parameters:

user_entropy (bytes) – Optional user-supplied entropy which is combined combined with the random seed, to help counteract compromised PRNGs.

You are encouraged to add an optional user_entropy string to protect against a compromised CSPRNG. This will be combined with the output from the CSPRNG. Note that if you do supply this value it only adds additional entropy and will not be sufficient to recover the random wallet. If you’re even saving user_entropy at all, you’re doing it wrong.

public_copy()[source]

Clone this wallet and strip it of its private information.

segwit_child()[source]

Equivalent to get_child(84, is_prime=True)

bytes_int(byte_seq)[source]
hex_check_length(val, hex_len)[source]
hex_int(val)[source]
is_hex_string(string)[source]

Check if the string is only composed of hex characters.

long_to_hex(l, size)[source]

Encode a long value as a hex string, 0-padding to size.

Note that size is the size of the resulting hex string. So, for a 32Byte long size should be 64 (two hex characters per byte”.

zpywallet.utils.descriptors module

Utility functions related to output descriptors

descsum_check(s, require=True)[source]

Verify that the checksum is correct in a descriptor

descsum_create(s)[source]

Add a checksum to a descriptor without

descsum_create_only(s)[source]

Returns only the checksum of the descriptor

descsum_expand(s)[source]
descsum_polymod(symbols)[source]
drop_origins(s)[source]

Drop the key origins from a descriptor

zpywallet.utils.keccak module

The keccak module provides an implementation of the Keccak hash function, including various parameter presets such as Keccak224, Keccak256, Keccak384, and Keccak512. The module offers a hashlib-compatible interface for easy integration into existing codebases.

Keccak224(initial_input=None)
SHA3 parameter preset with a bitrate of 1088 bits, a capacity of 512 bits,

and an output length of 256 bits.

Keccak256(initial_input=None)
SHA3 parameter preset with a bitrate of 832 bits, a capacity of 768 bits,

and an output length of 384 bits.

Keccak384(initial_input=None)
SHA3 parameter preset with a bitrate of 576 bits, a capacity of 1024 bits,

and an output length of 512 bits.

Keccak512(initial_input=None)
class KeccakHash(bitrate_bits, capacity_bits, output_bits)[source]

Bases: object

The Keccak hash function, with a hashlib-compatible interface.

Represents a Keccak hash object with customizable bitrate, capacity, and output length. It provides methods for updating the hash state with input data and generating the final hash value.

copy()[source]

Creates a deep copy of the KeccakHash object, including the internal state.

digest()[source]

Retrieves the final hash value as a bytes object. The hash state is finalized before generating the digest.

Returns:

The final hash value as a bytes object.

Return type:

bytes

hexdigest()[source]

Retrieves the final hash value as a hex string. The hash state is finalized before generating the digest.

Returns:

The final hash value as a hex string.

Return type:

str

static preset(bitrate_bits, capacity_bits, output_bits)[source]

Returns a factory function for the given bitrate, sponge capacity and output length. The function accepts an optional initial input, ala hashlib.

update(s)[source]

Updates the hash state by absorbing the input data s. The input data can be either a string or bytes object.

Parameters:

s (str or bytes) – The input data to update the hash state with.

class KeccakSponge(bitrate, width, padfn, permfn)[source]

Bases: object

Implements the sponge construction of the Keccak algorithm. It absorbs input data, applies the Keccak-f permutation, and produces output data based on the specified bitrate and capacity.

absorb(s)[source]

Absorbs input strings or bytes as byte data.

absorb_block(bb)[source]

Absorbs a block of data of the bitrate length into the sponge’s internal state.

absorb_final()[source]

Used to apply padding to the remaining input data and absorb it into the sponge’s internal state.

copy()[source]

Creates a deep copy of the KeccakHash object, including the internal state.

squeeze(l)[source]

Generates squeezed output data of the specified length from the sponge’s internal state.

Parameters:

l (int) – Length of squeezed data to return.

squeeze_once()[source]

Generates a single block of squeezed output data from the sponge’s internal state.

class KeccakState(bitrate, b)[source]

Bases: object

A keccak state container.

Represents the internal state of the Keccak algorithm. It maintains the state as a 5x5 table of integers and provides methods for manipulating the state, converting between byte sequences and lanes, and formatting the state as a hexadecimal string.

H = 5
W = 5
absorb(bb)[source]

Mixes in the given bitrate-length string to the state.

static bytes2lane(bb)[source]

Converts a sequence of byte values to a lane.

static format(st)[source]

Formats the given state as hex, in natural byte order.

get_bytes()[source]

Convert whole state to a byte string.

static lane2bytes(s, w)[source]

Converts the lane s to a sequence of byte values, assuming a lane is w bits.

range_h = [0, 1, 2, 3, 4]
range_w = [0, 1, 2, 3, 4]
set_bytes(bb)[source]

Set whole state from byte string, which is assumed to be the correct length.

squeeze()[source]

Returns the bitrate-length prefix of the state to be output.

static zero()[source]

Returns an zero state table.

bits2bytes(x)[source]
eth_transaction_hash(address: str, nonce: int) str[source]

Constructs an Ethereum transaction hash from an address and a transaction number

f_round(state, a, rc)[source]
is_checksum_address(address)[source]

Checks if a hexadecimal Ethereum address is in checksum format.

This function verifies whether a given hexadecimal Ethereum address is in checksum format.

Parameters:

address (str) – The hexadecimal Ethereum address to be checked.

Returns:

True if the address is in checksum format, False otherwise.

Return type:

bool

Example

>>> is_checksum_address("0x123aBc")
True
keccak_f(state)[source]
multirate_padding(used_bytes, align_bytes)[source]
rol(value, left, bits)[source]
ror(value, right, bits)[source]
to_checksum_address(address)[source]

Converts a hexadecimal Ethereum address to its checksum format.

This function takes a hexadecimal Ethereum address as input and returns the checksum format of the address.

Parameters:

address (str) – The hexadecimal Ethereum address to be converted.

Returns:

The checksum format of the Ethereum address.

Return type:

str

Example

>>> to_checksum_address("0x123abc")
'0x123aBc'

zpywallet.utils.keys module

Code from: https://github.com/michailbrynard/ethereum-bip44-python

This submodule provides the PublicKey, PrivateKey, and Signature classes. It also provides HDPublicKey and HDPrivateKey classes for working with HD wallets.

class Point(x, y)

Bases: tuple

x

Alias for field number 0

y

Alias for field number 1

class PrivateKey(ckey, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Bases: object

Encapsulation of a private key on the secp256k1 curve.

This class provides capability to generate private keys, obtain the corresponding public key, sign messages and serialize/deserialize into a variety of formats.

Parameters:

k (int) – The private key.

Returns:

The object representing the private key.

Return type:

PrivateKey

base64_sign(message)[source]

Signs message using this private key. The message is encoded in UTF-8.

Avoid using any non-printable characters or whitespace (except for 0x20 space and 0x0a newline) inside the signature.

Parameters:

message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.

Returns:

The signature encoded in DER form, which is again encoded in Base64.

Return type:

str

der_sign(message)[source]

Signs message using this private key. The message is encoded in UTF-8.

Avoid using any non-printable characters or whitespace (except for 0x20 space and 0x0a newline) inside the signature.

Parameters:

message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.

Returns:

The signature encoded in DER form.

Return type:

bytes

classmethod from_brainwallet(password: bytes, salt=b'zpywallet', network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generate a new key from a master password, and an optional salt.

This password is hashed via a single round of sha256 and is highly breakable, but it’s the standard brainwallet approach.

It is highly recommended to salt a password before hashing it to protect it from rainbow table attacks. You should not need to change it from the default value, though. WARNING: Either remember the salt, and add it after the end of the password, or always use this method to regenerate the brainwallet so you don’t lose your private key.

Parameters:
  • password (str) – The password to generate a private key from.

  • salt (str) – The salt to use. Unless you know what you’re doing, leave this as the default value.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

The object representing the private key.

Return type:

PrivateKey

static from_bytes(b, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates PrivateKey from the underlying bytes.

Parameters:
  • b (bytes) – A byte stream containing a 256-bit (32-byte) integer.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

A PrivateKey object and the remainder of the bytes.

Return type:

tuple(PrivateKey, bytes)

static from_hex(h, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates PrivateKey from a hex-encoded string.

Parameters:
  • h (str) – A hex-encoded string containing a 256-bit (32-byte) integer.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

A PrivateKey object.

Return type:

PrivateKey

static from_int(i, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Initializes a private key from an integer.

Parameters:
  • i (int) – Integer that is the private key.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

The object representing the private key.

Return type:

PrivateKey

static from_random(network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Initializes a private key from a random integer.

Parameters:

network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

The object representing the private key.

Return type:

PrivateKey

classmethod from_wif(wif: str, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Import a key in WIF format.

WIF is Wallet Import Format. It is a base58 encoded checksummed key. See https://en.bitcoin.it/wiki/Wallet_import_format for a full description.

This supports compressed WIFs - see this for an explanation: https://bitcoin.stackexchange.com/q/7299/112589 (specifically http://bitcoin.stackexchange.com/a/7958)

Parameters:
  • wif (str) – A base58-encoded string representing a private key.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

An object representing a private key.

Return type:

PrivateKey

get_extended_key(network)[source]

Get the extended key.

Extended keys contain the network bytes and the public or private key.

property network

Returns the network for this private key.

property public_key

Returns the public key associated with this private key.

Returns:

The PublicKey object that corresponds to this private key.

Return type:

PublicKey

rfc2440_sign(message)[source]

Signs message using this private key. The message is encoded in UTF-8.

Avoid using any non-printable characters or whitespace (except for 0x20 space and 0x0a newline) inside the signature.

This function returns a signature of this form:

—–BEGIN {{network.NAME.upper()}} SIGNED MESSAGE—– Message —–BEGIN {{network.NAME.upper()}} SIGNATURE—– Address Signature —–END {{network.NAME.upper()}} SIGNATURE—–

The message is printed as a UTF-8 string, whereas the address used is the default address for the mainnet. Address signatures are treated as if they are legacy P2PKH Base58-encoded addresses, for the purpose of the Bitcoin message signing algorithm, which was invented before any of the other address types existed. This is forced by the coincurve dependency which we use to calculate the signature. On the upside, coincurve calculates the signatures in an extremely robust and secure way.

Parameters:

message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.

Returns:

A text string in the form of RFC2440, in a similar form to Electrum.

Return type:

str

rsz_sign(message)[source]

Signs message using this private key. The message is encoded in UTF-8.

Avoid using any non-printable characters or whitespace (except for 0x20 space and 0x0a newline) inside the signature. Note that excessive leading or trailing whitespace will be trimmed from the message before signed or verified.

Parameters:

message (bytes) – The message to be signed. If a string is provided it is assumed the encoding is ‘ascii’ and converted to bytes. If this is not the case, it is up to the caller to convert the string to bytes appropriately and pass in the bytes.

Returns:

A tuple of R, S, and Z (message hash) values.

to_hex() str[source]

Returns the private key in hexadecimal form.

to_wif(compressed=False)[source]

Export a key to WIF.

Parameters:

compressed (bool) – False if you want a standard WIF export (the most standard option). True if you want the compressed form (Note that not all clients will accept this form). Defaults to None, which in turn uses the self.compressed attribute.

Returns:

THe WIF string

Return type:

str

See https://en.bitcoin.it/wiki/Wallet_import_format for a full description.

class PublicKey(ckey, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>, hashonly=False)[source]

Bases: object

Encapsulation of a Bitcoin ECDSA public key.

This class provides a high-level API to using an ECDSA public key, specifically for Bitcoin (secp256k1) purposes.

Parameters:
  • x (int) – The x component of the public key point.

  • y (int) – The y component of the public key point.

Returns:

The object representing the public key.

Return type:

PublicKey

address(compressed=True, witness_version=0)[source]

Returns the address genereated according to the first supported address format by the network.

classmethod address_script(address, network)[source]

Returns the appropriate script depending on the address value. Only applicable to Bitcoin-like blockchains.

Parameters:
  • address (string) –

  • network (string) –

Returns:

the address script.

Return type:

bytes

base58_address(compressed=True)[source]

Address property that returns a base58 encoding of the public key.

Parameters:

compressed (bool) – Whether or not the compressed key should be used.

Returns:

Address encoded in Base58Check.

Return type:

bytes

base64_verify(message, signature, address)[source]

Verifies a signed message in Base64 format.

Parameters:
  • message (bytes or str) – The message that the signature corresponds to.

  • signature (str) – A string Base64 encoded signature.

  • address (str) – Base58Check encoded address.

Returns:

True if the signature is authentic, False otherwise.

Return type:

bool

bech32_address(compressed=True, witness_version=0)[source]

Address property that returns a bech32 encoding of the public key.

Parameters:
  • compressed (bool) – Whether or not the compressed key should be used. It is recommended to leave this value as true - Uncompressed segwit addresses are non-standard on most networks, preventing them from being broadcasted normally, and should be avoided.

  • witness_version (int) – Witness version to use for theBech32 address. Allowed values are 0 (segwit) and 1 (Taproot).

Returns:

Address encoded in Bech32.

Return type:

bytes

der_verify(message, signature, address)[source]

Verifies a signed message.

Parameters:
  • message (bytes or str) – The message that the signature corresponds to.

  • signature (bytes) – A bytes DER signature.

  • address (str) – Base58Check encoded address.

Returns:

True if the signature is authentic, False otherwise.

Return type:

bool

classmethod from_address(address, network)[source]

Creates a public key hash from an address. Only applicable to Bitcoin-like blockchains.

Parameters:
  • address (string) –

  • network (string) –

static from_bytes(key_bytes, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates a public key object from a byte string.

The byte stream must be of the SEC variety (http://www.secg.org/): beginning with a single byte telling what key representation follows. A full, uncompressed key is represented by: 0x04 followed by 64 bytes containing the x and y components of the point. For compressed keys with an even y component, 0x02 is followed by 32 bytes containing the x component. For compressed keys with an odd y component, 0x03 is followed by 32 bytes containing the x component.

Parameters:
  • key_bytes (bytes) – A byte stream that conforms to the above.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

A PublicKey object.

Return type:

PublicKey

static from_hex(h, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates a public key object from a hex-encoded string.

See from_bytes() for requirements of the hex string.

Parameters:
  • h (str) – A hex-encoded string.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

A PublicKey object.

Return type:

PublicKey

static from_point(p, network=<class 'zpywallet.network.BitcoinSegwitMainNet'>)[source]

Generates a public key object from any object containing x, y coordinates.

Parameters:
  • p (Point) – An object containing a two-dimensional, affine representation of a point on the secp256k1 curve.

  • network – The network to use for things like defining key key paths and supported address formats. Defaults to Bitcoin mainnet.

Returns:

A PublicKey object.

Return type:

PublicKey

hash160(compressed=True)[source]

Return the RIPEMD-160 hash of the SHA-256 hash of the public key. Only defined if one of base58 or bech32 are supported by the network.

Parameters:

compressed (bool) – Whether or not the compressed key should be used.

Returns:

RIPEMD-160 byte string.

Return type:

bytes

hex_address()[source]

Address property that returns a hexadecimal encoding of the public key.

keccak256()[source]

Return the Keccak-256 hash of the SHA-256 hash of the public key. Only defined if hex addresses are supported by the network.

Returns:

Keccak-256 byte string.

Return type:

bytes

property network

Returns the network for this public key.

p2pk_script(compressed=True)[source]

Return the P2PK script bytes contianing the public key’s hash. Undefined for EVM blockchains.

Parameters:

compressed (bool) – Whether or not the compressed key should be used.

Returns:

A P2PK script.

Return type:

bytes

p2pkh_script(compressed=True)[source]

Return the P2PKH script bytes contianing the public key’s hash. Undefined for EVM blockchains.

Parameters:

compressed (bool) – Whether or not the compressed key should be used.

Returns:

A P2PKH script.

Return type:

bytes

p2sh_script()[source]

Return the P2SH script bytes contianing the script hash. Only applicable to Bitcoin-like blockchains

Parameters:

script_hash (bytes) – The script hash to use.

Returns:

A P2SH script.

Return type:

bytes

p2wpkh_script(compressed=True)[source]

Return the P2WPKH script bytes contianing the public key’s hash. Undefined by EVM blockchains.

Parameters:

compressed (bool) – Whether or not the compressed key should be used. DO NOT change this value or you might make a non-standard transaction.

Returns:

A P2WPKH script.

Return type:

bytes

p2wsh_script()[source]

Return the P2WSH script bytes contianing the script hash. Only applicable to Bitcoin-like blockchains.

Returns:

A P2WSH script.

Return type:

bytes

rfc2440_verify(text)[source]

Verifies a signed message in the RFC2440 format.

Parameters:

text (str) – The verfication message.

Returns:

True if the signature is authentic, False otherwise.

Return type:

bool

rsz_verify(message, r, s, z, address)[source]

Verifies a signed message.

Parameters:
  • message (bytes or str) – The message that the signature corresponds to.

  • r (bytes) – The signature’s R value.

  • s (bytes) – The signature’s S value.

  • z (bytes) – The signature’s Z value.

  • address (str) – Base58Check encoded address.

Returns:

True if the signature is authentic, False otherwise.

Return type:

bool

script()[source]

Returns the appropriate script depending on the network. Only applicable to Bitcoin-like blockchains.

Parameters:
  • address (string) –

  • network (string) –

Returns:

the address script.

Return type:

bytes

to_bytes(compressed=True) bytes[source]

Converts the public key into bytes.

Parameters:

compressed (bool) – Whether to return the compressed form. Default is true.

Returns:

A byte string.

Return type:

b (bytes)

to_hex(compressed=True) str[source]

Converts the public key into a hex string.

Parameters:

compressed (bool) – Whether to return the compressed form. Default is true.

Returns:

A hexadecimal string.

Return type:

b (str)

to_point()[source]
decode_der_signature(signature)[source]

Returns the R and S values of a DER signature.

encode_der_signature(r, s)[source]
class secp256k1[source]

Bases: object

Elliptic curve used in Bitcoin, Ethereum, and their derivatives.

A = 0
B = 7
G = Point(x=55066263022277343669578718895168534326250603453777594175500187360389116729240, y=32670510020758816978083085130507043184471273380659243275938904335757337482424)
H = 1
N = 115792089237316195423570985008687907852837564279074904382605163141518161494337
P = 115792089237316195423570985008687907853269984665640564039457584007908834671663
gx = 55066263022277343669578718895168534326250603453777594175500187360389116729240
gy = 32670510020758816978083085130507043184471273380659243275938904335757337482424

zpywallet.utils.ripemd160 module

class RMDContext[source]

Bases: object

f0(x, y, z)[source]
f1(x, y, z)[source]
f2(x, y, z)[source]
f3(x, y, z)[source]
f4(x, y, z)[source]
r(a, b, c, d, e, fj, kj, sj, rj, x)[source]
ripemd160(b: bytes) bytes[source]

Calculates the RIPEMD160 hash of binary data

rmd160_final(ctx)[source]
rmd160_transform(state, block)[source]
rmd160_update(ctx, inp, inplen)[source]
rol(n, x)[source]

Module contents