Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _try_usart_bootloader_connection(
serial_port: usart.SerialPort, bootloader_device: devices.DeviceInfo
) -> UsartBootloaderProbeResult:
"""
Probes the connection to a BitBoxBase bootloader
over the specified UART port.
"""
transport = usart.U2FUsart(serial_port)
try:
bootloader_attempt = Bootloader(transport, bootloader_device)
bootloader_attempt.versions()
success = UsartBootloaderProbeResult.SUCCESS
except usart.U2FUsartErrorResponse as err:
if err.error_code != usart.U2FUsartErrorResponse.ENDPOINT_UNAVAILABLE:
raise
success = UsartBootloaderProbeResult.NOT_AVAILABLE
except usart.U2FUsartTimeoutError:
success = UsartBootloaderProbeResult.TIMEOUT
finally:
bootloader_attempt.close()
return success
attestation_check_callback=attestation_check,
)
if debug:
print("Device Info:")
pprint.pprint(base_dev)
return SendMessageBitBoxBase(base_dev, debug).run()
except usart.U2FUsartErrorResponse as err:
if err.error_code != usart.U2FUsartErrorResponse.ENDPOINT_UNAVAILABLE:
raise
except usart.U2FUsartTimeoutError:
print("Timed out. Maybe the device is not connected?", file=sys.stderr)
return 1
print("BitBox unavailable. Starting bootloader connection.")
transport = usart.U2FUsart(serial_port)
bootloader = bitbox02.Bootloader(transport, bootloader_device)
return SendMessageBootloader(bootloader).run()
except devices.TooManyFoundException:
print("Multiple bitboxes detected. Only one supported")
return 1
except devices.NoneFoundException:
try:
bootloader = devices.get_any_bitbox02_bootloader()
except devices.TooManyFoundException:
print("Multiple bitbox bootloaders detected. Only one supported")
return 1
except devices.NoneFoundException:
print("Neither bitbox nor bootloader found.")
return 1
else:
hid_device = hid.device()
hid_device.open_path(bootloader["path"])
bootloader_connection = bitbox02.Bootloader(u2fhid.U2FHid(hid_device), bootloader)
boot_app = SendMessageBootloader(bootloader_connection)
return boot_app.run()
else:
def show_pairing(code: str) -> bool:
print("Please compare and confirm the pairing code on your BitBox02:")
print(code)
return True
def attestation_check(result: bool) -> None:
if result:
print("Device attestation PASSED")
else:
print("Device attestation FAILED")
hid_device = hid.device()
)
parser.add_argument("firmware", nargs=1, help="Firmware to flash.")
args = parser.parse_args()
if not args.debug and ".signed.bin" not in args.firmware[0]:
eprint("Expecting firmware to end with '.signed.bin'")
return 1
if args.usart is not None:
serial_port = usart.SerialPort(args.usart, 115200, timeout=3)
bootloader_device = _find_and_open_usart_bitbox(serial_port)
transport: TransportLayer = usart.U2FUsart(serial_port)
bootloader = Bootloader(transport, bootloader_device)
else:
bootloader_device, transport = _find_and_open_usb_bitbox02()
bootloader = Bootloader(transport, bootloader_device)
with open(args.firmware[0], "rb") as file:
firmware = file.read()
def progress(perc: float) -> None:
sys.stdout.write(f"{perc*100:.02f}%\r")
if bootloader.erased():
print("device contains NO firmware")
else:
print("firmware version: %d\nsigning pubkeys version: %d" % bootloader.versions())
firmware_hash, signing_keydata_hash = bootloader.get_hashes()
print("firmware hash:", firmware_hash.hex())
print("signing keydata hash:", signing_keydata_hash.hex())
if args.debug:
"--usart",
action="store",
help="Flash firmware using U2F-over-UART (BitBoxBase), with the specified serial port.",
)
parser.add_argument("firmware", nargs=1, help="Firmware to flash.")
args = parser.parse_args()
if not args.debug and ".signed.bin" not in args.firmware[0]:
eprint("Expecting firmware to end with '.signed.bin'")
return 1
if args.usart is not None:
serial_port = usart.SerialPort(args.usart, 115200, timeout=3)
bootloader_device = _find_and_open_usart_bitbox(serial_port)
transport: TransportLayer = usart.U2FUsart(serial_port)
bootloader = Bootloader(transport, bootloader_device)
else:
bootloader_device, transport = _find_and_open_usb_bitbox02()
bootloader = Bootloader(transport, bootloader_device)
with open(args.firmware[0], "rb") as file:
firmware = file.read()
def progress(perc: float) -> None:
sys.stdout.write(f"{perc*100:.02f}%\r")
if bootloader.erased():
print("device contains NO firmware")
else:
print("firmware version: %d\nsigning pubkeys version: %d" % bootloader.versions())
firmware_hash, signing_keydata_hash = bootloader.get_hashes()
print("firmware hash:", firmware_hash.hex())
else:
def show_pairing(code: str) -> bool:
print("Please compare and confirm the pairing code on your BitBox02:")
print(code)
return True
def attestation_check(result: bool) -> None:
if result:
print("Device attestation PASSED")
else:
print("Device attestation FAILED")
hid_device = hid.device()
hid_device.open_path(bitbox["path"])
bitbox_connection = bitbox02.BitBox02(
transport=u2fhid.U2FHid(hid_device),
device_info=bitbox,
show_pairing_callback=show_pairing,
attestation_check_callback=attestation_check,
)
if debug:
print("Device Info:")
pprint.pprint(bitbox)
return SendMessage(bitbox_connection, debug).run()
def _get_bitbox_and_reboot() -> devices.DeviceInfo:
"""Search for a bitbox and then reboot it into bootloader"""
device = devices.get_any_bitbox02()
# bitbox02 detected -> send command to reboot into bootloader to upgrade.
def _show_pairing(code: str) -> None:
print("Please compare and confirm the pairing code on your BitBox02:")
print(code)
hid_device = hid.device()
hid_device.open_path(device["path"])
bitbox = BitBox02(
transport=u2fhid.U2FHid(hid_device), device_info=device, show_pairing_callback=_show_pairing
)
bitbox.reboot()
# wait for it to reboot
while True:
try:
bootloader_device = devices.get_any_bitbox02_bootloader()
except NoneFoundException:
sys.stdout.write(".")
sys.stdout.flush()
sleep(1)
continue
return bootloader_device
def show_address(
self, bip32_path: str, address_type: str, wallet: Deterministic_Wallet
) -> str:
if self.bitbox02_device is None:
raise Exception(
"Need to setup communication first before attempting any BitBox02 calls"
)
address_keypath = bip32.convert_bip32_path_to_list_of_uint32(bip32_path)
coin_network = self.coin_network_from_electrum_network()
if address_type == "p2wpkh":
script_config = bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
)
elif address_type == "p2wpkh-p2sh":
script_config = bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
)
elif address_type == "p2wsh":
if type(wallet) is Multisig_Wallet:
script_config = self.btc_multisig_config(
coin_network, address_keypath, wallet
)
else:
raise Exception("Can only use p2wsh with multisig wallets")
else:
raise Exception(
"invalid address xtype: {} is not supported by the BitBox02".format(
Registers it on the device if not already registered.
"""
if self.bitbox02_device is None:
raise Exception(
"Need to setup communication first before attempting any BitBox02 calls"
)
account_keypath = bip32_path[:4]
xpubs = wallet.get_master_public_keys()
our_xpub = self.get_xpub(
bip32.convert_bip32_intpath_to_strpath(account_keypath), "p2wsh"
)
multisig_config = bitbox02.btc.BTCScriptConfig(
multisig=bitbox02.btc.BTCScriptConfig.Multisig(
threshold=wallet.m,
xpubs=[util.parse_xpub(xpub) for xpub in xpubs],
our_xpub_index=xpubs.index(our_xpub),
)
)
is_registered = self.bitbox02_device.btc_is_script_config_registered(
coin, multisig_config, account_keypath
)
if not is_registered:
name = self.handler.name_multisig_account()
try:
self.bitbox02_device.btc_register_script_config(
coin=coin,
script_config=multisig_config,
keypath=account_keypath,
"prev_tx": {
"version": prev_tx.version,
"locktime": prev_tx.locktime,
"inputs": prev_inputs,
"outputs": prev_outputs,
},
}
)
if tx_script_type == None:
tx_script_type = txin.script_type
elif tx_script_type != txin.script_type:
raise Exception("Cannot mix different input script types")
if tx_script_type == "p2wpkh":
tx_script_type = bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH
)
elif tx_script_type == "p2wpkh-p2sh":
tx_script_type = bitbox02.btc.BTCScriptConfig(
simple_type=bitbox02.btc.BTCScriptConfig.P2WPKH_P2SH
)
elif tx_script_type == "p2wsh":
if type(wallet) is Multisig_Wallet:
tx_script_type = self.btc_multisig_config(coin, full_path, wallet)
else:
raise Exception("Can only use p2wsh with multisig wallets")
else:
raise UserFacingException(
"invalid input script type: {} is not supported by the BitBox02".format(
tx_script_type
)