The 21 Machine Wallet (two1.wallet)

Posted by Nigel Drego

The 21 Machine Wallet (two1.wallet)

The wallet module within the 21 Bitcoin Library (two1.wallet) provides a fully-functional HD wallet that integrates with 21 and is optimized for machine-to-machine transactions. The wallet conforms to both BIP-32 https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki and BIP-44 https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki. It can be accessed both via the command line and programmatically.

Using two1.wallet via the wallet command line

Command-line interaction with the wallet is provided via a Click-based CLI implemented in

A wallet can be created via the command-line:

$ wallet create
Wallet successfully created!
Your wallet can be recovered using the following set of words (in that order).
Please store them safely.

home enter delay insect dose airport drink damp awake hedgehog toaster dawn

Or, if a different location is desired:

$ wallet -wp ~/test_wallets/test_wallet.json create
Wallet successfully created!
Your wallet can be recovered using the following set of words (in that order).
Please store them safely.

home enter delay insect dose airport drink damp awake hedgehog toaster dawn

In either case, the mnemonic (set of words) given should be backed up as it can be used to restore the wallet should there be any corruption, disk loss, etc.

Using two1.wallet programmatically

To create a wallet programmatically, the easiest way is to use Two1Wallet.configure():

from two1.blockchain.twentyone_provider import TwentyOneProvider
from two1.wallet.two1_wallet import Two1Wallet

options = dict(account_type="BIP32",
               data_provider=TwentyOneProvider(),
               passphrase="",  # Can be set to a passphrase, empty, or not provided
               testnet=False,
               wallet_path="/tmp/auto-wallet.json"
              )  # Or True if the wallet will be used with testnet

configured =  Two1Wallet.configure(options)

configured will be True if the wallet was created successfully. If the wallet should be created in a location other than the default, add wallet_path="..." to options.

In the above snippet, a data_provider was required. The Two1Wallet class makes use of the data provider to get blockchain information such as:

  • Address balances
  • Unspent transaction outputs (UTXOs) for addresses
  • Transactions

It also uses the data provider to broadcast transactions to the blockchain. The wallet is agnostic as to where it gets required data as long as the data provider meets the API specification in two1.blockchain.base_provider. This means you can write your own provider should you want to use something other than the default TwentyOneProvider.

The recommended way to interact with the created wallet is to make use of two1.wallet.two1_wallet.Wallet to initiate a Two1Wallet object. A very simple example to get the wallet's current payout address is:

from two1.wallet.two1_wallet import Wallet

w = Wallet()

print("payout address: %s" % w.get_payout_address())

It also assumes that the caller wants the currently logged-in user's default wallet (found in :file:~/.two1/wallet/default_wallet.json). Should the path to the desired wallet be different than this, the wallet_path argument can be provided:

from two1.wallet.two1_wallet import Wallet

w = Wallet(wallet_path='/tmp/auto-wallet.json')

print("payout address: %s" % w.get_payout_address())

two1.wallet.two1_wallet

This submodule provides the main Two1Wallet and Wallet classes.

class two1.wallet.two1_wallet.Two1Wallet(params_or_file, data_provider, passphrase='', utxo_selector=<function utxo_selector_smallest_first>, skip_discovery=False)

Bases: two1.wallet.base_wallet.BaseWallet

An HD wallet class capable of handling multiple types of wallets.

This wallet can implement a variety of account types, including: pure BIP-32, pure BIP-44, Hive, and Mycelium variants.

This class depends on pluggable elements which allow flexibility to use different backend data providers (bitcoind, chain.com, etc.) as well as different UTXO selection algorithms. In particular, these elements are:

  1. A bitcoin data provider class that implements the abstract class found in two1.blockchain.BaseProvider.
  2. A unspent transaction output selector (utxo_selector):

utxo_selector should be a filtering function with prototype:

selected, fees = utxo_selector_func(list(UnspentTransactionOutput), amount, num_outputs, fees)

