btclib package

Subpackages

Submodules

btclib.alias module

Aliases

mypy aliases, documenting also coding imput conventions.

btclib.amount module

Proper handling of monetary amounts.

Monetary amounts are expressed as number of satoshis in the Bitcoin Core client and this python library (e.g. 1 BTC is 100,000,000). Instead, monetary values are express as double-precision floats in the JSON API (e.g. 1 BTC is 1.00000000).

One needs to be aware of possible floating-point conversion issues: as example, with floats 1.1 + 2.2 != 3.3; algebra with bitcoin amounts should always be performed using satoshis.

The provided functions properly handle conversion between satoshi amounts and float monetary values.

btclib.amount.float_from_sat(amount: int) → float

Return the float monetary value equivalent of a satoshi amount.

btclib.amount.sat_from_float(value: float) → int

Return the satoshi amount equivalent of a float monetary value.

btclib.base58 module

Base58 encoding and decoding functions.

Binary-to-text encoding schemes are used to transport binary data across channels designed to deal with textual data. In Bitcoin they are mostly used to represent large integers as alphanumeric text.

Base58 is similar to Base64, which uses 10 digits, 26 lowercase characters, 26 uppercase characters, ‘+’ (plus sign), and ‘/’ (forward slash). Base58 omits the similar-looking letters 0 (zero), O (capital o), I (capital i), and l (lower case L) to avoid ambiguity when printed; moreover, it removes ‘+’ and ‘/’ so that a double-click does select the whole string.

Base58Check is the checksummed version of Base58, using hash256(v)[:4] as checksum suffix before encoding; at the decoding stage the checksum validity ensure data integrity.

This implementation of Base58 and Base58Check is originally from https://github.com/keis/base58, with the following modifications:

  • type annotated python3
  • using native python3 int.from_bytes() and i.to_bytes()
  • added optional check on output size for b58decode()
  • interface mimics the native python3 base64 interface, i.e. it supports encoding bytes-like objects to ASCII bytes, and decoding ASCII bytes-like objects or ASCII strings to bytes.
btclib.base58.b58decode(v: Union[bytes, str], out_size: Optional[int] = None) → bytes

Decode a Base58Check encoded bytes-like object or ASCII string.

Optionally, it also ensures required output size.

btclib.base58.b58encode(v: Union[bytes, str], in_size: Optional[int] = None) → bytes

Encode a bytes-like object using Base58Check.

btclib.base58address module

btclib.base58wif module

btclib.bech32 module

Bech32 encoding and decoding functions.

BIP173: https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki

This implementation of bech32 is originally from https://github.com/sipa/bech32/tree/master/ref/python, with the following modifications:

  • splitted the original segwit_addr.py file in bech32.py and segwitaddress.py
  • type annotated python3
  • avoided returning (None, None), throwing Exceptions instead
  • removed the 90-chars limit for bech32 string, enforced by segwitaddr instead
  • detailed error messages
  • interface mimics the native python3 base64 interface, i.e. it supports encoding bytes-like objects to ASCII bytes, and decoding ASCII bytes-like objects or ASCII strings to bytes.
btclib.bech32.b32decode(bech: Union[bytes, str]) → Tuple[str, List[int]]

Validate a bech32 string, and determine HRP and data.

btclib.bech32.b32encode(hrp: str, data: List[int]) → bytes

Compute a bech32 string given HRP and data values.

btclib.bech32address module

btclib.bip32 module

btclib.bip39 module

BIP39 entropy / mnemonic / seed functions.

https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki.

Checksummed entropy (ENT+CS) is converted from/to mnemonic.

  • bits per word = bpw = 11
  • ENT = raw entropy
  • CS = checksum = ENT / 32
  • MS = words in the mnemonic sentence = (ENT+CS) / bpw
ENT CS ENT+CS MS
128 4 132 12
160 5 165 15
192 6 198 18
224 7 231 21
256 8 264 24
btclib.bip39.entropy_from_mnemonic(mnemonic: str, lang: str = 'en') → str

Return the entropy from the BIP39 checksummed mnemonic sentence.

btclib.bip39.mnemonic_from_entropy(entropy: Union[str, int, bytes], lang: str = 'en') → str

