bitcoinlib.wallets module
- class bitcoinlib.wallets.Wallet(wallet, db_uri=None, db_cache_uri=None, session=None, main_key_object=None, db_password=None)[source]
Bases:
objectClass to create and manage keys Using the BIP0044 Hierarchical Deterministic wallet definitions, so you can use one Masterkey to generate as many child keys as you want in a structured manner.
You can import keys in many formats 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 the provided ID or name
- Parameters:
wallet (int, str) – Wallet name or ID
db_uri (str) – URI of the database
db_cache_uri (str) – URI of the cache database. If not specified the default cache database is used when using sqlite, for other databasetypes the cache database is merged with the wallet database (db_uri)
session (sqlalchemy.orm.session.Session) – Sqlalchemy session
main_key_object (HDKey) – Pass the main key object to save time
- account(account_id)[source]
Returns wallet key of the specified 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=None)[source]
Get a list of accounts for this wallet
- Parameters:
network (str) – The network name filter. Default filter is the network of first main key
- Return list of integers:
List of account IDs
- address_index(address_index, account_id=None, cosigner_id=None, change=0, network=None)[source]
Get the key with the specified address_index from this wallet. Always returns a key with the specified path, even if it is not created yet in wallet. Wrapper for the
key_for_path()method.To get an unused key / address use the
get_key()method and to create a new key use thenew_key()method.- Parameters:
address_index (int) – address_index of the specific key
account_id (int) – Account ID
cosigner_id (int) – ID of cosigner
change (int) – Change key = 1 or normal = 0, normally provided to ‘path’ argument
network (str) – The network name. Leave empty for default network
- Return WalletKey:
- addresslist(account_id=None, used=None, network=None, change=None, depth=None, key_id=None)[source]
Get a list of addresses defined in the 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) – The 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 an 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 the current key as a 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 the total balance of the unspent outputs for this wallet
- Parameters:
account_id (int) – Account ID filter
network (str) – The 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 the total wallet balance in the 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) – The 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, anti_fee_sniping=True, strict=True, ignore_dust=True, db_uri=None, db_cache_uri=None, db_password=None)[source]
Create Wallet and insert in the database. Generate a masterkey or imports a 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")>
To create a multi-signature wallet, specify multiple keys (private or public) and provide the sigs_required argument if it is different than 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")> >>> # 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) – The 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 a witness type, default is ‘segwit’, for native segregated witness wallet. Use ‘legacy’ for an old-style wallets or ‘p2sh-segwit’ for legacy compatible wallets
encoding (str) – Encoding used for address generation: base58 or bech32. Default is derive from the 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 wallet’s cosigner_id may be different.
key_path (list, str) – Key path for a multisig wallet, use to create your own non-standard key path. Key path must follow the following rules: * Path starts with masterkey (m) and ends 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 the path is 8 levels
anti_fee_sniping (boolean) – Set default locktime in transactions as current block height + 1 to avoid fee-sniping. Default is True, which will make the network more secure. You could disable it to avoid transaction fingerprinting.
strict (boolean) – Set to False, to ignore non-standard signatures or script. Can be usefull for blockchain parsing or external transactions
ignore_dust (boolean) – Ignore dust outputs in unspent transaction outputs. The dust output amount is defined in the network settings. Default is True.
db_uri (str) – URI of the database for wallets, wallet transactions and keys
db_cache_uri (str) – URI of the cache database. If not specified, the default cache database is used when using sqlite, for other databasetypes the cache database is merged with the wallet database (db_uri)
db_password – Password to encrypt the database. Requires the installation of sqlcipher (see
documentation). :type db_password: str
- Return Wallet:
- property default_account_id
- get_key(account_id=None, witness_type=None, network=None, cosigner_id=None, change=0)[source]
Get an 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 repeatedly to receive a list of keys 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/84'/0'/0'/0/...)>
- Parameters:
account_id (int) – Account ID. Default is the last used or created account ID.
witness_type (str) – Use to create a key with a specific witness_type
network (str) – The network name. Leave empty for the 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, witness_type=None, network=None)[source]
Get an 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 the last used or created account ID.
witness_type (str) – Use to create a key with the specific witness_type
network (str) – The network name. Leave empty for default network
- Return WalletKey:
- get_keys(account_id=None, witness_type=None, network=None, cosigner_id=None, number_of_keys=1, change=0)[source]
Get a list of unused keys / addresses or create 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 the last used or created account ID.
witness_type (str) – Use to create a key with the specific witness_type
network (str) – The 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, witness_type=None, network=None, number_of_keys=1)[source]
Get an 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 the last used or created account ID.
witness_type (str) – Use to create a key with the specific witness_type
network (str) – The 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=84, key_type=None)[source]
Add a new single key to the wallet.
- Parameters:
account_id (int) – Account ID. Default is the last used or created account ID.
name (str) – Specify name for this key, leave empty for default
network (str) – The network name, method will try to extract from the key if not specified. Raises warning if network could not be detected
purpose (int) – BIP44 definition used, default is 84 (segwit)
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, witness_type=None, network=None, recreate=False)[source]
Wrapper for the keys_for_path method. Returns a single wallet key.
- Parameters:
path (list, str) – Part of the key path, i.e. [0, 0] for [change=0, address_index=0]
level_offset (int) – Just create part of the path, when creating keys. For example -2 means create a 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
witness_type (str) – Use to create key with different witness_type
network (str) – The 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, witness_type=None, network=None, include_private=False, as_dict=False)[source]
Search for keys in the 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) [<WalletKey(id=..., name='bitcoinlib_legacy_wallet_test', wif='xprv9s21ZrQH143K3cxbMVswDTYgAc9CeXABQjCD9zmXCpXw4MxN93LanEARbBmV3utHZS9Db4FX1C1RbC5KSNAjQ5WNJ1dDBJ34PjfiSgRvS8x'>]
Returns a list of WalletKey objects 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)
witness_type (str) – Filter by witness_type
network (str) – The network name filter
include_private (bool) – Include private key information in dictionary
as_dict (bool) – Return keys as dictionary objects. Default is False: WalletKey objects
- Return list of WalletKey or list of dict:
List of keys from this wallet
- keys_accounts(account_id=None, network='bitcoin', as_dict=False)[source]
Get Database records of account key(s) with for the 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 this wallet, 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) – The network name filter
as_dict (bool) – Return as dictionary or WalletKey object. Default is False: WalletKey objects
- Return list of (WalletKey, 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 the current wallet. Wrapper for the
keys()methods.- Parameters:
account_id (int) – Account ID
used (bool) – Only return used or unused keys
network (str) – The network name filter
as_dict (bool) – Return as dictionary or WalletKey object. Default is False: WalletKey objects
:return list of WalletKey, list of 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 the current wallet. Wrapper for the
keys()methods.- Parameters:
account_id (int) – Account ID
used (bool) – Only return used or unused keys
network (str) – The network name filter
as_dict (bool) – Return as dictionary or WalletKey object. Default is False: WalletKey objects
:return list of WalletKey, list of 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 the 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) – The network name filter
depth (int) – Filter by key depth. Default for BIP44 and multisig is 5
as_dict (bool) – Return as dictionary or WalletKey object. Default is False: WalletKey objects
:return list of WalletKey, list of dict
- keys_for_path(path, level_offset=None, name=None, account_id=None, cosigner_id=None, address_index=0, change=0, witness_type=None, network=None, recreate=False, number_of_keys=1)[source]
Return the key for the specified path. Derive all wallet keys in a path if they do not already exist
>>> w = wallet_create_or_open('key_for_path_example') >>> key = w.key_for_path([0, 0]) >>> key.path "m/84'/0'/0'/0/0"
>>> w.key_for_path([], level_offset=-2).path "m/84'/0'/0'"
>>> w.key_for_path([], w.depth_public_master + 1).path "m/84'/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/84’/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
witness_type (str) – Use to create key with different witness_type
network (str) – The 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
number_of_keys (int) – Number of keys to create, use to create keys in bulk fast
- Return list of WalletKey:
- 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() >>> network_key[0].path "m/44'/0'"
- Parameters:
used (bool) – Only return used or unused keys
as_dict (bool) – Return as dictionary or WalletKey object. Default is False: WalletKey objects
- Return list of WalletKey, list of dict:
- last_address_index(account_id=None, cosigner_id=0, change=0, network=None)[source]
Get last used address_index for this wallet
- Parameters:
account_id (int) – Account ID
cosigner_id (int) – ID of cosigner
change (int) – Change key = 1 or normal = 0, normally provided to ‘path’ argument
network (str) – The network name. Leave empty for default network
- Return int:
- 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 a 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, witness_type=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 this 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 the last accounts ID + 1
witness_type (str) – Use to create a key with the specific witness_type
network (str) – The network name. Leave empty for default network
- Return WalletKey:
- new_key(name='', account_id=None, change=0, cosigner_id=None, witness_type=None, network=None)[source]
def new_key(self, name=’’, account_id=None, change=0, cosigner_id=None, witness_type=None, network=None):
- Parameters:
name (str) – Key name. Does not have to be unique, but if you use it as a reference, you might choose to enforce this. If not specified ‘Key #’ with a unique sequence number will be used
account_id (int) – Account ID. Default is the last used or created account ID.
change (int) – Change (1) or payments (0). Default is 0
cosigner_id (int) – Cosigner ID for key path
witness_type (str) – Use to create key with different witness_type
network (str) – The network name. Leave empty for default network
- Return WalletKey:
- new_key_change(name='', account_id=None, witness_type=None, network=None)[source]
Create a new key to receive change for a transaction. Calls
new_key()method with change=1.- Parameters:
name (str) – Key name. The default name is ‘Change #’ with an address index
account_id (int) – Account ID. Default is the last used or created account ID.
witness_type (str) – Use to create key with different witness_type
network (str) – The network name. Leave empty for default network
- Return WalletKey:
- new_keys(name='', account_id=None, change=0, cosigner_id=None, witness_type=None, number_of_keys=1, 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/84'/0'/0'/0/...)>
- Parameters:
name (str) – Key name. Does not have to be unique, but if you use it as a reference, you might choose to enforce this. If not specified ‘Key #’ with a unique sequence number will be used
account_id (int) – Account ID. Default is the last used or created account ID.
change (int) – Change (1) or payments (0). The default is 0
cosigner_id (int) – Cosigner ID for key path
witness_type (str) – Use to create a key with different witness_type
number_of_keys (int) – Number of keys to generate. Use a positive integer
network (str) – The network name. Leave empty for default network
- Return list of 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 a key path. Specify part of the key path to expand to the key path used in this wallet.
>>> w = Wallet('create_legacy_wallet_test') >>> w.path_expand([0,1200]) ['m', "84'", "0'", "0'", '0', '1200']
>>> w = Wallet('create_legacy_multisig_wallet_test') >>> w.path_expand([0,2], cosigner_id=1) ['m', "48'", "0'", "0'", "2'", '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) – The network name. Leave empty for default network
- Return list:
- public_master(account_id=None, name=None, as_private=False, witness_type=None, network=None)[source]
Return the 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 returned as a 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
witness_type (str) – Witness type, leave empty for default witness_type
network (str) – The 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 the 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 the 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) – The 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 the specified wallet key and update wallet transactions
- Parameters:
key (WalletKey, int) – The wallet key as an 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, ignore_dust=None)[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 the selected network. Difference will be added to the 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) – The 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
ignore_dust (bool) – Do not include small amounts to avoid dust inputs. Default is to use the Wallet.ignore dust setting which is True by default.
- Returns:
List of selected unspent transaction outputs
- Return type:
list[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, broadcast=False, number_of_change_outputs=1, random_output_order=True, replace_by_fee=False)[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 the 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)]) >>> 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) – The 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
broadcast (bool) – Just return the transaction object and do not send it when broadcast = False. Default is False
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
random_output_order (bool) – Shuffle order of transaction outputs to increase privacy. Default is True
replace_by_fee (bool) – Signal replace by fee and allow to send a new transaction with higher fees. Sets sequence value to SEQUENCE_REPLACE_BY_FEE
- 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, broadcast=False, number_of_change_outputs=1, random_output_order=True, replace_by_fee=False)[source]
Create a transaction and send it with default Service objects
services.sendrawtransaction()method.Wrapper for the wallet
send()method.>>> w = Wallet('bitcoinlib_legacy_wallet_test') >>> t = w.send_to('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:
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) – The 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
broadcast (bool) – Just return the transaction object and do not send it when broadcast = False. Default is False
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
random_output_order (bool) – Shuffle order of transaction outputs to increase privacy. Default is True
replace_by_fee (bool) – Signal replace by fee and allow to send a new transaction with higher fees. Sets sequence value to SEQUENCE_REPLACE_BY_FEE
- Return WalletTransaction:
- property session
- sign_message(message, key_term=None, use_rfc6979=True, k=None, hash_type=1, force_canonical=False)[source]
Sign a message with this wallet and the provided key. If no key ID is provided, the message will be signed with the first available key.
- Parameters:
message (bytes, hexstring) – Message to be signed. Must be unhashed and in bytes format.
key_term (int, str) – Key ID or address of signing key. Search term can be key ID, key address, key WIF or key name
use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k
k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing wrong value for k can result in leaking your private key!
hash_type (int) – Specific hash type, default is SIGHASH_ALL
force_canonical (bool) – Some wallets require a canonical s value, so you could set this to True
- Return Signature:
- 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, broadcast=False, replace_by_fee=False)[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 [(<address>, <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) – The 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 the 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
broadcast (bool) – Just return the transaction object and do not send it when broadcast = False. Default is False
replace_by_fee (bool) – Signal replace by fee and allow to send a new transaction with higher fees. Sets sequence value to SEQUENCE_REPLACE_BY_FEE
- Return WalletTransaction:
- transaction(txid)[source]
Get WalletTransaction object for the provided 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, replace_by_fee=False, ignore_dust=None)[source]
Create a new transaction with specified outputs.
Inputs can be specified, but if not provided they will be selected from the 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) – The 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 a 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. The default is True
replace_by_fee (bool) – Signal replace-by-fee and allow you to send a new transaction with higher fees. Sets sequence value to SEQUENCE_REPLACE_BY_FEE
ignore_dust (bool) – Do not include small amounts to avoid dust inputs. Default is to use the Wallet.ignore dust setting which is True by default.
- Return WalletTransaction:
object
- transaction_delete(txid)[source]
Remove specified transaction from this wallet and update related transactions.
- Parameters:
txid (str) – Transaction ID of transaction to remove
- Returns:
- transaction_import(t)[source]
Import a Transaction into this wallet. Link inputs to wallet keys if possible and return a 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) – The network name. Leave empty for default network
- Return WalletTransaction:
- transaction_last(address)[source]
Get transaction ID for the latest transaction in the database for given address
- Parameters:
address (str) – The address
- Return str:
- transaction_load(txid=None, filename=None)[source]
Load a transaction object from a file which has been stored with the
Transaction.save()method.Specify transaction ID or filename.
- Parameters:
txid (str) – Transaction ID. The Transaction object will be read from .bitcoinlib datadir
filename (str) – Name of transaction object file
- Return WalletTransaction:
- transaction_spent(txid, output_n)[source]
Check if transaction with the given transaction ID and output_n is spent and return transaction IDs of spent transactions.
Retrieves information from the database, does not update the 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 a 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 the list. The default is False
limit (int) – Maximum number of transactions to return. Combine with an offset parameter to use as pagination
offset (int) – Number of transactions to skip
- Return list of WalletTransaction:
- transactions_remove_unconfirmed(hours_old=0, account_id=None, network=None)[source]
Removes all unconfirmed transactions from this wallet and updates related transactions / utxos.
- Parameters:
hours_old (int, float) – Only delete unconfirmed transactions which are x hours old. You can also use decimals, ie: 0.5 for half an hour
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
- Returns:
- 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 the 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) – The 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 a transaction or list or of transactions for this wallet with provided transaction IDs
- Parameters:
txids (str, list of str, bytes, list of bytes) – Transaction ID, or list of transaction IDs
- Returns:
- transactions_update_confirmations()[source]
Update the number of confirmations and the status of transactions in the 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 the standard method of retrieving 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 the latest unspent output in the database for the specified 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 the 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) – The network name. Leave empty for default network
min_confirms (int) – Minimal confirmation needed to include in the 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
- verify_message(message, signature, key_term=None)[source]
Verify if a provided message is signed by the provided signature and matches a public key from this wallet.
If no key_term is provided, it will check the signature against all known keys for this wallet. This can be slow for larger wallets.
- Parameters:
message (bytes, hexstring) – Message to verify. Must be unhashed and in bytes format.
signature (Signature) – signature as Signature object
key_term (int, str) – Key ID or address of verifying key. Search term can be key ID, key address, key WIF or key name
- Return bool:
- wif(is_private=False, account_id=0)[source]
Return Wallet Import Format string for a 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:
- witness_types(account_id=None, network=None)[source]
Get witness types in use by this wallet. For example, ‘legacy’, ‘segwit’, ‘p2sh-segwit’
- Parameters:
account_id (int) – Account ID. Leave empty for the default account
network (str) – The network name filter. The default filter is DEFAULT_NETWORK
- Returns:
list of witness types for this Wallet class
- Return type:
list of str
- exception bitcoinlib.wallets.WalletError(msg='')[source]
Bases:
ExceptionHandle Wallet class Exceptions
- class bitcoinlib.wallets.WalletKey(key_id, session, hdkey_object=None)[source]
Bases:
objectUsed as an attribute of the 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 the database.
- Parameters:
key_id (int) – ID of the key as mentioned in the database
session (sqlalchemy.orm.session.Session) – Required Sqlalchemy Session object
hdkey_object (HDKey) – Optional HDKey object. Specify an HDKey object if available to increase performance
- as_dict(include_private=False)[source]
Return current key information as a dictionary
- Parameters:
include_private (bool) – Include private key information in dictionary
- static from_key(name, wallet_id, session, key, account_id=0, network=None, change=0, purpose=84, parent_id=0, path='m', key_type=None, encoding=None, witness_type='segwit', multisig=False, cosigner_id=None, new_key_id=None)[source]
Create WalletKey from an 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 'bc1qukcgc3guzt0a27j7vdegtgwxsrv4khc4688ycs' >>> wk <WalletKey(key_id=..., name=import_key, wif=zprvAWgYBBk7JR8GjN16pTBZUQvAgYBvsFM9g6Pu33oScnYHTEzphkbYKFHckMNncUg3kug1jAs1c3uNXiKWTYmHs5xPc5EQSwihPGvZwGiZeKD, 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 84
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 encoding
witness_type (str) – Witness type used when creating transaction script: legacy, p2sh-segwit or segwit.
multisig (bool) – Specify if the key is part of a 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.
new_key_id (int) – Key ID in the database (DbKey.id), use to directly insert key in the database without checks and without commiting. Mainly for internal usage, to significantly increase speed when inserting multiple keys.
- Return WalletKey:
The wallet key object
- property name
Return name of the wallet key
- Return str:
- public()[source]
Return the current key as a public WalletKey object with all private information removed
- Return WalletKey:
- sign_message(message, use_rfc6979=True, k=None, hash_type=1, force_canonical=False)[source]
Sign a message with this wallet key
- Parameters:
message (bytes, hexstring) – Message to be signed. Must be unhashed and in bytes format.
use_rfc6979 (bool) – Use deterministic value for k nonce to derive k from txid/message according to RFC6979 standard. Default is True, set to False to use random k
k (int) – Provide own k. Only use for testing or if you know what you are doing. Providing a wrong value for k can result in leaking your private key!
hash_type (int) – Specific hash type, default is SIGHASH_ALL
force_canonical (bool) – Some wallets require a canonical s value, so you could set this to True
- Return Signature:
- class bitcoinlib.wallets.WalletTransaction(hdwallet, account_id=None, *args, **kwargs)[source]
Bases:
TransactionUsed as an attribute of the Wallet class. Child of the Transaction object with an extra reference to the wallet and database object.
All WalletTransaction items are stored in a database
Initialize a 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
- add_input_from_wallet(amount_min=0, key_id=None, min_confirms=1)[source]
Add a new input from an utxo of this wallet. If key_id is not specified, it adds the first input it finds with the minimum amount and minimum confirms specified.
WARNING: Change output and fees are not updated, so you risk overpaying fees!
- Parameters:
amount_min (int) – Minimum value of new input
key_id (int) – Filter by this key id
min_confirms (int) – Minimum confirms of utxo
- Return int:
Index number of new input
- bumpfee(fee=0, extra_fee=0, broadcast=False)[source]
Increase the fee for this transaction. If replace-by-fee is signaled in this transaction, the fee can be increased to speed up inclusion on the blockchain.
If no fee or extra_fee is provided, the extra fee will be increased by the formule you can find in the code below using the BUMPFEE_DEFAULT_MULTIPLIER from the config settings.
The extra fee will be deducted from change output. This method fails if there are not enough change outputs to cover fees.
If this transaction does not have enough inputs to cover an extra fee, an extra wallet utxo will be aaded to inputs if available.
Previous broadcasted transaction will be removed from the wallet with this replace-by-fee transaction and wallet information updated.
- Parameters:
fee (int) – New fee for this transaction
extra_fee (int) – Extra fee to add to the current transaction fee
broadcast (bool) – Increase fee and directly broadcast transaction to the network
- Return None:
- delete()[source]
Delete this transaction from the 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 a 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 a WalletTransaction object from a Transaction object
- Parameters:
hdwallet (HDwallet, str, int) – Wallet object, wallet name or ID
t (Transaction) – Specify Transaction object
- Return WalletTransaction:
- classmethod from_txid(hdwallet, txid)[source]
Read a single transaction from the database with a given transaction ID / transaction hash
- Parameters:
hdwallet (Wallet) – Wallet object
txid (str, bytes) – Transaction hash as hexadecimal string
- Return WalletTransaction:
- save(filename=None)[source]
Store the transaction object as a file, so it can be imported in bitcoinlib later with the
load()method.- Parameters:
filename (str) – Location and name of the file, leave empty to store transaction in bitcoinlib data directory: .bitcoinlib/<transaction_id.tx)
- Returns:
- send(broadcast=True)[source]
Verify and push transaction to network. Update UTXO’s in the database after sending was successful.
- Parameters:
broadcast (bool) – Verify transaction and broadcast, if set to False, the transaction is verified but not broadcasted, i. Default is True
- 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 this 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 the 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, anti_fee_sniping=True, strict=True, ignore_dust=True, db_uri=None, db_cache_uri=None, db_password=None)[source]
Create a wallet with specified options if it doesn’t exist, otherwise open the existing wallet.
Returns Wallet object
See Wallets class create method for option documentation
- bitcoinlib.wallets.wallet_delete(wallet, db_uri=None, force=False, db_password=None)[source]
Delete wallet and associated keys and transactions from the database. If the 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
db_password (str) – Password to use for the encrypted database. Requires the installation of sqlcipher (see documentation).
- Return int:
Number of rows deleted, so 1 if successful
- bitcoinlib.wallets.wallet_delete_if_exists(wallet, db_uri=None, force=False, db_password=None)[source]
Delete wallet and associated keys from the database. If the 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
db_password (str) – Password to use for the encrypted database. Requires the installation of sqlcipher (see documentation).
- Return int:
Number of rows deleted, so 1 if successful
- bitcoinlib.wallets.wallet_empty(wallet, db_uri=None, db_password=None)[source]
Remove all generated keys and transactions from the 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
db_password (str) – Password to use for the encrypted database. Requires the installation of sqlcipher (see documentation).
- Return bool:
True if successful
- bitcoinlib.wallets.wallet_exists(wallet, db_uri=None, db_password=None)[source]
Check if Wallets is defined in the database
- Parameters:
wallet (int, str) – Wallet ID as integer or Wallet Name as string
db_uri (str) – URI of the database
db_password (str) – Password to use for the encrypted database. Requires the installation of sqlcipher (see documentation).
- Return bool:
True if the wallet exists otherwise False
- bitcoinlib.wallets.wallets_list(db_uri=None, include_cosigners=False, db_password=None)[source]
List Wallets from the 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
db_password (str) – Password to use for the encrypted database. Requires the installation of sqlcipher (see documentation).
- Return dict:
Dictionary of wallets defined in the database