The job of the selector is to choose from the input list of UTXOs which are to be used in a transaction such that there are sufficient coins to pay the total amount (2nd passed argument) and transaction fees. Since transaction fees are computed based on size of transaction, which is in turn (partially) determined by number of inputs and number of outputs (3rd passed argument), the selector must determine the required fees and return that amount as well, unless fees (5th passed argument) is not None in which case the application is specifiying the fees.

The return value must be a tuple where the first item is a dict keyed by address with a list of selected UnspentTransactionOutput objects and the second item is the fee amount (in satoshis).

This is pluggable to allow for different selection criteria, i.e. fewest number of inputs, oldest UTXOs first, newest UTXOs first, minimize change amount, etc.

Parameters:
  • params (dict) – A dict containing at minimum a “master_key” key with a Base58Check encoded HDPrivateKey as the value.
  • data_provider (BaseProvider) – An instance of a derived two1.blockchain.BaseProvider class as described above.
  • passphrase (str) – Passphrase to unlock wallet key if it is locked.
  • utxo_selector (function) – A filtering function with the prototype documented above.
  • skip_discovery (bool) – If True, skips account and address discovery. This should only be set to True on account creation!
Returns:

The wallet instance.

Return type:

Two1Wallet

AES_BLOCK_SIZE = 16
DEFAULT_ACCOUNT_TYPE = 'BIP32'
DEFAULT_WALLET_PATH = '~/.two1/wallet/default_wallet.json'
WALLET_CACHE_VERSION = '0.1.0'

The configuration options available for creating the wallet.

The keys of this dictionary are the available configuration settings/options for the wallet. The value for each key represents the possible values for each option. e.g. {key_style: [“HD”,”Brain”,”Simple”], ....}

WALLET_FILE_VERSION = '0.1.0'
account_map

Returns the mapping of account name to account index.

Returns:Key/value pairs of account names and indices.
Return type:dict
account_names

Names of all accounts in the wallet.

Returns:list – All account names.
Return type:str
accounts

All accounts in the wallet.

Returns:list – List of HDAccount objects.
Return type:HDAccount
address_belongs(address)

Returns the full path for generating this address.

Parameters:address (str) – Base58Check encoded bitcoin address.
Returns:The full key derivation path if found. Otherwise, returns None.
Return type:str or None
addresses(accounts=[])

Gets the address list for the current wallet.

Parameters:accounts (list) – A list of either account indices or names.
Returns:A dict keyed by account name containing a list of bitcoin addresses for that account.
Return type:dict
balances

Balance for the wallet.

Returns:Keys are ‘confirmed’ and ‘total’ with values being in satoshis. The ‘total’ balance includes any unconfirmed transactions.
Return type:dict
balances_by_address(account_name_or_index)

Returns a dict of balances by address

Parameters:account_name_or_index (str or int) – The account to retrieve the balances for.
Returns:key/value pairs of address and balance
Return type:dict
broadcast_transaction(tx)

Broadcasts the transaction to the Bitcoin network.

Parameters:tx (str or bytes or Transaction) – Transaction to be broadcasted to the Bitcoin network.
Returns:The name of the transaction that was broadcasted.
Return type:str
build_signed_transaction(addresses_and_amounts, use_unconfirmed=False, insert_into_cache=False, expiration=0, fees=None, accounts=[])

Makes raw signed unbroadcasted transaction(s) for the specified amount.

In the future, this function may create multiple transactions if a single one would be too big.

Parameters:
  • addresses_and_amounts (dict) – A dict keyed by recipient address and corresponding values being the amount - in satoshis - to send to that address.
  • use_unconfirmed (bool) – Use unconfirmed transactions if necessary.
  • insert_into_cache (bool) – Insert the transaction into the wallet’s cache and mark it as provisional.
  • expiration (int) – Time, in seconds from epoch, when a provisional transaction should be automatically pruned. This is invalid unless insert_into_cache=True. If expiration == 0, it is set to time.time() + CacheManager.PROVISIONAL_MAX_DURATION. This cannot be greater than CacheManager.PROVISIONAL_MAX_DURATION seconds in the future.
  • fees (int) – Specify the fee amount manually.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts may be used based on the chosen UTXO selection algorithm.
