bitcoinlib.wallets module
- class bitcoinlib.wallets.Wallet(wallet, db_uri=None, 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
db_uri (str) – URI of the database
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 master key
- Parameters
account_id (int) – ID of account. Default is 0
- Return WalletKey
- accounts(network='bitcoin')[source]
Get list of accounts for this wallet
- Parameters
network (str) – Network name filter. Default filter is DEFAULT_NETWORK
- Return list of integers
List of accounts IDs
- addresslist(account_id=None, used=None, network=None, change=None, depth=None, key_id=None)[source]
Get list of addresses defined in current wallet. Wrapper for the
keys()
methods.Use
keys_addresses()
method to receive full key objects>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.addresslist()[0] '16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg'
- 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. Default is None for standard key depth. Use -1 to show all keys
key_id (int) – Key ID to get address of just 1 key
- Return list of str
List of address strings
- as_dict(include_private=False)[source]
Return wallet information in dictionary format
- Parameters
include_private (bool) – Include private key information in dictionary
- Return dict
- as_json(include_private=False)[source]
Get current key as json formatted string
- Parameters
include_private (bool) – Include private key information in JSON
- Return str
- 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, keys=None, owner='', network=None, account_id=0, purpose=0, scheme='bip32', sort_keys=True, password='', witness_type=None, encoding=None, multisig=None, sigs_required=None, cosigner_id=None, key_path=None, db_uri=None)[source]
Create Wallet and insert in database. Generate masterkey or import key when specified.
When only a name is specified a legacy Wallet with a single masterkey is created with standard p2wpkh scripts.
>>> if wallet_delete_if_exists('create_legacy_wallet_test'): pass >>> w = Wallet.create('create_legacy_wallet_test') >>> w <Wallet(name=create_legacy_wallet_test, db_uri="None")>
To create a multi signature wallet specify multiple keys (private or public) and provide the sigs_required argument if it different then len(keys)
>>> if wallet_delete_if_exists('create_legacy_multisig_wallet_test'): pass >>> w = Wallet.create('create_legacy_multisig_wallet_test', keys=[HDKey(), HDKey().public()])
To create a native segwit wallet use the option witness_type = ‘segwit’ and for old style addresses and p2sh embedded segwit script us ‘ps2h-segwit’ as witness_type.
>>> if wallet_delete_if_exists('create_segwit_wallet_test'): pass >>> w = Wallet.create('create_segwit_wallet_test', witness_type='segwit')
Use a masterkey WIF when creating a wallet:
>>> wif = 'xprv9s21ZrQH143K3cxbMVswDTYgAc9CeXABQjCD9zmXCpXw4MxN93LanEARbBmV3utHZS9Db4FX1C1RbC5KSNAjQ5WNJ1dDBJ34PjfiSgRvS8x' >>> if wallet_delete_if_exists('bitcoinlib_legacy_wallet_test', force=True): pass >>> w = Wallet.create('bitcoinlib_legacy_wallet_test', wif) >>> w <Wallet(name=bitcoinlib_legacy_wallet_test, db_uri="None")> >>> # Add some test utxo data: >>> if w.utxo_add('16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg', 100000000, '748799c9047321cb27a6320a827f1f69d767fe889c14bf11f27549638d566fe4', 0): pass
Please mention account_id if you are using multiple accounts.
- Parameters
name (str) – Unique name of this Wallet
keys (str, bytes, int, HDKey, HDWalletKey, list of str, list of bytes, list of int, list of HDKey, list of HDWalletKey) – Masterkey to or list of keys to use for this wallet. Will be automatically created if not specified. One or more keys are obligatory for multisig wallets. 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) – BIP43 purpose field, will be derived from witness_type and multisig by default
scheme (str) – Key structure type, i.e. BIP32 or single
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
multisig (bool) – Multisig wallet or child of a multisig wallet, default is None / derive from number of keys.
sigs_required (int) – Number of signatures required for validation if using a multisignature wallet. For example 2 for 2-of-3 multisignature. Default is all keys must be signed
cosigner_id (int) – Set this if wallet contains only public keys, more than one private key or if you would like to create keys for other cosigners. Note: provided keys of a multisig wallet are sorted if sort_keys = True (default) so if your provided key list is not sorted the cosigned_id may be different.
key_path (list, str) – Key path for multisig wallet, use to create your own non-standard key path. Key path must follow the following rules: * Path start with masterkey (m) and end with change / address_index * If accounts are used, the account level must be 3. I.e.: m/purpose/coin_type/account/ * All keys must be hardened, except for change, address_index or cosigner_id * Max length of path is 8 levels
db_uri (str) – URI of the database
- Return Wallet
- property default_account_id
- get_key(account_id=None, network=None, cosigner_id=None, change=0)[source]
Get a unused key / address or create a new one with
new_key()
if there are no unused keys. Returns a key from this wallet which has no transactions linked to it.Use the get_keys() method to a list of unused keys. Calling the get_key() method repeatelly to receive a list of key doesn’t work: since the key is unused it would return the same result every time you call this method.
>>> w = Wallet('create_legacy_wallet_test') >>> w.get_key() <WalletKey(key_id=..., name=..., wif=..., path=m/44'/0'/0'/0/...)>
- Parameters
account_id (int) – Account ID. Default is last used or created account ID.
network (str) – Network name. Leave empty for default network
cosigner_id (int) – Cosigner ID for key path
change (int) – Payment (0) or change key (1). Default is 0
- Return WalletKey
- get_key_change(account_id=None, network=None)[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
- Return WalletKey
- get_keys(account_id=None, network=None, cosigner_id=None, number_of_keys=1, change=0)[source]
Get a list of unused keys / addresses or create a new ones with
new_key()
if there are no unused keys. Returns a list of keys from this wallet which has no transactions linked to it.Use the get_key() method to get a single key.
- Parameters
account_id (int) – Account ID. Default is last used or created account ID.
network (str) – Network name. Leave empty for default network
cosigner_id (int) – Cosigner ID for key path
number_of_keys (int) – Number of keys to return. Default is 1
change (int) – Payment (0) or change key (1). Default is 0
- Return list of WalletKey
- get_keys_change(account_id=None, network=None, number_of_keys=1)[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
- Return list of WalletKey
- import_key(key, account_id=0, name='', network=None, purpose=44, key_type=None)[source]
Add new single key to wallet.
- Parameters
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 WalletKey
- 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 5, with 0 low detail and 5 highest detail
- key(term)[source]
Return single key with given ID or name as WalletKey object
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.key('change 0').address '1HabJXe8mTwXiMzUWW5KdpYbFWu3hvtsbF'
- Parameters
term (int, str) – Search term can be key ID, key address, key WIF or key name
- Return WalletKey
Single key as object
- key_for_path(path, level_offset=None, name=None, account_id=None, cosigner_id=None, address_index=0, change=0, network=None, recreate=False)[source]
Return key for specified path. Derive all wallet keys in path if they not already exists
>>> w = wallet_create_or_open('key_for_path_example') >>> key = w.key_for_path([0, 0]) >>> key.path "m/44'/0'/0'/0/0"
>>> w.key_for_path([], level_offset=-2).path "m/44'/0'/0'"
>>> w.key_for_path([], w.depth_public_master + 1).path "m/44'/0'/0'"
Arguments provided in ‘path’ take precedence over other arguments. The address_index argument is ignored: >>> key = w.key_for_path([0, 10], address_index=1000) >>> key.path “m/44’/0’/0’/0/10” >>> key.address_index 10
- Parameters
path (list, str) – Part of key path, i.e. [0, 0] for [change=0, address_index=0]
level_offset (int) – Just create part of path, when creating keys. For example -2 means create path with the last 2 items (change, address_index) or 1 will return the master key ‘m’
name (str) – Specify key name for latest/highest key in structure
account_id (int) – Account ID
cosigner_id (int) – ID of cosigner
address_index (int) – Index of key, normally provided to ‘path’ argument
change (int) – Change key = 1 or normal = 0, normally provided to ‘path’ argument
network (str) – Network name. Leave empty for default network
recreate (bool) – Recreate key, even if already found in wallet. Can be used to update public key with private key info
- Return WalletKey
- keys(account_id=None, name=None, key_id=None, change=None, depth=None, used=None, is_private=None, has_balance=None, is_active=None, network=None, include_private=False, as_dict=False)[source]
Search for keys in database. Include 0 or more of account_id, name, key_id, change and depth.
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> all_wallet_keys = w.keys() >>> w.keys(depth=0) [<DbKey(id=..., name='bitcoinlib_legacy_wallet_test', wif='xprv9s21ZrQH143K3cxbMVswDTYgAc9CeXABQjCD9zmXCpXw4MxN93LanEARbBmV3utHZS9Db4FX1C1RbC5KSNAjQ5WNJ1dDBJ34PjfiSgRvS8x'>]
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 None (show all)
network (str) – Network name filter
include_private (bool) – Include private key information in dictionary
as_dict (bool) – Return keys as dictionary objects. Default is False: DbKey objects
- Return list of DbKey
List of Keys
- keys_accounts(account_id=None, network='bitcoin', as_dict=False)[source]
Get Database records of account key(s) with for current wallet. Wrapper for the
keys()
method.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> account_key = w.keys_accounts() >>> account_key[0].path "m/44'/0'/0'"
Returns nothing if no account keys are available for instance in multisig or single account wallets. In this case use
accounts()
method instead.- 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 of (DbKey, dict)
- 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 of (DbKey, dict)
- 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 of (DbKey, dict)
- keys_addresses(account_id=None, used=None, is_active=None, change=None, network=None, depth=None, as_dict=False)[source]
Get address keys of specified account_id for current wallet. Wrapper for the
keys()
methods.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.keys_addresses()[0].address '16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg'
- Parameters
account_id (int) – Account ID
used (bool) – Only return used or unused keys
is_active (bool) – Hide inactive keys. Only include active keys with either a balance or which are unused, default is True
change (int) – Search for Change
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 of (DbKey, dict)
- keys_networks(used=None, as_dict=False)[source]
Get keys of defined networks for this wallet. Wrapper for the
keys()
method>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> network_key = w.keys_networks() >>> # Address index of hardened key 0' is 2147483648 >>> network_key[0].address_index 2147483648 >>> network_key[0].path "m/44'/0'"
- 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 of (DbKey, dict)
- property name
Get wallet name
- Return str
- network_list(field='name')[source]
Wrapper for
networks()
method, returns a flat list with currently used networks for this wallet.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.network_list() ['bitcoin']
- Return list of str
- networks(as_dict=False)[source]
Get list of networks used by this wallet
- Parameters
as_dict (bool) – Return as dictionary or as Network objects, default is Network objects
- Return list of (Network, dict)
- new_account(name='', account_id=None, network=None)[source]
Create a new account with a child key 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 as name
account_id (int) – Account ID. Default is last accounts ID + 1
network (str) – Network name. Leave empty for default network
- Return WalletKey
- new_key(name='', account_id=None, change=0, cosigner_id=None, network=None)[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.
>>> w = Wallet('create_legacy_wallet_test') >>> w.new_key('my key') <WalletKey(key_id=..., name=my key, wif=..., path=m/44'/0'/0'/0/...)>
- 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 a unique sequence number will be used
account_id (int) – Account ID. Default is last used or created account ID.
change (int) – Change (1) or payments (0). Default is 0
cosigner_id (int) – Cosigner ID for key path
network (str) – Network name. Leave empty for default network
- Return WalletKey
- 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 WalletKey
- property owner
Get wallet Owner
- Return str
- path_expand(path, level_offset=None, account_id=None, cosigner_id=0, address_index=None, change=0, network='bitcoin')[source]
Create key path. Specify part of key path to expand to key path used in this wallet.
>>> w = Wallet('create_legacy_wallet_test') >>> w.path_expand([0,1200]) ['m', "44'", "0'", "0'", '0', '1200']
>>> w = Wallet('create_legacy_multisig_wallet_test') >>> w.path_expand([0,2], cosigner_id=1) ['m', "45'", '1', '0', '2']
- Parameters
path (list, str) – Part of path, for example [0, 2] for change=0 and address_index=2
level_offset (int) – Just create part of path. For example -2 means create path with the last 2 items (change, address_index) or 1 will return the master key ‘m’
account_id (int) – Account ID
cosigner_id (int) – ID of cosigner
address_index (int) – Index of key, normally provided to ‘path’ argument
change (int) – Change key = 1 or normal = 0, normally provided to ‘path’ argument
network (str) – Network name. Leave empty for default network
- Return list
- public_master(account_id=None, name=None, as_private=False, network=None)[source]
Return public master key(s) for this wallet. Use to import in other wallets to sign transactions or create keys.
For a multisig wallet all public master keys are return as list.
Returns private key information if available and as_private is True is specified
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.public_master().wif 'xpub6D2qEr8Z8WYKKns2xZYyyvvRviPh1NKt1kfHwwfiTxJwj7peReEJt3iXoWWsr8tXWTsejDjMfAezM53KVFVkSZzA5i2pNy3otprtYUvh4u1'
- Parameters
account_id (int) – Account ID of key to export
name (str) – Optional name for account key
as_private (bool) – Export public or private key, default is False
network (str) – Network name. Leave empty for default network
- Return list of WalletKey, WalletKey
- scan(scan_gap_limit=5, account_id=None, change=None, rescan_used=False, network=None, keys_ignore=None)[source]
Generate new addresses/keys and scan for new transactions using the Service providers. Updates all UTXO’s and balances.
Keep scanning for new transactions until no new transactions are found for ‘scan_gap_limit’ addresses. Only scan keys from default network and account unless another network or account is specified.
Use the faster
utxos_update()
method if you are only interested in unspent outputs. Use thetransactions_update()
method if you would like to manage the key creation yourself or if you want to scan a single key.- Parameters
scan_gap_limit (int) – Amount of new keys and change keys (addresses) created for this wallet. Default is 5, so scanning stops if after 5 addresses no transaction are found.
account_id (int) – Account ID. Default is last used or created account ID.
change (bool) – 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
rescan_used (bool) – Rescan already used addressed. Default is False, so funds send to old addresses will be ignored by default.
network (str) – Network name. Leave empty for default network
keys_ignore (list of int) – Id’s of keys to ignore
- Returns
- scan_key(key)[source]
Scan for new transactions for specified wallet key and update wallet transactions
- Parameters
key (WalletKey, int) – The wallet key as object or index
- Return bool
New transactions found?
- select_inputs(amount, variance=None, input_key_id=None, account_id=None, network=None, min_confirms=1, max_utxos=None, return_input_obj=True, skip_dust_amounts=True)[source]
Select available unspent transaction outputs (UTXO’s) which can be used as inputs for a transaction for the specified amount.
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.select_inputs(50000000) [<Input(prev_txid='748799c9047321cb27a6320a827f1f69d767fe889c14bf11f27549638d566fe4', output_n=0, address='16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg', index_n=0, type='sig_pubkey')>]
- Parameters
amount (int) – Total value of inputs in the smallest denominator (sathosi) to select
variance (int) – Allowed difference in total input value. Default is dust amount of selected network. Difference will be added to transaction fee.
input_key_id (int, list) – Limit UTXO’s search for inputs to this key ID or list of key IDs. Only valid if no input array is specified
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 be included in inputs. Default is 1 confirmation. 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
skip_dust_amounts (bool) – Do not include small amount to avoid dust inputs
- Returns
List of previous outputs
- Return type
list of DbTransactionOutput, list of Input
- send(output_arr, input_arr=None, input_key_id=None, account_id=None, network=None, fee=None, min_confirms=1, priv_keys=None, max_utxos=None, locktime=0, offline=True, number_of_change_outputs=1)[source]
Create a 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.
Uses the
transaction_create()
method to create a new transaction, and uses a random service client to send the transaction.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> t = w.send([('1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb', 200000)], offline=True) >>> t <WalletTransaction(input_count=1, output_count=2, status=new, network=bitcoin)> >>> t.outputs [<Output(value=..., address=..., type=p2pkh)>, <Output(value=..., address=..., type=p2pkh)>]
- Parameters
output_arr (list) – List of output tuples with address and amount. Must contain at least one item. Example: [(‘mxdLD8SAGS9fe2EeCXALDHcdTTbppMHp8N’, 5000000)]. Address can be an address string, Address object, HDKey object or WalletKey object
input_arr (list) – List of inputs tuples with reference to a UTXO, a wallet key and value. The format is [(txid, output_n, key_id, value)]
input_key_id (int, list) – Limit UTXO’s search for inputs to this key ID or list of key IDs. Only valid if no input array is specified
account_id (int) – Account ID
network (str) – Network name. Leave empty for default network
fee (int, str) – Set fee manually, leave empty to calculate fees automatically. Set fees in the smallest currency denominator, for example satoshi’s if you are using bitcoins. You can also supply a string: ‘low’, ‘normal’ or ‘high’ to determine fees automatically.
min_confirms (int) – Minimal confirmation needed for an UTXO before it will be included in inputs. Default is 1. 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 True
number_of_change_outputs (int) – Number of change outputs to create when there is a change value. Default is 1. Use 0 for random number of outputs: between 1 and 5 depending on send and change amount
- Return WalletTransaction
- send_to(to_address, amount, input_key_id=None, account_id=None, network=None, fee=None, min_confirms=1, priv_keys=None, locktime=0, offline=True, number_of_change_outputs=1)[source]
Create transaction and send it with default Service objects
services.sendrawtransaction()
method.Wrapper for wallet
send()
method.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> t = w.send_to('1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb', 200000, offline=True) >>> t <WalletTransaction(input_count=1, output_count=2, status=new, network=bitcoin)> >>> t.outputs [<Output(value=..., address=..., type=p2pkh)>, <Output(value=..., address=..., type=p2pkh)>]
- Parameters
to_address (str, Address, HDKey, WalletKey) – Single output address as string Address object, HDKey object or WalletKey object
amount (int, str, Value) – Output is the smallest denominator for this network (ie: Satoshi’s for Bitcoin), as Value object or value string as accepted by Value class
input_key_id (int, list) – Limit UTXO’s search for inputs to this key ID or list of key IDs. Only valid if no input array is specified
account_id (int) – Account ID, default is last used
network (str) – Network name. Leave empty for default network
fee (int, str) – Set fee manually, leave empty to calculate fees automatically. Set fees in the smallest currency denominator, for example satoshi’s if you are using bitcoins. You can also supply a string: ‘low’, ‘normal’ or ‘high’ to determine fees automatically.
min_confirms (int) – Minimal confirmation needed for an UTXO before it will be included in inputs. Default is 1. 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 True
number_of_change_outputs (int) – Number of change outputs to create when there is a change value. Default is 1. Use 0 for random number of outputs: between 1 and 5 depending on send and change amount
- Return WalletTransaction
- sweep(to_address, account_id=None, input_key_id=None, network=None, max_utxos=999, min_confirms=1, fee_per_kb=None, fee=None, locktime=0, offline=True)[source]
Sweep all unspent transaction outputs (UTXO’s) and send them to one or more output addresses.
Wrapper for the
send()
method.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> t = w.sweep('1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb') >>> t <WalletTransaction(input_count=1, output_count=1, status=new, network=bitcoin)> >>> t.outputs [<Output(value=..., address=1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb, type=p2pkh)>]
Output to multiple addresses
>>> to_list = [('1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb', 100000), (w.get_key(), 0)] >>> w.sweep(to_list) <WalletTransaction(input_count=1, output_count=2, status=new, network=bitcoin)>
- Parameters
to_address (str, list) – Single output address or list of outputs in format [(<adddress>, <amount>)]. If you specify a list of outputs, use amount value = 0 to indicate a change output
account_id (int) – Wallet’s account ID
input_key_id (int, list) – Limit sweep to UTXO’s with this key ID or list of key IDs
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. This option is ignored when the ‘fee’ option is specified
fee (int, str) – Total transaction fee in the smallest denominator (i.e. satoshis). Leave empty to get estimated fee from service providers. You can also supply a string: ‘low’, ‘normal’ or ‘high’ to determine fees automatically.
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 True
- Return WalletTransaction
- transaction(txid)[source]
Get WalletTransaction object for given transaction ID (transaction hash)
- Parameters
txid (str) – Hexadecimal transaction hash
- Return WalletTransaction
- transaction_create(output_arr, input_arr=None, input_key_id=None, account_id=None, network=None, fee=None, min_confirms=1, max_utxos=None, locktime=0, number_of_change_outputs=1, random_output_order=True)[source]
Create new transaction with specified outputs.
Inputs can be specified but if not provided they will be selected from wallets utxo’s with
select_inputs()
method.Output array is a list of 1 or more addresses and amounts.
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> t = w.transaction_create([('1J9GDZMKEr3ZTj8q6pwtMy4Arvt92FDBTb', 200000)]) >>> t <WalletTransaction(input_count=1, output_count=2, status=new, network=bitcoin)> >>> t.outputs [<Output(value=..., address=..., type=p2pkh)>, <Output(value=..., address=..., type=p2pkh)>]
- Parameters
output_arr (list of Output, tuple) – List of output as Output objects or tuples with address and amount. Must contain at least one item. Example: [(‘mxdLD8SAGS9fe2EeCXALDHcdTTbppMHp8N’, 5000000)]
input_arr (list of Input, tuple) – List of inputs as Input objects or tuples with reference to a UTXO, a wallet key and value. The format is [(txid, output_n, key_ids, value, signatures, unlocking_script, address)]
input_key_id (int) – Limit UTXO’s search for inputs to this key_id. Only valid if no input array is specified
account_id (int) – Account ID
network (str) – Network name. Leave empty for default network
fee (int, str) – Set fee manually, leave empty to calculate fees automatically. Set fees in the smallest currency denominator, for example satoshi’s if you are using bitcoins. You can also supply a string: ‘low’, ‘normal’ or ‘high’ to determine fees automatically.
min_confirms (int) – Minimal confirmation needed for an UTXO before it will be included in inputs. Default is 1 confirmation. 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
number_of_change_outputs (int) – Number of change outputs to create when there is a change value. Default is 1. Use 0 for random number of outputs: between 1 and 5 depending on send and change amount :type number_of_change_outputs: int
random_output_order (bool) – Shuffle order of transaction outputs to increase privacy. Default is True
- Return WalletTransaction
object
- transaction_import(t)[source]
Import a Transaction into this wallet. Link inputs to wallet keys if possible and return WalletTransaction 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 WalletTransaction
- transaction_import_raw(rawtx, network=None)[source]
Import a raw transaction. Link inputs to wallet keys if possible and return WalletTransaction object
- Parameters
rawtx (str, bytes) – Raw transaction
network (str) – Network name. Leave empty for default network
- Return WalletTransaction
- transaction_last(address)[source]
Get transaction ID for latest transaction in database for given address
- Parameters
address (str) – The address
- Return str
- transaction_load(txid=None, filename=None)[source]
Load transaction object from file which has been stored with the
Transaction.save()
method.Specify transaction ID or filename.
- Parameters
txid (str) – Transaction ID. Transaction object will be read from .bitcoinlib datadir
filename (str) – Name of transaction object file
- Return Transaction
- transaction_spent(txid, output_n)[source]
Check if transaction with given transaction ID and output_n is spent and return txid of spent transaction.
Retrieves information from database, does not update transaction and does not check if transaction is spent with service providers.
- Parameters
txid (str, bytes) – Hexadecimal transaction hash
output_n (int, bytes) – Output n
- Return str
Transaction ID
- transactions(account_id=None, network=None, include_new=False, key_id=None, as_dict=False)[source]
Get all known transactions input and outputs for this wallet.
The transaction only includes the inputs and outputs related to this wallet. To get full transactions use the
transactions_full()
method.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.transactions() [<WalletTransaction(input_count=0, output_count=1, status=confirmed, network=bitcoin)>]
- Parameters
account_id (int, None) – Filter by Account ID. Leave empty for default account_id
network (str, None) – 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, None) – Filter by key ID
as_dict (bool) – Output as dictionary or WalletTransaction object
- Return list of WalletTransaction
List of WalletTransaction or transactions as dictionary
- transactions_export(account_id=None, network=None, include_new=False, key_id=None, skip_change=True)[source]
- Export wallets transactions as list of tuples with the following fields:
(transaction_date, transaction_hash, in/out, addresses_in, addresses_out, value, value_cumulative, fee)
- Parameters
account_id (int, None) – Filter by Account ID. Leave empty for default account_id
network (str, None) – 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, None) – Filter by key ID
skip_change (bool) – Do not include change outputs. Default is True
- Return list of tuple
- transactions_full(network=None, include_new=False, limit=0, offset=0)[source]
Get all transactions of this wallet as WalletTransaction objects
Use the
transactions()
method to only get the inputs and outputs transaction parts related to this wallet- Parameters
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
limit (int) – Maximum number of transactions to return. Combine with offset parameter to use as pagination
offset (int) – Number of transactions to skip
- Return list of WalletTransaction
- transactions_update(account_id=None, used=None, network=None, key_id=None, depth=None, change=None, limit=20)[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. Only scan keys from default network and account unless another network or account is specified.
Use the
scan()
method for automatic address generation/management, and use theutxos_update()
method to only look for unspent outputs and balances.- 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)
limit (int) – Stop update after limit transactions to avoid timeouts with service providers. Default is MAX_TRANSACTIONS defined in config.py
- Return bool
True if all transactions are updated
- transactions_update_by_txids(txids)[source]
Update transaction or list or transaction for this wallet with provided transaction ID
- Parameters
txids (str, list of str, bytes, list of bytes) – Transaction ID, or list of transaction IDs
- Returns
- transactions_update_confirmations()[source]
Update number of confirmations and status for transactions in database
- Returns
- utxo_add(address, value, txid, output_n, confirmations=1, 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.
- 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
txid (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
- utxo_last(address)[source]
Get transaction ID for latest utxo in database for given address
>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.utxo_last('16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg') '748799c9047321cb27a6320a827f1f69d767fe889c14bf11f27549638d566fe4'
- Parameters
address (str) – The address
- Return str
- 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>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> w.utxos() [{'value': 100000000, 'script': '', 'output_n': 0, 'transaction_id': ..., 'spent': False, 'script_type': 'p2pkh', 'key_id': ..., 'address': '16QaHuFkfuebXGcYHmehRXBBX7RG9NbtLg', 'confirmations': 0, 'txid': '748799c9047321cb27a6320a827f1f69d767fe889c14bf11f27549638d566fe4', 'network_name': 'bitcoin'}]
- 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, list) – Key ID or list of key IDs to filter utxo’s for specific keys
- 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, max_utxos=20, rescan_all=True)[source]
Update UTXO’s (Unspent Outputs) for addresses/keys in this wallet using various Service providers.
This method does not import transactions: use
transactions_update()
function or to look for new addresses usescan()
.- 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 of dict.) – List of unspent outputs in dictionary format specified below. 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, "txid": "9df91f89a3eb4259ce04af66ad4caf3c9a297feea5e0b3bc506898b6728c5003", "value": 8970937 }
- Parameters
update_balance (bool) – Option to disable balance update after fetching UTXO’s. Can be used when utxos_update method is called several times in a row. Default is True
max_utxos (int) – Maximum number of UTXO’s to update
rescan_all (bool) – Remove old utxo’s and rescan wallet. Default is True. Set to False if you work with large utxo’s sets. Value will be ignored if key_id is specified in your call
- Return int
Number of new UTXO’s added
- wif(is_private=False, account_id=0)[source]
Return Wallet Import Format string for master private or public key which can be used to import key and recreate wallet in other software.
A list of keys will be exported for a multisig wallet.
- Parameters
is_private (bool) – Export public or private key, default is False
account_id (bool) – Account ID of key to export
- Return list, str
- exception bitcoinlib.wallets.WalletError(msg='')[source]
Bases:
Exception
Handle Wallet class Exceptions
- class bitcoinlib.wallets.WalletKey(key_id, session, hdkey_object=None)[source]
Bases:
object
Used as attribute of Wallet class. Contains HDKey class, and adds extra wallet related information such as key ID, name, path and balance.
All WalletKeys are stored in a database
Initialize WalletKey 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
- as_dict(include_private=False)[source]
Return current key information as dictionary
- Parameters
include_private (bool) – Include private key information in dictionary
- balance(as_string=False)[source]
Get total value of unspent outputs
- Parameters
as_string (bool) – Specify ‘string’ to return a string in currency format
- Return float, str
Key balance
- static from_key(name, wallet_id, session, key, account_id=0, network=None, change=0, purpose=44, parent_id=0, path='m', key_type=None, encoding=None, witness_type='legacy', multisig=False, cosigner_id=None)[source]
Create WalletKey from a HDKey object or key.
Normally you don’t need to call this method directly. Key creation is handled by the Wallet class.
>>> w = wallet_create_or_open('hdwalletkey_test') >>> wif = 'xprv9s21ZrQH143K2mcs9jcK4EjALbu2z1N9qsMTUG1frmnXM3NNCSGR57yLhwTccfNCwdSQEDftgjCGm96P29wGGcbBsPqZH85iqpoHA7LrqVy' >>> wk = WalletKey.from_key('import_key', w.wallet_id, w._session, wif) >>> wk.address '1MwVEhGq6gg1eeSrEdZom5bHyPqXtJSnPg' >>> wk <WalletKey(key_id=..., name=import_key, wif=xprv9s21ZrQH143K2mcs9jcK4EjALbu2z1N9qsMTUG1frmnXM3NNCSGR57yLhwTccfNCwdSQEDftgjCGm96P29wGGcbBsPqZH85iqpoHA7LrqVy, path=m)>
- 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, 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.
multisig (bool) – Specify if key is part of multisig wallet, used for create keys and key representations such as WIF and addreses
cosigner_id (int) – Set this if you would like to create keys for other cosigners.
- Return WalletKey
WalletKey object
- property name
Return name of wallet key
- Return str
- class bitcoinlib.wallets.WalletTransaction(hdwallet, account_id=None, *args, **kwargs)[source]
Bases:
Transaction
Used as attribute of Wallet class. Child of Transaction object with extra reference to wallet and database object.
All WalletTransaction items are stored in a database
Initialize WalletTransaction object with reference to a Wallet object
- Parameters
hdwallet – Wallet object, wallet name or ID
account_id (int) – Account ID
args (args) – Arguments for HDWallet parent class
kwargs (kwargs) – Keyword arguments for Wallet parent class
- delete()[source]
Delete this transaction from database.
WARNING: Results in incomplete wallets, transactions will NOT be automatically downloaded again when scanning or updating wallet. In normal situations only used to remove old unconfirmed transactions
- Return int
Number of deleted transactions
- export(skip_change=True)[source]
- Export this transaction as list of tuples in the following format:
(transaction_date, transaction_hash, in/out, addresses_in, addresses_out, value, fee)
A transaction with multiple inputs or outputs results in multiple tuples.
- Parameters
skip_change (boolean) – Do not include outputs to own wallet (default). Please note: So if this is set to True, then an internal transfer is not exported.
- Return list of tuple
- classmethod from_transaction(hdwallet, t)[source]
Create WalletTransaction object from Transaction object
- Parameters
hdwallet (HDwallet, str, int) – Wallet object, wallet name or ID
t (Transaction) – Specify Transaction object
- Return WalletClass
- classmethod from_txid(hdwallet, txid)[source]
Read single transaction from database with given transaction ID / transaction hash
- Parameters
hdwallet (Wallet) – Wallet object
txid (str, bytes) – Transaction hash as hexadecimal string
- Return WalletClass
- save(filename=None)[source]
Store transaction object as file, so it can be imported in bitcoinlib later with the
load()
method.- Parameters
filename (str) – Location and name of file, leave empty to store transaction in bitcoinlib data directory: .bitcoinlib/<transaction_id.tx)
- Returns
- send(offline=False)[source]
Verify and push transaction to network. Update UTXO’s in database after successful send
- Parameters
offline (bool) – Just return the transaction object and do not send it when offline = True. Default is False
- Return None
- sign(keys=None, index_n=0, multisig_key_n=None, hash_type=1, fail_on_unknown_key=False, replace_signatures=False)[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
fail_on_unknown_key (bool) – Method fails if public key from signature is not found in public key list
replace_signatures (bool) – Replace signature with new one if already signed.
- Return None
- bitcoinlib.wallets.normalize_path(path)[source]
Normalize BIP0044 key path for HD keys. Using single quotes for hardened keys
>>> normalize_path("m/44h/2p/1'/0/100") "m/44'/2'/1'/0/100"
- Parameters
path (str) – BIP0044 key path
- Return str
Normalized BIP0044 key path with single quotes
- bitcoinlib.wallets.wallet_create_or_open(name, keys='', owner='', network=None, account_id=0, purpose=None, scheme='bip32', sort_keys=True, password='', witness_type=None, encoding=None, multisig=None, sigs_required=None, cosigner_id=None, key_path=None, db_uri=None)[source]
Create a wallet with specified options if it doesn’t exist, otherwise just open
Returns Wallet object
See Wallets class create method for option documentation
- bitcoinlib.wallets.wallet_delete(wallet, db_uri=None, 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
db_uri (str) – URI of the database
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 successful
- bitcoinlib.wallets.wallet_delete_if_exists(wallet, db_uri=None, 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 the wallet does not exist return False
- Parameters
wallet (int, str) – Wallet ID as integer or Wallet Name as string
db_uri (str) – URI of the database
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 successful
- bitcoinlib.wallets.wallet_empty(wallet, db_uri=None)[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
db_uri (str) – URI of the database
- Return bool
True if successful
- bitcoinlib.wallets.wallet_exists(wallet, db_uri=None)[source]
Check if Wallets is defined in database
- Parameters
wallet (int, str) – Wallet ID as integer or Wallet Name as string
db_uri (str) – URI of the database
- Return bool
True if wallet exists otherwise False
- bitcoinlib.wallets.wallets_list(db_uri=None, include_cosigners=False)[source]
List Wallets from database
- Parameters
db_uri (str) – URI of the database
include_cosigners (bool) – Child wallets for multisig wallets are for internal use only and are skipped by default
- Return dict
Dictionary of wallets defined in database