Convert input entropy to BIP39 checksummed mnemonic sentence.

Input entropy can be expressed as binary 0/1 string, bytes-like, or integer; it must be 128, 160, 192, 224, or 256 bits.

In the case of binary 0/1 string and bytes-like, leading zeros are not considered redundant padding.

In the case of integer, where leading zeros cannot be represented, if the bit length is not an allowed value, then the binary 0/1 string is padded with leading zeros up to the next allowed bit length; if the integer bit length is longer than the maximum length, then only the leftmost bits are retained.

btclib.bip39.seed_from_mnemonic(mnemonic: str, passphrase: str, verify_checksum=True) → bytes

Return the seed from the provided BIP39 mnemonic sentence.

The mnemonic checksum verification can be skipped if needed.

btclib.blocks module

btclib.bms module

btclib.borromean module

btclib.borromean.assert_as_valid(msg: bytes, e0: bytes, s: Dict[int, List[int]], pubk_rings: Dict[int, List[Tuple[int, int]]]) → bool
btclib.borromean.sign(msg: Union[bytes, str], ks: Sequence[int], sign_key_idx: Sequence[int], sign_keys: Sequence[int], pubk_rings: Dict[int, List[Tuple[int, int]]]) → Tuple[bytes, Dict[int, List[int]]]

Borromean ring signature - signing algorithm

https://github.com/ElementsProject/borromean-signatures-writeup https://github.com/Blockstream/borromean_paper/blob/master/borromean_draft_0.01_9ade1e49.pdf

inputs: - msg: message to be signed (bytes) - sign_key_idx: list of indexes representing each signing key per ring - sign_keys: list containing the whole set of signing keys (one per ring) - pubk_rings: dictionary of sequences representing single rings of pubkeys

btclib.borromean.verify(msg: Union[bytes, str], e0: bytes, s: Dict[int, List[int]], pubk_rings: Dict[int, List[Tuple[int, int]]]) → bool

Borromean ring signature - verification algorithm

inputs:

  • msg: message to be signed (bytes)
  • e0: pinned e-value needed to start the verification algorithm
  • s: s-values, both real (one per ring) and forged
  • pubk_rings: dictionary of sequences representing single rings of pubkeys

btclib.curve module

Elliptic curve classes and functions.

class btclib.curve.Curve(p: Union[bytes, str, int], a: Union[bytes, str, int], b: Union[bytes, str, int], G: Tuple[int, int], n: Union[bytes, str, int], h: int, weakness_check: bool = True, name: Optional[str] = None)

Bases: btclib.curve.CurveSubGroup

Prime order subgroup of the points of an elliptic curve over Fp.

class btclib.curve.CurveSubGroup(p: Union[bytes, str, int], a: Union[bytes, str, int], b: Union[bytes, str, int], G: Tuple[int, int])

Bases: btclib.curvegroup.CurveGroup

Subgroup of the points of an elliptic curve over Fp generated by G.

btclib.curve.double_mult(u: Union[bytes, str, int], H: Tuple[int, int], v: Union[bytes, str, int], Q: Tuple[int, int], ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) → Tuple[int, int]

Double scalar multiplication (u*H + v*Q).

btclib.curve.mult(m: Union[bytes, str, int], Q: Tuple[int, int] = None, ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) → Tuple[int, int]

Elliptic curve scalar multiplication.

btclib.curve.multi_mult(scalars: Sequence[Union[bytes, str, int]], points: Sequence[Tuple[int, int]], ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) → Tuple[int, int]

Return the multi scalar multiplication u1*Q1 + … + un*Qn.

Use Bos-Coster’s algorithm for efficient computation.

btclib.curvegroup module

Elliptic CurveGroup class and functions.

Note that CurveGroup does not have to be a cyclic subgroup. For the cyclic subgroup class CurveSubGroup and the cyclic subgroup class of prime order Curve, see the btclib.curve module.

class btclib.curvegroup.CurveGroup(p: Union[bytes, str, int], a: Union[bytes, str, int], b: Union[bytes, str, int])

Bases: object

Finite group of the points of an elliptic curve over Fp.