Returns:

list – A list of WalletTransaction objects

Return type:

WalletTransaction

static check_wallet_file(wallet_path='~/.two1/wallet/default_wallet.json')

Returns whether the specified wallet file exists and contains the minimum set of parameters required to load the wallet.

Returns:True if the wallet file exists and is ready to use, False otherwise.
Return type:bool
config_options = {'testnet': [True, False], 'data_provider': <class 'two1.blockchain.base_provider.BaseProvider'>, 'account_type': dict_keys(['BIP32', 'Hive', 'BIP44Testnet', 'BreadWallet', 'Mycelium', 'BIP44BitcoinMainnet']), 'passphrase': '', 'wallet_path': ''}
static configure(config_options)

Creates a wallet.

If ‘wallet_path’ is found in config_options, the wallet is stored at that location. Otherwise, it is created in ~/.two1/wallet/default_wallet.json.

Parameters:config_options (dict) – A dict of config options, the keys and allowed values of each key are found in the class variable of the same name.
Returns:True if the wallet was created and written to disk, False otherwise.
Return type:bool
confirmed_balance(account_name_or_index=None)

Gets the current confirmed balance of the wallet in Satoshi.

Parameters:account_name_or_index (str or int) – The account to retrieve the payout address from. If not provided, the default account (0’) is used.
Returns:The current confirmed balance.
Return type:number
static create(data_provider, passphrase='', account_type='BIP32', utxo_selector=<function utxo_selector_smallest_first>, testnet=False)

Creates a Two1Wallet using a random seed.

This will create a wallet using the default account type (currently BIP32).

Parameters:
  • data_provider (BaseProvider) – An instance of a derived two1.blockchain.BaseProvider class as described above.
  • passphrase (str) – A passphrase to lock the wallet with.
  • account_type (str) – One of the account types in account_types.py.
  • utxo_selector (function) – A filtering function with the prototype documented above.
  • testnet (bool) – Whether or not this wallet will be used for testnet.
Returns:

tuple – The wallet instance and the mnemonic

Return type:

Two1Wallet, mnemonic

create_account(name)

Creates an account.

Note

Account creation may fail if there is an existing account that has no transactions associated with it as creating a new account would violate the BIP-44 account discovery protocol: https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#Account_discovery or There is an existing account with the same name.

Parameters:name (str) – The name of the account.
Returns:True if account creation was successful, False otherwise.
Return type:bool
current_address

Gets the preferred address.

Returns:The current preferred payment address.
Return type:str
static decrypt(master_key_enc, master_seed_enc, passphrase, key_salt)
discover_accounts()

Discovers all accounts associated with the wallet.

Account discovery is accomplished by the discovery procedure outlined in BIP44. Namely, we start with account 0’, check to see if there are used addresses. If there are, we continue to account 1’ and proceed until the first account with no used addresses.

The discovered accounts are stored internally, but can be retrieved with the Two1Wallet.accounts property.

static encrypt(master_key, master_seed, passphrase, key_salt)
find_addresses(addresses)

Returns the paths to the address, if found.

All discovered accounts are checked. Within an account, all addresses up to GAP_LIMIT (20) addresses beyond the last known index for the chain are checked.

Parameters:addresses (list) – list of Base58Check encoded addresses.
Returns:Dict keyed by address with the path (account index first) corresponding to the derivation path for that key.
Return type:dict
get_account_name(index)

Returns the account name for the given index.

Note

The name of the account is a convenience item only - it serves no purpose other than being a human-readable identifier.

Parameters:index (int) – The index of the account to retrieve the name for.
Returns:The name of the account if found, or None.
Return type:str or None
get_change_address(account_name_or_index=None)

Gets the next change address.

Parameters:account_name_or_index (str or int) – The account to retrieve the change address from. If not provided, the default account (0’) is used.
Returns:A Base58Check encoded bitcoin address.
Return type:str
get_change_public_key(account_name_or_index=None)

Gets the next change public_key.

