API Usage¶
The library API for use by projects importing hwilib
can be found here.
Hardware Wallet Client Interface¶
The HardwareWalletClient
is the class which all of the specific device implementations subclass.
-
class
hwilib.hwwclient.
HardwareWalletClient
(path, password, expert)¶ Create a client for a HID device that has already been opened.
This abstract class defines the methods that hardware wallet subclasses should implement.
- Parameters
path (str) – Path to the device as returned by
enumerate()
password (str) – A password/passphrase to use with the device. Typically a BIP 39 passphrase, but not always. See device specific documentation for further details.
expert (bool) – Whether to return additional information intended for experts.
- Return type
None
-
get_master_xpub
(addrtype=wit, account=0)¶ Retrieves a BIP 44 master public key
Get the extended public key used to derive receiving and change addresses with the BIP 44 derivation path scheme. The returned xpub will be dependent on the address type requested, the chain type, and the BIP 44 account number.
- Returns
The extended public key
- Parameters
addrtype (hwilib.common.AddressType) –
account (int) –
- Return type
-
get_master_fingerprint
()¶ Get the master public key fingerprint as bytes.
Retrieves the fingerprint of the master public key of a device. Typically implemented by fetching the extended public key at “m/0h” and extracting the parent fingerprint from it.
- Returns
The fingerprint as bytes
- Return type
bytes
-
get_pubkey_at_path
(bip32_path)¶ Get the public key at the BIP 32 derivation path.
- Parameters
bip32_path (str) – The BIP 32 derivation path
- Returns
The extended public key
- Return type
-
sign_tx
(psbt)¶ Sign a partially signed bitcoin transaction (PSBT).
- Parameters
psbt (hwilib.psbt.PSBT) – The PSBT to sign
- Returns
The PSBT after being processed by the hardware wallet
- Return type
-
sign_message
(message, bip32_path)¶ Sign a message (bitcoin message signing).
Signs a message using the legacy Bitcoin Core signed message format. The message is signed with the key at the given path.
- Parameters
message (Union[str, bytes]) – The message to be signed. First encoded as bytes if not already.
bip32_path (str) – The BIP 32 derivation for the key to sign the message with.
- Returns
The signature
- Return type
str
-
display_singlesig_address
(bip32_path, addr_type)¶ Display and return the single sig address of specified type at the given derivation path.
- Parameters
bip32_path (str) – The BIP 32 derivation path to get the address for
addr_type (hwilib.common.AddressType) – The address type
- Returns
The retrieved address also being shown by the device
- Return type
str
-
display_multisig_address
(addr_type, multisig)¶ Display and return the multisig address of specified type given the descriptor.
- Parameters
addr_type (hwilib.common.AddressType) – The address type
multisig (hwilib.descriptor.MultisigDescriptor) – A
MultisigDescriptor
that describes the multisig to display.
- Returns
The retrieved address also being shown by the device
- Return type
str
-
wipe_device
()¶ Wipe the device.
- Returns
Whether the wipe was successful
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
setup_device
(label='', passphrase='')¶ Setup the device.
- Parameters
label (str) – A label to apply to the device. See device specific documentation for details as to what this actually does.
passphrase (str) – A passphrase to apply to the device. Typically a BIP 39 passphrase. See device specific documentation for details as to what this actually does.
- Returns
Whether the setup was successful
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
restore_device
(label='', word_count=24)¶ Restore the device.
- Parameters
label (str) – A label to apply to the device. See device specific documentation for details as to what this actually does.
word_count (int) – The number of BIP 39 mnemonic words.
- Returns
Whether the restore was successful
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
backup_device
(label='', passphrase='')¶ Backup the device.
- Parameters
label (str) – A label to apply to the backup. See device specific documentation for details as to what this actually does.
passphrase (str) – A passphrase to apply to the backup. See device specific documentation for details as to what this actually does.
- Returns
Whether the backup was successful
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
close
()¶ Close the HID device.
- Return type
None
-
prompt_pin
()¶ Prompt for PIN.
- Returns
Whether the PIN prompt was successful
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
send_pin
(pin)¶ Send PIN.
- Parameters
pin (str) – The PIN
- Returns
Whether the PIN successfully unlocked the device
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
-
toggle_passphrase
()¶ Toggle passphrase.
- Returns
Whether the passphrase was successfully toggled
- Raises
UnavailableActionError – if appropriate for the device.
- Return type
bool
Commands¶
The functions in this module are the primary way to interact with hardware wallets.
Each function that takes a client
uses a HardwareWalletClient
.
The functions then call public members of that client to retrieve the data needed.
Clients can be constructed using find_device()
or get_client()
.
The enumerate()
function returns information about what devices are available to be connected to.
These information can then be used with find_device()
or get_client()
to get a HardwareWalletClient
.
Note that this documentation does not specify every exception that can be raised.
Many exceptions are buried within the functions implemented by each device’s HardwareWalletClient
.
For more information about the exceptions that those can raise, please see the specific client documentation.
-
hwilib.commands.
get_client
(device_type, device_path, password='', expert=False)¶ Returns a HardwareWalletClient for the given device type at the device path
- Parameters
device_type (str) – The type of device
device_path (str) – The path specifying where the device can be accessed as returned by
enumerate()
password (str) – The password to use for this device
expert (bool) – Whether the device should be opened in expert mode (prints more information for some commands)
- Returns
A
HardwareWalletClient
to interact with the device- Raises
UnknownDeviceError: if the device type is not known by HWI
- Return type
Optional[hwilib.hwwclient.HardwareWalletClient]
-
hwilib.commands.
enumerate
(password='')¶ Enumerate all of the devices that HWI can potentially access.
- Parameters
password (str) – The password to use for devices which take passwords from the host.
- Returns
A list of devices for which clients can be created for.
- Return type
List[Dict[str, Any]]
-
hwilib.commands.
find_device
(password='', device_type=None, fingerprint=None, expert=False)¶ Find a device from the device type or fingerprint and get a client to access it. This is used as an alternative to
get_client()
if the device path is not known.- Parameters
password (str) – A password that may be needed to access the device if it can take passwords from the host
device_type (Optional[str]) – The type of device. The client returned will be for this type of device. If not provided, the fingerprint must be provided
fingerprint (Optional[str]) – The fingerprint of the master public key for the device. The client returned will have a master public key fingerprint matching this. If not provided, device_type must be provided.
expert (bool) – Whether the device should be opened in expert mode (enables additional output for some actions)
- Returns
A client to interact with the found device
- Return type
Optional[hwilib.hwwclient.HardwareWalletClient]
-
hwilib.commands.
getmasterxpub
(client, addrtype=wit, account=0)¶ Get the master extended public key from a client
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
addrtype (hwilib.common.AddressType) –
account (int) –
- Returns
A dictionary containing the public key at the
m/44'/0'/0'
derivation path. Returned as{"xpub": <xpub string>}
.- Return type
Dict[str, str]
-
hwilib.commands.
signtx
(client, psbt)¶ Sign a Partially Signed Bitcoin Transaction (PSBT) with the client.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
psbt (str) – The PSBT to sign
- Returns
A dictionary containing the processed PSBT serialized in Base64. Returned as
{"psbt": <base64 psbt string>}
.- Return type
Dict[str, str]
-
hwilib.commands.
getxpub
(client, path, expert=False)¶ Get the master public key at a path from a client
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
path (str) – The derivation path for the public key to retrieve
expert (bool) – Whether to provide more information intended for experts.
- Returns
A dictionary containing the public key at the
bip32_path
. With expert mode, the information contained within the xpub are decoded and displayed. Returned as{"xpub": <xpub string>}
.- Return type
Dict[str, Any]
-
hwilib.commands.
signmessage
(client, message, path)¶ Sign a message using the key at the derivation path with the client.
The message will be signed using the Bitcoin signed message standard used by Bitcoin Core. The message can be either a string which is then encoded to bytes, or bytes.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
message (str) – The message to sign
path (str) – The derivation path for the key to sign with
- Returns
A dictionary containing the signature. Returned as
{"signature": <base64 signature string>}
.- Return type
Dict[str, str]
-
hwilib.commands.
getdescriptor
(client, master_fpr, path=None, internal=False, addr_type=wit, account=0, start=None, end=None)¶ Get a descriptor from the client.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
master_fpr (bytes) – The hex string for the master fingerprint of the device to use in the descriptor
path (Optional[str]) – The derivation path for the xpub from which additional keys will be derived.
internal (bool) – Whether the dictionary should indicate that the descriptor should be for change addresses
addr_type (hwilib.common.AddressType) – The type of address the descriptor should create
account (int) – The BIP 44 account to use if
path
is not specifiedstart (Optional[int]) – The start of the range to import, inclusive
end (Optional[int]) – The end of the range to import, inclusive
- Returns
The descriptor constructed given the above arguments and key fetched from the device
- Raises
BadArgumentError: if an argument is malformed or missing.
- Return type
-
hwilib.commands.
getkeypool
(client, path, start, end, internal=False, keypool=True, account=0, addr_type=wit, addr_all=False)¶ Get a dictionary which can be passed to Bitcoin Core’s
importmulti
orimportdescriptors
RPCs to import a watchonly wallet based on the client. By default, a descriptor for legacy addresses is returned.- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
path (str) – The derivation path for the xpub from which additional keys will be derived.
start (int) – The start of the range to import, inclusive
end (int) – The end of the range to import, inclusive
internal (bool) – Whether the dictionary should indicate that the descriptor should be for change addresses
keypool (bool) – Whether the dictionary should indicate that the dsecriptor should be added to the Bitcoin Core keypool/addresspool
account (int) – The BIP 44 account to use if
path
is not specifiedsh_wpkh – Whether to return a descriptor specifying p2sh-segwit addresses
wpkh – Whether to return a descriptor specifying native segwit addresses
addr_all (bool) – Whether to return a multiple descriptors for every address type
addr_type (hwilib.common.AddressType) –
- Returns
The dictionary containing the descriptor and all of the arguments for
importmulti
orimportdescriptors
- Raises
BadArgumentError: if an argument is malformed or missing.
- Return type
List[Dict[str, Any]]
-
hwilib.commands.
getdescriptors
(client, account=0)¶ Get descriptors from the client.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
account (int) – The BIP 44 account to use
- Returns
Multiple descriptors from the device matching the BIP 44 standard paths and the given
account
.- Raises
BadArgumentError: if an argument is malformed or missing.
- Return type
Dict[str, List[str]]
-
hwilib.commands.
displayaddress
(client, path=None, desc=None, addr_type=wit)¶ Display an address on the device for client. The address can be specified by the path with additional parameters, or by a descriptor.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
path (Optional[str]) – The path of the address to display. Mutually exclusive with
desc
desc (Optional[str]) – The descriptor to display the address for. Mutually exclusive with
path
addr_type (hwilib.common.AddressType) – The address type to return. Only works with
path
- Returns
A dictionary containing the address displayed. Returned as
{"address": <base58 or bech32 address string>}
.- Raises
BadArgumentError: if an argument is malformed, missing, or conflicts.
- Return type
Dict[str, str]
-
hwilib.commands.
setup_device
(client, label='', backup_passphrase='')¶ Setup a device that has not yet been initialized.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
label (str) – The label to apply to the newly setup device
backup_passphrase (str) – The passphrase to use for the backup, if backups are encrypted for that device
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
wipe_device
(client)¶ Wipe a device
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
restore_device
(client, label='', word_count=24)¶ Restore a backup to a device that has not yet been initialized.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
label (str) – The label to apply to the newly setup device
word_count (int) – The number of words in the recovery phrase
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
backup_device
(client, label='', backup_passphrase='')¶ Create a backup of the device
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
label (str) – The label to apply to the newly setup device
backup_passphrase (str) – The passphrase to use for the backup, if backups are encrypted for that device
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
prompt_pin
(client)¶ Trigger the device to show the setup for PIN entry.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
send_pin
(client, pin)¶ Send a PIN to the device after
prompt_pin()
has been called.- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
pin (str) – The PIN to send
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
toggle_passphrase
(client)¶ Toggle whether the device is using a BIP 39 passphrase.
- Parameters
client (hwilib.hwwclient.HardwareWalletClient) – The client to interact with
- Returns
A dictionary with the
success
key.- Return type
Dict[str, bool]
-
hwilib.commands.
install_udev_rules
(source, location)¶ Install the udev rules to the local machine. The rules will be copied from the source to the location.
udevadm
will also be triggered and the rules reloaded so that the devices can be plugged in and used immediately. Aplugdev
group will also be created if it does not exist and the user will be added to it.The recommended source location is
hwilib/udev
. The recommended destination location is/etc/udev/rules.d
This function is equivalent to:
sudo cp hwilib/udev/*rules /etc/udev/rules.d/ sudo udevadm trigger sudo udevadm control --reload-rules sudo groupadd plugdev sudo usermod -aG plugdev `whoami`
- Parameters
source (str) – The directory containing the udev rules to install
location (str) – The directory to install the udev rules to
- Returns
A dictionary with the
success
key.- Raises
NotImplementedError: if udev rules cannot be installed on this system, i.e. it is not linux.
- Return type
Dict[str, bool]
Errors and Error Codes¶
HWI has several possible Exceptions with corresponding error codes.
HardwareWalletClient
functions and commands
functions will generally raise an exception that is a subclass of HWWError
.
The HWI command line tool will convert these exceptions into a dictionary containing the error message and error code.
These look like {"error": "<msg>", "code": <code>}
.
-
hwilib.errors.
NO_DEVICE_TYPE
= -1¶ Device type was not specified
-
hwilib.errors.
MISSING_ARGUMENTS
= -2¶ Arguments are missing
-
hwilib.errors.
DEVICE_CONN_ERROR
= -3¶ Error connecting to the device
-
hwilib.errors.
UNKNWON_DEVICE_TYPE
= -4¶ Device type is unknown
-
hwilib.errors.
INVALID_TX
= -5¶ Transaction is invalid
-
hwilib.errors.
NO_PASSWORD
= -6¶ No password provided, but one is needed
-
hwilib.errors.
BAD_ARGUMENT
= -7¶ Bad, malformed, or conflicting argument was provided
-
hwilib.errors.
NOT_IMPLEMENTED
= -8¶ Function is not implemented
-
hwilib.errors.
UNAVAILABLE_ACTION
= -9¶ Function is not available for this device
-
hwilib.errors.
DEVICE_ALREADY_INIT
= -10¶ Device is already initialized
-
hwilib.errors.
DEVICE_ALREADY_UNLOCKED
= -11¶ Device is already unlocked
-
hwilib.errors.
DEVICE_NOT_READY
= -12¶ Device is not ready
-
hwilib.errors.
UNKNOWN_ERROR
= -13¶ An unknown error occurred
-
hwilib.errors.
ACTION_CANCELED
= -14¶ Action was canceled by the user
-
hwilib.errors.
DEVICE_BUSY
= -15¶ Device is busy
-
hwilib.errors.
NEED_TO_BE_ROOT
= -16¶ User needs to be root to perform action
-
hwilib.errors.
HELP_TEXT
= -17¶ Help text was requested by the user
-
hwilib.errors.
DEVICE_NOT_INITIALIZED
= -18¶ Device is not initialized
-
exception
hwilib.errors.
HWWError
(msg, code)¶ Generic exception type produced by HWI Subclassed by specific Errors to have Exceptions that have specific error codes.
Contains a message and error code.
Create an exception with the message and error code
- Parameters
msg (str) – The error message
code (int) – The error code
- Return type
None
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
NoPasswordError
(msg)¶ HWWError
forNO_PASSWORD
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
HWWError
forUNAVAILABLE_ACTION
- Parameters
msg (str) – The error message
Get the error code for this Error
- Returns
The error code
- Return type
int
Get the error message for this Error
- Returns
The error message
- Return type
str
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceAlreadyInitError
(msg)¶ HWWError
forDEVICE_ALREADY_INIT
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceNotReadyError
(msg)¶ -
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceAlreadyUnlockedError
(msg)¶ HWWError
forDEVICE_ALREADY_UNLOCKED
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
UnknownDeviceError
(msg)¶ HWWError
forDEVICE_TYPE
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
NotImplementedError
(msg)¶ -
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
PSBTSerializationError
(msg)¶ HWWError
forINVALID_TX
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
BadArgumentError
(msg)¶ HWWError
forBAD_ARGUMENT
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceFailureError
(msg)¶ -
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
ActionCanceledError
(msg)¶ -
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceConnectionError
(msg)¶ HWWError
forDEVICE_CONN_ERROR
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
DeviceBusyError
(msg)¶ HWWError
forDEVICE_BUSY
- Parameters
msg (str) – The error message
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
exception
hwilib.errors.
NeedsRootError
(msg)¶ Create an exception with the message and error code
- Parameters
msg (str) – The error message
code – The error code
-
get_code
()¶ Get the error code for this Error
- Returns
The error code
- Return type
int
-
get_msg
()¶ Get the error message for this Error
- Returns
The error message
- Return type
str
-
with_traceback
()¶ Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
-
hwilib.errors.
handle_errors
(msg=None, result=None, code=- 13, debug=False)¶ Context manager to catch all Exceptions and HWWErrors to return them as dictionaries containing the error message and code.
- Parameters
msg (Optional[str]) – Error message prefix. Attached to the beginning of each error message
result (Optional[Dict[str, Any]]) – The dictionary to put the resulting error in
code (int) – The default error code to use for Exceptions
debug (bool) – Whether to also print out the traceback for debugging purposes
- Return type
Iterator[None]
UDev Rules Installer¶
Classes and utilities for installing device udev rules.
-
class
hwilib.udevinstaller.
UDevInstaller
¶ Installs the udev rules
- Return type
None
-
static
install
(source, location)¶ Install the udev rules from source into location. This will also reload and trigger udevadm so that devices matching the new rules will be detected. The user will be added to the
plugdev
group. If the group doesn’t exist, the user will be added to it.- Parameters
source (str) – The path to the source directory containing the rules
location (str) – The path to the directory to copy the rules to
- Returns
Whether the install was successful
- Return type
bool
-
trigger
()¶ Run
udevadm trigger
- Return type
None
-
reload_rules
()¶ Run
udevadm control --reload-rules
- Return type
None
-
add_user_plugdev_group
()¶ Add the user to the
plugdev
group- Return type
None
-
copy_udev_rule_files
(source, location)¶ Copy the udev rules from source to location
- Parameters
source (str) – The path to the source directory containing the rules
location (str) – The path to the directory to copy the rules to
- Return type
None
PSBT Classes and Utilities¶
-
class
hwilib.psbt.
PartiallySignedInput
¶ An object for a PSBT input map.
- Return type
None
-
set_null
()¶ Clear all values in this PSBT input map.
- Return type
None
-
deserialize
(f)¶ Deserialize a serialized PSBT input.
- Parameters
f (hwilib._serialize.Readable) – A byte stream containing the serialized PSBT input
- Return type
None
-
serialize
()¶ Serialize this PSBT input
- Returns
The serialized PSBT input
- Return type
bytes
-
class
hwilib.psbt.
PartiallySignedOutput
¶ An object for a PSBT output map.
- Return type
None
-
set_null
()¶ Clear this PSBT output map
- Return type
None
-
deserialize
(f)¶ Deserialize a serialized PSBT output map
- Parameters
f (hwilib._serialize.Readable) – A byte stream containing the serialized PSBT output
- Return type
None
-
serialize
()¶ Serialize this PSBT output
- Returns
The serialized PSBT output
- Return type
bytes
-
class
hwilib.psbt.
PSBT
(tx=None)¶ A class representing a PSBT
- Parameters
tx (Optional[hwilib.tx.CTransaction]) – A Bitcoin transaction that specifies the inputs and outputs to use
- Return type
None
-
deserialize
(psbt)¶ Deserialize a base 64 encoded PSBT.
- Parameters
psbt (str) – A base 64 PSBT.
- Return type
None
-
serialize
()¶ Serialize the PSBT as a base 64 encoded string.
- Returns
The base 64 encoded string.
- Return type
str
Output Script Descriptors¶
HWI has a more limited implementation of descriptors. See Bitcoin Core’s documentation for more details on descriptors.
This implementation only supports sh()
, wsh()
, pkh()
, wpkh()
, multi()
, and sortedmulti()
descriptors.
Descriptors can be parsed, however the actual scripts are not generated.
-
class
hwilib.descriptor.
ExpandedScripts
(output_script, redeem_script, witness_script)¶ Create new instance of ExpandedScripts(output_script, redeem_script, witness_script)
-
count
(value, /)¶ Return number of occurrences of value.
-
index
(value, start=0, stop=9223372036854775807, /)¶ Return first index of value.
Raises ValueError if the value is not present.
-
property
output_script
¶ Alias for field number 0
-
property
redeem_script
¶ Alias for field number 1
-
property
witness_script
¶ Alias for field number 2
-
-
hwilib.descriptor.
DescriptorChecksum
(desc)¶ Compute the checksum for a descriptor
- Parameters
desc (str) – The descriptor string to compute a checksum for
- Returns
A checksum
- Return type
str
-
hwilib.descriptor.
AddChecksum
(desc)¶ Compute and attach the checksum for a descriptor
- Parameters
desc (str) – The descriptor string to add a checksum to
- Returns
Descriptor with checksum
- Return type
str
-
class
hwilib.descriptor.
PubkeyProvider
(origin, pubkey, deriv_path)¶ A public key expression in a descriptor. Can contain the key origin info, the pubkey itself, and subsequent derivation paths for derivation from the pubkey The pubkey can be a typical pubkey or an extended pubkey.
- Parameters
origin (Optional[KeyOriginInfo]) – The key origin if one is available
pubkey (str) – The public key. Either a hex string or a serialized extended pubkey
deriv_path (Optional[str]) – Additional derivation path if the pubkey is an extended pubkey
- Return type
None
-
classmethod
parse
(s)¶ Deserialize a key expression from the string into a
PubkeyProvider
.- Parameters
s (str) – String containing the key expression
- Returns
A new
PubkeyProvider
containing the details given bys
- Return type
-
to_string
()¶ Serialize the pubkey expression to a string to be used in a descriptor
- Returns
The pubkey expression as a string
- Return type
str
-
get_full_derivation_path
(pos)¶ Returns the full derivation path at the given position, including the origin
- Parameters
pos (int) –
- Return type
str
-
get_full_derivation_int_list
(pos)¶ Returns the full derivation path as an integer list at the given position. Includes the origin and master key fingerprint as an int
- Parameters
pos (int) –
- Return type
List[int]
-
class
hwilib.descriptor.
Descriptor
(pubkeys, subdescriptor, name)¶ An abstract class for Descriptors themselves. Descriptors can contain multiple
PubkeyProvider
s and no more than oneDescriptor
as a subdescriptor.- Parameters
pubkeys (List[PubkeyProvider]) – The
PubkeyProvider
s that are part of this descriptorsubdescriptor (Optional[Descriptor]) – The
Descriptor
that is part of this descriptorname (str) – The name of the function for this descriptor
- Return type
None
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
class
hwilib.descriptor.
PKHDescriptor
(pubkey)¶ A descriptor for
pkh()
descriptors- Parameters
pubkey (PubkeyProvider) – The
PubkeyProvider
for this descriptor- Return type
None
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
class
hwilib.descriptor.
WPKHDescriptor
(pubkey)¶ A descriptor for
wpkh()
descriptors- Parameters
pubkey (PubkeyProvider) – The
PubkeyProvider
for this descriptor- Return type
None
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
class
hwilib.descriptor.
MultisigDescriptor
(pubkeys, thresh, is_sorted)¶ A descriptor for
multi()
andsortedmulti()
descriptors- Parameters
pubkeys (List[PubkeyProvider]) – The
PubkeyProvider
s for this descriptorthresh (int) – The number of keys required to sign this multisig
is_sorted (bool) – Whether this is a
sortedmulti()
descriptor
- Return type
None
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
class
hwilib.descriptor.
SHDescriptor
(subdescriptor)¶ A descriptor for
sh()
descriptors- Parameters
subdescriptor (Optional[Descriptor]) – The
Descriptor
that is a sub-descriptor for this descriptor- Return type
None
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
class
hwilib.descriptor.
WSHDescriptor
(subdescriptor)¶ A descriptor for
wsh()
descriptors- Parameters
pubkey – The
Descriptor
that is a sub-descriptor for this descriptorsubdescriptor (Optional[Descriptor]) –
- Return type
None
-
expand
(pos)¶ Returns the scripts for a descriptor at the given pos for ranged descriptors.
- Parameters
pos (int) –
- Return type
-
to_string
()¶ Serializes the descriptor as a string wtih the checksum
- Returns
The descriptor with a checksum
- Return type
str
-
to_string_no_checksum
()¶ Serializes the descriptor as a string without the descriptor checksum
- Returns
The descriptor string
- Return type
str
-
hwilib.descriptor.
parse_pubkey
(expr)¶ Parses an individual pubkey expression from a string that may contain more than one pubkey expression.
- Parameters
expr (str) – The expression to parse a pubkey expression from
- Returns
The
PubkeyProvider
that is parsed as the first item of a tuple, and the remainder of the expression as the second item.- Return type
Tuple[hwilib.descriptor.PubkeyProvider, str]
-
hwilib.descriptor.
parse_descriptor
(desc)¶ Parse a descriptor string into a
Descriptor
. Validates the checksum if one is provided in the string- Parameters
desc (str) – The descriptor string
- Returns
The parsed
Descriptor
- Raises
ValueError: if the descriptor string is malformed
- Return type
Key Classes and Utilities¶
Classes and utilities for working with extended public keys, key origins, and other key related things.
-
hwilib.key.
H_
(x)¶ Shortcut function that “hardens” a number in a BIP44 path.
- Parameters
x (int) –
- Return type
int
-
hwilib.key.
is_hardened
(i)¶ Returns whether an index is hardened
- Parameters
i (int) –
- Return type
bool
-
class
hwilib.key.
ExtendedKey
(version, depth, parent_fingerprint, child_num, chaincode, privkey, pubkey)¶ A BIP 32 extended public key.
- Parameters
version (bytes) – The version bytes for this xpub
depth (int) – The depth of this xpub as defined in BIP 32
parent_fingerprint (bytes) – The 4 byte fingerprint of the parent xpub as defined in BIP 32
child_num (int) – The number of this xpub as defined in BIP 32
chaincode (bytes) – The chaincode of this xpub as defined in BIP 32
privkey (Optional[bytes]) – The private key for this xpub if available
pubkey (bytes) – The public key for this xpub
- Return type
None
-
classmethod
deserialize
(xpub)¶ Create an
ExtendedKey
from a Base58 check encoded xpub- Parameters
xpub (str) – The Base58 check encoded xpub
- Return type
-
serialize
()¶ Serialize the ExtendedKey with the serialization format described in BIP 32. Does not create an xpub string, but the bytes serialized here can be Base58 check encoded into one.
- Returns
BIP 32 serialized extended key
- Return type
bytes
-
to_string
()¶ Serialize the ExtendedKey as a Base58 check encoded xpub string
- Returns
Base58 check encoded xpub
- Return type
str
-
get_printable_dict
()¶ Get the attributes of this ExtendedKey as a dictionary that can be printed
- Returns
Dictionary containing ExtendedKey information that can be printed
- Return type
Dict[str, object]
-
derive_pub
(i)¶ Derive the public key at the given child index.
- Parameters
i (int) – The child index of the pubkey to derive
- Return type
-
derive_pub_path
(path)¶ Derive the public key at the given path
- Parameters
path (Sequence[int]) – Sequence of integers for the path of the pubkey to derive
- Return type
-
class
hwilib.key.
KeyOriginInfo
(fingerprint, path)¶ Object representing the origin of a key.
- Parameters
fingerprint (bytes) – The 4 byte BIP 32 fingerprint of a parent key from which this key is derived from
path (Sequence[int]) – The derivation path to reach this key from the key at
fingerprint
- Return type
None
-
classmethod
deserialize
(s)¶ Deserialize a serialized KeyOriginInfo. They will be serialized in the same way that PSBTs serialize derivation paths
- Parameters
s (bytes) –
- Return type
-
serialize
()¶ Serializes the KeyOriginInfo in the same way that derivation paths are stored in PSBTs
- Return type
bytes
-
to_string
()¶ Return the KeyOriginInfo as a string in the form <fingerprint>/<index>/<index>/… This is the same way that KeyOriginInfo is shown in descriptors
- Return type
str
-
classmethod
from_string
(s)¶ Create a KeyOriginInfo from the string
- Parameters
s (str) – The string to parse
- Return type
-
get_derivation_path
()¶ Return the string for just the path
- Return type
str
-
get_full_int_list
()¶ Return a list of ints representing this KeyOriginInfo. The first int is the fingerprint, followed by the path
- Return type
List[int]
-
hwilib.key.
parse_path
(nstr)¶ Convert BIP32 path string to list of uint32 integers with hardened flags. Several conventions are supported to set the hardened flag: -1, 1’, 1h
e.g.: “0/1h/1” -> [0, 0x80000001, 1]
- Parameters
nstr (str) – path string
- Returns
list of integers
- Return type
List[int]
-
hwilib.key.
get_bip44_purpose
(addrtype)¶ Determine the BIP 44 purpose based on the given
AddressType
.- Parameters
addrtype (hwilib.common.AddressType) – The address type
- Return type
int
-
hwilib.key.
get_bip44_chain
(chain)¶ Determine the BIP 44 coin type based on the Bitcoin chain type.
For the Bitcoin mainnet chain, this returns 0. For the other chains, this returns 1.
- Parameters
chain (hwilib.common.Chain) – The chain
- Return type
int
Common Classes and Utilities¶
-
class
hwilib.common.
Chain
(value)¶ The blockchain network to use
-
MAIN
= 0¶ Bitcoin Main network
-
TEST
= 1¶ Bitcoin Test network
-
REGTEST
= 2¶ Bitcoin Core Regression Test network
-
SIGNET
= 3¶ Bitcoin Signet
-
-
class
hwilib.common.
AddressType
(value)¶ The type of address to use
-
LEGACY
= 1¶ Legacy address type. P2PKH for single sig, P2SH for scripts.
-
WIT
= 2¶ Native segwit v0 address type. P2WPKH for single sig, P2WPSH for scripts.
-
SH_WIT
= 3¶ Nested segwit v0 address type. P2SH-P2WPKH for single sig, P2SH-P2WPSH for scripts.
-
-
hwilib.common.
sha256
(s)¶ Perform a single SHA256 hash.
- Parameters
s (bytes) – Bytes to hash
- Returns
The hash
- Return type
bytes
-
hwilib.common.
ripemd160
(s)¶ Perform a single RIPEMD160 hash.
- Parameters
s (bytes) – Bytes to hash
- Returns
The hash
- Return type
bytes
-
hwilib.common.
hash256
(s)¶ Perform a double SHA256 hash. A SHA256 is performed on the input, and then a second SHA256 is performed on the result of the first SHA256
- Parameters
s (bytes) – Bytes to hash
- Returns
The hash
- Return type
bytes
-
hwilib.common.
hash160
(s)¶ perform a single SHA256 hash followed by a single RIPEMD160 hash on the result of the SHA256 hash.
- Parameters
s (bytes) – Bytes to hash
- Returns
The hash
- Return type
bytes