The elliptic curve is the set of points (x, y) that are solutions to a Weierstrass equation y^2 = x^3 + a*x + b, with x, y, a, and b in Fp (p being a prime), together with a point at infinity INF. The constants a, b must satisfy the relationship 4 a^3 + 27 b^2 ≠ 0.

The group is defined by the point addition group law.

add(Q1: Tuple[int, int], Q2: Tuple[int, int]) → Tuple[int, int]

Return the sum of two points.

The input points must be on the curve.

is_on_curve(Q: Tuple[int, int]) → bool

Return True if the point is on the curve.

negate(Q: Tuple[int, int]) → Tuple[int, int]

Return the opposite point.

The input point is not checked to be on the curve.

negate_jac(Q: Tuple[int, int, int]) → Tuple[int, int, int]

Return the opposite Jacobian point.

The input point is not checked to be on the curve.

require_on_curve(Q: Tuple[int, int]) → None

Require the input curve Point to be on the curve.

An Error is raised if not.

y(x: int) → int

Return the y coordinate from x, as in (x, y).

y_even(x: int) → int

Return the odd/even affine y-coordinate associated to x.

y_low(x: int) → int

Return the low/high affine y-coordinate associated to x.

y_quadratic_residue(x: int) → int

Return the quadratic residue affine y-coordinate.

btclib.curvegroup.cached_multiples
btclib.curvegroup.cached_multiples_fixwind

Made to precompute values for _mult_fixed_window_cached. Do not use it for other functions. Made to be used for w=4, do not use w.

btclib.curvegroup.convert_number_to_base(i: int, base: int) → List[int]

Return the digits of an integer in the requested base.

btclib.curvegroup.multiples(Q: Tuple[int, int, int], size: int, ec: btclib.curvegroup.CurveGroup) → List[Tuple[int, int, int]]

Return {k_i * Q} for k_i in {0, …, size-1)

btclib.curvegroup2 module

Elliptic curve point multiplication functions.

The implemented algorithms are:
  • Montgomery Ladder
  • Scalar multiplication on basis 3
  • Fixed window
  • Sliding window
  • w-ary non-adjacent form (wNAF)
References:
TODO:
btclib.curvegroup2.mods(m: int, w: int) → int

Signed modulo function.

btclib.curvegroup2.multiplier_decomposer(m: int, ec: btclib.curvegroup.CurveGroup) → Tuple[int, int]

Decompose m in two integers m1 e m2 so that mP = m1*P + m2*lambda*P.

Used for point multiplication with efficiently computable endomorphisms.

Based on alghoritm 3.74 of D. Hankerson, ‘Guide to Elliptic Curve Cryptography’. Values computed for secp256k1.

btclib.curvegroup2.wNAF_of_m(m: int, w: int) → List[int]

wNAF (width-w Non-adjacent form) of number m

Given an integer m, wNAF is a method of rapresentation with powers of 2, where the coefficients are odd or 0, and where at most one of any w consecutive digits is nonzero. It has the following propreties: - m has a unique width-w NAF. -The length of wNAF(m) is at most one more than the length of the binary representation of k. -The average density of nonzero digits is approximately 1/(w + 1).

For complete reference see: D. Hankerson, ‘Guide to Elliptic Curve Cryptography’ chapter 3

btclib.curvegroupf module

CurveGroup explorer functions.

These functions are meant to explore low-cardinality CurveGroup, for didactical (and fun) reason only.

btclib.curvegroupf.find_all_points(ec: btclib.curvegroup.CurveGroup) → List[Tuple[int, int]]

Attemp to find all group points, if p is low.

Very unsofisticated walk-through approach, for didactical sake only.

btclib.curvegroupf.find_subgroup_points(ec: btclib.curvegroup.CurveGroup, G: Tuple[int, int]) → List[Tuple[int, int]]

Attemp to count all G-generated subgroup points, if p is low.

Very unsofisticated walk-through approach, for didactical sake only.

btclib.der module

btclib.dh module

Diffie-Hellman elliptic curve key agreement scheme.

Implementation of the Diffie-Hellman key agreement scheme using elliptic curve cryptography. A key agreement scheme is used by two entities to establish shared keying data, which will be later utilized e.g. in symmetric cryptographic scheme.

The two entities must agree on the elliptic curve and key derivation function to use.