Parameters:account_name_or_index (str or int) – The account to retrieve the change address from. If not provided, the default account (0’) is used.
Returns:A public key object
Return type:PublicKey
get_message_signing_public_key(account_name_or_index=None, key_index=0)

Retrieves the public key typically used for message signing. The default is to use the first account and the 0-th public key from the payout (external) chain.

Parameters:
  • account_name_or_index (str or int) – The account to retrieve the public key from. If not provided, the default account (0’) is used.
  • key_index (int) – The index of the key in the external chain to use.
Returns:

The public key object

Return type:

PublicKey

get_payout_address(account_name_or_index=None)

Gets the next payout address.

Parameters:account_name_or_index (str or int) – The account to retrieve the payout address from. If not provided, the default account (0’) is used.
Returns:A Base58Check encoded bitcoin address.
Return type:str
get_payout_public_key(account_name_or_index=None)

Gets the next payout public key.

Parameters:account_name_or_index (str or int) – The account to retrieve the payout address from. If not provided, the default account (0’) is used.
Returns:A public key object
Return type:PublicKey
get_private_for_public(public_key)

Returns the private key for the given public_key, if it is a part of this wallet.

Parameters:public_key (PublicKey) – The public key object to retrieve the private key for.
Returns:A private key object or None.
Return type:PrivateKey
get_private_key(address)

Returns the private key corresponding to address, if it is a part of this wallet.

Parameters:address (str) – A Base58Check encoded bitcoin address
Returns:A private key object or None.
Return type:PrivateKey
get_private_keys(addresses)

Returns private keys for a list of addresses, if they are a part of this wallet.

get_utxos(include_unconfirmed=False, accounts=[])

Returns all UTXOs for all addresses in all specified accounts.

Parameters:
  • include_unconfirmed (bool) – If True, includes any unconfirmed UTXOs.
  • accounts (list) – A list of either account indices or names.
Returns:

A dict keyed by address containing a list of UnspentTransactionOutput objects for that address. Only addresses for which there are current UTXOs are included.

Return type:

dict

get_utxos_above_threshold(threshold, include_unconfirmed=False, accounts=[])

Returns all UTXOs >= threshold satoshis.

Parameters:
  • threshold (int) – UTXO value must be >= to this value.
  • include_unconfirmed (bool) – Include unconfirmed UTXOs.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts will be done.
static import_from_mnemonic(data_provider=None, mnemonic=None, passphrase='', utxo_selector=<function utxo_selector_smallest_first>, account_type='BIP32')

Creates a Two1Wallet from an existing mnemonic.

Parameters:
  • mnemonic (str) – The mnemonic representing the wallet seed.
  • data_provider (BaseProvider) – An instance of a derived two1.blockchain.BaseProvider class as described above.
  • passphrase (str) – A passphrase to lock the wallet with.
  • utxo_selector (function) – A filtering function with the prototype documented above.
  • account_type (str) – One of the account types in account_types.py.
Returns:

The wallet instance.

Return type:

Two1Wallet

static is_configured()

Returns the configuration/initialization status of the wallet.

Returns:True if the default wallet has been configured and ready to use. Otherwise False.
Return type:bool
static is_locked(wallet_path='~/.two1/wallet/default_wallet.json')

Returns whether a wallet is locked with a passphrase.

Returns:True if the wallet has been locked with a passphrase, False otherwise.
Return type:bool
logger = <two1.commands.util.logger.ClickLogger object>
make_signed_transaction_for(address, amount, use_unconfirmed=False, insert_into_cache=False, expiration=0, fees=None, accounts=[])

Makes a raw signed unbroadcasted transaction for the specified amount.

Parameters:
  • address (str) – The address to send the Bitcoin to.
  • amount (number) – The amount of Bitcoin to send.
  • use_unconfirmed (bool) – Use unconfirmed transactions if necessary.
  • insert_into_cache (bool) – Insert the transaction(s) into the wallet’s cache and mark it as provisional.
  • expiration (int) – Time, in seconds from epoch, when a provisional transaction should be automatically pruned. This is invalid unless insert_into_cache=True. If expiration == 0, it is set to time.time() + CacheManager.PROVISIONAL_MAX_DURATION. This cannot be greater than CacheManager.PROVISIONAL_MAX_DURATION seconds in the future.
  • fees (int) – Specify the fee amount manually.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts may be used based on the chosen UTXO selection algorithm.
Returns:

list – A list of dicts containing transaction names and raw transactions. e.g.: [{“txid”: txid0, “txn”: txn_hex0}, ...]

Return type:

dict

make_signed_transaction_for_multiple(addresses_and_amounts, use_unconfirmed=False, insert_into_cache=False, expiration=0, fees=None, accounts=[])

Makes raw signed unbroadcasted transaction(s) for the specified amount.

In the future, this function may create multiple transactions if a single one would be too big.

Parameters:
  • addresses_and_amounts (dict) – A dict keyed by recipient address and corresponding values being the amount - in satoshis - to send to that address.
  • use_unconfirmed (bool) – Use unconfirmed transactions if necessary.
  • insert_into_cache (bool) – Insert the transaction(s) into the wallet’s cache and mark it as provisional.
  • expiration (int) – Time, in seconds from epoch, when a provisional transaction should be automatically pruned. This is invalid unless insert_into_cache=True. If expiration == 0, it is set to time.time() + CacheManager.PROVISIONAL_MAX_DURATION. This cannot be greater than CacheManager.PROVISIONAL_MAX_DURATION seconds in the future.
  • fees (int) – Specify the fee amount manually.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts may be used based on the chosen UTXO selection algorithm.
Returns:

list – A list of dicts containing transaction names and raw transactions. e.g.: [{“txid”: txid0, “txn”: txn_hex0}, ...]

Return type:

dict

required_params = ['master_key', 'locked', 'key_salt', 'passphrase_hash', 'account_type']
send_to(address, amount, use_unconfirmed=False, fees=None, accounts=[])

Sends Bitcoin to the provided address for the specified amount.

Parameters:
  • address (str) – The address to send the Bitcoin too.
  • amount (int) – The amount of Bitcoin - in satoshis - to send.
  • use_unconfirmed (bool) – Use unconfirmed transactions if necessary.
  • fees (int) – Specify the fee amount manually.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts may be used based on the chosen UTXO selection algorithm.
Returns:

list – A list of dicts containing transaction names and raw transactions. e.g.: [{“txid”: txid0, “txn”: txn_hex0}, ...]

Return type:

dict

send_to_multiple(addresses_and_amounts, use_unconfirmed=False, fees=None, accounts=[])

Sends bitcoins to multiple addresses.

Parameters:
  • addresses_and_amounts (dict) – A dict keyed by recipient address and corresponding values being the amount - in satoshis - to send to that address.
  • use_unconfirmed (bool) – Use unconfirmed transactions if necessary.
  • fees (int) – Specify the fee amount manually.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts may be used based on the chosen UTXO selection algorithm.
Returns:

A string containing the submitted TXID or None.

Return type:

str or None

sign_bitcoin_message(message, address)

Bitcoin signs an arbitrary message.

This function signs the message using a specific key in a specific account. By default, if account or key are not given, it will use the first (default) account and the 0-th public key. In all circumstances it uses keys from the payout (external) chain.

Note

0x18 + b”Bitcoin Signed Message:” + newline + len(message) is prepended to the message before signing.

Parameters:
  • message (bytes or str) – Message to be signed.
  • address (str) – Bitcoin address from which the private key will be retrieved and used to sign the message.
Returns:

A Base64-encoded string of the signature. The first byte of the encoded message contains information about how to recover the public key. In bitcoind parlance, this is the magic number containing the recovery ID and whether or not the key was compressed or not. (This function always processes full, uncompressed public-keys, so the magic number will always be either 27 or 28).

Return type:

str

sign_message(message, account_name_or_index=None, key_index=0)

Signs an arbitrary message.

This function signs the message using a specific key in a specific account. By default, if account or key are not given, it will use the first (default) account and the 0-th public key. In all circumstances it uses keys from the payout (external) chain.

