Bit is Python's fastest Bitcoin library and was designed from the beginning to feel intuitive, be effortless to use, and have readable source code.

Overview

Bit: Bitcoin made easy.

https://img.shields.io/pypi/v/bit.svg?style=flat-square https://img.shields.io/travis/ofek/bit.svg?branch=master&style=flat-square https://img.shields.io/codecov/c/github/ofek/bit.svg?style=flat-square https://img.shields.io/pypi/pyversions/bit.svg?style=flat-square https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square

Bit is Python's fastest Bitcoin library and was designed from the beginning to feel intuitive, be effortless to use, and have readable source code. It is heavily inspired by Requests and Keras.

Bit is so easy to use, in fact, you can do this:

>>> from bit import Key
>>>
>>> my_key = Key(...)
>>> my_key.get_balance('usd')
'12.51'
>>>
>>> # Let's donate!
>>> outputs = [
>>>     # Wikileaks
>>>     ('1HB5XMLmzFVj8ALj6mfBsbifRoD4miY36v', 0.0035, 'btc'),
>>>     # Internet Archive
>>>     ('1Archive1n2C579dMsAu3iC6tWzuQJz8dN', 190, 'jpy'),
>>>     # The Pirate Bay
>>>     ('129TQVAroeehD9fZpzK51NdZGQT4TqifbG', 3, 'eur'),
>>>     # xkcd
>>>     ('14Tr4HaKkKuC1Lmpr2YMAuYVZRWqAdRTcr', 2.5, 'cad')
>>> ]
>>>
>>> my_key.send(outputs)
'9f59f5c6757ec46fdc7440acbeb3920e614c8d1d247ac174eb6781b832710c1c'

Here is the transaction https://blockchain.info/tx/9f59f5c6757ec46fdc7440acbeb3920e614c8d1d247ac174eb6781b832710c1c.

Features

  • Python's fastest available implementation (100x faster than closest library)
  • Seamless integration with existing server setups
  • Supports keys in cold storage
  • Fully supports 25 different currencies
  • First class support for storing data in the blockchain
  • Deterministic signatures via RFC 6979
  • Access to the blockchain (and testnet chain) through multiple APIs for redundancy
  • Exchange rate API, with optional caching
  • Optimal transaction fee API, with optional caching
  • Compressed public keys by default
  • Multiple representations of private keys; WIF, PEM, DER, etc.
  • Legacy P2PKH and Segwit nested-P2WPKH transactions
  • Legacy P2SH and Segwit nested-P2WSH transactions

If you are intrigued, continue reading. If not, continue all the same!

Installation

Bit is distributed on PyPI as a universal wheel and is available on Linux/macOS and Windows and supports Python 3.5+ and PyPy3.5-v5.7.1+. pip >= 8.1.2 is required.

$ pip install bit

Documentation

Docs are hosted by Github Pages and are automatically built and published by Travis after every successful commit to Bit's master branch.

Credits