btclib.dh.ansi_x9_63_kdf(z: bytes, size: int, hf: Callable[[], Any], shared_info: Optional[bytes]) → bytes

Return keying data according to ANSI-X9.63-KDF.

Return a keying data octet sequence of the requested size according to ANSI-X9.63-KDF specifications for the key derivation function.

http://www.secg.org/sec1-v2.pdf, section 3.6.1

btclib.dh.diffie_hellman(dU: int, QV: Tuple[int, int], size: int, shared_info: Optional[bytes] = None, ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), hf: Callable[[], Any] = <built-in function openssl_sha256>) → bytes

Diffie-Hellman elliptic curve key agreement scheme.

http://www.secg.org/sec1-v2.pdf, section 6.1

btclib.dsa module

btclib.electrum module

Electrum entropy / mnemonic / seed functions.

Electrum mnemonic is versioned, conveying BIP32 derivation rule too.

btclib.electrum.entropy_from_mnemonic(mnemonic: str, lang: str = 'en') → str

Return the entropy from the Electrum versioned mnemonic sentence.

btclib.electrum.mnemonic_from_entropy(entropy: Union[str, int, bytes], version_str: str = 'standard', lang: str = 'en') → str

Convert input entropy to Electrum versioned mnemonic sentence.

Input entropy can be expressed as binary 0/1 string, bytes-like, or integer.

In the case of binary 0/1 string and bytes-like, leading zeros are considered redundant padding.

btclib.electrum.version_from_mnemonic(mnemonic: str) → Tuple[str, str]

Return the (Electrum version, clean mnemonic) tuple.

The clean mnemonic is free from spurious whitespace characters (extra spaces, tab, newline, return, formfeed, etc.)

btclib.entropy module

Entropy conversion functions.

Depending on the function, input entropy can be expressed as raw (i.e. binary 0/1 string), bytes, or integer and their equivalent representations.

Leading zeros in raw or bytes entropy are never considered redundant padding.

Output entropy is always raw.

btclib.entropy.binstr_from_binstr(str_entropy: str, bits: Union[int, Iterable[int]] = (128, 160, 192, 224, 256, 512)) → str

Return raw entropy from the input raw entropy.

Input entropy must be expressed as raw entropy; it is never padded to satisfy the bit-size requirement.

If more bits than required are provided, the leftmost ones are retained.

Default bit-sizes are 128, 160, 192, 224, 256, or 512 bits.

btclib.entropy.binstr_from_bytes(bytes_entropy: Union[bytes, str], bits: Union[int, Iterable[int]] = (128, 160, 192, 224, 256, 512)) → str

Return raw entropy from the input Octets entropy.

Input entropy can be expressed as hex-string or bytes; it is never padded to satisfy the bit-size requirement.

If more bits than required are provided, the leftmost ones are retained.

Default bit-sizes are 128, 160, 192, 224, 256, or 512 bits.

btclib.entropy.binstr_from_entropy(entr: Union[str, int, bytes], bits: Union[int, Iterable[int]] = (128, 160, 192, 224, 256, 512)) → str

Return raw entropy from the input entropy.

Input entropy can be expressed as:

  • raw (i.e. binary 0/1 string) entropy
  • bytes (no hex-string, as they would conflict with raw entropy representation)
  • integer (int, no string starting with “0b”/”0x”)

In the case of raw entropy and bytes, entropy is never padded to satisfy the bit-size requirement; instead, integer entropy is front-padded with zeros digits as much as necessary to satisfy the bit-size requirement.

In all cases if more bits than required are provided, the leftmost ones are retained.

Default bit-sizes are 128, 160, 192, 224, 256, or 512 bits.

btclib.entropy.binstr_from_int(int_entropy: Union[int, str], bits: Union[int, Iterable[int]] = (128, 160, 192, 224, 256, 512)) → str

Return raw entropy from the input integer entropy.

Input entropy can be expressed as int or string starting with “0x”/”0b”; it is front-padded with zeros digits as much as necessary to satisfy the bit-size requirement.

If more bits than required are provided, the leftmost ones are retained.

Default bit-sizes are 128, 160, 192, 224, 256, or 512 bits.

btclib.entropy.binstr_from_rolls(bits: int, dice_sides: int, rolls: List[int], shuffle: bool = True) → str

Return raw entropy from the input dice rolls.

Dice rolls are represented by integers in the [1-dice_sides] range; there must be enough rolls to satisfy the bit-size requirement.

Only rolls having value in the [1-base] range are used, with base being the highest power of 2 that is lower than the dice_sides (e.g. for a traditional D6 dice, only rolls having value in [1-4] are used; for a D20 dice, only rolls having value in [1-16] are used; etc.). Rolls can also be shuffled.

If more bits than required are provided, the leftmost ones are retained.

btclib.entropy.collect_rolls(bits: int) → Tuple[int, List[int]]
btclib.entropy.randbinstr(bits: int, entropy: Optional[str] = None, to_be_hashed: bool = True) → str

Return CSPRNG raw entropy XOR-ed with input raw entropy.

The input raw entropy is used as initialization value; if not provided, then entropy is generated with the system cryptographically strong pseudo-random number generator (CSPRNG).

Then, this entropy is:

  • XOR-ed with CSPRNG system entropy
  • possibly hashed (if requested)

btclib.exceptions module

Expception classes.

This are only meant to dicriminate between Exceptions being raised by btclib from those raised by other codebase.

Users are usually better off just dealing with the regular ValueError, TypeError, and RuntimeError from which the btclib versions are derived.

exception btclib.exceptions.BTClibRuntimeError

Bases: RuntimeError

exception btclib.exceptions.BTClibTypeError

Bases: TypeError

exception btclib.exceptions.BTClibValueError

Bases: ValueError

btclib.hashes module

btclib.mnemonic module

Entropy conversion from/to mnemonic word-list sentence.

Entropy must be represented as binary 0/1 string.

Warning: these functions are not meant for end-users which are better served by the bip39 and electrum module functions.

class btclib.mnemonic.WordLists

Bases: object

Class for word-lists to be used in entropy/mnemonic conversions.

Word-lists are from:

More word-lists can be added using the load_lang method.

Word-lists are loaded only if needed and read only once from disk.

language_length(lang: str) → int

Return the number of words in the language word-list.

load_lang(lang: str, filename: str = None) → None

Load/add a language word-list if not loaded/added yet.

The language file has to be provided for adding new languages beyond those already provided.

wordlist(lang: str) → List[str]

Return the language word-list.

btclib.network module

btclib.numbertheory module

Number theory and modular arithmetic functions.

Implementations originally from https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm and https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root/43267 with the following modifications:

  • type annotated python3
  • minor improvements
  • added extensive unit test
btclib.numbertheory.legendre_symbol(a, p) → int

Compute the Legendre symbol a|p using Euler’s criterion.

p is a prime, a is relatively prime to p (if p divides a, then a|p = 0). It returns 1 if a has a square root modulo p, -1 otherwise.

https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root/43267

btclib.numbertheory.mod_inv(a: int, m: int) → int

Return the inverse of a (mod m). m does not have to be a prime.

Based on Extended Euclidean Algorithm, see: https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm

btclib.numbertheory.mod_sqrt(a: int, p: int) → int

Return a quadratic residue (mod p) of a; p must be a prime.

Solve the equation:
x^2 = a mod p

and return x. Note that p - x is also a root.

If a simple solution is not available for p, then the Tonelli-Shanks algorithm is used.

https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root/43267

btclib.numbertheory.tonelli(a: int, p: int) → int

Return a quadratic residue (mod p) of a; p must be a prime.

The Tonelli-Shanks algorithm is used.

https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root/43267

btclib.numbertheory.xgcd(a: int, b: int) → Tuple[int, int, int]

Return (g, x, y) such that a*x + b*y = g = gcd(x, y).

based on Extended Euclidean Algorithm, see https://en.wikibooks.org/wiki/Algorithm_Implementation/Mathematics/Extended_Euclidean_algorithm

btclib.pedersen module

Pedersen commitment functions.

In a commitment scheme the committer:

  • decides (or is given) a secret message v
  • decides a random secret r
  • commits to v by applying the public commitment scheme algorithm and producing a commitment C=Commit(r,v)
  • makes C public