Note

This is different from sign_bitcoin_message as there is nothing prepended to the message and the signature recovery id is not provided, making public key recovery impossible.

Parameters:
  • message (bytes or str) – Message to be signed.
  • account_name_or_index (str or int) – The account to retrieve the change address from. If not provided, the default account (0’) is used.
  • key_index (int) – The index of the key in the external chain to use.
Returns:

A Base64-encoded string of the signature.

Return type:

str

spread_utxos(threshold, num_addresses, accounts=[])

Spreads out UTXOs >= threshold satoshis to a set of new change addresses.

Parameters:
  • threshold (int) – UTXO value must be >= to this value (in satoshis).
  • num_addresses (int) – Number of addresses to spread out the matching UTXOs over. This must be > 1 and <= 100.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts will be done.
sweep(address, accounts=[], fee_calculator=<function _fee_calc>)

Sweeps the entire balance to a single address.

Parameters:
  • address (str) – Bitcoin address to send entire balance to.
  • accounts (list) – List of accounts to use. If not provided, all discovered accounts will be done.
  • fee_calculator (callable) – A callable that calculates the fee needed in satoshis from positional arguments corresponding to: the number of input utxos, the total value of the wallet, and a dictionary containing keys ‘per_kb’, ‘per_input’ and ‘per_output’ corresponding to the estimated fee per kb, per input, and per output in satoshis respectively.
Returns:

list – List of txids used to complete the sweep.

Return type:

str

sync_accounts()

Syncs all accounts with the blockchain and prunes all expired provisional transactions.

sync_wallet_file(force_cache_write=False)

Syncs all wallet data to the wallet file used to construct this wallet instance, if one was used.

testnet

Getter testnet property

to_dict()

Creates a dict of critical parameters.

Returns:A dict containing key/value pairs that is JSON serializable.
Return type:dict
to_file(file_or_filename, force_cache_write=False)

Writes all wallet information to a file.

transaction_history(accounts=[])

Returns a list containing all transactions associated with this wallet. Transactions are ordered from oldest to most recent.

unconfirmed_balance(account_name_or_index=None)

Gets the current total balance of the wallet in Satoshi, including unconfirmed transactions

Parameters:account_name_or_index (str or int) – The account to retrieve the payout address from. If not provided, the default account (0’) is used.
Returns:The current unconfirmed balance.
Return type:number
verify_bitcoin_message(message, signature, address)

Verifies a bitcoin signed message

Parameters:
  • message (bytes or str) – The message that the signature corresponds to.
  • signature (bytes or str) – A Base64 encoded signature.
  • address (str) – Base58Check encoded address corresponding to the uncompressed key.
Returns:

True if the signature verified properly, False otherwise.

Return type:

bool

class two1.wallet.two1_wallet.Wallet(wallet_path='~/.two1/wallet/default_wallet.json', data_provider=None, passphrase='')

Bases: object

Abstraction layer over wallet object

Rather than using the Two1Wallet class, this class should be used in the vast majority of cases. An example of when the Two1Wallet class should be used instead is creating/configuring a wallet.

This abstraction will make it easy to transparently add alternative wallet backends in the future, such as a wallet backend that caches transaction data.

Parameters:
  • wallet_path (str) – Path to the wallet to be opened. If no path is provided, Two1Wallet.DEFAULT_WALLET_PATH is used.
  • data_provider (BaseProvider) – A blockchain data provider object. If no data provider is passed in, a TwentyOneProvider with the default host is used.
  • passphrase (str) – Passphrase used to unlock the wallet, if necessary.
Returns:

A proxy object.

Return type:

Two1WalletProxy

two1.wallet.base_wallet module

This submodule provides abstract base classes implemented by two1_wallet.

class two1.wallet.base_wallet.BaseWallet

Bases: object

An abstract wallet class.

addresses

Gets the address list for the current wallet.

Returns:The current list of addresses in this wallet.
Return type:list
balance()

Gets the confirmed balance of the wallet in Satoshi.

Returns:The current confirmed balance.
Return type:number
broadcast_transaction(tx)

