### Create and activate a virtual environment Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md It is recommended to use a virtual environment for installing BitcoinLib. This example shows how to create and activate one on Linux using virtualenv. ```bash virtualenv -p ~/.virtualenvs/bitcoinlib source ~/.virtualenvs/bitcoinlib/bin/activate ``` -------------------------------- ### Install BitcoinLib on Ubuntu Source: https://github.com/1200wd/bitcoinlib/blob/master/README.rst Installs necessary packages on Ubuntu and then installs the bitcoinlib using pip. ```bash $ sudo apt install build-essential python3-dev libgmp3-dev ``` ```bash $ pip install bitcoinlib ``` -------------------------------- ### Run BitcoinLib unittests Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md After installation, you can run all unit tests to verify the installation. This command should be executed from the root of the cloned repository. ```bash python -m unittest ``` -------------------------------- ### Install BitcoinLib from source Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md Clone the repository and install BitcoinLib using pip. This method is useful for development or when needing the latest unreleased features. ```bash git clone https://github.com/1200wd/bitcoinlib.git cd bitcoinlib python -m pip install . ``` -------------------------------- ### Install BitcoinLib with development dependencies Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md Install BitcoinLib along with extra dependencies required for development, including database support. ```bash python -m pip install .[dev] ``` -------------------------------- ### Install Bcoin Docker Image Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bcoin.md Use this command to pull the optimized Bcoin Docker image for use with Bitcoinlib. ```bash docker pull blocksmurfer/bcoin ``` -------------------------------- ### Create and Sign a Multi-signature Transaction Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.command-line-wallet.md This example demonstrates creating a transaction in a multi-signature wallet, exporting its dictionary, and then importing it into another wallet to complete the signing process. ```bash $ clw -w ms22 -s blt1qxu6z7evkrmz5s7sk63dr0u3h9xsf2j2vys88reg75cjvjuz4vf2srkxp7p 0.1 ``` ```bash $ clw new -w multisig-2-2-signer2 -n bitcoinlib_test -m 2 2 BC18rEEZrakM87qWbSSUv19vnRkEFL7ZtNtGx3exB886VbeFZp6aq9JLZucYAj1EtsHKUB2mkjvafCCGaeYeUVtdFcz5xTxTTgEPCE8fDC8LcahM BC19UtECk2r9PVQYhaAa8kEgBMPWHC4fJVJD48zBMMb9gSpY9LQVvQ1HhzB3Xmkm2BpiH5SyWoboiewpbeexPLsw8QBfAqMbDfet6kLhedtfQF8r ``` ```bash $ clw -w multisig-2-2-signer2 -r ``` ```bash $ clw -w multisig-2-2-signer2 -x ``` ```bash $ clw -w multisig-2-2-signer2 -a tx.tx ``` -------------------------------- ### Install SQLCipher Packages Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.sqlcipher.md Install the necessary SQLCipher packages on Ubuntu. Refer to the official SQLCipher documentation for other systems. ```bash $ sudo apt install sqlcipher libsqlcipher0 libsqlcipher-dev $ pip install sqlcipher3-binary ``` -------------------------------- ### Bitcoin Node Configuration (bitcoin.conf) Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bitcoind-connection.md Example settings for a bitcoin.conf file for testnet. For mainnet, use port 8332 and remove 'testnet=1'. Ensure server and txindex are set to 1. ```text server=1 port=18332 txindex=1 testnet=1 rpcauth=bitcoinlib:01cf8eb434e3c9434e244daf3fc1cc71$9cdfb346b76935569683c12858e13147eb5322399580ba51d2d878148a880d1d rpcbind=0.0.0.0 rpcallowip=192.168.0.0/24 ``` -------------------------------- ### Install BitcoinLib with pip Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md Use this command to install the latest stable version of BitcoinLib from the Python Package Index. ```none $ pip install bitcoinlib ``` -------------------------------- ### Bitcoinlib Provider Configuration (providers.json) Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bitcoind-connection.md Example JSON configuration for connecting bitcoinlib to a testnet bitcoind node via the service provider settings. ```json { "bitcoind.testnet": { "provider": "bitcoind", "network": "testnet", "client_class": "BitcoindClient", "url": "http://user:password@server_url:18332", "api_key": "", "priority": 11, "denominator": 100000000, "network_overrides": null, "timeout": 0 } } ``` -------------------------------- ### Create Bitcoin Wallet and Generate Address Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.html Creates a new Bitcoin wallet named 'Wallet1' and generates a new receiving address. Use this to start managing your Bitcoin. ```python from bitcoinlib.wallets import Wallet w = Wallet.create('Wallet1') key1 = w.get_key() print(key1.address) ``` -------------------------------- ### Send a Transaction with BitcoinLib Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Use the `send_to()` method on a wallet object to create, sign, and broadcast a transaction. This example sends 4000 satoshis with a fee of 1000 satoshis to a specified address. ```python from bitcoinlib.wallets import wallet_create_or_open w = wallet_create_or_open('bitcoinlib-testnet1', network='testnet', witness_type='segwit') t = w.send_to('tb1qprqnf4dqwuphxs9xqpzkjdgled6eeptn389nec', 4000, fee=1000) t.info() ``` -------------------------------- ### Configure ElectrumX Provider in providers.json Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.setup-electrumx.md Add this JSON configuration to your providers.json file to connect Bitcoinlib to a local ElectrumX instance. Adjust the URL and port as necessary for your setup. Increase priority to ensure it's the default provider. ```json "localhost.electrumx": { "provider": "electrumx", "network": "bitcoin", "client_class": "ElectrumxClient", "provider_coin_id": "", "url": "localhost:50001", "api_key": "", "priority": 100, "denominator": 1, "network_overrides": null } ``` -------------------------------- ### Configure ElectrumX Provider in providers.json Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-electrumx.md Add this JSON configuration to your .bitcoinlib/providers.json file to connect Bitcoinlib to a local ElectrumX instance. Adjust the URL and port as necessary for your ElectrumX server setup. ```json { "localhost.electrumx": { "provider": "electrumx", "network": "bitcoin", "client_class": "ElectrumxClient", "provider_coin_id": "", "url": "localhost:50001", "api_key": "", "priority": 100, "denominator": 1, "network_overrides": null } } ``` -------------------------------- ### Create a New Bitcoin Wallet via Command Line Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.md Shows how to create a new Bitcoin wallet using the BitcoinLib command-line tool. It includes the process of setting a passphrase and confirms wallet creation. ```bash $ python bitcoinlib/tools/clw.py new -w newwallet Command Line Wallet - BitcoinLib 0.6.29 CREATE wallet 'newwallet' (bitcoin network) Passphrase: sibling undo gift cat garage survey taxi index admit odor surface waste Please write down on paper and backup. With this key you can restore your wallet and all keys Type 'yes' if you understood and wrote down your key: yes Wallet info for newwallet === WALLET === ID 21 Name newwallet Owner Scheme bip32 Multisig False Witness type segwit Main network bitcoin Latest update None = Wallet Master Key = ID 177 Private True Depth 0 - NETWORK: bitcoin - - - Keys 182 m/84`/0`/0`/0/0 bc1qza24j7snqlmx7603z8qplm4rzfkr0p0mneraqv address index 0 0.00000000 ₿ - - Transactions Account 0 (0) = Balance Totals (includes unconfirmed) = ``` -------------------------------- ### Create Wallet and Generate Address Source: https://github.com/1200wd/bitcoinlib/blob/master/README.rst Demonstrates creating a new wallet named 'Wallet1' and generating a new Bitcoin address for receiving funds. ```python >>> from bitcoinlib.wallets import Wallet >>> w = Wallet.create('Wallet1') >>> w.get_key().address 'bc1qk25wwkvz3am9smmm3372xct5s7cwf0hmnq8szj' ``` -------------------------------- ### Upgrade BitcoinLib with pip Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md Use this command to upgrade an existing installation of BitcoinLib to the latest version available on PyPI. ```none $ pip install bitcoinlib --upgrade ``` -------------------------------- ### Build and Run Bitcoinlib Docker Container Source: https://github.com/1200wd/bitcoinlib/blob/master/docker/README.rst Use these commands to build a Docker image from a Dockerfile and then run the container. The container will execute all unittests upon startup. ```bash $ cd $ docker build -t bitcoinlib . $ docker run -it bitcoinlib ``` -------------------------------- ### Remove Install Log Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.install.md Delete the '.bitcoinlib/install.log' file to force an update of configuration files with new versions. This is typically done after upgrading BitcoinLib. ```none $ rm .bitcoinlib/install.log ``` -------------------------------- ### Create New Bitcoin Wallet via CLI Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.html Illustrates the command-line interface for creating a new Bitcoin wallet. It prompts for confirmation and displays the generated mnemonic phrase. ```bash $ 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 ``` -------------------------------- ### Connect to MySQL Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.databases.md Instantiate a wallet using a MySQL database by providing the connection URI. The database tables will be created automatically upon the first application run. ```python db_uri = 'mysql://bitcoinlib:secret@localhost:3306/bitcoinlib' w = wallet_create_or_open('wallet_mysql', db_uri=db_uri) w.info() ``` -------------------------------- ### Import New Service Class Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.add-provider.md Add the newly created service class to the bitcoinlib.services.__init__.py file to make it available for use. ```python import bitcoinlib.services.bitgo ``` -------------------------------- ### Get Estimated Transaction Fee Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.html Retrieves the estimated transaction fee in Satoshis per Kilobyte for confirmation within a specified number of blocks using the Service module. ```python from bitcoinlib.services.services import Service Service().estimatefee(5) ``` -------------------------------- ### Create or Open a Testnet Segwit Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Use `wallet_create_or_open` for a testnet segwit wallet. This is useful when you are unsure if the wallet already exists. It generates a new key and prints a deposit address. ```python from bitcoinlib.wallets import wallet_create_or_open w = wallet_create_or_open('bitcoinlib-testnet1', network='testnet', witness_type='segwit') wk = w.new_key() print("Deposit to address %s to get started" % wk.address) ``` -------------------------------- ### Generate Receive Address Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Use the '-r' or '--receive' option with your wallet to display an unused address for receiving funds. QR codes can be displayed if the 'pyqrcode' module is installed. ```none $ clw -w mywallet -r Command Line Wallet for BitcoinLib Receive address is bc1qza24j7snqlmx7603z8qplm4rzfkr0p0mneraqv ``` -------------------------------- ### Create a Bitcoin Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Use the `Wallet.create()` method to initialize a new wallet with a given name. This method will raise an error if the wallet already exists. ```python from bitcoinlib.wallets import Wallet w = Wallet.create('jupyter-test-wallet') w.info() ``` -------------------------------- ### Create Key from WIF Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Initializes a Key object from a provided Wallet Import Format (WIF) string and prints its associated Bitcoin address. ```python from bitcoinlib.keys import Key wif = 'KyAoQkmmoAgdC8YXamgpqFb2R8j6g5jiBnGdJo62aDJCxstboTqS' k = Key(wif) print(k.address()) ``` -------------------------------- ### Create a New Service Client Class Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.add-provider.md Implement a new client class inheriting from BaseClient to handle requests for the new provider. This includes defining initialization and request composition logic. ```python from bitcoinlib.services.baseclient import BaseClient PROVIDERNAME = 'bitgo' class BitGoClient(BaseClient): def __init__(self, network, base_url, denominator, api_key=''): super(self.__class__, self). __init__(network, PROVIDERNAME, base_url, denominator, api_key) def compose_request(self, category, data, cmd='', variables=None, method='get'): if data: data = '/' + data url_path = category + data if cmd: url_path += '/' + cmd return self.request(url_path, variables, method=method) def estimatefee(self, blocks): res = self.compose_request('tx', 'fee', variables={'numBlocks': blocks}) return res['feePerKb'] ``` -------------------------------- ### Create a 2-of-2 Multisig Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Use the `new` command with the `-w` flag to name the wallet, `-n` for the network, and specify the required number of signatures (`-m 2`) and the total number of cosigners (`2`). Provide the public master keys of the cosigners. ```bash $ clw new -w multisig-2-2 -n bitcoinlib_test -m 2 2 BC19UtECk2r9PVQYhY4yboRf92XKEnKZf9hQEd1qBqCgQ98HkBeysLPqYewcWDUuaBRSSVXCShDfmhpbtgZ33sWeGPqfwoLwamzPEcnfwLoeqfQM BC18rEEvE8begagfJs7kdxx1yW9tFsz7879c9vQQ2mnGbF6WSeKuBEGtmxJYLEy8rpVV9wXffbBtnL1LPKZqujPtEKzHqQeERiRybKB3DRBBoSFH Command Line Wallet - BitcoinLib 0.6.14 CREATE wallet 'ms22' (bitcoinlib_test network) Wallet info for ms22 === WALLET === ID 22 Name ms22 Owner Scheme bip32 Multisig True Multisig Wallet IDs 23, 24 Cosigner ID 1 Witness type segwit Main network bitcoinlib_test Latest update None = Multisig Public Master Keys = 0 183 BC18rEEvE8begagfJs7kdxx1yW9tFsz7879c9vQQ2mnGbF6WSeKuBEGtmxJYLEy8rpVV9wXffbBtnL1LPKZqujPtEKzHqQeERiRybKB3DRBBoSFH bip32 cosigner 1 186 BC18rEEZrakM87qWbSSUv19vnRkEFL7ZtNtGx3exB886VbeFZp6aq9JLZucYAj1EtsHKUB2mkjvafCCGaeYeUVtdFcz5xTxTTgEPCE8fDC8LcahM bip32 main * For main keys a private master key is available in this wallet to sign transactions. * cosigner key for this wallet - NETWORK: bitcoinlib_test - - - Keys - - Transactions Account 0 (0) = Balance Totals (includes unconfirmed) = ``` -------------------------------- ### Retrieve Blockchain Information and Statistics Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bitcoind-connection.md Example Python code to fetch blockchain data and node statistics using a connected BitcoindClient instance. This includes general chain info, transaction stats, and mempool details. ```python from bitcoinlib.services.bitcoind import BitcoindClient # Retrieve some blockchain information and statistics bdc.proxy.getblockchaininfo() bdc.proxy.getchaintxstats() bdc.proxy.getmempoolinfo() # Add a node to the node list bdc.proxy.addnode('blocksmurfer.io', 'add') ``` -------------------------------- ### Encrypt and Decrypt a Key Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Demonstrates encrypting a private key with a password and then importing the encrypted WIF to retrieve the original private key. ```python from bitcoinlib.keys import Key k = Key() print(k.private_hex) encrypted_wif = k.encrypt('secret') print(encrypted_wif) k_import = Key(encrypted_wif, password='secret') print(k_import.private_hex) ``` -------------------------------- ### Generate a Receiving Address for a Multisig Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Use the `-r` flag with your specified wallet (`-w ms22`) to generate a new receiving address for the multisig wallet. You may need to install the `pyqrcode` module to display QR codes. ```bash $ clw -w ms22 -r Command Line Wallet - BitcoinLib 0.6.14 Receive address: blt1qxu6z7evkrmz5s7sk63dr0u3h9xsf2j2vys88reg75cjvjuz4vf2srkxp7p Install qr code module to show QR codes: pip install pyqrcode ``` -------------------------------- ### Create a New Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.command-line-wallet.md Use this command to create a new wallet. Specify the wallet name and optionally set the password, network, and witness type. ```bash clw.py new --wallet_name my_wallet --network testnet --witness-type segwit ``` -------------------------------- ### Create a New Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Use the 'new' command with a wallet name to create a new wallet. You will be prompted to set a passphrase and confirm understanding. ```none $ clw new -w mywallet CREATE wallet 'newwallet' (bitcoin network) Passphrase: sibling undo gift cat garage survey taxi index admit odor surface waste Please write it down on paper and backup. With this key you can restore your wallet and all keys Type 'yes' if you understood and wrote down your key: yes Wallet info for newwallet === WALLET === ID 21 Name newwallet Owner Scheme bip32 Multisig False Witness type segwit Main network bitcoin Latest update None = Wallet Master Key = ID 177 Private True Depth 0 - NETWORK: bitcoin - - - Keys 182 m/84'/0'/0'/0/0 bc1qza24j7snqlmx7603z8qplm4rzfkr0p0mneraqv address index 0 0.00000000 ₿ - - Transactions Account 0 (0) = Balance Totals (includes unconfirmed) = ``` -------------------------------- ### Test New Provider Integration Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.add-provider.md Instantiate the Service class with the new provider and test its methods, such as estimatefee. Ensure the library is re-initialized after adding new providers. ```python from bitcoinlib import services srv = Service(providers=['blockchair']) print(srv.estimatefee(5)) ``` -------------------------------- ### Create a New Multisig Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Use the `new` command with the `-m` option to create a multisig wallet. Specify the number of signatures required, the total number of keys, and then provide the public or private keys. If a key is not provided, it will be generated. ```bash clw.py new -m 2 2 tprv8ZgxMBicQKsPd1Q44tfDiZC98iYouKRC2CzjT3HGt1yYw2zuX2awTotzGAZQEAU9bi2M5MCj8iedP9MREPjUgpDEBwBgGi2C8eK5zNYeiX8 tprv8ZgxMBicQKsPeUbMS6kswJc11zgVEXUnUZuGo3bF6bBrAg1ieFfUdPc9UHqbD5HcXizThrcKike1c4z6xHrz6MWGwy8L6YKVbgJMeQHdWDp ``` -------------------------------- ### Create and Configure a New Multi-signature Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md This command creates a new multi-signature wallet, specifying the network, the required number of signatures, and the public keys of the participants. It also generates a receive address and updates UTXOs. ```bash $ clw new -w multisig-2-2-signer2 -n bitcoinlib_test -m 2 2 BC18rEEZrakM87qWbSSUv19vnRkEFL7ZtNtGx3exB886VbeFZp6aq9JLZucYAj1EtsHKUB2mkjvafCCGaeYeUVtdFcz5xTxTTgEPCE8fDC8LcahM BC19UtECk2r9PVQYhaAa8kEgBMPWHC4fJVJD48zBMMb9gSpY9LQVvQ1HhzB3Xmkm2BpiH5SyWoboiewpbeexPLsw8QBfAqMbDfet6kLhedtfQF8r ``` ```bash $ clw -w multisig-2-2-signer2 -r ``` ```bash $ clw -w multisig-2-2-signer2 -x ``` -------------------------------- ### Create Multisig Wallet and Transaction Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.html Demonstrates creating a 2-of-2 multisig wallet, sweeping funds into it, and then importing, signing, and sending the transaction from a second wallet. ```python 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) ``` ```python w1.utxos_update() t = w1.sweep('mwCwTceJvYV27KXBc3NJZys6CjsgsoeHmf', min_confirms=0) t.info() ``` ```python w2.get_key() t2 = w2.transaction_import(t) t2.sign() t2.send() t2.info() ``` -------------------------------- ### Connect to Bitcoind using base_url Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bitcoind-connection.md Instantiate BitcoindClient directly with a base_url, which includes authentication credentials. This method offers flexibility but requires secure handling of sensitive information. ```python from bitcoinlib.services.bitcoind import BitcoindClient base_url = 'http://user:password@server_url:18332' bdc = BitcoindClient(base_url=base_url) txid = 'e0cee8955f516d5ed333d081a4e2f55b999debfff91a49e8123d20f7ed647ac5' rt = bdc.getrawtransaction(txid) print("Raw: %s" % rt) ``` -------------------------------- ### Create a Simple Bitcoin Transaction Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Demonstrates creating a new transaction, adding an input, and adding an output with a new address. Use this for basic transaction construction. ```python from bitcoinlib.transactions import Transaction from bitcoinlib.keys import HDKey t = Transaction() prev_hash = '9c81f44c29ff0226f835cd0a8a2f2a7eca6db52a711f8211b566fd15d3e0e8d4' t.add_input(prev_hash, output_n=0) k = HDKey() t.add_output(100000, k.address()) t.info() ``` -------------------------------- ### Create MySQL Database Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.databases.md Use this command in the MySQL prompt to create a new database for Bitcoinlib. Ensure the database name matches the one specified in your connection URI. ```mysql mysql> create database bitcoinlib; ``` -------------------------------- ### Create PostgreSQL User and Database Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.databases.md This bash script demonstrates creating a PostgreSQL user and database. It prompts for user details and database creation. Ensure you are logged in as the postgres user. ```bash $ su - postgres postgres@localhost:~$ createuser --interactive --pwprompt Enter name of role to add: bitcoinlib Enter password for new role: Enter it again: Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) n Shall the new role be allowed to create more new roles? (y/n) n $ createdb bitcoinlib ``` -------------------------------- ### Create PostgreSQL Database Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.databases.md Create a new PostgreSQL database named 'bitcoinlib' after creating the user. This command is executed from the shell. ```bash $ createdb bitcoinlib ``` -------------------------------- ### Add Provider Settings to providers.json Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.add-provider.md Define the configuration for a new service provider in the providers.json file. Ensure all required fields like provider name, network, client class, and URL are correctly set. ```json { "bitgo": { "provider": "bitgo", "network": "bitcoin", "client_class": "BitGo", "provider_coin_id": "", "url": "https://www.bitgo.com/api/v1/", "api_key": "", "priority": 10, "denominator": 1, "network_overrides": null, "timeout": 0 } } ``` -------------------------------- ### Run specific unittests Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md If you have uninstalled SQLAlchemy or are running without database support, you can run specific unittests, such as those for key management. ```bash python -m pip unittest tests/test_keys.py ``` -------------------------------- ### Create MySQL User and Grant Privileges Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.databases.md Create a dedicated user for your application in MySQL and grant it all necessary privileges on the bitcoinlib database. Remember to replace 'secret' with a strong password. ```mysql mysql> create user bitcoinlib@localhost identified by 'secret'; mysql> grant all on bitcoinlib.* to bitcoinlib@localhost with grant option; ``` -------------------------------- ### Create 2-of-2 Multisignature Wallets Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.md Sets up two multisignature wallets with 2 cosigners. Each wallet requires both cosigners to sign a transaction. The deposit address for the first wallet is printed. ```python 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) ``` -------------------------------- ### Configure Bcoin Provider in Bitcoinlib Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.setup-bcoin.md Add these JSON credentials to your `.bitcoinlib/providers.json` file to configure Bitcoinlib to use your Bcoin node. You can increase the priority to ensure it's always used first. ```json "bcoin": { "provider": "bcoin", "network": "bitcoin", "client_class": "BcoinClient", "provider_coin_id": "", "url": "https://user:pass@localhost:8332/", "api_key": "", "priority": 20, "denominator": 100000000, "network_overrides": null, "timeout": 0 }, ``` -------------------------------- ### Create Wallet from Passphrase with Multiple Accounts and Currencies Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/index.md Creates a wallet with specified accounts and networks from a mnemonic passphrase. The passphrase serves as the master key for recovery. ```python 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() ``` -------------------------------- ### Import and Sign a Transaction Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Import a previously created transaction dictionary into the wallet to sign it. This command will update the transaction status and verify signatures. ```bash $ clw -w multisig-2-2-signer2 -a tx.tx ``` -------------------------------- ### Transaction Details After Creation Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md This output shows the details of a newly created transaction, including its inputs, outputs, size, fee, and signature status. Note that it is not yet verified as only one signature is available. ```bash Connected to pydev debugger (build 233.13135.95) Command Line Wallet - BitcoinLib 0.6.14 Transaction created Transaction 3b96f493d189667565271041abbc0efbd8631bb54d76decb90e144bb145fa613 Date: None Network: bitcoinlib_test Version: 1 Witness type: segwit Status: new Verified: False Inputs - blt1qxu6z7evkrmz5s7sk63dr0u3h9xsf2j2vys88reg75cjvjuz4vf2srkxp7p 1.00000000 TST 7b020ae9c7f8ba84a5a5136ae32e6195af5a4f25316f790a1278e04f479ca77d 0 segwit p2sh_multisig; sigs: 1 (2-of-2) not validated Outputs - blt1qxu6z7evkrmz5s7sk63dr0u3h9xsf2j2vys88reg75cjvjuz4vf2srkxp7p 0.10000000 TST p2wsh U - blt1qe4tr993nftagprtapclxrm7ahrcvl4w0dnxfnhz2cx6pjaeg989syy9zge 0.89993601 TST p2wsh U Size: 192 Vsize: 192 Fee: 6399 Confirmations: None Block: None Pushed to network: False Wallet: ms22 Transaction created but not sent yet. Transaction dictionary for export: {} ``` -------------------------------- ### Key for Different Networks and Encodings Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Creates a Key object for the Litecoin network and demonstrates generating addresses in both standard and bech32 (segwit) encodings. ```python from bitcoinlib.keys import Key k = Key(network='litecoin') print(k.address()) print(k.address(encoding='bech32')) ``` -------------------------------- ### Create Encrypted Wallet with Password Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.sqlcipher.md Create or open an encrypted wallet by providing a password directly to the Wallet object. This method uses SQLCipher for full database encryption. ```python password = 'secret' db_uri = '/home/user/.bitcoinlib/database/bcl_encrypted.db' wlt = wallet_create_or_open('bcltestwlt4', network='bitcoinlib_test', db_uri=db_uri, db_password=password) ``` -------------------------------- ### Generate Public Master Keys using Paths Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/bitcoinlib-10-minutes.ipynb Creates a private master HDKey and then derives public master keys using two different methods: one directly and another using a specific BIP32 path. ```python from bitcoinlib.keys import HDKey prv_masterkey = HDKey() pub_masterkey = prv_masterkey.public_master() print("Public masterkey to exchange (method 1): %s" % pub_masterkey.wif()) pub_masterkey = prv_masterkey.key_for_path("m/44'/0'/0'") print("Public masterkey to exchange (method 2): %s" % pub_masterkey.wif()) ``` -------------------------------- ### Create a Multisig Wallet Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/source/_static/manuals.command-line-wallet.md Create a new multisignature wallet by specifying the number of required signatures, the total number of keys, and providing the public or private keys. If private keys are not provided, they will be generated. ```bash clw.py new -m 2 2 tprv8ZgxMBicQKsPd1Q44tfDiZC98iYouKRC2CzjT3HGt1yYw2zuX2awTotzGAZQEAU9bi2M5MCj8iedP9MREPjUgpDEBwBgGi2C8eK5zNYeiX8 tprv8ZgxMBicQKsPeUbMS6kswJc11zgVEXUnUZuGo3bF6bBrAg1ieFfUdPc9UHqbD5HcXizThrcKike1c4z6xHrz6MWGwy8L6YKVbgJMeQHdWDp ``` -------------------------------- ### Restore Wallet with Passphrase Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.command-line-wallet.md Restore or create a wallet using the '--passphrase' option with a new wallet name. Use '-u' or '--update-transactions' to recreate and scan an old wallet, generating new addresses and updating unspent outputs. ```none $ clw new -w mywallet --passphrase "mutual run dynamic armed brown meadow height elbow citizen put industry work" ``` ```none $ clw mywallet -ui ``` -------------------------------- ### Uninstall SQLAlchemy Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md To run BitcoinLib without database support, uninstall the SQLAlchemy module. Note that this will cause some unittests to fail. ```bash python -m pip uninstall sqlalchemy ``` -------------------------------- ### Reset configuration files Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.install.md To ensure configuration files are updated to the latest version after an upgrade, delete the .bitcoinlib/install.log file. This will cause the config files to be overwritten. ```bash rm .bitcoinlib/install.log ``` -------------------------------- ### Connect to PostgreSQL Service with Caching Source: https://github.com/1200wd/bitcoinlib/blob/master/docs/_static/manuals.databases.md Configure a Service object to use PostgreSQL for caching by providing the cache URI. This allows for caching of service requests. ```python srv = Service(cache_uri='postgresql+psycopg://postgres:postgres@localhost:5432/') res = srv.gettransactions('12spqcvLTFhL38oNJDDLfW1GpFGxLdaLCL') ```