Python Bitcoin Library

0.12.2 · active · verified Thu Apr 16

python-bitcoinlib is a comprehensive Python library designed to interact with the Bitcoin protocol. It provides utilities for handling cryptographic operations, addresses, scripts, transactions, and more. The current stable version is 0.12.2, with releases occurring sporadically based on needed updates and bug fixes.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a new Bitcoin private key and derive its corresponding P2PKH address for the Mainnet. It showcases the basic cryptographic primitives used for wallet management. Remember to handle private keys with extreme care in production environments.

from bitcoin.wallet import CBitcoinSecret, P2PKHAddress
from bitcoin.main import MAINNET # Import specific networks

# 1. Generate a new random private key for the Bitcoin Mainnet
# In a real application, you must store this secret securely.
# For Testnet, replace MAINNET with TESTNET.
private_key = CBitcoinSecret.from_secret_bytes(CBitcoinSecret.generate_secret_bytes(), MAINNET)

# 2. Derive the corresponding public key
public_key = private_key.pub

# 3. Derive a Pay-to-Public-Key-Hash (P2PKH) address from the public key
address = P2PKHAddress.from_pubkey(public_key)

print(f"Generated Private Key (WIF format): {private_key.D.to_string()}")
print(f"Corresponding Bitcoin Address: {address}")
print(f"Network: {'Mainnet' if private_key.is_mainnet else 'Testnet' if private_key.is_testnet else 'Unknown'}")

view raw JSON →