Broadcasts the transaction to the Bitcoin network.

Parameters:tx (str) – Hex string serialization of the transaction to be broadcasted to the Bitcoin network..
Returns:The name of the transaction that was broadcasted.
Return type:str
config_options = {}
static configure(config_options)

Automatically configures the wallet with the provided configuration options

confirmed_balance()

Gets the current confirmed balance of the wallet in Satoshi.

Returns:The current confirmed balance.
Return type:number
current_address

Gets the preferred address.

Returns:The current preferred payment address.
Return type:str
static is_configured()

Returns the configuration/initialization status of the wallet.

Returns:True if the wallet has been configured and ready to use otherwise False
Return type:bool
make_signed_transaction_for(address, amount)

Makes a raw signed unbrodcasted transaction for the specified amount.

Parameters:
  • address (str) – The address to send the Bitcoin to.
  • amount (number) – The amount of Bitcoin to send.
Returns:

list – A list of dicts containing transaction names and raw transactions. e.g.: [{“txid”: txid0, “txn”: txn_hex0}, ...]

Return type:

dict

send_to(address, amount)

Sends Bitcoin to the provided address for the specified amount.

Parameters:
  • address (str) – The address to send the Bitcoin to.
  • amount (number) – The amount of Bitcoin to send.
Returns:

list – A list of dicts containing transaction names and raw transactions. e.g.: [{“txid”: txid0, “txn”: txn_hex0}, ...]

Return type:

dict

unconfirmed_balance()

Gets the current unconfirmed balance of the wallet in Satoshi.

Returns:The current unconfirmed balance.
Return type:number
two1.wallet.base_wallet.convert_to_btc(satoshis)

Converts an amount in satoshis to BTC.

The return value of this function should only be used for display purposes. All internal calculations should be done using satoshis (integers)

Parameters:satoshis (int) – Amount in satoshis
Returns:Amount in BTC
Return type:decimal
two1.wallet.base_wallet.convert_to_satoshis(btc)

Converts an amount in BTC to satoshis.

This function takes care of rounding and quantization issues (i.e. IEEE-754 precision/representation) and guarantees the correct BTC value. Specifically, any floating point digits beyond 1e-8 will be rounded to the nearest satoshi.

Parameters:btc (float) – Amount in BTC.
Returns:Amount in satoshis.
Return type:int

two1.wallet.hd_account module

This submodule implements HDAccount, which provides a single HD account that is used in an HD (“hierarchical deterministic”) wallet.

class two1.wallet.hd_account.HDAccount(hd_key, name, index, data_provider, cache_manager, testnet=False, last_state=None, skip_discovery=False)

Bases: object

An implementation of a single HD account to be used in an HD wallet.

This class handles key generation/management for both internal (change) and external (payout) purposes. If provided with only a public key, it is only useful for public key generation/management. If a private key is provided instead, private keys can be generated for signing (spending) purposes.

Transaction signing capability is NOT provided by this class. This is a conscious design decision as the wallet is better suited to signing & spending as there may be situations requiring spending coins from multiple accounts in a single transaction.

This relies on a data provider that derives from TransactionDataProvider, which provides transaction data and balance information for provided addresses.

Parameters:
  • hd_key (HDKey) – Either a HDPrivateKey (enables private key generation) or HDPublicKey which is the root of this account.
  • name (str) – Name of this account
  • index (int) – Child index of this account relative to the parent.
  • data_provider (BaseProvider) – A compatible data provider.
  • testnet (bool) – Whether or not this account will be used on testnet.
CHANGE_CHAIN = 1
DISCOVERY_INCREMENT = 100
GAP_LIMIT = 20
MAX_UPDATE_THRESHOLD = 30
PAYOUT_CHAIN = 0
all_used_addresses

List of all used addresses

Returns:list – list of all used addresses (Base58Check encoded)
Return type:str
balance

Returns balances, both confirmed and total, for this account.

Returns:‘confirmed’ and ‘total’ keys with balance values in satoshis for each. The total balance includes unconfirmed transactions.
Return type:dict
balances_by_address()

