A Python library for 'bitcoin cryptography'
btclib is a Python3 type annotated library for teaching, learning and using bitcoin, focused on elliptic curve cryptography and bitcoin's blockchain. It started as a teaching tool for Ferdinando Ametrano's Bitcoin and Blockchain Technology course, it is used in production today (still marked as beta because it is often refactored for improved clarity).
The test suite covers virtually the whole code base, a floor the build
enforces, and it answers to vectors their authors publish: the BIPs' and
the SLIPs' own, Bitcoin Core's script, transaction, sighash and
key-encoding files, HWI's, trezor's for BIP39 and SLIP39, and Appendix A.2
of RFC 6979. tests/_data/README.md pins each vendored file to the
upstream commit it was copied from, and says whether the two still match —
including the few vectors that are btclib's own, having no upstream.
The library is not limited to secp256k1, and for that curve it always calls btclib_libsecp256k1, FFI bindings to Bitcoin Core's optimized C library libsecp256k1. They are a required dependency and not an optional accelerator, so installing btclib needs one of their wheels or a C toolchain. The Python arithmetic serves every other curve, and the suite validates it against the bindings: libsecp256k1 says what the right answer is, being what bitcoin consensus relies on.
Included features are:
- modulo algebra functions (gcd, inverse, legendre symbol, square root)
- octets / integer / point / var_int / var_bytes helper functions
- elliptic curve class
- fast algebra implemented using Jacobian coordinates
- double scalar multiplication (Straus's algorithm, also known as Shamir's trick)
- multi scalar multiplication (Bos-coster's algorithm)
- point symmetry solution: odd/even, low/high, and quadratic residue
- elliptic curves: SEC 1 v1 and v2, NIST, Brainpool, and low cardinality test curves
- ECDSA signature with (transaction) DER encoding
- ECDSA signature with (message) compact encoding: standard p2pkh and BIP137/Electrum extensions to p2wpkh and p2wpkh-p2sh
- BIP322 signed messages, where the address is a script to satisfy rather than a key to recover: the simple, full and proof-of-funds variants, verified by the script engine, so multisig, taproot and time locks sign as well as p2pkh does
- RFC 6979 for deterministic signature schemes
- EC Schnorr signature (according to
BIP340
bitcoin standardization)
- batch validation
- threshold signature (see test-suite)
- MuSig2 multi-signature: key aggregation with plain and x-only tweaking, nonce aggregation, partial signatures and their aggregation, one primitive per round of the protocol
- Borromean ring signature
- Sign-to-contract commitment
- Diffie-Hellman, and the x-only ECDH on the BIP324 ElligatorSwift encoding of a public key
- ECIES in the BIE1 layout, the block cipher supplied by the caller
- Pedersen commitment
- Base58 encoding/decoding
- p2pkh/p2sh addresses and WIFs
- Bech32 encoding/decoding
- p2wpkh/p2wsh native segwit addresses and their legacy p2sh-wrapped versions
- BIP32 hierarchical deterministic key chains
- BIP39 mnemonic for generating deterministic keys, in the twelve wordlists of the reference implementation, with the language read off the words
- Electrum standard for mnemonic, in the five wordlists Electrum reads
- SLIP39 Shamir backup: a master secret split into mnemonic shares, of which a threshold number recovers it
- BIP44
address from an extended key and a
m/purpose'/coin_type'/account'/change/address_indexpath, the purpose selecting the encoding: 44 p2pkh, 49 p2wpkh-p2sh, 84 p2wpkh (BIP84), 86 p2tr (BIP86) - SLIP132 key versions (xprv, yprv, zprv, Yprv, Zprv, tprv, uprv, vprv, and Uprv) with corresponding mapping to p2pkh/p2sh, p2wpkh-p2sh, p2wpkh, p2wsh-p2sh, p2wsh and p2tr addresses
- Script encoding/decoding
- nulldata, p2pk, p2ms, p2pkh, p2sh, p2wpkh, p2wsh and p2tr ScriptPubKeys
- a script engine: a transaction verified against the consensus rules, legacy, segwit and tapscript, with Bitcoin Core's own vectors behind it
- BIP380 output descriptors: the checksum, the parser, the scripts a descriptor names, and the spend
- BIP379
miniscript, read, written and spent, inside
wsh()and as atr()leaf: the expression compiled to a script, a script read back into the expression it is, the type system that says an expression is well formed, the bounds a spend of it is analysed by, and the non-malleable witness that satisfies it - OutPoint, TxIn, TxOut, and TX data classes
- legacy, segwit_v0 and taproot transaction hash signatures
- BlockHeader and Block data classes
- merkle proofs verified against a header's merkle root
- proof-of-work arithmetic: compact targets, retargeting, work, hash rate
- BIP174 partially signed bitcoin transactions (PSBT): PsbtIn, PsbtOut, and Psbt data classes, with the taproot fields of BIP371 and the MuSig2 ones of BIP373
- BIP370 PSBT version 2, the unsigned transaction computed from the fields rather than carried as one: the lock time its inputs require, the identifier that ignores their sequences, the modifiable flags a Constructor must obey, and conversion either way
- BIP21
bitcoin:payment URIs - fee rates carrying their unit (sat/kvB and sat/vB), the fee a virtual size owes at one, and the dust threshold of any output type, computed as Bitcoin Core computes it rather than tabulated
- wallets, three sources of addresses behind one vocabulary: an extended
key at a BIP44 account or a set of individual keys, which also answer
the private key that signs for an address — what
sign(address, msg)needs — an output descriptor per chain, and a script template with multisig quorums in it, for the pre-descriptor wallets no descriptor states. Each answersaddress(branch, index),script_pub_key(branch, index)andposition_of(script_pub_key), the last being "is this output mine", compared whole and never on a key origin's fingerprint - an external signer behind one contract, with Bitcoin Core's HWI behind it for a hardware wallet
- a chain backend behind one interface — a transaction by id, the output an outpoint names, the chain tip — over a full node's JSON-RPC or a block explorer's HTTP api
Secrets, and where constant time ends
btclib is used to teach and to prototype as much as to build, and the two uses want different things of it. What follows is the boundary between them, before a private key is handed to any of the above.
A Python object carrying secret material cannot be reliably zeroized: it stays in the process memory until garbage collection, and the interpreter may have copied it meanwhile. The constant-time properties are libsecp256k1's, and they hold on the C side of the call — not before it, and not after.
Not every operation crosses that call. dsa.sign and ssa.sign reach the
bindings for secp256k1 with sha256 and no nonce of the caller's; another
curve, another hash function, or a nonce you supply runs the Python
arithmetic instead, which the suite validates against the bindings but
which is not constant-time. So a caller whose threat model includes timing
should stay on the delegated paths, or keep the key out of the process
altogether: btclib.hwi drives a hardware wallet through HWI, behind the
same PsbtSigner contract a software signer answers.
SECURITY's "Limitations, not vulnerabilities" states each condition exactly — which arguments delegate, which do not, and what the Python path does hide — and is the canonical text; this section is the pointer to it.
Module layout
Three pairs of modules are one idea split in two, and each split runs one way only:
| the codec / the arithmetic | the bitcoin semantics on top |
|---|---|
btclib.curves — Curve, mult |
btclib.ecc — dsa, ssa, bms |
btclib.base58 — the encoding |
btclib.b58 — WIF, p2pkh, p2sh |
btclib.bech32 — the encoding |
btclib.b32 — p2wpkh, p2wsh, p2tr |
The right column imports the left one; the left never imports the right.
So from btclib.ecc import dsa for a signature,
from btclib.curves import mult for a point multiplication, btclib.b58
for an address, btclib.base58 for the encoding on its own. Each of the
six modules says the same in its own docstring.
The rest, roughly bottom-up. alias holds the types the public API
accepts, much of it taking anything convertible rather than one type, and
exceptions the errors it raises. to_prv_key and to_pub_key accept
any key representation and hand back one. bip32 and mnemonic derive
keys. script, tx, block and psbt build and validate what goes on
the chain, and script.engine runs a transaction against the consensus
rules.
Above them, bip44 composes bip32, script.taproot and both address
encodings into an address from an extended key and a derivation path, and
descriptors reads the BIP380 grammar and hands back the scripts a
descriptor names -- with descriptors.miniscript reading BIP379's
language, which is a script written as a tree of fragments, and
satisfying one. psbt_signer
is the contract an external signer answers; hwi is that contract over
Bitcoin Core's HWI.
Nothing in the library imports bip21, bip322, slip132, fee,
wallet, hwi or fetch: they are the top of the stack, and fetch
is the only one that goes out to the network. wallet remembers which
addresses it has handed out — over bip44, over descriptors or over a
script template of its own — and its key wallets sign for one with
ecc.bms.
bip322 is the other message signing, and it is at the top rather than
beside ecc.bms because it needs everything below it: a script, a
transaction, a psbt and the engine that runs them.
The rpc client fetch speaks through is not in that stack: it is
bitcoin-core-rpc, a
package of its own that btclib depends on — one file, standard library
only, installable or copyable, and usable by anyone who wants a node
client and no bitcoin library. btclib.fetch turns its answers into Tx
and TxOut, and checks the chain the node reports against the network
those are labelled for.
The dependency stops at btclib/fetch/. bitcoin-core-rpc declares its own
FetchError, importing nothing of btclib's being what lets its file be
vendored, and btclib.fetch.fetcher.client_errors re-raises it as
btclib.exceptions' own, with the status and the code carried across:
an except FetchError written against btclib catches what a fetcher
raises, and no module outside that package loads urllib.request.
Constructing a client opens no socket; the first call does.
To install, or upgrade:
python -m pip install --upgrade btclib
In a virtual environment:
python -m venv venv_btclib
source venv_btclib/bin/activate
python -m pip install --upgrade btclib
On Windows the second line is venv_btclib\Scripts\activate in CMD and
PowerShell, source venv_btclib/Scripts/activate in Git bash.
CONTRIBUTING is for development, SECURITY for reporting a vulnerability.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file btclib-2026.8.9.tar.gz.
File metadata
- Download URL: btclib-2026.8.9.tar.gz
- Upload date:
- Size: 7.9 MB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e0b959c304f4418036f1d333bf225b0f39603a3db107a1954729f7362731788f
|
|
| MD5 |
8fc7c89dcd009d3a334589740a19f747
|
|
| BLAKE2b-256 |
a4e8e5f8ec27f964a5dbf74784a771b43ff57ecbd5774c28b164db5cb5ba2e76
|
Provenance
The following attestation bundles were made for btclib-2026.8.9.tar.gz:
Publisher:
release.yml on btclib-org/btclib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
btclib-2026.8.9.tar.gz -
Subject digest:
e0b959c304f4418036f1d333bf225b0f39603a3db107a1954729f7362731788f - Sigstore transparency entry: 2398901252
- Sigstore integration time:
-
Permalink:
btclib-org/btclib@69c899ffa29361c01f15d82d6478ab72923f0ea9 -
Branch / Tag:
refs/tags/v2026.8.9 - Owner: https://github.com/btclib-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@69c899ffa29361c01f15d82d6478ab72923f0ea9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file btclib-2026.8.9-py3-none-any.whl.
File metadata
- Download URL: btclib-2026.8.9-py3-none-any.whl
- Upload date:
- Size: 700.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
567486c67ef4f52df48f22c8713ddda9e5d1f6053ed837d885f279c80def179a
|
|
| MD5 |
0407f4d538577c27254a34a48f564a30
|
|
| BLAKE2b-256 |
b32d1fdf90e79b3d9c5b7355d7916e1ded1e2879a8fcaf1c9f31aa809bffde8b
|
Provenance
The following attestation bundles were made for btclib-2026.8.9-py3-none-any.whl:
Publisher:
release.yml on btclib-org/btclib
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
btclib-2026.8.9-py3-none-any.whl -
Subject digest:
567486c67ef4f52df48f22c8713ddda9e5d1f6053ed837d885f279c80def179a - Sigstore transparency entry: 2398901290
- Sigstore integration time:
-
Permalink:
btclib-org/btclib@69c899ffa29361c01f15d82d6478ab72923f0ea9 -
Branch / Tag:
refs/tags/v2026.8.9 - Owner: https://github.com/btclib-org
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@69c899ffa29361c01f15d82d6478ab72923f0ea9 -
Trigger Event:
push
-
Statement type: