candidateblock_bitcoin_library package
Submodules
- candidateblock_bitcoin_library.base58 module
- candidateblock_bitcoin_library.btc_hash module
- candidateblock_bitcoin_library.hd_wallet module
- candidateblock_bitcoin_library.keys module
- candidateblock_bitcoin_library.mnem_bip39_word_list module
- candidateblock_bitcoin_library.mnemonic module
- candidateblock_bitcoin_library.prefix module
PrefixPrefix.BIP_32_EXTENDED_PRIVATE_KEYPrefix.BIP_32_EXTENDED_PUBLIC_KEYPrefix.PAY_TO_PUBKEY_HASHPrefix.PAY_TO_SCRIPT_HASHPrefix.PRIVATE_KEY_WIFPrefix.TESTNET_BIP_32_EXTENDED_PRIVATE_KEYPrefix.TESTNET_BIP_32_EXTENDED_PUBLIC_KEYPrefix.TESTNET_PAY_TO_PUBKEY_HASHPrefix.TESTNET_PAY_TO_SCRIPT_HASHPrefix.TESTNET_PRIVATE_KEY_WIF
- candidateblock_bitcoin_library.transaction module
- candidateblock_bitcoin_library.version module
Module contents
Candidate Block Bitcoin Library (cbl), easy to learn, fast to code
cbl is a Python module aims to provide simple and efficient solutions to learning and using the Bitcoin protocol.
See https://candidateblock-bitcoin-library.readthedocs.io for complete documentation.
- class candidateblock_bitcoin_library.Base58
Bases:
object- classmethod check_decode(b58: str = '') tuple
_summary_
- Parameters:
b58 (str) – Base58Check encoded string
- Raises:
ValueError – Checksum not valid
- Returns:
A tuple containing, respectively, a bytes (address prefix) and a bytes (payload) and a bytes (checksum)
- classmethod check_encode(payload: bytes = b'') str
Encode a hex string using Base58Check
Base58Check 1. Takes input bytes payload 2. Computes the double-SHA256 checksum (4-Byte) and appends to end 3. Base58 encodes result
- Parameters:
payload (bytes) – value in bytes
- Returns:
Base58Check encoded paload & (4-Byte) checksum
- Return type:
str
- classmethod decode(b58: str = '') bytes
Decode the Base58 encoded string
Check base58 string is valid, remove padding. A ValueError is raised if base58 has invalid chars Decode Base58 into bytes, even char pad with ‘0’ and with any leading ‘00’
- Parameters:
b58 (str) – Base58 encoded string
- Raises:
ValueError – Input string can not be empty
ValueError – string argument should contain only Base58 characters
- Returns:
value in bytes
- Return type:
bytes
- classmethod encode(input: bytes = b'') str
Encode bytes into a string using Base58
Take the input bytes and convert to Base58 using the Bitcoin alphabet, including leading 0x00’s coverted to ‘1’s
- Parameters:
input (bytes) – value in bytes
- Returns:
Base58 encoded
- Return type:
str
- class candidateblock_bitcoin_library.Hashes
Bases:
object- static double_sha256(value: bytes) tuple[bytes, bytes]
Compute the ‘double-SHA256’ and checksum.
Input bytes string is coverted to byte array then hashed with Secure Hash Algorithm (SHA), specifically the 256-Bit (32-byte) version, twice resutling in 256-Bit (32-byte) double hash. Checksum is the first 32-Bit (4-byte) of result
- Parameters:
value (bytes) – bytes to be double hashed
- Returns:
(double-SHA256 32-Bytes, check_sum 4-Bytes)
- Return type:
Tuple
- static hash160(value: bytes) bytes
Compute the ‘Double Hash’ or ‘HASH160’.
Input hex string is coverted to byte array then 1. Hashed with SHA256 resutling in 256-Bit (32-byte) hash 2. The result is hashed with RACE Integrity Primitives Evaluation Message Digest (RIPEMD) specifically the 160-bit version, (RIPEMD160) resulting in 160-bit (20-Byte)
- Parameters:
value (bytes) – bytes to be hash160
- Returns:
hash160 160-Bits, 20-Bytes
- Return type:
bytes
- static hmac_sha512(key: bytes, msg: bytes) bytes
Compute the HMAC-SHA512 HMAC (Keyed-Hashing for Message Authentication)
Input hex string is coverted to byte array then 1. Hashed with SHA256 resutling in 256-Bit (32-byte) hash 2. The result is hashed with RACE Integrity Primitives Evaluation Message Digest (RIPEMD) specifically the 160-bit version, (RIPEMD160) resulting in 160-bit (20-Byte)
- Parameters:
key (bytes) – bytes to be hash
msg (bytes) – bytes to be hash
- Returns:
hash512 512-Bits, 64-Bytes
- Return type:
bytes
- static pbkdf2_hmac(password: bytes, salt: bytes) bytes
The PBKDF2 function is used to ‘stretch’ passwords with 2048 rounds. The iteration count is set to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the result is 512 bits (64 bytes).
- Parameters:
password (bytes) – bytes to be pbkdf2_hmac streched
salt (bytes) – bytes to be pbkdf2_hmac streched
- Returns:
512-Bits, 64-Bytes
- Return type:
bytes
- static sha256(value: bytes) bytes
Compute the ‘SHA256’
Input bytes string is coverted to byte array then hashed with Secure Hash Algorithm (SHA), specifically the 256-Bit (32-byte) version,
- Parameters:
value (bytes) – bytes to be hashed
- Returns:
SHA256 256-Bits, 32-Bytes
- Return type:
bytes
- class candidateblock_bitcoin_library.HdWallet
Bases:
objectHierarchical Deterministic Wallet Class
The word “wallet” refers to the data structure used to store and manage a users keys. In a sense the “wallet” is just a keychain. We will only implement industry-standard-based hierarchical deterministic (HD BIP-32/BIP-44) wallet with a mnemonic seed (BIP-39) for backup.
- HARDEND = 2147483648
- classmethod child_key_derivation(parent_key: bytes, parent_chaincode: bytes, index: int, is_private: bool)
- static encode(key: bytes = b'', chain_code: bytes = b'', parent_key: bytes = b'', depth: int = 0, child: int = 0, is_master: bool = False, is_private: bool = True, is_mainnet: bool = True) str
Extended public and private keys are serialized as follows:
4 byte: version bytes (mainnet: 0x0488B21E public, 0x0488ADE4 private; testnet: 0x043587CF public, 0x04358394 private) 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 derived keys, …. 4 bytes: the fingerprint of the parent’s key (0x00000000 if master key) 4 bytes: child number. This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key) 32 bytes: the chain code 33 bytes: the public key or private key data (serP(K) for public keys, 0x00 || ser256(k) for private keys) This 78 byte structure can be encoded like other Bitcoin data in Base58, by first adding 32 checksum bits (derived from the double SHA-256 checksum), and then converting to the Base58 representation. This results in a Base58-encoded string of up to 112 characters. Because of the choice of the version bytes, the Base58 representation will start with “xprv” or “xpub” on mainnet, “tprv” or “tpub” on testnet.
- Parameters:
key (bytes) – Private 256-bits (32-Bytes) or COMPRESSED Private key 264-bits (33-Bytes)
chain_code (bytes) – Private or Public Chain Code 256-bits (32-Bytes)
parent_key (bytes) – Parent Key, Private 256-bits (32-Bytes) or COMPRESSED Private key 264-bits (33-Bytes), or nohting if master node
depth (int) – 0 for master nodes, 1 for level-1 derived keys, ….
child (int) – child number. This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key)
is_master (bool) – Are we encoding (serializing) the master / root key
is_private (bool) – Are we encoding (serializing) as Public or Private key
is_mainnet (bool) – Are we encoding for Mainnet or Testnet
- Returns:
Base58Check encoded
- Return type:
str
- static master_key_generation(seed: bytes = b'')
- classmethod parse_path(path: str = '') List[int]
Parse Path BIP-32 HD wallet path parse and clean hardended char ‘ to H and all upper case
- Parameters:
path (str) – in form m/84’/0’/1’ or m/84h/0h/1h
- Returns:
Array of integers with two dimensions 1. depth, 2. index + hardened [0x800000] if applicable
- Return type:
List[int]
- class candidateblock_bitcoin_library.Keys
Bases:
objectBitcoin Private and Public Key Class
Bitcoin has a Private Key (that should remain secret) and a Public Key that can be shared. A Private key is just a random 256-Bit (32-byte) number (with some size limitation due to discrete Elliptic Curve). A Public key is generated from a one way cryptographic function called secp256k1 which uses an Elliptic Curve.
- classmethod btc_address_p2pkh(pub_key: bytes = b'', is_mainnet: bool = True) str
Convert the Public Key to a Pay To PubKey Hash (P2PKH) Bitcoin address
The Public Key can be compressed (33-Bytes) or uncompressed (32-Bytes) it is hashed via HASH160 resulting in 160-Bits, 20-Bytes (a reduction) The result is prefixed with PayToPubKeyHash 0x00 and Base58Check encoded
- Parameters:
pub_key (bytes) – Public Key 32/33-bytes, 256/264-bits
- Returns:
P2PKH Bitcoin address Base58Check encoded
- Return type:
str
- classmethod generate_priv_key() bytes
Generate Private Key
Generate a 256-Bit Private Key by using a cryptographically secure random number and checking valid over Elliptic Curve finite field
- Returns:
Raw 256-bit (32-byte) Private Key = Random Number
- Return type:
bytes
- classmethod generate_pub_key(priv_key: bytes = b'', is_compressed: bool = True) bytes
Calculate Public key from the Private Key
The public key is calculated from the private key using elliptic curve multiplication, which is irreversible: K = k * G, where k is the private key, G is a constant point called the generator point, and K is the resulting public key.
The secp256k1 curve is defined by the following function, y^2 = (X^3 + 7) over Fp or Y^2 mod p = (x^3 +7) mod p The mod p (modulo prime number p) indicates that this curve is over a finite field of prime order p, where p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1, a very large prime number.
“Uncompressed” Public Key Format “x04” prefix (1-Byte) -> “Uncompressed” + X Coordinate as 256-Bit (32-Byte) + Y Coordinate as 256-Bit (32-Byte) result string = 520-Bit (65-Byte)
“Compressed” Public Key Format “Compressed” means store x coordinate value and y coordinate sign “x02” prefix (1-Byte) if y is even “x03” prefix (1-Byte) if y is odd Even or Odd Hex prefix -> “Compressed” + X Coordinate as 256-Bit (32-Byte) result string = 264-Bit (33) This results in nearly a 50% size reduction compared to the “Uncompressed” Private Key size of 520-Bit (65-Bytes) 264 / 520 = 50.8%
- Parameters:
priv_key (bytes) – private key 32-bytes, 256-bits
is_compressed (bool) – private key format
- Returns:
Public key 32-bytes, 256-bits
- Return type:
bytes
- classmethod is_priv_key_valid(priv_key: bytes) bool
Verify if Private Key Valid
Check if number (containted in input bytes) is within the range limits of the Elliptic Curve which is defined over a finite field of prime order instead of over the real numbers
- Parameters:
priv_key (bytes) – private key 32-bytes, 256-bits
- Returns:
private key is valid
- Return type:
bool
- classmethod priv_key_wif_decode(wif_b58: str = '') tuple
Private Key ‘Wallet Import Format’ (Base58 Check) decoded to private key, compressed, network
Decode Private key WIF back to constituent parts. Verify length, Base58 Check checksum and Version Byte Prefix for Mainnet or Testnet
- Parameters:
wif_b58 (str) – Base58 encoded WIF Private Key
- Returns:
A tuple containing, respectively, a bytes (private key 32-bytes, 256-bits) and a bool (Should this private key be used to generate compressed public keys) and a bool (Network for the private key to be used on [Mainnet or Testnet]).
- classmethod priv_key_wif_encode(priv_key: bytes = b'', is_compressed: bool = True, is_mainnet: bool = True) str
Private Key encoded to ‘Wallet Import Format’ (Base58 Check)
A WIF private key is a standard private key, but with a few added extras: 1. Version Byte prefix - Indicates which network the private key is to be used on. 2. Compression Byte suffix (optional) 3. Checksum
- Parameters:
priv_key (bytes) – private key 32-bytes, 256-bits
is_compressed (bool) – Should this private key be used to generate compressed public keys
is_mainnet (bool) – Network for the private key to be used on (Mainnet or Testnet)
- Returns:
Base58 Check encoded WIF Private Key
- Return type:
str
- class candidateblock_bitcoin_library.Mnemonic
Bases:
objectMnemonic Class
A mnemonic sentence (“mnemonic code”, “seed phrase”, “seed words”) is a way of representing a large randomly-generated number as a sequence of words, making it easier for humans to store BIP-39 defines the method
- classmethod decode(bip39_mnemonic: str) bytes
For each word in the bip39 mnemonic sentence, convert to its 11-Bit numberic value and logic shift the bits in to the correct integer place. Verify the checksum is valid.
- Parameters:
bip39_mnemonic (str) – A string storing Mnemonic 12-24 words
- Returns:
entropy (orginal entropy, a cryptographically secure random number)
- Return type:
bytes
- classmethod encode(entropy: bytes, words: int) str
Mnemonic words are generated automatically by the wallet using the standardized process defined in BIP-39.
Input a random sequence (entropy) of 128 to 256 bits. Create a checksum of the random sequence by taking the first (entropy-length/32) bits of its SHA256 hash. Add the checksum to the end of the random sequence. Split the result into 11-bit length segments. Map each 11-bit value to a word from the predefined dictionary of 2048 words. The mnemonic code is the sequence of words.
- Parameters:
entropy (bytes) – entropy (a cryptographically secure random number)
words (int) – Number of words only valid values 12, 15, 18, 21 or 24
- Returns:
A string storing Mnemonic 12-24 words
- Return type:
str
- classmethod generate_mnemonic(words: int) str
Mnemonic words are generated automatically by the wallet using the standardized process defined in BIP-39.
Create a random sequence (entropy) of 128 to 256 bits. Generate the mnemonic sentence (a sequence of 12-24 words).
- Parameters:
words (int) – Number of words only valid values 12, 15, 18, 21 or 24
- Returns:
A string storing Mnemonic 12-24 words
- Return type:
str
- classmethod mnemonic_to_seed(mnemonic_sentence: str, passphrase: str = '') bytes
Mnemonic To Seed
To create a binary seed from the mnemonic, we use the PBKDF2 function with a mnemonic sentence (in UTF-8 NFKD) used as the password and the string “mnemonic” + passphrase (again in UTF-8 NFKD) used as the salt. The iteration count is set to 2048 and HMAC-SHA512 is used as the pseudo-random function. The length of the derived key is 512 bits (64 bytes).
- Parameters:
mnemonic_sentence (str) – A string storing Mnemonic 12-24 words
- Returns:
seed 512 bits (64 bytes).
- Return type:
bytes
- class candidateblock_bitcoin_library.Prefix
Bases:
objectbytes values of the address prefixes
- Parameters:
Enum (_type_) – bytes values of prefix
- BIP_32_EXTENDED_PRIVATE_KEY = b'\x04\x88\xad\xe4'
- BIP_32_EXTENDED_PUBLIC_KEY = b'\x04\x88\xb2\x1e'
- PAY_TO_PUBKEY_HASH = b'\x00'
- PAY_TO_SCRIPT_HASH = b'\x05'
- PRIVATE_KEY_WIF = b'\x80'
- TESTNET_BIP_32_EXTENDED_PRIVATE_KEY = b'\x045\x83\x94'
- TESTNET_BIP_32_EXTENDED_PUBLIC_KEY = b'\x045\x87\xcf'
- TESTNET_PAY_TO_PUBKEY_HASH = b'o'
- TESTNET_PAY_TO_SCRIPT_HASH = b'\xc4'
- TESTNET_PRIVATE_KEY_WIF = b'\xef'