bitcoinlib.wallets module

class bitcoinlib.wallets.HDWallet(wallet, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite', session=None, main_key_object=None)[source]

Bases: object

Class to create and manage keys Using the BIP0044 Hierarchical Deterministic wallet definitions, so you can use one Masterkey to generate as much child keys as you want in a structured manner.

You can import keys in many format such as WIF or extended WIF, bytes, hexstring, seeds or private key integer. For the Bitcoin network, Litecoin or any other network you define in the settings.

Easily send and receive transactions. Compose transactions automatically or select unspent outputs.

Each wallet name must be unique and can contain only one cointype and purpose, but practically unlimited accounts and addresses.

Open a wallet with given ID or name

Parameters:
  • wallet (int, str) – Wallet name or ID
  • databasefile (str) – Location of database file. Leave empty to use default
  • session (sqlalchemy.orm.session.Session) – Sqlalchemy session
  • main_key_object (HDKey) – Pass main key object to save time
account(account_id)[source]

Returns wallet key of specific BIP44 account.

Account keys have a BIP44 path depth of 3 and have the format m/purpose’/network’/account’

I.e: Use account(0).key().wif_public() to get wallet’s public account key

Parameters:account_id (int) – ID of account. Default is 0
Return HDWalletKey:
 
accounts(network=None)[source]

Get list of accounts for this wallet

Parameters:network (str) – Network name filter
Return list:List of accounts as HDWalletKey objects
addresslist(account_id=None, used=None, network=None, change=None, depth=5, key_id=None)[source]

Get list of addresses defined in current wallet

Parameters:
  • account_id (int) – Account ID
  • used (bool, None) – Only return used or unused keys
  • network (str) – Network name filter
  • change – Only include change addresses or not. Default is None which returns both
  • depth (int) – Filter by key depth
  • key_id (int) – Key ID to get address of just 1 key
Return list:

List of address strings

balance(account_id=None, network=None, as_string=False)[source]

Get total of unspent outputs

Parameters:
  • account_id (int) – Account ID filter
  • network (str) – Network name. Leave empty for default network
  • as_string (boolean) – Set True to return a string in currency format. Default returns float.
Return float, str:
 

Key balance

balance_update_from_serviceprovider(account_id=None, network=None)[source]

Update balance of currents account addresses using default Service objects getbalance method. Update total wallet balance in database.

Please Note: Does not update UTXO’s or the balance per key! For this use the ‘updatebalance’ method instead

Parameters:
  • account_id (int) – Account ID. Leave empty for default account
  • network (str) – Network name. Leave empty for default network
Return int:

Total balance

classmethod create(name, key='', owner='', network=None, account_id=0, purpose=44, scheme='bip44', parent_id=None, sort_keys=True, password='', witness_type='legacy', encoding=None, databasefile=None)[source]

Create HDWallet and insert in database. Generate masterkey or import key when specified.

Please mention account_id if you are using multiple accounts.

Parameters:
  • name (str) – Unique name of this Wallet
  • key (str, bytes, int, bytearray) – Masterkey to use for this wallet. Will be automatically created if not specified. Can contain all key formats accepted by the HDKey object, a HDKey object or BIP39 passphrase
  • owner (str) – Wallet owner for your own reference
  • network (str) – Network name, use default if not specified
  • account_id (int) – Account ID, default is 0
  • purpose (int) – BIP44 purpose field, default is 44
  • scheme (str) – Key structure type, i.e. BIP44, single or multisig
  • parent_id (int) – Parent Wallet ID used for multisig wallet structures
  • sort_keys (bool) – Sort keys according to BIP45 standard (used for multisig keys)
  • password (str) – Password to protect passphrase, only used if a passphrase is supplied in the ‘key’ argument.
  • witness_type (str) – Specify witness type, default is ‘legacy’. Use ‘segwit’ for native segregated witness wallet, or ‘p2sh-segwit’ for legacy compatible wallets
  • encoding (str) – Encoding used for address generation: base58 or bech32. Default is derive from wallet and/or witness type
  • databasefile (str) – Location of database file. Leave empty to use default
Return HDWallet:
 
classmethod create_multisig(name, key_list, sigs_required=None, owner='', network=None, account_id=0, purpose=45, multisig_compressed=True, sort_keys=True, witness_type='legacy', encoding=None, databasefile=None)[source]

Create a multisig wallet with specified name and list of keys. The list of keys can contain 2 or more public or private keys. For every key a cosigner wallet will be created with a BIP44 key structure or a single key depending on the key_type.

Parameters:
  • name (str) – Unique name of this Wallet
  • key_list (list) – List of keys in HDKey format or any other format supported by HDKey class
  • sigs_required (int) – Number of signatures required for validation. For example 2 for 2-of-3 multisignature. Default is all keys must signed
  • network (str) – Network name, use default if not specified
  • account_id (int) – Account ID, default is 0
  • purpose (int) – BIP44 purpose field, default is 44
  • multisig_compressed (bool) – Use compressed multisig keys for this wallet. Default is True
  • sort_keys (bool) – Sort keys according to BIP45 standard (used for multisig keys)
  • witness_type (str) – Specify wallet type, default is legacy. Use ‘segwit’ for segregated witness wallet.
  • encoding (str) – Encoding used for address generation: base58 or bech32. Default is derive from wallet and/or witness type
  • databasefile (str) – Location of database file. Leave empty to use default
Return HDWallet:
 
dict(detail=3)[source]

Return wallet information in dictionary format

Parameters:detail (int) – Level of detail to show, can be 0, 1, 2 or 3
Return dict:
get_key(account_id=None, network=None, number_of_keys=1, change=0, depth_of_keys=5)[source]

Get a unused key or create a new one if there are no unused keys. Returns a key from this wallet which has no transactions linked to it.

Parameters:
  • account_id (int) – Account ID. Default is last used or created account ID.
  • network (str) – Network name. Leave empty for default network
  • number_of_keys (int) – Number of keys to return. Default is 1
  • change (int) – Payment (0) or change key (1). Default is 0
  • depth_of_keys (int) – Depth of account keys. Default is 5 according to BIP44 standards
Return HDWalletKey:
 
get_key_change(account_id=None, network=None, number_of_keys=1, depth_of_keys=5)[source]

Get a unused change key or create a new one if there are no unused keys. Wrapper for the get_key method

Parameters:
  • account_id (int) – Account ID. Default is last used or created account ID.
  • network (str) – Network name. Leave empty for default network
  • number_of_keys (int) – Number of keys to return. Default is 1
  • depth_of_keys (int) – Depth of account keys. Default is 5 according to BIP44 standards
Return HDWalletKey:
 
get_keys(account_id=None, network=None, change=0, depth_of_keys=5)[source]

Get a unused key or create a new one if there are no unused keys. Returns a key from this wallet which has no transactions linked to it.

Parameters:
  • account_id (int) – Account ID. Default is last used or created account ID.
  • network (str) – Network name. Leave empty for default network
  • change (int) – Payment (0) or change key (1). Default is 0
  • depth_of_keys (int) – Depth of account keys. Default is 5 according to BIP44 standards
Return HDWalletKey:
 
import_key(key, account_id=0, name='', network=None, purpose=44, key_type=None)[source]

Add new single key to wallet.

Parameters:
  • key (str, bytes, int, bytearray) – Key to import
  • account_id (int) – Account ID. Default is last used or created account ID.
  • name (str) – Specify name for key, leave empty for default
  • network (str) – Network name, method will try to extract from key if not specified. Raises warning if network could not be detected
  • purpose (int) – BIP definition used, default is BIP44
  • key_type (str) – Key type of imported key, can be single (unrelated to wallet, bip32, bip44 or master for new or extra master key import. Default is ‘single’
Return HDWalletKey:
 
import_master_key(hdkey, name='Masterkey (imported)')[source]

Import (another) masterkey in this wallet

Parameters:
  • hdkey (HDKey, str) – Private key
  • name (str) – Key name of masterkey
Return HDKey:

Main key as HDKey object

info(detail=3)[source]

Prints wallet information to standard output

Parameters:detail (int) – Level of detail to show. Specify a number between 0 and 4, with 0 low detail and 4 highest detail
key(term)[source]

Return single key with given ID or name as HDWalletKey object

Parameters:term (int, str) – Search term can be key ID, key address, key WIF or key name
Return HDWalletKey:
 Single key as object
key_add_private(wallet_key, private_key)[source]

Change public key in wallet to private key in current HDWallet object and in database

Parameters:
  • wallet_key (HDWalletKey) – Key object of wallet
  • private_key (HDKey, str) – Private key wif or HDKey object
Return HDWalletKey:
 
key_for_path(path, name='', account_id=0, change=0, enable_checks=True)[source]

Create key with specified path. Can be used to create non-default (non-BIP0044) paths.

Can cause problems if already used account ID’s or address indexes are provided.

Parameters:
  • path (str) – Path string in m/#/#/# format. With quote (‘) or (p/P/h/H) character for hardened child key derivation
  • name (str) – Key name to use
  • account_id (int) – Account ID
  • change (int) – Change 0 or 1
  • enable_checks (bool) – Use checks for valid BIP0044 path, default is True
Return HDWalletKey:
 
keys(account_id=None, name=None, key_id=None, change=None, depth=None, used=None, is_private=None, has_balance=None, is_active=True, network=None, as_dict=False)[source]

Search for keys in database. Include 0 or more of account_id, name, key_id, change and depth.

Returns a list of DbKey object or dictionary object if as_dict is True

Parameters:
  • account_id (int) – Search for account ID
  • name (str) – Search for Name
  • key_id (int) – Search for Key ID
  • change (int) – Search for Change
  • depth (int) – Only include keys with this depth
  • used (bool) – Only return used or unused keys
  • is_private (bool) – Only return private keys
  • has_balance (bool) – Only include keys with a balance or without a balance, default is both
  • is_active (bool) – Hide inactive keys. Only include active keys with either a balance or which are unused, default is True
  • network (str) – Network name filter
  • as_dict – Return keys as dictionary objects. Default is False: DbKey objects
Return list:

List of Keys

keys_accounts(account_id=None, network=None, as_dict=False)[source]

Get Database records of account key(s) with for current wallet. Wrapper for the keys() method.

Parameters:
  • account_id (int) – Search for Account ID
  • network (str) – Network name filter
  • as_dict (bool) – Return as dictionary or DbKey object. Default is False: DbKey objects
Return list:

DbKey or dictionaries

keys_address_change(account_id=None, used=None, network=None, as_dict=False)[source]

Get payment addresses (change=1) of specified account_id for current wallet. Wrapper for the keys() methods.

Parameters:
  • account_id (int) – Account ID
  • used (bool) – Only return used or unused keys
  • network (str) – Network name filter
  • as_dict (bool) – Return as dictionary or DbKey object. Default is False: DbKey objects
Return list:

DbKey or dictionaries

keys_address_payment(account_id=None, used=None, network=None, as_dict=False)[source]

Get payment addresses (change=0) of specified account_id for current wallet. Wrapper for the keys() methods.

Parameters:
  • account_id (int) – Account ID
  • used (bool) – Only return used or unused keys
  • network (str) – Network name filter
  • as_dict (bool) – Return as dictionary or DbKey object. Default is False: DbKey objects
Return list:

DbKey or dictionaries

keys_addresses(account_id=None, used=None, network=None, depth=5, as_dict=False)[source]

Get address-keys of specified account_id for current wallet. Wrapper for the keys() methods.

Parameters:
  • account_id (int) – Account ID
  • used (bool) – Only return used or unused keys
  • network (str) – Network name filter
  • depth (int) – Filter by key depth. Default for BIP44 and multisig is 5
  • as_dict (bool) – Return as dictionary or DbKey object. Default is False: DbKey objects
Return list:

DbKey or dictionaries

keys_networks(used=None, as_dict=False)[source]

Get keys of defined networks for this wallet. Wrapper for the keys() method

Parameters:
  • used (bool) – Only return used or unused keys
  • as_dict (bool) – Return as dictionary or DbKey object. Default is False: DbKey objects
Return list:

DbKey or dictionaries

name

Get wallet name

Return str:
network_list(field='network_name')[source]

Wrapper for networks methods, returns a flat list with currently used networks for this wallet.

Returns:list
networks()[source]

Get list of networks used by this wallet

Returns:List of networks as dictionary
new_account(name='', account_id=None, network=None)[source]

Create a new account with a childkey for payments and 1 for change.

An account key can only be created if wallet contains a masterkey.

Parameters:
  • name (str) – Account Name. If not specified ‘Account #” with the account_id will be used
  • account_id (int) – Account ID. Default is last accounts ID + 1
  • network (str) – Network name. Leave empty for default network
Return HDWalletKey:
 
new_key(name='', account_id=None, network=None, change=0, max_depth=5)[source]

Create a new HD Key derived from this wallet’s masterkey. An account will be created for this wallet with index 0 if there is no account defined yet.

Parameters:
  • name (str) – Key name. Does not have to be unique but if you use it at reference you might chooce to enforce this. If not specified ‘Key #’ with an unique sequence number will be used
  • account_id (int) – Account ID. Default is last used or created account ID.
  • network (str) – Network name. Leave empty for default network
  • change (int) – Change (1) or payments (0). Default is 0
  • max_depth (int) – Maximum path depth. Default for BIP0044 is 5, any other value is non-standard and might cause unexpected behavior
Return HDWalletKey:
 
new_key_change(name='', account_id=None, network=None)[source]

Create new key to receive change for a transaction. Calls new_key method with change=1.

Parameters:
  • name (str) – Key name. Default name is ‘Change #’ with an address index
  • account_id (int) – Account ID. Default is last used or created account ID.
  • network (str) – Network name. Leave empty for default network
Return HDWalletKey:
 
owner

Get wallet Owner

Return str:
scan(scan_gap_limit=10, account_id=None, change=None, network=None, _keys_ignore=None, _recursion_depth=0)[source]

Generate new keys for this wallet and scan for UTXO’s.

Parameters:
  • scan_gap_limit (int) – Amount of new keys and change keys (addresses) created for this wallet
  • account_id (int) – Account ID. Default is last used or created account ID.
  • change – Filter by change addresses. Set to True to include only change addresses, False to only include regular addresses. None (default) to disable filter and include both
  • network (str) – Network name. Leave empty for default network
Returns:

select_inputs(amount, variance=None, account_id=None, network=None, min_confirms=0, max_utxos=None, return_input_obj=True)[source]

Select available inputs for given amount

Parameters:
  • amount (int) – Total value of inputs to select
  • variance (int) – Allowed difference in total input value. Default is dust amount of selected network.
  • account_id (int) – Account ID
  • network (str) – Network name. Leave empty for default network
  • min_confirms (int) – Minimal confirmation needed for an UTXO before it will included in inputs. Default is 0 confirmations. Option is ignored if input_arr is provided.
  • max_utxos (int) – Maximum number of UTXO’s to use. Set to 1 for optimal privacy. Default is None: No maximum
  • return_input_obj (bool) – Return inputs as Input class object. Default is True
Return Input, dict:
 

Selected inputs as dict or Input object

send(output_arr, input_arr=None, account_id=None, network=None, fee=None, min_confirms=0, priv_keys=None, max_utxos=None, locktime=0, offline=False)[source]

Create new transaction with specified outputs and push it to the network. Inputs can be specified but if not provided they will be selected from wallets utxo’s. Output array is a list of 1 or more addresses and amounts.

Parameters:
  • output_arr (list) – List of output tuples with address and amount. Must contain at least one item. Example: [(‘mxdLD8SAGS9fe2EeCXALDHcdTTbppMHp8N’, 5000000)]
  • input_arr (list) – List of inputs tuples with reference to a UTXO, a wallet key and value. The format is [(tx_hash, output_n, key_id, value)]
  • account_id (int) – Account ID
  • network (str) – Network name. Leave empty for default network
  • fee (int) – Set fee manually, leave empty to calculate fees automatically. Set fees in smallest currency denominator, for example satoshi’s if you are using bitcoins
  • min_confirms (int) – Minimal confirmation needed for an UTXO before it will included in inputs. Default is 0. Option is ignored if input_arr is provided.
  • priv_keys (HDKey, list) – Specify extra private key if not available in this wallet
  • max_utxos (int) – Maximum number of UTXO’s to use. Set to 1 for optimal privacy. Default is None: No maximum
  • locktime (int) – Transaction level locktime. Locks the transaction until a specified block (value from 1 to 5 million) or until a certain time (Timestamp in seconds after 1-jan-1970). Default value is 0 for transactions without locktime
  • offline (bool) – Just return the transaction object and do not send it when offline = True. Default is False
Return HDWalletTransaction:
 
send_to(to_address, amount, account_id=None, network=None, fee=None, min_confirms=0, priv_keys=None, locktime=0, offline=False)[source]

Create transaction and send it with default Service objects sendrawtransaction method

Parameters:
  • to_address (str) – Single output address
  • amount (int) – Output is smallest denominator for this network (ie: Satoshi’s for Bitcoin)
  • account_id (int) – Account ID, default is last used
  • network (str) – Network name. Leave empty for default network
  • fee (int) – Fee to use for this transaction. Leave empty to automatically estimate.
  • min_confirms (int) – Minimal confirmation needed for an UTXO before it will included in inputs. Default is 0. Option is ignored if input_arr is provided.
  • priv_keys (HDKey, list) – Specify extra private key if not available in this wallet
  • locktime (int) – Transaction level locktime. Locks the transaction until a specified block (value from 1 to 5 million) or until a certain time (Timestamp in seconds after 1-jan-1970). Default value is 0 for transactions without locktime
  • offline (bool) – Just return the transaction object and do not send it when offline = True. Default is False
Return HDWalletTransaction:
 
sweep(to_address, account_id=None, input_key_id=None, network=None, max_utxos=999, min_confirms=0, fee_per_kb=None, locktime=0, offline=False)[source]

Sweep all unspent transaction outputs (UTXO’s) and send them to one output address. Wrapper for the send method.

Parameters:
  • to_address (str) – Single output address
  • account_id (int) – Wallet’s account ID
  • input_key_id (int) – Limit sweep to UTXO’s with this key_id
  • network (str) – Network name. Leave empty for default network
  • max_utxos (int) – Limit maximum number of outputs to use. Default is 999
  • min_confirms (int) – Minimal confirmations needed to include utxo
  • fee_per_kb (int) – Fee per kilobyte transaction size, leave empty to get estimated fee costs from Service provider.
  • locktime (int) – Transaction level locktime. Locks the transaction until a specified block (value from 1 to 5 million) or until a certain time (Timestamp in seconds after 1-jan-1970). Default value is 0 for transactions without locktime
  • offline (bool) – Just return the transaction object and do not send it when offline = True. Default is False
Return HDWalletTransaction:
 
transaction_create(output_arr, input_arr=None, account_id=None, network=None, fee=None, min_confirms=0, max_utxos=None, locktime=0)[source]

Create new transaction with specified outputs. Inputs can be specified but if not provided they will be selected from wallets utxo’s. Output array is a list of 1 or more addresses and amounts.

Parameters:
  • output_arr (list) – List of output tuples with address and amount. Must contain at least one item. Example: [(‘mxdLD8SAGS9fe2EeCXALDHcdTTbppMHp8N’, 5000000)]
  • input_arr (list) – List of inputs tuples with reference to a UTXO, a wallet key and value. The format is [(tx_hash, output_n, key_ids, value, signatures, unlocking_script, address)]
  • account_id (int) – Account ID
  • network (str) – Network name. Leave empty for default network
  • fee (int) – Set fee manually, leave empty to calculate fees automatically. Set fees in smallest currency denominator, for example satoshi’s if you are using bitcoins
  • min_confirms (int) – Minimal confirmation needed for an UTXO before it will included in inputs. Default is 0 confirmations. Option is ignored if input_arr is provided.
  • max_utxos (int) – Maximum number of UTXO’s to use. Set to 1 for optimal privacy. Default is None: No maximum
  • locktime (int) – Transaction level locktime. Locks the transaction until a specified block (value from 1 to 5 million) or until a certain time (Timestamp in seconds after 1-jan-1970). Default value is 0 for transactions without locktime
Return HDWalletTransaction:
 

object

transaction_import(t)[source]

Import a Transaction into this wallet. Link inputs to wallet keys if possible and return HDWalletTransaction object. Only imports Transaction objects or dictionaries, use transaction_import_raw method to import a raw transaction.

Parameters:t (Transaction, dict) – A Transaction object or dictionary
Return HDWalletTransaction:
 
transaction_import_raw(raw_tx, network=None)[source]

Import a raw transaction. Link inputs to wallet keys if possible and return HDWalletTransaction object

Parameters:
  • raw_tx (str, bytes) – Raw transaction
  • network (str) – Network name. Leave empty for default network
Return HDWalletTransaction:
 
transactions(account_id=None, network=None, include_new=False, key_id=None)[source]
Parameters:
  • account_id (int) – Filter by Account ID. Leave empty for default account_id
  • network (str) – Filter by network name. Leave empty for default network
  • include_new (bool) – Also include new and incomplete transactions in list. Default is False
  • key_id (int) – Filter by key ID
Return list:

List of transactions as dictionary

transactions_update(account_id=None, used=None, network=None, key_id=None, depth=None, change=None)[source]

Update wallets transaction from service providers. Get all transactions for known keys in this wallet. The balances and unspent outputs (UTXO’s) are updated as well, but for large wallets use the utxo_update method if possible.

Parameters:
  • account_id (int) – Account ID
  • used (bool, None) – Only update used or unused keys, specify None to update both. Default is None
  • network (str) – Network name. Leave empty for default network
  • key_id (int) – Key ID to just update 1 key
  • depth (int) – Only update keys with this depth, default is depth 5 according to BIP0048 standard. Set depth to None to update all keys of this wallet.
  • change (int) – Only update change or normal keys, default is both (None)
Return bool:

True if all transactions are updated

utxo_add(address, value, tx_hash, output_n, confirmations=0, script='')[source]

Add a single UTXO to the wallet database. To update all utxo’s use utxos_update method.

Use this method for testing, offline wallets or if you wish to override standard method of retreiving UTXO’s

This method does not check if UTXO exists or is still spendable.

[{
‘address’: ‘n2S9Czehjvdmpwd2YqekxuUC1Tz5ZdK3YN’, ‘script’: ‘’, ‘confirmations’: 10, ‘output_n’: 1, ‘tx_hash’: ‘9df91f89a3eb4259ce04af66ad4caf3c9a297feea5e0b3bc506898b6728c5003’, ‘value’: 8970937

}]

Parameters:
  • address (str) – Address of Unspent Output. Address should be available in wallet
  • value (int) – Value of output in sathosis or smallest denominator for type of currency
  • tx_hash (str) – Transaction hash or previous output as hex-string
  • output_n (int) – Output number of previous transaction output
  • confirmations (int) – Number of confirmations. Default is 0, unconfirmed
  • script (str) – Locking script of previous output as hex-string
Return int:

Number of new UTXO’s added, so 1 if successful

utxos(account_id=None, network=None, min_confirms=0, key_id=None)[source]

Get UTXO’s (Unspent Outputs) from database. Use utxos_update method first for updated values

Parameters:
  • account_id (int) – Account ID
  • network (str) – Network name. Leave empty for default network
  • min_confirms (int) – Minimal confirmation needed to include in output list
  • key_id (int) – Key ID to just get 1 key
Return list:

List of transactions

utxos_update(account_id=None, used=None, networks=None, key_id=None, depth=None, change=None, utxos=None, update_balance=True)[source]

Update UTXO’s (Unspent Outputs) in database of given account using the default Service object.

Delete old UTXO’s which are spent and append new UTXO’s to database.

For usage on an offline PC, you can import utxos with the utxos parameter as a list of dictionaries: [{

‘address’: ‘n2S9Czehjvdmpwd2YqekxuUC1Tz5ZdK3YN’, ‘script’: ‘’, ‘confirmations’: 10, ‘output_n’: 1, ‘tx_hash’: ‘9df91f89a3eb4259ce04af66ad4caf3c9a297feea5e0b3bc506898b6728c5003’, ‘value’: 8970937

}]

Parameters:
  • account_id (int) – Account ID
  • used (bool) – Only check for UTXO for used or unused keys. Default is both
  • networks (str, list) – Network name filter as string or list of strings. Leave empty to update all used networks in wallet
  • key_id (int) – Key ID to just update 1 key
  • depth (int) – Only update keys with this depth, default is depth 5 according to BIP0048 standard. Set depth to None to update all keys of this wallet.
  • change (int) – Only update change or normal keys, default is both (None)
  • utxos (list) – List of unspent outputs in dictionary format specified in this method DOC header
  • update_balance (bool) – Option to disable balance update after fetching UTXO’s, used when utxos_update method is called several times in a row. Default is True
Return int:

Number of new UTXO’s added

class bitcoinlib.wallets.HDWalletKey(key_id, session, hdkey_object=None)[source]

Bases: object

Normally only used as attribute of HDWallet class. Contains HDKey object and extra information such as path and balance.

All HDWalletKey are stored in a database

Initialize HDWalletKey with specified ID, get information from database.

Parameters:
  • key_id (int) – ID of key as mentioned in database
  • session (sqlalchemy.orm.session.Session) – Required Sqlalchemy Session object
  • hdkey_object (HDKey) – Optional HDKey object. Specify HDKey object if available for performance
balance(fmt='')[source]

Get total of unspent outputs

Parameters:fmt (str) – Specify ‘string’ to return a string in currency format
Return float, str:
 Key balance
dict()[source]

Return current key information as dictionary

static from_key(wallet_id, session, key='', account_id=0, network=None, change=0, purpose=44, parent_id=0, path='m', key_type=None, encoding='base58', witness_type=None)[source]

Create HDWalletKey from a HDKey object or key

Parameters:
  • name (str) – New key name
  • wallet_id (int) – ID of wallet where to store key
  • session (sqlalchemy.orm.session.Session) – Required Sqlalchemy Session object
  • key (str, int, byte, bytearray, HDKey) – Optional key in any format accepted by the HDKey class
  • account_id (int) – Account ID for specified key, default is 0
  • network (str) – Network of specified key
  • change (int) – Use 0 for normal key, and 1 for change key (for returned payments)
  • purpose (int) – BIP0044 purpose field, default is 44
  • parent_id (int) – Key ID of parent, default is 0 (no parent)
  • path (str) – BIP0044 path of given key, default is ‘m’ (masterkey)
  • key_type (str) – Type of key, single or BIP44 type
  • encoding (str) – Encoding used for address, i.e.: base58 or bech32. Default is base58
  • witness_type (str) – Witness type used when creating transaction script: legacy, p2sh-segwit or segwit.
Return HDWalletKey:
 

HDWalletKey object

fullpath(change=None, address_index=None, max_depth=5)[source]

Full BIP0044 key path: - m / purpose’ / coin_type’ / account’ / change / address_index

Parameters:
  • change (int) – Normal = 0, change =1
  • address_index (int) – Index number of address (path depth 5)
  • max_depth (int) – Maximum depth of output path. I.e. type 3 for account path
Return list:

Current key path

key()[source]

Get HDKey object for current HDWalletKey

Return HDKey:
class bitcoinlib.wallets.HDWalletTransaction(hdwallet, *args, **kwargs)[source]

Bases: bitcoinlib.transactions.Transaction

Normally only used as attribute of HDWallet class. Child of Transaction object with extra reference to wallet and database object.

All HDWalletTransaction items are stored in a database

Initialize HDWalletTransaction object with reference to a HDWallet object

Parameters:
  • hdwallet – HDWallet object, wallet name or ID
  • args (args) – Arguments for HDWallet parent class
  • kwargs (kwargs) – Keyword arguments for HDWallet parent class
classmethod from_transaction(hdwallet, t)[source]

Create HDWalletTransaction object from Transaction object

Parameters:
  • hdwallet (HDwallet, str, int) – HDWallet object, wallet name or ID
  • t (Transaction) – Specify Transaction object
Return HDWalletClass:
 
info()[source]

Print Wallet transaction information to standard output. Include send information.

save()[source]

Save this transaction to database

Return int:Transaction ID
send(offline=False)[source]

Verify and push transaction to network. Update UTXO’s in database after successfull send

Parameters:offline (bool) – Just return the transaction object and do not send it when offline = True. Default is False
Return bool:Returns True if succesfully pushed to the network
sign(keys=None, index_n=0, multisig_key_n=None, hash_type=1)[source]

Sign this transaction. Use existing keys from wallet or use keys argument for extra keys.

Parameters:
  • keys (HDKey, str) – Extra private keys to sign the transaction
  • index_n (int) – Transaction index_n to sign
  • multisig_key_n (int) – Index number of key for multisig input for segwit transactions. Leave empty if not known. If not specified all possibilities will be checked
  • hash_type (int) – Hashtype to use, default is SIGHASH_ALL
Return bool:

True is successfully signed

exception bitcoinlib.wallets.WalletError(msg='')[source]

Bases: Exception

Handle Wallet class Exceptions

bitcoinlib.wallets.normalize_path(path)[source]

Normalize BIP0044 key path for HD keys. Using single quotes for hardened keys

Parameters:path (str) – BIP0044 key path
Return str:Normalized BIP0044 key path with single quotes
bitcoinlib.wallets.parse_bip44_path(path)[source]

Assumes a correct BIP0044 path and returns a dictionary with path items. See Bitcoin improvement proposals BIP0043 and BIP0044.

Specify path in this format: m / purpose’ / cointype’ / account’ / change / address_index. Path length must be between 1 and 6 (Depth between 0 and 5)

Parameters:path (str) – BIP0044 path as string, with backslash (/) seperator.
Return dict:Dictionary with path items: isprivate, purpose, cointype, account, change and address_index
bitcoinlib.wallets.script_type_default(witness_type, key_type, locking_script=False)[source]

Determine default script type for wallet type and key type combination used in this library.

Parameters:
  • witness_type (str) – Type of wallet: standard or segwit
  • key_type (str) – Type of keys used in this wallet
  • locking_script (bool) – Limit search to locking_script. Specify False for locking scripts and True for unlocking scripts
Return str:

Default script type

bitcoinlib.wallets.wallet_create_or_open(name, key='', owner='', network=None, account_id=0, purpose=44, scheme='bip44', parent_id=None, sort_keys=False, password='', witness_type='legacy', encoding=None, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite')[source]

Create a wallet with specified options if it doesn’t exist, otherwise just open

See Wallets class create method for option documentation

bitcoinlib.wallets.wallet_create_or_open_multisig(name, key_list, sigs_required=None, owner='', network=None, account_id=0, purpose=45, multisig_compressed=True, sort_keys=True, witness_type='legacy', encoding=None, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite')[source]

Create a wallet with specified options if it doesn’t exist, otherwise just open

See Wallets class create method for option documentation

bitcoinlib.wallets.wallet_delete(wallet, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite', force=False)[source]

Delete wallet and associated keys and transactions from the database. If wallet has unspent outputs it raises a WalletError exception unless ‘force=True’ is specified

Parameters:
  • wallet (int, str) – Wallet ID as integer or Wallet Name as string
  • databasefile (str) – Location of Sqlite database. Leave empty to use default
  • force (bool) – If set to True wallet will be deleted even if unspent outputs are found. Default is False
Return int:

Number of rows deleted, so 1 if succesfull

bitcoinlib.wallets.wallet_delete_if_exists(wallet, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite', force=False)[source]

Delete wallet and associated keys from the database. If wallet has unspent outputs it raises a WalletError exception unless ‘force=True’ is specified. If wallet wallet does not exist return False

Parameters:
  • wallet (int, str) – Wallet ID as integer or Wallet Name as string
  • databasefile (str) – Location of Sqlite database. Leave empty to use default
  • force (bool) – If set to True wallet will be deleted even if unspent outputs are found. Default is False
Return int:

Number of rows deleted, so 1 if succesfull

bitcoinlib.wallets.wallet_empty(wallet, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite')[source]

Remove all generated keys and transactions from wallet. Does not delete the wallet itself or the masterkey, so everything can be recreated.

Parameters:
  • wallet (int, str) – Wallet ID as integer or Wallet Name as string
  • databasefile (str) – Location of Sqlite database. Leave empty to use default
Return bool:

True if succesfull

bitcoinlib.wallets.wallet_exists(wallet, databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite')[source]

Check if Wallets is defined in database

Parameters:
  • wallet (int, str) – Wallet ID as integer or Wallet Name as string
  • databasefile (str) – Location of Sqlite database. Leave empty to use default
Return bool:

True if wallet exists otherwise False

bitcoinlib.wallets.wallets_list(databasefile='/home/docs/.bitcoinlib/database/bitcoinlib.sqlite')[source]

List Wallets from database

Parameters:databasefile (str) – Location of Sqlite database. Leave empty to use default
Return dict:Dictionary of wallets defined in database