Returns a dict with balances for each used address in the account

Returns:key/values are addresses and current balance
Return type:dict
find_addresses(addresses)

Searches both the change and payout chains up to self.GAP_LIMIT addresses beyond the last known index for the chain.

Parameters:addresses (list(str) – List of Base58Check encoded addresses
Returns:Dictionary keyed by address where the value is a tuple containing the chain (0 or 1) and child index in the chain. Only found addresses are included in the dict.
Return type:dict
get_address(change, n=-1)

Returns a public address

Parameters:
  • change (bool) – If True, returns an address for change purposes, otherwise returns an address for payment.
  • n (int) – index of address in chain. If n == -1, a new key is created with index = self.last_[change|payout]_index + 1
Returns:

A bitcoin address

Return type:

str

get_next_address(change)

Returns the next public address in the specified chain.

A new address is only returned if there are transactions found for the current address.

Parameters:change (bool) – If True, returns an address for change purposes, otherwise returns an address for payment.
Returns:A bitcoin address
Return type:str
get_next_public_key(change)

Returns the next public key in the specified chain.

A new key is only returned if there are transactions found for the current key.

Parameters:change (bool) – If True, returns a PublicKey for change purposes, otherwise returns a PublicKey for payment.
Returns:A public key
Return type:PublicKey
get_private_key(change, n)

Returns a private key in the chain for use in signing messages or transactions.

Parameters:
  • change (bool) – If True, returns an address for change purposes, otherwise returns an address for payment.
  • n (int) – index of address in chain.
Returns:

A private key in this account’s chain.

Return type:

HDPrivateKey

get_public_key(change, n=-1)

Returns a public key in the chain

Parameters:
  • change (bool) – If True, returns an address for change purposes, otherwise returns an address for payment.
  • n (int) – index of address in chain. If n == -1, a new key is created with index = self.last_[change|payout]_index + 1
Returns:

A public key in this account’s chain.

Return type:

HDPublicKey

get_utxos(include_unconfirmed=False)

Gets all unspent transactions associated with all addresses up to and including the last known indices for both change and payout chains.

has_txns()

Returns whether or not there are any discovered transactions associated with any address in the account.

Returns:True if there are discovered transactions, False otherwise.
Return type:bool
to_dict()

Returns a JSON-serializable dict to save account data

Returns:Dict that can be serialized into a JSON string
Return type:dict

two1.wallet.exceptions module

This is a simple submodule that enumerates the different kinds of exceptions that the two1.wallet module raises.

exception two1.wallet.exceptions.AccountCreationError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.DaemonNotRunningError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.DaemonRunningError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.DaemonizerError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.DustLimitError

Bases: two1.wallet.exceptions.WalletError, ValueError

exception two1.wallet.exceptions.OverfullTransactionException

Bases: two1.wallet.exceptions.TransactionBuilderException

exception two1.wallet.exceptions.PassphraseError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.SatoshiUnitsError

Bases: two1.wallet.exceptions.WalletError, TypeError

exception two1.wallet.exceptions.TransactionBuilderException

Bases: Exception

exception two1.wallet.exceptions.TransactionSendError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.TxidMismatchError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.UndefinedMethodError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.UnknownDataProviderError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.UnreasonableFeeError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.WalletBalanceError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.WalletError

Bases: Exception

exception two1.wallet.exceptions.WalletLockedError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.WalletNotLoadedError

Bases: two1.wallet.exceptions.WalletError

exception two1.wallet.exceptions.WalletSigningError

Bases: two1.wallet.exceptions.WalletError

two1.wallet.account_types module

This is a simple submodule that stores the different kinds of account types and their corresponding derivation prefixes.

class two1.wallet.account_types.AccountType(account_derivation_prefix)

Bases: tuple

account_derivation_prefix

Alias for field number 0

two1.wallet.utxo_selectors module

This is a simple submodule that provides functions to select UTXOs (unspent transaction outputs).

two1.wallet.utxo_selectors.utxo_selector_smallest_first(utxos_by_addr, amount, num_outputs, fees=None)