Skip to main content

Bitcoin and Other cryptocurrency Library

Project description

Python Bitcoin Library

Bitcoin, Litecoin and Dash Crypto Currency Library for Python.

Includes a fully functional wallet with multi-signature, multi-currency and multiple accounts. You this library at a high level and create and manage wallets for the command line or at a low level and create your own custom made transactions, keys or wallets.

The BitcoinLib connects to various service providers automatically to update wallets, transactions and blockchain information. It does currently not parse the blockchain itself.

Unittests PyPi RTD Coveralls Known Vulnerabilities

Documentation

Read the full documentation at: http://bitcoinlib.readthedocs.io/

Disclaimer

This library is still in development, please use at your own risk and test sufficiently before using it in a production environment.

Some Examples

Wallet

The bitcoin library contains a wallet implementation using SQLAlchemy and SQLite3 to import, create and manage keys in a Hierarchical Deterministic way.

Example: Create wallet and generate new address (key) to receive bitcoins

>>> from bitcoinlib.wallets import Wallet
>>> w = Wallet.create('Wallet1')
>>> key1 = w.get_key()
>>> key1.address
'1Fo7STj6LdRhUuD1AiEsHpH65pXzraGJ9j'

Now send a small transaction to your wallet and use the scan() method to update transactions and UTXO’s

>>> w.scan()
>>> w.info()  # Shows wallet information, keys, transactions and UTXO's

When your wallet received a payment and has unspent transaction outputs, you can send bitcoins easily. If successful a transaction ID is returned

>>> t = w.send_to('1PWXhWvUH3bcDWn6Fdq3xhMRPfxRXTjAi1', '0.001 BTC', offline=False)
'b7feea5e7c79d4f6f343b5ca28fa2a1fcacfe9a2b7f44f3d2fd8d6c2d82c4078'
>>> t.info  # Shows transaction information and send results

Wallet from passphrase with accounts and multiple currencies

The following code creates a wallet with two Bitcoin and one Litecoin account from a Mnemonic passphrase. The complete wallet can be recovered from the passphrase, which is the masterkey.

from bitcoinlib.wallets import Wallet, wallet_delete
from bitcoinlib.mnemonic import Mnemonic

passphrase = Mnemonic().generate()
print(passphrase)
w = Wallet.create("Wallet2", keys=passphrase, network='bitcoin')
account_btc2 = w.new_account('Account BTC 2')
account_ltc1 = w.new_account('Account LTC', network='litecoin')
w.get_key()
w.get_key(account_btc2.account_id)
w.get_key(account_ltc1.account_id)
w.info()

Multi-Signature Wallets

Create a Multisig wallet with 2 cosigners which both need to sign a transaction.

from bitcoinlib.wallets import Wallet
from bitcoinlib.keys import HDKey

NETWORK = 'testnet'
k1 = HDKey('tprv8ZgxMBicQKsPd1Q44tfDiZC98iYouKRC2CzjT3HGt1yYw2zuX2awTotzGAZQEAU9bi2M5MCj8iedP9MREPjUgpDEBwBgGi2C8eK'
            '5zNYeiX8', network=NETWORK)
k2 = HDKey('tprv8ZgxMBicQKsPeUbMS6kswJc11zgVEXUnUZuGo3bF6bBrAg1ieFfUdPc9UHqbD5HcXizThrcKike1c4z6xHrz6MWGwy8L6YKVbgJ'
            'MeQHdWDp', network=NETWORK)
w1 = Wallet.create('multisig_2of2_cosigner1', sigs_required=2,
                     keys=[k1, k2.public_master(multisig=True)], network=NETWORK)
w2 = Wallet.create('multisig_2of2_cosigner2',  sigs_required=2,
                     keys=[k1.public_master(multisig=True), k2], network=NETWORK)
print("Deposit testnet bitcoin to this address to create transaction: ", w1.get_key().address)

Create a transaction in the first wallet

w1.utxos_update()
t = w1.sweep('mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf', min_confirms=0)
t.info()

And then import the transaction in the second wallet, sign it and push it to the network

w2.get_key()
t2 = w2.transaction_import(t)
t2.sign()
t2.send()
t2.info()

Segregated Witness Wallet

Easily create and manage segwit wallets. Both native segwit with base32/bech32 addresses and P2SH nested segwit wallets with traditional addresses are available.

Create a native single key P2WPKH wallet:

>>> from bitcoinlib.wallets import Wallet
>>> w = Wallet.create('wallet_segwit_p2wpkh', witness_type='segwit')
>>> w.get_key().address
bc1q84y2quplejutvu0h4gw9hy59fppu3thg0u2xz3

Or create a P2SH nested single key P2SH_P2WPKH wallet:

>>> from bitcoinlib.wallets import Wallet
>>> w = Wallet.create('wallet_segwit_p2sh_p2wpkh', witness_type='p2sh-segwit')
>>> w.get_key().address
36ESSWgR4WxXJSc4ysDSJvecyY6FJkhUbp

Command Line Tool

With the command line tool you can create and manage a wallet without any Python programming.

To create a new Bitcoin wallet

$ clw newwallet
Command Line Wallet for BitcoinLib

Wallet newwallet does not exist, create new wallet [yN]? y

CREATE wallet 'newwallet' (bitcoin network)

Your mnemonic private key sentence is: force humble chair kiss season ready elbow cool awake divorce famous tunnel

Please write down on paper and backup. With this key you can restore your wallet and all keys

You can use clw to create simple or multisig wallets for various networks, manage public and private keys and managing transactions.

For the full command line wallet documentation please read

http://bitcoinlib.readthedocs.io/en/latest/_static/manuals.command-line-wallet.html

Mnemonic key generation

Allows you to use easy to remember passphrases consisting of a number of words to store private keys (BIP0039). You can password protect this passphrase (BIP0038), and use the HD Wallet structure to generate an almost infinite number of new private keys and bitcoin addresses (BIP0043 and BIP0044).

Example: Generate a list of words passphrase and derive a private key seed

>>> from bitcoinlib.mnemonic import Mnemonic
>>> from bitcoinlib.encoding import to_hexstring
>>> words = Mnemonic().generate()
>>> words
unique aisle iron extend earn cigar trust source next depart yard bind
>>> to_hexstring(Mnemonic().to_seed(words))
'9c6f41a347bf4f326f9c989fb522bec1b82c36463580d1769daadba7d59f69a305505fdd5d2131c9c60255c79279d4e8896155e0b126abea036da56a766f81a1'

Service providers

Communicates with pools of bitcoin service providers to retrieve transaction, address, blockchain information. Can be used to push a transaction to the network, determine optimal service fee for a transaction or to update your wallet’s balance.

When working with wallets, connections to service providers are automatically managed, so you don’t have to worry about them. You can however easily use the Service object directly.

Example: Get estimated transaction fee in Sathosis per Kb for confirmation within 5 blocks

>>> from bitcoinlib.services.services import Service
>>> Service().estimatefee(5)
138964

Other Databases

Bitcoinlib uses the SQLite database by default, but other databases are supported as well. See http://bitcoinlib.readthedocs.io/en/latest/_static/manuals.databases.html for instructions on how to use MySQL or PostgreSQL.

More examples

For more examples see https://github.com/1200wd/bitcoinlib/tree/master/examples

Implements the following Bitcoin Improvement Proposals

  • Hierarchical Deterministic Wallets (BIP0032)

  • Passphrase-protected private key (BIP0038)

  • Mnemonic code for generating deterministic keys (BIP0039)

  • Purpose Field for Deterministic Wallets (BIP0043)

  • Multi-Account Hierarchy for Deterministic Wallets (BIP0044)

  • Structure for Deterministic P2SH Multisignature Wallets (BIP0045)

  • Bech32/base32 address format for native v0-16 witness outputs (BIP0173)

  • Native and P2SH nested Segregated Witness transactions (BIP0141 and BIP0143)

Installing and updating

Pre-requirements Linux

sudo apt install build-essential python-dev python3-dev libgmp3-dev

To install OpenSSL development package on Debian, Ubuntu or their derivatives

sudo apt install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL

sudo yum install gcc openssl-devel

Pre-requirements Windows

This library requires a Microsoft Visual C++ Compiler. See http://bitcoinlib.readthedocs.io/en/latest/_static/manuals.install.html

The fastecdsa library is not enabled at this moment on windows, the slower ecdsa library is installed.

Install with pip

pip install bitcoinlib

These packages will be installed * fastecdsa (or ecdsa on Windows) * pyaes * scrypt * sqlalchemy * requests * enum34 (for older Python installations) * pathlib2 (for Python 2) * six

Install development environment

Required packages:

sudo apt install -y postgresql postgresql-contrib mysql-server libpq-dev libmysqlclient-dev

Create a virtual environment for instance on linux with virtualenv:

$ virtualenv -p python3 venv/bitcoinlib
$ source venv/bitcoinlib/bin/activate

Then clone the repository and install dependencies:

$ git clone https://github.com/1200wd/bitcoinlib.git
$ cd bitcoinlib
$ pip install -r requirements-dev.txt

Troubleshooting

When you experience issues with the scrypt package when installing, you can try to solve this by removing and reinstall scrypt:

$ pip uninstall scrypt
$ pip install scrypt

Please make sure you also have the Python development and SSL development packages installed, see ‘Other requirements’ above.

You can also use pyscrypt instead of scrypt. Pyscrypt is a pure Python scrypt password-based key derivation library. It works but it is slow when using BIP38 password protected keys.

$ pip install pyscrypt

If you run into issues, do not hesitate to contact us or file an issue at https://github.com/1200wd/bitcoinlib/issues

Update library

Update to the latest version of the library with

$ pip install bitcoinlib --upgrade

To upgrade make sure everything is backuped and run updatedb.py from the installation directory.

$ python updatedb.py -d [<link-to-database-if-not-standard>]

For more information on installing, updating and maintenance see https://bitcoinlib.readthedocs.io/en/latest/_static/manuals.install.html#installation

Future / Roadmap

  • Create Block class

  • Create Script class and support advanced scripts

  • Fully support timelocks

  • Support for lightning network

  • Support for Trezor wallet

  • Improve speed and security

  • Integrate in ERP and shopping solutions such as Odoo, Magento, Shopware

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bitcoinlib-0.6.4.tar.gz (3.0 MB view details)

Uploaded Source

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

bitcoinlib-0.6.4-py3-none-any.whl (327.1 kB view details)

Uploaded Python 3

bitcoinlib-0.6.4-py2-none-any.whl (320.7 kB view details)

Uploaded Python 2

File details

Details for the file bitcoinlib-0.6.4.tar.gz.

File metadata

  • Download URL: bitcoinlib-0.6.4.tar.gz
  • Upload date:
  • Size: 3.0 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.26.0 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.8.3 keyring/23.4.1 rfc3986/1.5.0 colorama/0.4.4 CPython/3.6.8

File hashes

Hashes for bitcoinlib-0.6.4.tar.gz
Algorithm Hash digest
SHA256 7fde6e3a86d7a751fb66456e6c800d89035f139945f073f408b5e99eab8232d9
MD5 e90f8e0fd2bc725d0bf7b0492578e181
BLAKE2b-256 c4ff43be69c133c79bc306b1a5b9fe2bab1e3168c4c67696c03b4de6bc36e16f

See more details on using hashes here.

File details

Details for the file bitcoinlib-0.6.4-py3-none-any.whl.

File metadata

  • Download URL: bitcoinlib-0.6.4-py3-none-any.whl
  • Upload date:
  • Size: 327.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.8.0 pkginfo/1.8.2 readme-renderer/32.0 requests/2.26.0 requests-toolbelt/0.9.1 urllib3/1.26.8 tqdm/4.63.0 importlib-metadata/4.8.3 keyring/23.4.1 rfc3986/1.5.0 colorama/0.4.4 CPython/3.6.8

File hashes

Hashes for bitcoinlib-0.6.4-py3-none-any.whl
Algorithm Hash digest
SHA256 467f64309172d36bdec114c25505b189307ba668dfd7dd0afb5d896bf35613f2
MD5 0a9b8ac762091ef1648e7549ca7fc9bd
BLAKE2b-256 a8f60be9be4fbf374fe8ef0d99fec677d98c9d5c74c2e2a0d98dac7e09281934

See more details on using hashes here.

File details

Details for the file bitcoinlib-0.6.4-py2-none-any.whl.

File metadata

  • Download URL: bitcoinlib-0.6.4-py2-none-any.whl
  • Upload date:
  • Size: 320.7 kB
  • Tags: Python 2
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.10.0 pkginfo/1.2.1 requests/2.18.4 setuptools/39.0.1 requests-toolbelt/0.8.0 tqdm/4.19.5 CPython/3.6.9

File hashes

Hashes for bitcoinlib-0.6.4-py2-none-any.whl
Algorithm Hash digest
SHA256 67f9934a748eb0c34848fe8dc566cd108d70176133addb009a28b837bbe7bdde
MD5 edbe353493d119b6503ad124fd3b930a
BLAKE2b-256 aa0f45ea6680e1af7d5ea4a8991ec8152b6716e40476726a317ea4e318d54d3a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page