Later, when he reveals r and v, the verifier opens the commitment checking if indeed C=Commit(r,v).

Pedersen commitment uses a public group of large order n in which the discrete logarithm is hard. In the case of an elliptic curve group, the generator G is supplemented with a second random generator H and the commitment algorithm is Commit(r,v)=rG+vH. It is crucial for H to be Nothing-Up-My-Sleeve (NUMS), i.e. the discrete logarithm of H with respect to G must be unknown.

btclib.pedersen.commit(r: int, v: int, ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), hf: Callable[[], Any] = <built-in function openssl_sha256>) → Tuple[int, int]

Commit to r, returning rG+vH.

Commit to r, returning rG+vH. H is the second Nothing-Up-My-Sleeve (NUMS) generator of the curve.

btclib.pedersen.second_generator(ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), hf: Callable[[], Any] = <built-in function openssl_sha256>) → Tuple[int, int]

Second (with respect to G) elliptic curve generator.

Second (with respect to G) Nothing-Up-My-Sleeve (NUMS) elliptic curve generator.

The hash of G is coerced it to a point (x_H, y_H). If the resulting point is not on the curve, keep on incrementing x_H until a valid curve point (x_H, y_H) is obtained.

idea: https://crypto.stackexchange.com/questions/25581/second-generator-for-secp256k1-curve

source: https://github.com/ElementsProject/secp256k1-zkp/blob/secp256k1-zkp/src/modules/rangeproof/main_impl.hash_

btclib.pedersen.verify(r: int, v: int, C: Tuple[int, int], ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), hf: Callable[[], Any] = <built-in function openssl_sha256>) → bool

Open the commitment C and return True if valid.

btclib.psbt module

btclib.psbt_in module

btclib.psbt_out module

btclib.rfc6979 module

btclib.script module

Bitcoin Script.

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

Scripts are represented by List[ScriptToken], where ScriptToken = Union[int, str, bytes]:

  • int [-1, 16] are shorcuts for ‘OP_1NEGATE’, ‘OP_0’ - ‘OP_16’
  • str are for opcodes (e.g. ‘OP_HASH160’) or hexstring data
  • bytes are for data (but integers are often casted to int)
btclib.script.deserialize(stream: Union[_io.BytesIO, bytes, str]) → List[Union[int, str, bytes]]
btclib.script.serialize(script: List[Union[int, str, bytes]]) → bytes

btclib.scriptpubkey module

btclib.scriptpubkey_address module

btclib.secpoint module

SEC compressed/uncompressed point representation.

btclib.secpoint.bytes_from_point(Q: Tuple[int, int], ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1), compressed: bool = True) → bytes

Return a point as compressed/uncompressed octet sequence.

Return a point as compressed (0x02, 0x03) or uncompressed (0x04) octet sequence, according to SEC 1 v.2, section 2.3.3.

btclib.secpoint.point_from_octets(pubkey: Union[bytes, str], ec: btclib.curve.Curve = Curve('FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE FFFFFC2F', 0, 7, ('79BE667E F9DCBBAC 55A06295 CE870B07 029BFCDB 2DCE28D9 59F2815B 16F81798', '483ADA77 26A3C465 5DA4FBFC 0E1108A8 FD17B448 A6855419 9C47D08F FB10D4B8'), 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141', 1)) → Tuple[int, int]

Return a tuple (x_Q, y_Q) that belongs to the curve.

Return a tuple (x_Q, y_Q) that belongs to the curve according to SEC 1 v.2, section 2.3.4.

btclib.sighash module

btclib.signtocontract module

btclib.slip132 module

btclib.ssa module

btclib.to_prvkey module

btclib.to_pubkey module

btclib.tx module

btclib.tx_in module

btclib.tx_out module

btclib.utils module

Assorted conversion utilities.

Most conversions from SEC 1 v.2 2.3 are included.

https://www.secg.org/sec1-v2.pdf

btclib.utils.bytes_from_octets(octets: Union[bytes, str], out_size: Union[int, Iterable[int], None] = None) → bytes

Return bytes from a hex-string, stripping leading/trailing spaces.

If the input is not a string, then it goes untouched. Optionally, it also ensures required output size.

btclib.utils.bytesio_from_binarydata(stream: Union[_io.BytesIO, bytes, str]) → _io.BytesIO

Return a BytesIO stream object from BinaryIO or Octets.

If the input is not Octets (i.e. str or bytes), then it goes untouched.

btclib.utils.ensure_is_power_of_two(n: int, var_name: str = None) → None
btclib.utils.hash160(octets: Union[bytes, str]) → bytes

Return the HASH160=RIPEMD160(SHA256) of the input octet sequence.

btclib.utils.hash256(octets: Union[bytes, str]) → bytes

Return the SHA256(SHA256(*)) of the input octet sequence.

btclib.utils.hex_string(i: Union[bytes, str, int]) → str

Return a hex-string from many positive integer representations.

Negative integers are not allowed.

The resulting hex-string has an even number of hex-digits and includes a space every four bytes (i.e. every eight hex-digits).

btclib.utils.int_from_bits(octets: Union[bytes, str], nlen: int) → int

Return the leftmost nlen bits.

Take as input a sequence of blen bits and calculate a non-negative integer i that is less than 2^nlen according to SEC 1 v.2 section 4.1.3 (5). Note that an additional reduction modulo n would be required to ensure that 0 < i < n.

int_from_bits is not the reverse of i.to_bytes, even for input sequences of length nlen: i.to_bytes will add some bits on the left, while int_from_bits will discard some bits on the right. i.to_bytes is the reverse of int_from_bits only when nlen is a multiple of 8 and bit sequences already have length nlen. See https://tools.ietf.org/html/rfc6979#section-2.3.5.

btclib.utils.int_from_integer(i: Union[bytes, str, int]) → int

Return an int from many possible integer representations.

Allowed integer representations are:

  • 3735928559
  • -3735928559
  • “0xdeadbeef”
  • “-0xdeadbeef”
  • “deadbeef”
  • b’Þ­¾ï’

The binary representation is not allowed because there is no way to discriminate it from a valid hex-string (e.g. “0b11011110101011011011111011101111”).

btclib.utils.merkle_root(data: List[bytes], hf: Callable[[Union[bytes, str]], bytes]) → bytes

Return the Merkel tree root of a list of binary hashes.

The Merkel tree is a binary tree constructed with the provided list of binary data as bottom level, then recursively going up one level by hashing every hash value pair in the current level, until a single value (root) is obtained.

btclib.utils.sha256(octets: Union[bytes, str]) → bytes

Return the SHA256(*) of the input octet sequence.

btclib.utils.token_or_string_to_hex_string(val: Union[int, str, bytes]) → str

Return a readable string from a ScriptToken or a String object.

If val are bytes a hex string is returned. If val is an int his string representation is returned.

btclib.utils.token_or_string_to_printable(val: Union[List[Union[int, str, bytes]], List[Union[bytes, str]]]) → List[Union[int, str]]

btclib.varbytes module

Varbytes encoding and decoding functions.

btclib.varbytes.deserialize(stream: Union[_io.BytesIO, bytes, str], forbid_zero_size=False) → bytes

Return the variable-length octets read from a stream.

btclib.varbytes.serialize(octets: Union[bytes, str]) → bytes

Return the varint(len(octets)) + octets serialization of octets.

btclib.varint module

Varint encoding and decoding functions.

A varint (variable integer) is variable-length quantity that uses an arbitrary number of binary octets (eight-bit bytes) to represent an arbitrarily large integer. It is usually a base-128 (7 bits) representation of an unsigned integer with the addition of the eighth bit to mark continuation of bytes; it is used to save additional space for a resource constrained system.

This is the slightly different Bitcoin implementation, used in transaction data to indicate the number of upcoming fields or the length of the upcoming field.

Up to 0xfc, a varint is just 1 byte; however, if the integer is greater than 0xfc, then it is expanded as [1 byte prefix][number]:

  • prefix 0xfd markes the next two bytes as the number;
  • prefix 0xfe markes the next four bytes as the number;
  • prefix 0xff markes the next eight bytes as the number.
btclib.varint.deserialize(stream: Union[_io.BytesIO, bytes, str]) → int

Return the variable-length integer read from a stream.

btclib.varint.serialize(i: int) → bytes

Return the varint bytes encoding of an integer.

Module contents