Comments
  • Add P2SH-Multisig support

    Add P2SH-Multisig support

    Adds support for Pay-To-Script-Hash (P2SH) multi-signature contracts.

    The multi-signature scheme is compatible with Bitcoin Core, and therefore partially-signed transactions can be co-signed between both implementations.

    New classes:

    MultiSig and MultiSigTestnet.

    Example usage:

    from bit import *
    
    # Creating three private keys:
    key1 = PrivateKeyTestnet("cNZYKrewErp2wG9LXiAU4H6dzgtyYsSm78tSU14QST9Hu57CMRaJ")
    key2 = PrivateKeyTestnet("cMgHThJYoUYc19UjMWn1xabRJLh3PCKyKfiTM1ssV2ZPe7V6eaBL")
    key3 = PrivateKeyTestnet("cR1C9ZB7qoVktmQDQsUP8KcTM37G1PYN3oR2B6ua27EycGDVN6fE")
    
    # Making a list containing the public keys in hex:
    key1p = key1.pub_to_hex()
    key2p = key2.pub_to_hex()
    key3p = key3.pub_to_hex()
    plist = [key1p, key2p, key3p]
    
    # Creating a P2SH multi-signature contract instance with key1 requiring two signatures from the total of three keys:
    multi = MultiSigTestnet(key1, plist, 2)
    
    # Showing the multi-signature address to send (testnet) bitcoins to:
    multi.address
    # 2MvkZtmW1w7hBPMSjQmEhHzrtcgiQGEBrtD
    
    # Create and partially-sign a new transaction spending from the multi-signature contract:
    tx = multi.create_transaction([], fee=21, leftover='mpDJqjKMyQaFjEMwYHKJBP3mM4rM2ejJdk')
    
    # Create another instance of the multi-signature contract with key2:
    multi2 = MultiSigTestnet(key2, plist, 2)
    
    # Fully sign the spending transaction using our second instance of the multi-signature contract:
    tx_signed = multi2.sign_transaction(tx)
    

    This is only thought of as a first start to implement P2SH and therefore bugs are still expected and more rigorous testing and optimization may be necessary.

    opened by bjarnemagnussen 30
  • Signing and verifying

    Signing and verifying

    Hi

    I'm looking for 2 features that existing popular wallets already offer:

    1. Sign a message using private keys
    2. Verify a message, given the message and signature

    Is this possible? I dont see it in the documentation

    opened by 7hacker 22
  • Transfer BTC. InsufficientFunds

    Transfer BTC. InsufficientFunds

    When I try to create a transaction, it gives an error that there are not enough funds on the balance: bit.exceptions.InsufficientFunds: Balance 54022 is less than 60800 (including fee).

    key.send([(address, 0.0001, 'btc')], fee=200) 0.0001 btc = 10000 satoshi. So total is 30000 satoshi (0.0003 btc).

    Why im getting error? I noticed that when transferring the indicated amount, it is added to the whole balance and is trying to transfer it.

    opened by deliugard 20
  • [WIP] Adds support for `NetworkAPI` to use a remote Bitcoin node

    [WIP] Adds support for `NetworkAPI` to use a remote Bitcoin node

    This PR adds a method allowing the NetworkAPI to connect to a remote Bitcoin node instead of relying on web APIs. It is marked as a work-in-progress to allow testing, code improvements and test cases to be added.

    It has been implemented in a way to minimize changes to the codebase and to not break already existing tests. Any suggestions however on how to better connect the new class bit.network.services.RPCHost with the NetworkAPI is welcome! Right now inside NetworkAPI it simply overrides its web-API values using the RPCHost instead.

    This implementation also allows to connect to two different Bitcoin nodes: one for mainnet and one for testnet; and keeps them separate.

    Example code

    import bit
    
    # To connect to a remote Bitcoin node:
    from bit.network import NetworkAPI
    NetworkAPI.connect_to_node(user='user', password='password', host='localhost', port='18443', use_https=False, testnet=True)
    
    # We could additionally choose to connect to some mainnet node:
    NetworkAPI.connect_to_node(user='user', password='password', host='domain', port='8332', use_https=True, testnet=False)
    
    # Do some bit stuff...
    k_test = bit.PrivateKeyTestnet()
    k_test.get_unspents()  # will use the testnet node for API
    k_main = bit.PrivateKey()
    k_main.get_unspents()  # will use the mainnet node for API
    # ...
    

    Remarks

    Bitcoin Core is not a blockchain explorer and thus only keeps full track of addresses in its wallet! Therefore to use it as a remote node all addresses generated with Bit and that should be tracked must be added as (watch-only) addresses to Bitcoin Core as follows:

    >>> bitcoin-cli importaddress "WATCH_ONLY_ADDRESS"
    

    See importaddress for more details.

    It may be useful to add a helper function that can add generated Bit addresses to the Bitcoin Core wallet.

    Bitcoin Core RPC behaves particular with regard to coinbase transactions

    Coinbase transactions directly received inside a Bitcoin Core wallet address will as expected be returned as a list of Unspent objects when using PrivateKey().get_unused(). However, they will not show up when using PrivateKey().get_transactions(). A fix would be to rewrite the RPCHost method get_transactions to use the RPC method listsinceblock, which returns all transactions associated to the Bitcoin Core wallet but hence also requires Bit to filter them by addresses. As this is an edge case and wasteful for big wallets it has been ignored (for now). See the discussion here.

    TODOs

    • ~~Add test cases~~
    • ~~Add helper function adding addresses as watch-only to the node~~
    • ~~Add documentation~~
    • ~~Check SSL to allow self-signed certs (rpcssl is deprecated, see https://bitcoin.org/en/release/v0.12.0#rpc-ssl-support-dropped)~~
    opened by bjarnemagnussen 19
  • Fixes testing network APIs + adds 3 new APIs (btc.com, blockchair.com and blockstream.info)

    Fixes testing network APIs + adds 3 new APIs (btc.com, blockchair.com and blockstream.info)

    Due to time-out errors adding more network API's makes it even more difficult to pass all the tests. This problem still persists with this PR and may make it worse due to the three new APIs!

    Fix for testing balance > 0

    This PR fixes the testing error from test_get_balance_main_used inside BitpayAPI, BlockchainAPI and SmartbitAPI.

    The reason was that the address being checked was used up and has a balance of 0, while the tests are asserting that the balance must be greater than 0.

    It has been fixed by referring to Counterparty's burn-of-proof address 1CounterpartyXXXXXXXXXXXXXXXUWLpVr and should therefore always have a balance greater than 0.

    Adding network APIs

    The PR further adds three new network APIs:

    • Btc.com,
    • Blockstream.info, and
    • Blockchair.com.

    Blockchair was the most straight-forward to implement as it includes a "context" with each response that is very useful in case the immediate response does not include information that we need (e.g. confirmations, scriptPubKey, etc.). However for the first two APIs there were minor issues that I want to mention and eventually discuss:

    1. For the new BTCcomAPI and BlockstreamAPI: When unspents are returned the scriptPubKey of the address is not included with the response. We must therefore calculate it from the address using our helper function address_to_scriptpubkey found inside bit.transaction.
    2. For the new BlockstreamAPI: When unspents are returned it will include the block number the transaction was confirmed in, but neither include the number of confirmations nor the current block height. We must therefore first poll the current block height to then be able to calculate the confirmations for each unspent transaction returned.
    3. For the new BlockstreamAPI: Returned unspents are not sorted by any metric and appear to be random. To compare them directly with unspents returned from other APIs the returned unspents are immediately sorted by their confirmation number.

    Future development

    If this PR has been checked and should be approved, then the next step will be to add a features-supported functionality, allowing NetworkAPI to poll the APIs with required features supported depending on the use-case, e.g. for bech32 addresses.

    opened by bjarnemagnussen 18
  • How do you generate a public address?

    How do you generate a public address?

    I'm not sure where else to ask, but I can't seem to generate a public address(for sending transactions). According to your wiki after generating a private key via key = Key() I should be able to use the address attribute. but key.address give back the private key again and key.public_key generates something unusable (at least by a novice).

    What am I doing wrong?

    opened by linux-mining 16
  • How to estimate tx fee?

    How to estimate tx fee?

    Hello,

    I know the content of a balance, a quantity and I have 3 outputs: A, B and C and I'm using a segwit address. My quantity is at least equals to my balance.

    • I want to send 1% of the quantity to A. if my balance is superior enough to my quantity:
    • I want to send 99% (the rest of the quantity) to B.
    • Use C as a leftover address (the tx fee will be deducted from what he will receive) else:
    • I will use B as a leftover address, so he will receive 99% minus the tx fee. C will not receive anything

    My question is: how to detect my balance is sufficient to send the rest of the quantity, pay the fees and add a leftover? I looked into the code and found this: https://github.com/ofek/bit/blob/defa2e6b9afe9f45e5d0928489dcfc888a706d81/bit/transaction.py#L180

    But I don't understand how to use it (I think it is not in the documentation).

    Thanks for your help, Thomas

    opened by Th0rgal 13
  • ImportError: No module named 'coincurve'

    ImportError: No module named 'coincurve'

    When I go to run a program based on this, I get: Traceback (most recent call last): File "C:\Users*\Desktop\bit-master\bitcoin2.py", line 1, in from bit import Key File "C:\Users*\Desktop\bit-master\bit_init_.py", line 1, in from bit.format import verify_sig File "C:\Users***\Desktop\bit-master\bit\format.py", line 2, in from coincurve import * ImportError: No module named 'coincurve'

    The problem is I imported coincurve directly into my folder as well as installing it with pip. Further I tried to look for verify_sig anywhere and could not find it.

    opened by vivosmith 11
  • API fixes

    API fixes

    In continuation of #86

    • Removes Bitpay API
    • Adds three new APIs
    • Adds new test address with many unspents and guaranteed > 0 balance
    • Increases timeout for network testing
    opened by bjarnemagnussen 10
  • Local node support

    Local node support

    Hi,

    This seems to be the only sanest python bitcoin library. Truely, great work there.

    I would love to use this library but unfortunately local nodes are not supported.

    Do you have any timeline to support the local nodes?

    Do you need funding or donation?

    Please, let me know.

    opened by johndoe123445 10
  • Generating multisig addresses

    Generating multisig addresses

    I'm working on escrow/multisig system. Bit is great and I'd be sad to not implement it just because it doesn't support generating multisig addresses. I understand this behavior might not be the priority (https://github.com/ofek/bit/issues/6), but here I go.

    I plan to use couple of Multisig instances, which will share the same Key as private_key, as all the paths the trade could get. For this it should be enough to write function which will calculate the appropriate values for this universal Key: address, public_key etc.. Am I thinking right or is it more complicated?

    Thanks.

    opened by xplsek03 9
  • ConnectionError: Transaction broadcast failed, or Unspents were already used.

    ConnectionError: Transaction broadcast failed, or Unspents were already used.

    Hi everyone,

    I make a transaction with this code:

    txHex = my_key.send([(to, amount,'btc')])

    Yesterday works fine for me but today, impossible, I get this message: ConnectionError: Transaction broadcast failed, or Unspents were already used.

    And I have founds inside, in fact finally, I make a transaction with Coinomi Wallets and works perfect...

    Any idea??

    Thanks

    opened by cibermosso 0
  • Ubuntu 22.04 - ValueError: unsupported hash type ripemd160

    Ubuntu 22.04 - ValueError: unsupported hash type ripemd160

    Using Ubuntun 22.04 and Python 3.10.6 the code throws an error

    my_key = PrivateKeyTestnet()
    print(my_key.address)
    
    
     File "/home/user/.local/lib/python3.10/site-packages/bit/wallet.py", line 572, in address
        self._address = public_key_to_address(self._public_key, version=self.version)
      File "/home/user/.local/lib/python3.10/site-packages/bit/format.py", line 121, in public_key_to_address
        return b58encode_check(version + ripemd160_sha256(public_key))
      File "/home/user/.local/lib/python3.10/site-packages/bit/crypto.py", line 19, in ripemd160_sha256
        return new('ripemd160', sha256(bytestr)).digest()
      File "/usr/lib/python3.10/hashlib.py", line 166, in __hash_new
        return __get_builtin_constructor(name)(data)
      File "/usr/lib/python3.10/hashlib.py", line 123, in __get_builtin_constructor
        raise ValueError('unsupported hash type ' + name)
    ValueError: unsupported hash type ripemd160
    

    Using same code in virtual env python3.9 does work.

    opened by reisenmachtfreude 1
  • logging in your project will damage other logging's output format

    logging in your project will damage other logging's output format

    Hi ofek! Your peoject uselogging.debug directly to print debug log, if I defind a logger in my project using code

    logger = logging.getLogger("MyLog")
    handler  = logging.StreamHandler()
    handler.setFormatter(logging.Formatter("%(asctime)s|%(levelname)s|%(name)s|%(message)s"))
    logger.addHandler(handler)
    logger.setLevel(logging.DEBUG)
    logger.debug('some debug info')
    

    This will print a normal debug info : 2022-07-12 14:38:40,173 DEBUG MyLog some debug info Then I import bit to my project and send some coin

    from bit import Key
    my_key = Key(...)
    outputs=[....]
    my_key.send(outputs)
    

    If I run logger.debug('some debug info') again, it will output 2 lines as below

    2022-07-12 14:41:10,353	DEBUG	MyLog	some debug info
    DEBUG:MyLog:some debug info
    

    Because in bit.transaction.estimate_tx_fee you used logging.debug to print debug info, which corrupted my project logger,kindly recommend you to defind a logger in other py file and then import and use it

    opened by dc3l1ne 2
  • How to instantiate MultiSigTestnet to create a MultiSig 2 of 3?

    How to instantiate MultiSigTestnet to create a MultiSig 2 of 3?

    In the official documentation they do not address the issue of creating a multisignature in depth. For example, they only show these 2 lines of code: tx_1 = multisig1.create_transaction([('1Archive1n2C579dMsAu3iC6tWzuQJz8dN', 190, 'jpy')]) tx_2 = multisig2.sign_transaction(tx_1)

    When we look at the parameters that MultiSigTestnet receives, we see a private key, a list of public keys, and the number of signatures needed. I assume that I get the private key from an instance of PrivateKeyTestnet, but where do I get the list of public keys from? Ex. user1_key = PrivateKeyTestnet() user2_key = PrivateKeyTestnet() user3_key = PrivateKeyTestnet() multisig = MultiSigTestnet(user1_key,[user1_key.public_key, user2_key.public_key, user3_key.public_key],2)

    I think the above is wrong. I will appreciate any help

    opened by Pep3M 0
  • Can't get balance and public key calculated wrong?

    Can't get balance and public key calculated wrong?

    I am quite new to this but the documentation seemed quite straightforward so I don't understand where did I mess up or what's happening here.

    from bit import PrivateKey
    
    key = PrivateKey('PrivateKeyFromExodusWallet')
    
    print(key.address)
    print(key.get_balance('btc'))
    print(key.balance)
    

    The address that is shown is wrong. My actual address for that private key: bc1qx34ptd6jldlge63tk5cvvfksg9dj8x8ehvtys9 What the print shows: 15n9DswZzpYZ6QyNzToUtZinbQB3jUdGTS

    Balance is also 0 but shouldn't be. I am using Exodus wallet. I can't see where I messed up here so can someone please help me out?

    opened by eriktlu 1
Owner
Ofek Lev
I like developing beautiful APIs.
Ofek Lev
Mizogg-Bitcoin-Tools - A Python Tools for Bitcoin Information Balance, HASH160, DEC

Mizogg-Bitcoin-Tools Tools for Bitcoin Information Balance, HASH160, DEC, Englis

null 38 Nov 18, 2022
Generate bitcoin public and private keys and check if they match a filelist of existing addresses that have a nonzero balance

btc-heist Running Install deps, i.e., python3 -m pip install -r requirements.txt Download the CSV dump of all bitcoin addresses with a balance and cut

Denis Khoshaba 100 Nov 15, 2022
Bsvlib - Bitcoin SV (BSV) Python Library

bsvlib A Bitcoin SV (BSV) Python Library that is extremely simple to use but mor

Aaron 22 May 6, 2022
Looks for Bitcoin Wallets starting 1 compresses and Uncompressesed, segwit address and MultiSig starting 3.

Looks for Bitcoin Wallets starting 1 compresses and Uncompressesed, segwit address and MultiSig starting 3. Pick your starting and stop numbers to start looking. Need a database of addresses to check. Made with https://pypi.org/project/PySimpleGUI/

null 8 Nov 5, 2022
Create and finder all address wallet bitcoin and check balance , transaction

BTCCrackWallet Create and finder all address wallet bitcoin and check balance , transaction bitcoin wallet generator generated address wallet , public

MMDRZA 11 Nov 26, 2022
Accept Bitcoin donations on Twitch, and integrate them into your alerts!

The system in action Check out how seamlessly the project works! Support the project You can tip me with some sats here!

Fitti 26 Aug 31, 2022
Connects to an active BitCoin Peer and communicates in order to locate a specific block number (height)

BitCoin-Peer-Client Connects to an active BitCoin Peer, and locates a predetermined block number (height) by downloading block headers. Once required

Henry Song 1 Jan 16, 2022
Bitcoin Clipper malware made in Python.

a BTC Clipper or a "Bitcoin Clipper" is a type of malware designed to target cryptocurrency transactions.

Nightfall 88 Oct 6, 2022
The Intelligent Bitcoin Miner, Part II

The Intelligent Bitcoin Miner, Part II At a Glance This app simulates the behavior and profitability of Bitcoin miners for The Intelligent Bitcoin Min

Karim Helmy 21 Jul 3, 2022
ūüďäPython implementation of the Colin Talks Crypto Bitcoin Bull Run Index (CBBI).

Colin Talks Crypto Bitcoin Bull Run Index (CBBI) This is a Python implementation of the Colin Talks Crypto Bitcoin Bull Run Index (CBBI). It makes use

Kamil Monicz 82 Nov 19, 2022
This is a simple Bitcoin non-deterministic wallet address generator coded in Python 3.

This is a simple Bitcoin non-deterministic wallet address generator coded in Python 3. It generates a Private Key in different formats (hex, wif and compressed wif) and corresponding Public Addresses, raw, P2WPKH addresses starting with prefix 1, P2SH addresses starting with prefix 3 as part of Segwit soft fork and Bech32 addresses with prefix bc1 P2WPKH and P2WSH.

null 5 Nov 5, 2022
Bitcoin Wallet Address Generator

Bitcoin Wallet Address Generator This is a simple Bitcoin non-deterministic wallet address generator coded in Python 3. It generates a Private Key in different formats (hex, wif and compressed wif) and corresponding Public Addresses, raw, P2WPKH addresses starting with prefix 1, P2SH addresses starting with prefix 3 as part of Segwit soft fork and Bech32 addresses with prefix bc1 P2WPKH and P2WSH.

null 8 Nov 5, 2022
Address Validator (Bitcoin & Monero)

The Bitcoin address is an identifier of 26-35 alphanumeric characters, beginning with the number 1, 3 or bc1. 0, O, I, l are removed to avoid visual a

null 0 Mar 29, 2022
Simple bitcoin ticker for the Pimorono Inky pHAT Red.

bitcoin-ticker Simple bitcoin ticker for the Pimorono Inky pHAT Red. Equipment Raspberry Pi Zero W v1.1 or Pi 2 model b v1.1 Pimorono Inky pHAT Red (S

null 2 Mar 15, 2022
SimpleWallet - Simple wallet for Bitcoin

Simple Wallet This is a basic python starter package to be used as a template fo

Mystic 1 Jan 8, 2022
BlockVis - Create beautiful visualizations of Bitcoin Blockheaders

BlockVis Create beautiful visualizations of Bitcoin Blockheaders How to run To r

Egge 2 Jan 5, 2022
Bitcoin & Lightning Container Manager for facilitating development tools

Torch-cli Bitcoin & Lightning Container Manager for facilitating development too

Gray Finance 3 Aug 22, 2022
Aplicação de monitoramento de valores de criptos através da API do Mercado Bitcoin.

myCrypto_MercadoBitcoin Aplicação de monitoramento de valores de criptos através da API do Mercado Bitcoin. Apoie esse projeto! ?? ?? Olá! Você pode r

Vinícius Azevedo 121 Oct 26, 2022
Tink is a multi-language, cross-platform, open source library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse.

Tink A multi-language, cross-platform library that provides cryptographic APIs that are secure, easy to use correctly, and hard(er) to misuse. Ubuntu

Google 12.8k Nov 23, 2022