diff --git a/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.c b/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.c index 40003da50..8128e353b 100644 --- a/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.c +++ b/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.c @@ -29,21 +29,60 @@ // #if MICROPY_PY_TREZORMINTLAYER -#include "modtrezormintlayer-utils.h" +#include "modtrezormintlayer.h" -STATIC const mp_rom_map_elem_t mp_module_trezormintlayer_globals_table[] = { +STATIC const mp_rom_map_elem_t mod_trezormintlayer_globals_table[] = { {MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_trezormintlayer)}, - {MP_ROM_QSTR(MP_QSTR_utils), MP_ROM_PTR(&mod_trezormintlayer_utils_module)}, + {MP_ROM_QSTR(MP_QSTR_encode_utxo_input), + MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_utxo_input_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_account_spending_input), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_account_spending_input_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_account_command_input), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_account_command_input_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_transfer_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_transfer_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_lock_then_transfer_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_lock_then_transfer_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_burn_output), + MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_burn_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_create_stake_pool_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_create_stake_pool_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_produce_from_stake_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_produce_from_stake_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_create_delegation_id_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_create_delegation_id_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_delegate_staking_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_delegate_staking_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_issue_fungible_token_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_issue_fungible_token_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_issue_nft_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_issue_nft_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_data_deposit_output), + MP_ROM_PTR( + &mod_trezormintlayer_utils_mintlayer_encode_data_deposit_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_htlc_output), + MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_htlc_output_obj)}, + {MP_ROM_QSTR(MP_QSTR_encode_compact_length), + MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_comact_length_obj)}, }; -STATIC MP_DEFINE_CONST_DICT(mp_module_trezormintlayer_globals, - mp_module_trezormintlayer_globals_table); +STATIC MP_DEFINE_CONST_DICT(mod_trezormintlayer_globals, + mod_trezormintlayer_globals_table); -const mp_obj_module_t mp_module_trezormintlayer = { +STATIC const mp_obj_module_t mp_module_trezormintlayer = { .base = {&mp_type_module}, - .globals = (mp_obj_dict_t *)&mp_module_trezormintlayer_globals, + .globals = (mp_obj_dict_t *)&mod_trezormintlayer_globals, }; MP_REGISTER_MODULE(MP_QSTR_trezormintlayer, mp_module_trezormintlayer); // #endif // MICROPY_PY_TREZORMINTLAYER - diff --git a/core/embed/extmod/modtrezormintlayer/modtrezormintlayer-utils.h b/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.h similarity index 82% rename from core/embed/extmod/modtrezormintlayer/modtrezormintlayer-utils.h rename to core/embed/extmod/modtrezormintlayer/modtrezormintlayer.h index a92f603ad..fdd3b8b39 100644 --- a/core/embed/extmod/modtrezormintlayer/modtrezormintlayer-utils.h +++ b/core/embed/extmod/modtrezormintlayer/modtrezormintlayer.h @@ -87,7 +87,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3( mod_trezormintlayer_utils_mintlayer_encode_utxo_input_obj, mod_trezormintlayer_utils_mintlayer_encode_utxo_input); -/// def encode_account_spending_input(nonce: int, delegation_id: str, amount: +/// def encode_account_spending_input(nonce: int, delegation_id: bytes, amount: /// bytes) -> bytes: /// """ /// encodes an utxo account spendinf from nonce and delegation id @@ -125,10 +125,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3( mod_trezormintlayer_utils_mintlayer_encode_account_spending_input_obj, mod_trezormintlayer_utils_mintlayer_encode_account_spending_input); -/// def encode_account_command_input(nonce: int, command: int token_id: str, +/// def encode_account_command_input(nonce: int, command: int, token_id: bytes, /// data: bytes) -> bytes: /// """ -/// encodes an account command from the nonce, command, token id and additional command data +/// encodes an account command from the nonce, command, token id and +/// additional command data /// """ STATIC mp_obj_t mod_trezormintlayer_utils_mintlayer_encode_account_command_input( @@ -164,8 +165,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezormintlayer_utils_mintlayer_encode_account_command_input_obj, 4, 4, mod_trezormintlayer_utils_mintlayer_encode_account_command_input); -/// def encode_transfer_output(amount: str, token_id: str, address: str) -> -/// bytes: +/// def encode_transfer_output(amount: bytes, token_id: bytes, address: bytes) +/// -> bytes: /// """ /// encodes a transfer output with given amount and destination address /// """ @@ -196,10 +197,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3( mod_trezormintlayer_utils_mintlayer_encode_transfer_output_obj, mod_trezormintlayer_utils_mintlayer_encode_transfer_output); -/// def encode_lock_then_transfer_output(amount: str, token_id: str, lock_type: -/// int, lock_amount:int, address: str) -> bytes: +/// def encode_lock_then_transfer_output(amount: bytes, token_id: bytes, +/// lock_type: int, lock_amount:int, address: bytes) -> bytes: /// """ -/// encodes a transfer output with given amount, lock type and amount, and destination address +/// encodes a transfer output with given amount, lock type and amount, and +/// destination address /// """ STATIC mp_obj_t mod_trezormintlayer_utils_mintlayer_encode_lock_then_transfer_output( @@ -231,7 +233,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezormintlayer_utils_mintlayer_encode_lock_then_transfer_output_obj, 5, 5, mod_trezormintlayer_utils_mintlayer_encode_lock_then_transfer_output); -/// def encode_burn_output(amount: str, token_id: str) -> +/// def encode_burn_output(amount: bytes, token_id: bytes) -> /// bytes: /// """ /// encodes a burn output with given amount @@ -260,9 +262,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2( mod_trezormintlayer_utils_mintlayer_encode_burn_output_obj, mod_trezormintlayer_utils_mintlayer_encode_burn_output); -/// def encode_create_stake_pool_output(pool_id: str, pledge_amount: str, -/// staker: str, vrf_public_key: str, decommission_key: str, -/// margin_ratio_per_thousand: int, cost_per_block: str) -> bytes: +/// def encode_create_stake_pool_output(pool_id: bytes, pledge_amount: bytes, +/// staker: bytes, vrf_public_key: bytes, decommission_key: bytes, +/// margin_ratio_per_thousand: int, cost_per_block: bytes) -> bytes: /// """ /// encodes a create stake pool output /// """ @@ -304,7 +306,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezormintlayer_utils_mintlayer_encode_create_stake_pool_output_obj, 7, 7, mod_trezormintlayer_utils_mintlayer_encode_create_stake_pool_output); -/// def encode_produce_from_stake_output(destination: str, pool_id: str) -> +/// def encode_produce_from_stake_output(destination: bytes, pool_id: bytes) -> /// bytes: /// """ /// encodes a produce from stake output @@ -334,8 +336,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2( mod_trezormintlayer_utils_mintlayer_encode_produce_from_stake_output_obj, mod_trezormintlayer_utils_mintlayer_encode_produce_from_stake_output); -/// def encode_create_delegation_id_output(destination: str, pool_id: str) -> -/// bytes: +/// def encode_create_delegation_id_output(destination: bytes, pool_id: bytes) +/// -> bytes: /// """ /// encodes a create delegation id output /// """ @@ -364,7 +366,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2( mod_trezormintlayer_utils_mintlayer_encode_create_delegation_id_output_obj, mod_trezormintlayer_utils_mintlayer_encode_create_delegation_id_output); -/// def encode_delegate_staking_output(amount: str, delegation_id: str) -> +/// def encode_delegate_staking_output(amount: bytes, delegation_id: bytes) -> /// bytes: /// """ /// encodes a delegation staking output, given the amount and delegation id @@ -394,9 +396,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2( mod_trezormintlayer_utils_mintlayer_encode_delegate_staking_output_obj, mod_trezormintlayer_utils_mintlayer_encode_delegate_staking_output); -/// def encode_issue_fungible_token_output(token_ticker: str, -/// number_of_decimals: int, metadata_uri: str, total_supply_type: int, -/// fixed_amount: str, authority: str, is_freezable: int) -> bytes: +/// def encode_issue_fungible_token_output(token_ticker: bytes, +/// number_of_decimals: int, metadata_uri: bytes, total_supply_type: int, +/// fixed_amount: bytes, authority: bytes, is_freezable: int) -> bytes: /// """ /// encodes a issue fungible token output /// """ @@ -436,10 +438,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( 7, 7, mod_trezormintlayer_utils_mintlayer_encode_issue_fungible_token_output); -/// def encode_issue_nft_output(token_id: str, -/// creator: str, name: str, destination: str, -/// ticker: str, icon_uri: str, additional_metadata_uri: str, media_uri: str, -/// media_hash: str, destination: str) -> bytes: +/// def encode_issue_nft_output(token_id: bytes, +/// creator: bytes, name: bytes, destination: bytes, +/// ticker: bytes, icon_uri: bytes, additional_metadata_uri: bytes, media_uri: +/// bytes, media_hash: bytes, destination: bytes) -> bytes: /// """ /// encodes a issue NFT output /// """ @@ -488,7 +490,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN( mod_trezormintlayer_utils_mintlayer_encode_issue_nft_output_obj, 10, 10, mod_trezormintlayer_utils_mintlayer_encode_issue_nft_output); -/// def encode_data_deposit_output(deposit: str) -> +/// def encode_data_deposit_output(deposit: bytes) -> /// bytes: /// """ /// encodes a data deposit output @@ -515,9 +517,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1( mod_trezormintlayer_utils_mintlayer_encode_data_deposit_output_obj, mod_trezormintlayer_utils_mintlayer_encode_data_deposit_output); -/// def encode_htlc_output(amount: str, token_id: str, lock_type: -/// int, lock_amount:int, refund_key: str, spend_key: str, secret_has: bytes) -> -/// bytes: +/// def encode_htlc_output(amount: bytes, token_id: bytes, lock_type: +/// int, lock_amount:int, refund_key: bytes, spend_key: bytes, secret_has: +/// bytes) -> bytes: /// """ /// encodes an htlc output with given amount and lock /// """ @@ -578,55 +580,3 @@ mod_trezormintlayer_utils_mintlayer_encode_comact_length(mp_obj_t length) { STATIC MP_DEFINE_CONST_FUN_OBJ_1( mod_trezormintlayer_utils_mintlayer_encode_comact_length_obj, mod_trezormintlayer_utils_mintlayer_encode_comact_length); - -STATIC const mp_rom_map_elem_t mod_trezormintlayer_utils_globals_table[] = { - {MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_bip32)}, - {MP_ROM_QSTR(MP_QSTR_encode_utxo_input), - MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_utxo_input_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_account_spending_input), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_account_spending_input_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_account_command_input), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_account_command_input_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_transfer_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_transfer_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_lock_then_transfer_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_lock_then_transfer_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_burn_output), - MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_burn_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_create_stake_pool_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_create_stake_pool_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_produce_from_stake_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_produce_from_stake_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_create_delegation_id_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_create_delegation_id_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_delegate_staking_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_delegate_staking_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_issue_fungible_token_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_issue_fungible_token_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_issue_nft_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_issue_nft_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_data_deposit_output), - MP_ROM_PTR( - &mod_trezormintlayer_utils_mintlayer_encode_data_deposit_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_htlc_output), - MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_htlc_output_obj)}, - {MP_ROM_QSTR(MP_QSTR_encode_compact_length), - MP_ROM_PTR(&mod_trezormintlayer_utils_mintlayer_encode_comact_length_obj)}, -}; -STATIC MP_DEFINE_CONST_DICT(mod_trezormintlayer_utils_globals, - mod_trezormintlayer_utils_globals_table); - -STATIC const mp_obj_module_t mod_trezormintlayer_utils_module = { - .base = {&mp_type_module}, - .globals = (mp_obj_dict_t *)&mod_trezormintlayer_utils_globals, -}; diff --git a/core/mocks/generated/trezormintlayer.pyi b/core/mocks/generated/trezormintlayer.pyi index c97a6249d..0252498e4 100644 --- a/core/mocks/generated/trezormintlayer.pyi +++ b/core/mocks/generated/trezormintlayer.pyi @@ -1,123 +1,125 @@ from typing import * -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h +# extmod/modtrezormintlayer/modtrezormintlayer.h def encode_utxo_input(tx_hash: bytes, index: int, utxo_type: int) -> bytes: """ encodes an utxo input from tx_hash and index """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_account_spending_input(nonce: int, delegation_id: str, amount: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_account_spending_input(nonce: int, delegation_id: bytes, amount: bytes) -> bytes: """ encodes an utxo account spendinf from nonce and delegation id """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_account_command_input(nonce: int, command: int token_id: str, +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_account_command_input(nonce: int, command: int, token_id: bytes, data: bytes) -> bytes: """ - encodes an account command from the nonce, command, token id and additional command data + encodes an account command from the nonce, command, token id and + additional command data """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_transfer_output(amount: str, token_id: str, address: str) -> -bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_transfer_output(amount: bytes, token_id: bytes, address: bytes) +-> bytes: """ encodes a transfer output with given amount and destination address """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_lock_then_transfer_output(amount: str, token_id: str, lock_type: -int, lock_amount:int, address: str) -> bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_lock_then_transfer_output(amount: bytes, token_id: bytes, +lock_type: int, lock_amount:int, address: bytes) -> bytes: """ - encodes a transfer output with given amount, lock type and amount, and destination address + encodes a transfer output with given amount, lock type and amount, and + destination address """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_burn_output(amount: str, token_id: str) -> +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_burn_output(amount: bytes, token_id: bytes) -> bytes: """ encodes a burn output with given amount """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_create_stake_pool_output(pool_id: str, pledge_amount: str, -staker: str, vrf_public_key: str, decommission_key: str, -margin_ratio_per_thousand: int, cost_per_block: str) -> bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_create_stake_pool_output(pool_id: bytes, pledge_amount: bytes, +staker: bytes, vrf_public_key: bytes, decommission_key: bytes, +margin_ratio_per_thousand: int, cost_per_block: bytes) -> bytes: """ encodes a create stake pool output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_produce_from_stake_output(destination: str, pool_id: str) -> +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_produce_from_stake_output(destination: bytes, pool_id: bytes) -> bytes: """ encodes a produce from stake output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_create_delegation_id_output(destination: str, pool_id: str) -> -bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_create_delegation_id_output(destination: bytes, pool_id: bytes) +-> bytes: """ encodes a create delegation id output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_delegate_staking_output(amount: str, delegation_id: str) -> +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_delegate_staking_output(amount: bytes, delegation_id: bytes) -> bytes: """ encodes a delegation staking output, given the amount and delegation id """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_issue_fungible_token_output(token_ticker: str, -number_of_decimals: int, metadata_uri: str, total_supply_type: int, -fixed_amount: str, authority: str, is_freezable: int) -> bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_issue_fungible_token_output(token_ticker: bytes, +number_of_decimals: int, metadata_uri: bytes, total_supply_type: int, +fixed_amount: bytes, authority: bytes, is_freezable: int) -> bytes: """ encodes a issue fungible token output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_issue_nft_output(token_id: str, -creator: str, name: str, destination: str, -ticker: str, icon_uri: str, additional_metadata_uri: str, media_uri: str, -media_hash: str, destination: str) -> bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_issue_nft_output(token_id: bytes, +creator: bytes, name: bytes, destination: bytes, +ticker: bytes, icon_uri: bytes, additional_metadata_uri: bytes, media_uri: +bytes, media_hash: bytes, destination: bytes) -> bytes: """ encodes a issue NFT output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_data_deposit_output(deposit: str) -> +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_data_deposit_output(deposit: bytes) -> bytes: """ encodes a data deposit output """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h -def encode_htlc_output(amount: str, token_id: str, lock_type: -int, lock_amount:int, refund_key: str, spend_key: str, secret_has: bytes) -> -bytes: +# extmod/modtrezormintlayer/modtrezormintlayer.h +def encode_htlc_output(amount: bytes, token_id: bytes, lock_type: +int, lock_amount:int, refund_key: bytes, spend_key: bytes, secret_has: +bytes) -> bytes: """ encodes an htlc output with given amount and lock """ -# extmod/modtrezormintlayer/modtrezormintlayer-utils.h +# extmod/modtrezormintlayer/modtrezormintlayer.h def encode_compact_length(length: int) -> bytes: """ encodes a comapct length to bytes diff --git a/core/src/all_modules.py b/core/src/all_modules.py index 781d76ddf..68d64b78c 100644 --- a/core/src/all_modules.py +++ b/core/src/all_modules.py @@ -561,8 +561,6 @@ import apps.mintlayer.sign_tx.progress apps.mintlayer.sign_tx.signer import apps.mintlayer.sign_tx.signer - apps.mintlayer.writers - import apps.mintlayer.writers apps.monero import apps.monero apps.monero.diag diff --git a/core/src/apps/bitcoin/sign_tx/layout.py b/core/src/apps/bitcoin/sign_tx/layout.py index 33bc1768b..ebd9bc098 100644 --- a/core/src/apps/bitcoin/sign_tx/layout.py +++ b/core/src/apps/bitcoin/sign_tx/layout.py @@ -44,7 +44,6 @@ def format_coin_amount(amount: int, coin: CoinInfo, amount_unit: AmountUnit) -> decimals -= 3 shortcut = "m" + shortcut - # we don't need to do anything for AmountUnit.BITCOIN return f"{format_amount(amount, decimals)} {shortcut}" diff --git a/core/src/apps/mintlayer/get_address.py b/core/src/apps/mintlayer/get_address.py index 7a66b770a..1d04d0ddc 100644 --- a/core/src/apps/mintlayer/get_address.py +++ b/core/src/apps/mintlayer/get_address.py @@ -1,7 +1,8 @@ from typing import TYPE_CHECKING from apps.common.keychain import with_slip44_keychain -from . import CURVE, SLIP44_ID, PATTERNS + +from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: from trezor.messages import MintlayerAddress, MintlayerGetAddress @@ -11,13 +12,12 @@ @with_slip44_keychain(*PATTERNS, curve=CURVE, slip44_id=SLIP44_ID) async def get_address(msg: MintlayerGetAddress, keychain: Keychain) -> MintlayerAddress: + from trezor.crypto.bech32 import Encoding, bech32_encode, convertbits from trezor.messages import MintlayerAddress from trezor.ui.layouts import show_address from apps.common import paths - from trezor.crypto.bech32 import bech32_encode, Encoding - HRP = "mtc" address_n = msg.address_n # local_cache_attribute @@ -25,7 +25,8 @@ async def get_address(msg: MintlayerGetAddress, keychain: Keychain) -> Mintlayer node = keychain.derive(address_n) pubkey = node.public_key() - address = bech32_encode(HRP, pubkey, Encoding.BECH32M) + data = convertbits(pubkey, 8, 5) + address = bech32_encode(HRP, data, Encoding.BECH32M) if msg.show_display: await show_address( address, @@ -35,4 +36,3 @@ async def get_address(msg: MintlayerGetAddress, keychain: Keychain) -> Mintlayer ) return MintlayerAddress(address=address) - diff --git a/core/src/apps/mintlayer/get_public_key.py b/core/src/apps/mintlayer/get_public_key.py index 803010af6..83c554ace 100644 --- a/core/src/apps/mintlayer/get_public_key.py +++ b/core/src/apps/mintlayer/get_public_key.py @@ -1,7 +1,8 @@ from typing import TYPE_CHECKING from apps.common.keychain import with_slip44_keychain -from . import CURVE, SLIP44_ID, PATTERNS + +from . import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: from trezor.messages import MintlayerGetPublicKey, MintlayerPublicKey @@ -29,9 +30,10 @@ async def get_public_key( path = paths.address_n_to_str(msg.address_n) await show_pubkey( hexlify(pubkey).decode(), - account=paths.get_account_name("BNB", msg.address_n, PATTERNS[0], SLIP44_ID), + account=paths.get_account_name( + "BNB", msg.address_n, PATTERNS[0], SLIP44_ID + ), path=path, ) return MintlayerPublicKey(public_key=pubkey, chain_code=chain_code) - diff --git a/core/src/apps/mintlayer/sign_message.py b/core/src/apps/mintlayer/sign_message.py index 290e1abac..4c468063b 100644 --- a/core/src/apps/mintlayer/sign_message.py +++ b/core/src/apps/mintlayer/sign_message.py @@ -1,9 +1,11 @@ from typing import TYPE_CHECKING -from apps.common.keychain import with_slip44_keychain -from . import CURVE, SLIP44_ID, PATTERNS from trezor.crypto import hashlib +from apps.common.keychain import with_slip44_keychain + +from . import CURVE, PATTERNS, SLIP44_ID + if TYPE_CHECKING: from trezor.messages import MessageSignature, MintlayerSignMessage @@ -11,10 +13,12 @@ @with_slip44_keychain(*PATTERNS, curve=CURVE, slip44_id=SLIP44_ID) -async def sign_message(msg: MintlayerSignMessage, keychain: Keychain) -> MessageSignature: +async def sign_message( + msg: MintlayerSignMessage, keychain: Keychain +) -> MessageSignature: from trezor.crypto.curve import bip340 - from trezor.ui.layouts import confirm_signverify from trezor.messages import MessageSignature + from trezor.ui.layouts import confirm_signverify from apps.common.signverify import decode_message @@ -40,4 +44,3 @@ async def sign_message(msg: MintlayerSignMessage, keychain: Keychain) -> Message other_sig = bip340.sign(node.private_key(), digest) return MessageSignature(signature=other_sig, address=msg.address) - diff --git a/core/src/apps/mintlayer/sign_tx/__init__.py b/core/src/apps/mintlayer/sign_tx/__init__.py index bf16161da..9948f1819 100644 --- a/core/src/apps/mintlayer/sign_tx/__init__.py +++ b/core/src/apps/mintlayer/sign_tx/__init__.py @@ -1,20 +1,21 @@ from typing import TYPE_CHECKING from apps.common.keychain import with_slip44_keychain -from .. import CURVE, SLIP44_ID, PATTERNS + +from .. import CURVE, PATTERNS, SLIP44_ID if TYPE_CHECKING: from typing import Protocol from trezor.messages import ( MintlayerSignTx, + MintlayerTxRequest, TxAckInput, TxAckOutput, TxAckPrevExtraData, TxAckPrevInput, TxAckPrevMeta, TxAckPrevOutput, - MintlayerTxRequest, ) from apps.common.coininfo import CoinInfo @@ -49,15 +50,13 @@ async def sign_tx( msg: MintlayerSignTx, keychain: Keychain, ) -> MintlayerTxRequest: - from trezor.wire import DataError from trezor.enums import MintlayerRequestType from trezor.messages import MintlayerTxRequest + from trezor.wire import DataError from trezor.wire.context import call - from . import progress + from . import helpers, progress from .signer import Mintlayer - from . import helpers - if msg.inputs_count == 0: raise DataError("Cannot sign a transaction with 0 inputs") @@ -77,6 +76,4 @@ async def sign_tx( res = await req.confirm_dialog() progress.progress.report_init() else: - raise TypeError("Invalid signing instruction") - diff --git a/core/src/apps/mintlayer/sign_tx/helpers.py b/core/src/apps/mintlayer/sign_tx/helpers.py index 215545c9e..e1a08ebef 100644 --- a/core/src/apps/mintlayer/sign_tx/helpers.py +++ b/core/src/apps/mintlayer/sign_tx/helpers.py @@ -1,31 +1,29 @@ +from micropython import const from typing import TYPE_CHECKING, Tuple + from trezor import utils from trezor.enums import MintlayerRequestType from trezor.wire import DataError -from ..writers import TX_HASH_SIZE from . import layout if TYPE_CHECKING: from typing import Any, Awaitable - from trezor.enums import AmountUnit from trezor.messages import ( - PrevInput, - PrevOutput, - PrevTx, - SignTx, - TxAckPaymentRequest, + MintlayerOutputTimeLock, MintlayerTxInput, MintlayerTxOutput, - MintlayerOutputTimeLock, - TxOutput, MintlayerTxRequest, + PrevTx, + SignTx, ) from apps.common.coininfo import CoinInfo from apps.common.paths import Bip32Path +TX_HASH_SIZE = const(32) + # Machine instructions # === @@ -40,7 +38,7 @@ def confirm_dialog(self) -> Awaitable[Any]: class UiConfirmOutput(UiConfirm): def __init__( self, - output: TxOutput, + output: MintlayerTxOutput, coin: CoinInfo, output_index: int, chunkify: bool, @@ -59,93 +57,6 @@ def confirm_dialog(self) -> Awaitable[Any]: ) -class UiConfirmDecredSSTXSubmission(UiConfirm): - def __init__(self, output: TxOutput, coin: CoinInfo, amount_unit: AmountUnit): - self.output = output - self.coin = coin - self.amount_unit = amount_unit - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_decred_sstx_submission( - self.output, self.coin, self.amount_unit - ) - - -class UiConfirmPaymentRequest(UiConfirm): - def __init__( - self, - payment_req: TxAckPaymentRequest, - coin: CoinInfo, - amount_unit: AmountUnit, - ): - self.payment_req = payment_req - self.amount_unit = amount_unit - self.coin = coin - - def confirm_dialog(self) -> Awaitable[bool]: - return layout.should_show_payment_request_details( - self.payment_req, self.coin, self.amount_unit - ) - - __eq__ = utils.obj_eq - - -class UiConfirmReplacement(UiConfirm): - def __init__(self, title: str, txid: bytes): - self.title = title - self.txid = txid - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_replacement(self.title, self.txid) - - -class UiConfirmModifyOutput(UiConfirm): - def __init__( - self, - txo: TxOutput, - orig_txo: TxOutput, - coin: CoinInfo, - amount_unit: AmountUnit, - ): - self.txo = txo - self.orig_txo = orig_txo - self.coin = coin - self.amount_unit = amount_unit - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_modify_output( - self.txo, self.orig_txo, self.coin, self.amount_unit - ) - - -class UiConfirmModifyFee(UiConfirm): - def __init__( - self, - title: str, - user_fee_change: int, - total_fee_new: int, - fee_rate: float, - coin: CoinInfo, - amount_unit: AmountUnit, - ): - self.title = title - self.user_fee_change = user_fee_change - self.total_fee_new = total_fee_new - self.fee_rate = fee_rate - self.coin = coin - self.amount_unit = amount_unit - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_modify_fee( - self.title, - self.user_fee_change, - self.total_fee_new, - self.fee_rate, - self.coin, - self.amount_unit, - ) - - class UiConfirmTotal(UiConfirm): def __init__( self, @@ -153,14 +64,12 @@ def __init__( fee: int, fee_rate: float, coin: CoinInfo, - amount_unit: AmountUnit, address_n: Bip32Path | None, ): self.spending = spending self.fee = fee self.fee_rate = fee_rate self.coin = coin - self.amount_unit = amount_unit self.address_n = address_n def confirm_dialog(self) -> Awaitable[Any]: @@ -169,36 +78,10 @@ def confirm_dialog(self) -> Awaitable[Any]: self.fee, self.fee_rate, self.coin, - self.amount_unit, self.address_n, ) -class UiConfirmJointTotal(UiConfirm): - def __init__( - self, spending: int, total: int, coin: CoinInfo, amount_unit: AmountUnit - ): - self.spending = spending - self.total = total - self.coin = coin - self.amount_unit = amount_unit - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_joint_total( - self.spending, self.total, self.coin, self.amount_unit - ) - - -class UiConfirmFeeOverThreshold(UiConfirm): - def __init__(self, fee: int, coin: CoinInfo, amount_unit: AmountUnit): - self.fee = fee - self.coin = coin - self.amount_unit = amount_unit - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_feeoverthreshold(self.fee, self.coin, self.amount_unit) - - class UiConfirmChangeCountOverThreshold(UiConfirm): def __init__(self, change_count: int): self.change_count = change_count @@ -222,60 +105,17 @@ def confirm_dialog(self) -> Awaitable[Any]: return paths.show_path_warning(self.address_n) -class UiConfirmNonDefaultLocktime(UiConfirm): - def __init__(self, lock_time: int, lock_time_disabled: bool): - self.lock_time = lock_time - self.lock_time_disabled = lock_time_disabled - - def confirm_dialog(self) -> Awaitable[Any]: - return layout.confirm_nondefault_locktime( - self.lock_time, self.lock_time_disabled - ) - - class UiConfirmMultipleAccounts(UiConfirm): def confirm_dialog(self) -> Awaitable[Any]: return layout.confirm_multiple_accounts() -def confirm_output(output: TxOutput, coin: CoinInfo, output_index: int, chunkify: bool) -> Awaitable[None]: # type: ignore [awaitable-is-generator] +def confirm_output(output: MintlayerTxOutput, coin: CoinInfo, output_index: int, chunkify: bool) -> Awaitable[None]: # type: ignore [awaitable-is-generator] return (yield UiConfirmOutput(output, coin, output_index, chunkify)) -def confirm_decred_sstx_submission(output: TxOutput, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[None]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmDecredSSTXSubmission(output, coin, amount_unit)) - - -def should_show_payment_request_details(payment_req: TxAckPaymentRequest, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[bool]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmPaymentRequest(payment_req, coin, amount_unit)) - - -def confirm_replacement(description: str, txid: bytes) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmReplacement(description, txid)) - - -def confirm_modify_output(txo: TxOutput, orig_txo: TxOutput, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmModifyOutput(txo, orig_txo, coin, amount_unit)) - - -def confirm_modify_fee(title: str, user_fee_change: int, total_fee_new: int, fee_rate: float, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return ( - yield UiConfirmModifyFee( - title, user_fee_change, total_fee_new, fee_rate, coin, amount_unit - ) - ) - - -def confirm_total(spending: int, fee: int, fee_rate: float, coin: CoinInfo, amount_unit: AmountUnit, address_n: Bip32Path | None) -> Awaitable[None]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmTotal(spending, fee, fee_rate, coin, amount_unit, address_n)) - - -def confirm_joint_total(spending: int, total: int, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmJointTotal(spending, total, coin, amount_unit)) - - -def confirm_feeoverthreshold(fee: int, coin: CoinInfo, amount_unit: AmountUnit) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmFeeOverThreshold(fee, coin, amount_unit)) +def confirm_total(spending: int, fee: int, fee_rate: float, coin: CoinInfo, address_n: Bip32Path | None) -> Awaitable[None]: # type: ignore [awaitable-is-generator] + return (yield UiConfirmTotal(spending, fee, fee_rate, coin, address_n)) def confirm_change_count_over_threshold(change_count: int) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] @@ -290,25 +130,10 @@ def confirm_foreign_address(address_n: list) -> Awaitable[Any]: # type: ignore return (yield UiConfirmForeignAddress(address_n)) -def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool) -> Awaitable[Any]: # type: ignore [awaitable-is-generator] - return (yield UiConfirmNonDefaultLocktime(lock_time, lock_time_disabled)) - - def confirm_multiple_accounts() -> Awaitable[Any]: # type: ignore [awaitable-is-generator] return (yield UiConfirmMultipleAccounts()) -def request_tx_meta(tx_req: TxRequest, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevTx]: # type: ignore [awaitable-is-generator] - from trezor.messages import TxAckPrevMeta - - assert tx_req.details is not None - tx_req.request_type = MintlayerRequestType.TXMETA - tx_req.details.tx_hash = tx_hash - ack = yield TxAckPrevMeta, tx_req - _clear_tx_request(tx_req) - return _sanitize_tx_meta(ack.tx, coin) - - def request_tx_input(tx_req: MintlayerTxRequest, i: int) -> Awaitable[MintlayerTxInput]: # type: ignore [awaitable-is-generator] from trezor.messages import MintlayerTxAckUtxoInput @@ -320,19 +145,7 @@ def request_tx_input(tx_req: MintlayerTxRequest, i: int) -> Awaitable[MintlayerT return _sanitize_tx_input(ack.tx.input) -def request_tx_prev_input(tx_req: MintlayerTxRequest, i: int, tx_hash: bytes | None = None) -> Awaitable[PrevInput]: # type: ignore [awaitable-is-generator] - from trezor.messages import TxAckPrevInput - - assert tx_req.details is not None - tx_req.request_type = MintlayerRequestType.TXINPUT - tx_req.details.request_index = i - tx_req.details.tx_hash = tx_hash - ack = yield TxAckPrevInput, tx_req - _clear_tx_request(tx_req) - return _sanitize_tx_prev_input(ack.tx.input, coin) - - -def request_tx_output(tx_req: TxRequest, i: int, tx_hash: bytes | None = None) -> Awaitable[MintlayerTxOutput]: # type: ignore [awaitable-is-generator] +def request_tx_output(tx_req: MintlayerTxRequest, i: int, tx_hash: bytes | None = None) -> Awaitable[MintlayerTxOutput]: # type: ignore [awaitable-is-generator] from trezor.messages import MintlayerTxAckOutput assert tx_req.details is not None @@ -347,20 +160,7 @@ def request_tx_output(tx_req: TxRequest, i: int, tx_hash: bytes | None = None) - return _sanitize_tx_output(ack.tx.output) -def request_tx_prev_output(tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: bytes | None = None) -> Awaitable[PrevOutput]: # type: ignore [awaitable-is-generator] - from trezor.messages import TxAckPrevOutput - - assert tx_req.details is not None - tx_req.request_type = MintlayerRequestType.TXOUTPUT - tx_req.details.request_index = i - tx_req.details.tx_hash = tx_hash - ack = yield TxAckPrevOutput, tx_req - _clear_tx_request(tx_req) - # return sanitize_tx_prev_output(ack.tx, coin) # no sanitize is required - return ack.tx.output - - -def request_tx_finish(tx_req: TxRequest) -> Awaitable[None]: # type: ignore [awaitable-is-generator] +def request_tx_finish(tx_req: MintlayerTxRequest) -> Awaitable[None]: # type: ignore [awaitable-is-generator] tx_req.request_type = MintlayerRequestType.TXFINISHED yield None, tx_req _clear_tx_request(tx_req) @@ -379,9 +179,6 @@ def _clear_tx_request(tx_req: MintlayerTxRequest) -> None: serialized = [] # serialized.signature = None # serialized.signature_index = None - # typechecker thinks serialized_tx is `bytes`, which is immutable - # we know that it is `bytearray` in reality - # serialized.serialized_tx[:] = bytes() # type: ignore ["__setitem__" method not defined on type "bytes"] # Data sanitizers @@ -449,13 +246,15 @@ def _sanitize_tx_input(txi: MintlayerTxInput) -> MintlayerTxInput: raise DataError("Input's address_n must be present for signing.") elif txi.account_command: cmd = txi.account_command - no_cmd = (cmd.mint is None - and cmd.unmint is None - and cmd.freeze_token is None - and cmd.unfreeze_token is None - and cmd.lock_token_supply is None - and cmd.change_token_metadata_uri is None - and cmd.change_token_authority is None) + no_cmd = ( + cmd.mint is None + and cmd.unmint is None + and cmd.freeze_token is None + and cmd.unfreeze_token is None + and cmd.lock_token_supply is None + and cmd.change_token_metadata_uri is None + and cmd.change_token_authority is None + ) if no_cmd: raise DataError("No account command present") @@ -465,17 +264,9 @@ def _sanitize_tx_input(txi: MintlayerTxInput) -> MintlayerTxInput: if not txi.account.address_n: raise DataError("Input's address_n must be present for signing.") else: - raise DataError("No input type present either utxo, account_command or account must be present") - - return txi - - -def _sanitize_tx_prev_input(txi: PrevInput, coin: CoinInfo) -> PrevInput: - if len(txi.prev_hash) != TX_HASH_SIZE: - raise DataError("Provided prev_hash is invalid.") - - if not coin.decred and txi.decred_tree is not None: - raise DataError("Decred details provided but Decred coin not specified.") + raise DataError( + "No input type present either utxo, account_command or account must be present" + ) return txi @@ -518,5 +309,5 @@ def get_lock(x: MintlayerOutputTimeLock) -> Tuple[int, int]: lock_type = 3 lock_amount = x.for_seconds else: - raise Exception("unhandled mintlayer lock type") + raise DataError("unhandled mintlayer lock type") return (lock_type, lock_amount) diff --git a/core/src/apps/mintlayer/sign_tx/layout.py b/core/src/apps/mintlayer/sign_tx/layout.py index 031a55540..533f01dd6 100644 --- a/core/src/apps/mintlayer/sign_tx/layout.py +++ b/core/src/apps/mintlayer/sign_tx/layout.py @@ -1,34 +1,25 @@ -from micropython import const from typing import TYPE_CHECKING from trezor import TR +from trezor.crypto.bech32 import Encoding, bech32_encode, convertbits from trezor.enums import ButtonRequestType, MintlayerTokenTotalSupplyType from trezor.strings import format_amount from trezor.ui import layouts from apps.common.paths import address_n_to_str -from trezor.crypto.bech32 import bech32_encode, convertbits, Encoding - -from ...bitcoin import addresses -from ...bitcoin.common import ( - BIP32_WALLET_DEPTH, - format_fee_rate, -) +from ...bitcoin.common import BIP32_WALLET_DEPTH, format_fee_rate from ...bitcoin.keychain import address_n_to_name if TYPE_CHECKING: - from trezor.enums import AmountUnit - from trezor.messages import TxAckPaymentRequest, TxOutput, MintlayerTokenOutputValue, MintlayerOutputTimeLock - - from apps.common.coininfo import CoinInfo - from apps.common.paths import Bip32Path - from trezor.messages import ( + MintlayerOutputTimeLock, + MintlayerTokenOutputValue, MintlayerTxOutput, ) -_LOCKTIME_TIMESTAMP_MIN_VALUE = const(500_000_000) + from apps.common.coininfo import CoinInfo + from apps.common.paths import Bip32Path ML_COIN = "ML" POOL_HRP = "mpool" @@ -41,9 +32,9 @@ def format_coin_amount(amount: bytes, token: MintlayerTokenOutputValue | None) - name = ML_COIN else: decimals = token.number_of_decimals - name = "ML Token: " + token.token_ticker.decode('utf-8') + name = "ML Token: " + token.token_ticker.decode("utf-8") - amount_int = int.from_bytes(amount, 'big') + amount_int = int.from_bytes(amount, "big") amount_str = format_amount(amount_int, decimals) return f"{amount_str} {name}" @@ -57,6 +48,7 @@ def account_label(coin: CoinInfo, address_n: Bip32Path | None) -> str: or f"Path {address_n_to_str(address_n)}" ) + def lock_to_string(lock: MintlayerOutputTimeLock) -> str: if lock.until_time: return f"Lock until {lock.until_time} time" @@ -69,6 +61,7 @@ def lock_to_string(lock: MintlayerOutputTimeLock) -> str: else: raise Exception("unhandled lock type") + async def confirm_output( output: MintlayerTxOutput, coin: CoinInfo, @@ -76,6 +69,7 @@ async def confirm_output( chunkify: bool, ) -> None: from ubinascii import hexlify + title = TR.bitcoin__title_confirm_details if output.transfer: x = output.transfer @@ -110,10 +104,11 @@ async def confirm_output( x = output.create_delegation_id assert x.destination is not None amount = "" + # FIXME: extract those 2 into 1 helper function data = convertbits(x.pool_id, 8, 5) pool_id_address = bech32_encode(POOL_HRP, data, Encoding.BECH32M) address_short = f"Address: {x.destination}\nPoolId: {pool_id_address}" - address_label = f"Create delegation ID" + address_label = "Create delegation ID" elif output.delegate_staking: x = output.delegate_staking assert x.delegation_id is not None @@ -124,10 +119,8 @@ async def confirm_output( address_label = "Delegation staking" elif output.issue_fungible_token: x = output.issue_fungible_token - ticker = x.token_ticker.decode('utf-8') - name = x.name.decode('utf-8') - additional_metadata_uri = x.additional_metadata_uri.decode('utf-8') if x.additional_metadata_uri else None - metadata_uri = x.metadata_uri.decode('utf-8') if x.metadata_uri else None + ticker = x.token_ticker.decode("utf-8") + metadata_uri = x.metadata_uri.decode("utf-8") if x.metadata_uri else None if x.total_supply.type == MintlayerTokenTotalSupplyType.UNLIMITED: total_supply = "UNLIMITED" elif x.total_supply.type == MintlayerTokenTotalSupplyType.LOCKABLE: @@ -135,7 +128,7 @@ async def confirm_output( elif x.total_supply.type == MintlayerTokenTotalSupplyType.FIXED: if not x.total_supply.fixed_amount: raise ValueError("Token Fixed supply without amount") - amount = int.from_bytes(x.total_supply.fixed_amount, 'big') + amount = int.from_bytes(x.total_supply.fixed_amount, "big") formated_amount = format_amount(amount, x.number_of_decimals) total_supply = f"FIXED {formated_amount}" else: @@ -152,11 +145,15 @@ async def confirm_output( address_label = "Issue fungible token" elif output.issue_nft: x = output.issue_nft - ticker = x.ticker.decode('utf-8') - name = x.name.decode('utf-8') - icon_uri = x.icon_uri.decode('utf-8') if x.icon_uri else None - additional_metadata_uri = x.additional_metadata_uri.decode('utf-8') if x.additional_metadata_uri else None - media_uri = x.media_uri.decode('utf-8') if x.media_uri else None + ticker = x.ticker.decode("utf-8") + name = x.name.decode("utf-8") + icon_uri = x.icon_uri.decode("utf-8") if x.icon_uri else None + additional_metadata_uri = ( + x.additional_metadata_uri.decode("utf-8") + if x.additional_metadata_uri + else None + ) + media_uri = x.media_uri.decode("utf-8") if x.media_uri else None address_short = f"""Name: {name} Creator: {x.creator} ticker: {ticker} @@ -191,81 +188,28 @@ async def confirm_output( chunkify=chunkify, ) else: - layout = layouts.confirm_text("confirm_address", + layout = layouts.confirm_text( + "confirm_address", title=title, - data= address_short, - description= address_label, - br_code= ButtonRequestType.ConfirmOutput, + data=address_short, + description=address_label, + br_code=ButtonRequestType.ConfirmOutput, ) await layout -async def confirm_decred_sstx_submission( - output: TxOutput, coin: CoinInfo, amount_unit: AmountUnit -) -> None: - assert output.address is not None - address_short = addresses.address_short(coin, output.address) - amount = format_coin_amount(output.amount, coin, amount_unit) - - await layouts.confirm_value( - TR.bitcoin__title_purchase_ticket, - amount, - TR.bitcoin__ticket_amount, - "confirm_decred_sstx_submission", - ButtonRequestType.ConfirmOutput, - verb=TR.buttons__confirm, - ) - - await layouts.confirm_value( - TR.bitcoin__title_purchase_ticket, - address_short, - TR.bitcoin__voting_rights, - "confirm_decred_sstx_submission", - ButtonRequestType.ConfirmOutput, - verb=TR.buttons__purchase, - ) - - -async def should_show_payment_request_details( - msg: TxAckPaymentRequest, - coin: CoinInfo, - amount_unit: AmountUnit, -) -> bool: - from trezor import wire - - memo_texts: list[str] = [] - for m in msg.memos: - if m.text_memo is not None: - memo_texts.append(m.text_memo.text) - elif m.refund_memo is not None: - pass - elif m.coin_purchase_memo is not None: - memo_texts.append(f"{TR.words__buying} {m.coin_purchase_memo.amount}.") - else: - raise wire.DataError("Unrecognized memo type in payment request memo.") - - assert msg.amount is not None - - return await layouts.should_show_payment_request_details( - msg.recipient_name, - format_coin_amount(msg.amount, coin, amount_unit), - memo_texts, - ) - - async def confirm_total( spending: int, fee: int, fee_rate: float, coin: CoinInfo, - amount_unit: AmountUnit, address_n: Bip32Path | None, ) -> None: await layouts.confirm_total( - format_coin_amount(spending.to_bytes(16, 'big'), None), - format_coin_amount(fee.to_bytes(16, 'big'), None), + format_coin_amount(spending.to_bytes(16, "big"), None), + format_coin_amount(fee.to_bytes(16, "big"), None), fee_rate_amount=format_fee_rate(fee_rate, coin) if fee_rate >= 0 else None, account_label=account_label(coin, address_n), ) @@ -298,32 +242,3 @@ async def confirm_multiple_accounts() -> None: button=TR.buttons__continue, br_code=ButtonRequestType.SignTx, ) - - -async def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool) -> None: - from trezor.strings import format_timestamp - - if lock_time_disabled: - await layouts.show_warning( - "nondefault_locktime", - TR.bitcoin__locktime_no_effect, - TR.words__continue_anyway, - button=TR.buttons__continue, - br_code=ButtonRequestType.SignTx, - ) - else: - if lock_time < _LOCKTIME_TIMESTAMP_MIN_VALUE: - text = TR.bitcoin__locktime_set_to_blockheight - value = str(lock_time) - else: - text = TR.bitcoin__locktime_set_to - value = format_timestamp(lock_time) - await layouts.confirm_value( - TR.bitcoin__confirm_locktime, - value, - text, - "nondefault_locktime", - br_code=ButtonRequestType.SignTx, - verb=TR.buttons__confirm, - ) - diff --git a/core/src/apps/mintlayer/sign_tx/progress.py b/core/src/apps/mintlayer/sign_tx/progress.py index 5a97777fc..eb212cdbc 100644 --- a/core/src/apps/mintlayer/sign_tx/progress.py +++ b/core/src/apps/mintlayer/sign_tx/progress.py @@ -1,11 +1,7 @@ from typing import TYPE_CHECKING -from trezor.messages import MintlayerSignTx - if TYPE_CHECKING: - from trezor.messages import SignTx - - from apps.common.coininfo import CoinInfo + from trezor.messages import MintlayerSignTx # Checking previous transactions typically requires the following pieces of # information to be fetched for each input: @@ -105,4 +101,3 @@ def assert_finished(self) -> None: progress = Progress() - diff --git a/core/src/apps/mintlayer/sign_tx/signer.py b/core/src/apps/mintlayer/sign_tx/signer.py index 041bb2e47..e4c1a322c 100644 --- a/core/src/apps/mintlayer/sign_tx/signer.py +++ b/core/src/apps/mintlayer/sign_tx/signer.py @@ -1,21 +1,27 @@ -from apps.common.coininfo import by_name -from trezor.crypto.bech32 import mintlayer_decode_address_to_bytes -from trezor.messages import MintlayerSignTx, MintlayerTxRequestSerializedType, MintlayerSignature, MintlayerTxInput, MintlayerTxOutput from micropython import const from typing import TYPE_CHECKING -from trezor import workflow, log -from trezor.crypto.hashlib import blake2b +from trezor import log, workflow from trezor.crypto import mintlayer_utils -from trezor.enums import AmountUnit -from trezor.utils import empty_bytearray +from trezor.crypto.bech32 import mintlayer_decode_address_to_bytes from trezor.crypto.curve import bip340 +from trezor.crypto.hashlib import blake2b +from trezor.messages import ( + MintlayerSignature, + MintlayerSignTx, + MintlayerTxInput, + MintlayerTxOutput, + MintlayerTxRequestSerializedType, +) +from trezor.utils import empty_bytearray + +from apps.common.coininfo import by_name -from .progress import progress from . import helpers +from .progress import progress if TYPE_CHECKING: - from typing import List, Tuple, Dict + from typing import Dict, List, Tuple from trezor.crypto import bip32 from trezor.messages import MintlayerOutputValue @@ -23,31 +29,47 @@ from apps.common.keychain import Keychain -ML_COIN = 'ML' +ML_COIN = "ML" # the number of bytes to preallocate for serialized transaction chunks _MAX_SERIALIZED_CHUNK_SIZE = const(2048) _SERIALIZED_TX_BUFFER = empty_bytearray(_MAX_SERIALIZED_CHUNK_SIZE) + class TxUtxoInput: - def __init__(self, input: MintlayerTxInput, utxo: MintlayerTxOutput | None, node: List[Tuple[bip32.HDNode, int | None]]): + def __init__( + self, + input: MintlayerTxInput, + utxo: MintlayerTxOutput | None, + node: List[Tuple[bip32.HDNode, int | None]], + ): self.input = input self.utxo = utxo self.node = node class TxInfo: - def __init__(self, tx: MintlayerSignTx, inputs: List[TxUtxoInput], outputs: List[MintlayerTxOutput]): + def __init__( + self, + tx: MintlayerSignTx, + inputs: List[TxUtxoInput], + outputs: List[MintlayerTxOutput], + ): self.tx = tx self.inputs = inputs self.outputs = outputs - - def add_input(self, txi: MintlayerTxInput, txo: MintlayerTxOutput | None, node: List[Tuple[bip32.HDNode, int | None]]): - self.inputs.append(TxUtxoInput(input= txi, utxo= txo, node= node)) + def add_input( + self, + txi: MintlayerTxInput, + txo: MintlayerTxOutput | None, + node: List[Tuple[bip32.HDNode, int | None]], + ): + self.inputs.append(TxUtxoInput(input=txi, utxo=txo, node=node)) def add_output(self, txo: MintlayerTxOutput): self.outputs.append(txo) + class Mintlayer: def init_signing(self) -> None: # Next shown progress bar is already signing progress, but it isn't shown until approval from next dialog @@ -69,14 +91,12 @@ async def signer(self) -> None: fee = input_totals[ML_COIN] - output_totals[ML_COIN] fee_rate = 0 - coin = by_name('Bitcoin') - amount_unit = AmountUnit.BITCOIN + coin = by_name("Bitcoin") await helpers.confirm_total( output_totals[ML_COIN], fee, fee_rate, coin, - amount_unit, None, ) @@ -98,16 +118,18 @@ async def signer(self) -> None: # Check that inputs are unchanged. Serialize inputs and sign the non-segwit ones. encoded_inputs, encoded_input_utxos = await self.step4_serialize_inputs() if __debug__: - log.debug(__name__, f"encoded inputs: {encoded_inputs}") - log.debug(__name__, f"encoded utxos: {encoded_input_utxos}") + log.debug(__name__, "encoded inputs: %s", str(encoded_inputs)) + log.debug(__name__, "encoded utxos: %s", str(encoded_input_utxos)) # Serialize outputs. encoded_outputs = await self.step5_serialize_outputs() if __debug__: - log.debug(__name__, f"encoded outputs: {encoded_outputs}") + log.debug(__name__, "encoded outputs: %s", str(encoded_outputs)) # Sign segwit inputs and serialize witness data. - signatures = await self.step6_sign_inputs(encoded_inputs, encoded_input_utxos, encoded_outputs) + signatures = await self.step6_sign_inputs( + encoded_inputs, encoded_input_utxos, encoded_outputs + ) # Write footer and send remaining data. await self.step7_finish(signatures) @@ -118,10 +140,7 @@ def __init__( keychain: Keychain, # approver: approvers.Approver | None, ) -> None: - from trezor.messages import ( - MintlayerTxRequest, - TxRequestDetailsType, - ) + from trezor.messages import MintlayerTxRequest, MintlayerTxRequestDetailsType global _SERIALIZED_TX_BUFFER @@ -144,7 +163,7 @@ def __init__( self.serialized_tx = _SERIALIZED_TX_BUFFER self.serialize = tx.serialize self.tx_req = MintlayerTxRequest() - self.tx_req.details = TxRequestDetailsType() + self.tx_req.details = MintlayerTxRequestDetailsType() self.tx_req.serialized = [] # The digest of the presigned external inputs streamed for approval in Step 1. This is @@ -170,20 +189,30 @@ async def step1_process_inputs(self) -> Dict[str, int]: txi = await helpers.request_tx_input(self.tx_req, i) if txi.utxo: # get the utxo - txo = await helpers.request_tx_output(self.tx_req, txi.utxo.prev_index, txi.utxo.prev_hash) + txo = await helpers.request_tx_output( + self.tx_req, txi.utxo.prev_index, txi.utxo.prev_hash + ) node = [] for address in txi.utxo.address_n: - node.append((self.keychain.derive(address.address_n), address.multisig_idx)) + node.append( + (self.keychain.derive(address.address_n), address.multisig_idx) + ) update_totals(totals, txo) self.tx_info.add_input(txi, txo, node) elif txi.account: node = [] for address in txi.account.address_n: - node.append((self.keychain.derive(address.address_n), address.multisig_idx)) + node.append( + (self.keychain.derive(address.address_n), address.multisig_idx) + ) value = txi.account.value - amount = int.from_bytes(value.amount, 'big') - token_or_coin = str(value.token.token_ticker.decode('utf-8')) if value.token else ML_COIN + amount = int.from_bytes(value.amount, "big") + token_or_coin = ( + str(value.token.token_ticker.decode("utf-8")) + if value.token + else ML_COIN + ) if token_or_coin in totals: totals[token_or_coin] += amount else: @@ -192,7 +221,9 @@ async def step1_process_inputs(self) -> Dict[str, int]: elif txi.account_command: node = [] for address in txi.account_command.address_n: - node.append((self.keychain.derive(address.address_n), address.multisig_idx)) + node.append( + (self.keychain.derive(address.address_n), address.multisig_idx) + ) self.tx_info.add_input(txi, None, node) else: raise Exception("Unhandled tx input type") @@ -206,7 +237,7 @@ async def step2_approve_outputs(self) -> Dict[str, int]: # STAGE_REQUEST_2_OUTPUT in legacy progress.advance() txo = await helpers.request_tx_output(self.tx_req, i) - coin = by_name('Bitcoin') + coin = by_name("Bitcoin") await helpers.confirm_output(txo, coin, i, False) update_totals(totals, txo) self.tx_info.add_output(txo) @@ -222,17 +253,21 @@ async def step4_serialize_inputs(self) -> Tuple[List[bytes], List[bytes]]: progress.advance() if inp.input.utxo and inp.utxo: x = inp.input.utxo - encoded_inp = mintlayer_utils.encode_utxo_input(x.prev_hash, x.prev_index, int(x.type)) + encoded_inp = mintlayer_utils.encode_utxo_input( + x.prev_hash, x.prev_index, int(x.type) + ) encoded_inputs.append(encoded_inp) data = mintlayer_decode_address_to_bytes(x.address) encoded_inp_utxo = self.serialize_output(inp.utxo) - encoded_input_utxos.append(b'\x01' + encoded_inp_utxo) + encoded_input_utxos.append(b"\x01" + encoded_inp_utxo) elif inp.input.account: x = inp.input.account - encoded_inp = mintlayer_utils.encode_account_spending_input(x.nonce, x.delegation_id, x.value.amount) + encoded_inp = mintlayer_utils.encode_account_spending_input( + x.nonce, x.delegation_id, x.value.amount + ) encoded_inputs.append(encoded_inp) - encoded_input_utxos.append(b'\x00') + encoded_input_utxos.append(b"\x00") elif inp.input.account_command: x = inp.input.account_command if x.mint: @@ -242,23 +277,25 @@ async def step4_serialize_inputs(self) -> Tuple[List[bytes], List[bytes]]: elif x.unmint: command = 1 token_id = x.unmint.token_id - data = b'' + data = b"" elif x.lock_token_supply: command = 2 token_id = x.lock_token_supply.token_id - data = b'' + data = b"" elif x.freeze_token: command = 3 token_id = x.freeze_token.token_id - data = int(x.freeze_token.is_token_unfreezabe).to_bytes(1, 'big') + data = int(x.freeze_token.is_token_unfreezabe).to_bytes(1, "big") elif x.unfreeze_token: command = 4 token_id = x.unfreeze_token.token_id - data = b'' + data = b"" elif x.change_token_authority: command = 5 token_id = x.change_token_authority.token_id - data = mintlayer_decode_address_to_bytes(x.change_token_authority.destination) + data = mintlayer_decode_address_to_bytes( + x.change_token_authority.destination + ) elif x.change_token_metadata_uri: command = 5 token_id = x.change_token_metadata_uri.token_id @@ -266,10 +303,11 @@ async def step4_serialize_inputs(self) -> Tuple[List[bytes], List[bytes]]: else: raise Exception("unknown account command") - encoded_inp = mintlayer_utils.encode_account_command_input(x.nonce, command, token_id, data) + encoded_inp = mintlayer_utils.encode_account_command_input( + x.nonce, command, token_id, data + ) encoded_inputs.append(encoded_inp) - encoded_input_utxos.append(b'\x00') - + encoded_input_utxos.append(b"\x00") return encoded_inputs, encoded_input_utxos @@ -277,59 +315,103 @@ def serialize_output(self, out: MintlayerTxOutput) -> bytes: if out.transfer: x = out.transfer data = mintlayer_decode_address_to_bytes(x.address) - token_id = b'' if not x.value.token else x.value.token.token_id - encoded_out = mintlayer_utils.encode_transfer_output(x.value.amount, token_id, data) + token_id = b"" if not x.value.token else x.value.token.token_id + encoded_out = mintlayer_utils.encode_transfer_output( + x.value.amount, token_id, data + ) elif out.lock_then_transfer: x = out.lock_then_transfer data = mintlayer_decode_address_to_bytes(x.address) lock_type, lock_amount = helpers.get_lock(x.lock) - token_id = b'' if not x.value.token else x.value.token.token_id - encoded_out = mintlayer_utils.encode_lock_then_transfer_output(x.value.amount, token_id, lock_type, lock_amount, data) + token_id = b"" if not x.value.token else x.value.token.token_id + encoded_out = mintlayer_utils.encode_lock_then_transfer_output( + x.value.amount, token_id, lock_type, lock_amount, data + ) elif out.burn: x = out.burn - token_id = b'' if not x.value.token else x.value.token.token_id + token_id = b"" if not x.value.token else x.value.token.token_id encoded_out = mintlayer_utils.encode_burn_output(x.value.amount, token_id) elif out.create_stake_pool: x = out.create_stake_pool staker = mintlayer_decode_address_to_bytes(x.staker) vrf_public_key = mintlayer_decode_address_to_bytes(x.vrf_public_key) decommission_key = mintlayer_decode_address_to_bytes(x.decommission_key) - encoded_out = mintlayer_utils.encode_create_stake_pool_output(x.pool_id, x.pledge, staker, vrf_public_key, decommission_key, x.margin_ratio_per_thousand, x.cost_per_block) + encoded_out = mintlayer_utils.encode_create_stake_pool_output( + x.pool_id, + x.pledge, + staker, + vrf_public_key, + decommission_key, + x.margin_ratio_per_thousand, + x.cost_per_block, + ) elif out.create_delegation_id: x = out.create_delegation_id destination = mintlayer_decode_address_to_bytes(x.destination) - encoded_out = mintlayer_utils.encode_create_delegation_id_output(destination, x.pool_id) + encoded_out = mintlayer_utils.encode_create_delegation_id_output( + destination, x.pool_id + ) elif out.delegate_staking: x = out.delegate_staking - encoded_out = mintlayer_utils.encode_delegate_staking_output(x.amount, x.delegation_id) + encoded_out = mintlayer_utils.encode_delegate_staking_output( + x.amount, x.delegation_id + ) elif out.produce_block_from_stake: x = out.produce_block_from_stake destination = mintlayer_decode_address_to_bytes(x.destination) - encoded_out = mintlayer_utils.encode_produce_from_stake_output(destination, x.pool_id) + encoded_out = mintlayer_utils.encode_produce_from_stake_output( + destination, x.pool_id + ) elif out.issue_fungible_token: x = out.issue_fungible_token authority = mintlayer_decode_address_to_bytes(x.authority) - encoded_out = mintlayer_utils.encode_issue_fungible_token_output(x.token_ticker, x.number_of_decimals, x.metadata_uri, x.total_supply.type, x.total_supply.fixed_amount, authority, int(x.is_freezable)) + encoded_out = mintlayer_utils.encode_issue_fungible_token_output( + x.token_ticker, + x.number_of_decimals, + x.metadata_uri, + x.total_supply.type, + x.total_supply.fixed_amount, + authority, + int(x.is_freezable), + ) elif out.issue_nft: x = out.issue_nft creator = mintlayer_decode_address_to_bytes(x.creator) destination = mintlayer_decode_address_to_bytes(x.destination) - encoded_out = mintlayer_utils.encode_issue_nft_output(x.token_id, creator, x.name, x.destination, x.ticker, x.icon_uri, x.additional_metadata_uri, x.media_uri, x.media_hash, destination) + encoded_out = mintlayer_utils.encode_issue_nft_output( + x.token_id, + creator, + x.name, + x.destination, + x.ticker, + x.icon_uri, + x.additional_metadata_uri, + x.media_uri, + x.media_hash, + destination, + ) elif out.data_deposit: x = out.data_deposit encoded_out = mintlayer_utils.encode_data_deposit_output(x.data) elif out.htlc: x = out.htlc - token_id = b'' if not x.value.token else x.value.token.token_id + token_id = b"" if not x.value.token else x.value.token.token_id spend_key = mintlayer_decode_address_to_bytes(x.spend_key) refund_key = mintlayer_decode_address_to_bytes(x.refund_key) lock_type, lock_amount = helpers.get_lock(x.refund_timelock) - encoded_out = mintlayer_utils.encode_htlc_output(x.value.amount, token_id, lock_type, lock_amount, refund_key, spend_key, x.secret_hash) + encoded_out = mintlayer_utils.encode_htlc_output( + x.value.amount, + token_id, + lock_type, + lock_amount, + refund_key, + spend_key, + x.secret_hash, + ) else: raise Exception("unhandled tx output type") return encoded_out - async def step5_serialize_outputs(self) -> List[bytes]: encoded_outputs = [] for out in self.tx_info.outputs: @@ -339,7 +421,12 @@ async def step5_serialize_outputs(self) -> List[bytes]: return encoded_outputs - async def step6_sign_inputs(self, encoded_inputs: List[bytes], encoded_input_utxos: List[bytes], encoded_outputs: List[bytes]) -> List[List[Tuple[bytes, int | None]]]: + async def step6_sign_inputs( + self, + encoded_inputs: List[bytes], + encoded_input_utxos: List[bytes], + encoded_outputs: List[bytes], + ) -> List[List[Tuple[bytes, int | None]]]: from trezor.utils import HashWriter signatures = [] @@ -348,23 +435,24 @@ async def step6_sign_inputs(self, encoded_inputs: List[bytes], encoded_input_utx for node, multisig_idx in self.tx_info.inputs[i].node: writer = HashWriter(blake2b()) # mode - writer.extend(b'\x01') + writer.extend(b"\x01") # version - writer.extend(b'\x01') + writer.extend(b"\x01") # flags - writer.extend(bytes([0]*16)) - + writer.extend(bytes([0] * 16)) - writer.extend(len(encoded_inputs).to_bytes(4, 'little')) + writer.extend(len(encoded_inputs).to_bytes(4, "little")) for inp in encoded_inputs: writer.extend(inp) - writer.extend(len(encoded_input_utxos).to_bytes(4, 'little')) + writer.extend(len(encoded_input_utxos).to_bytes(4, "little")) for utxo in encoded_input_utxos: writer.extend(utxo) - encoded_len = mintlayer_utils.encode_compact_length(len(encoded_outputs)) + encoded_len = mintlayer_utils.encode_compact_length( + len(encoded_outputs) + ) writer.extend(encoded_len) for out in encoded_outputs: writer.extend(out) @@ -379,15 +467,28 @@ async def step6_sign_inputs(self, encoded_inputs: List[bytes], encoded_input_utx return signatures - async def step7_finish(self, signatures: List[List[Tuple[bytes, int | None]]]) -> None: - sigs = [MintlayerTxRequestSerializedType(signature_index=i, signatures=[MintlayerSignature(signature=s[0], multisig_idx=s[1]) for s in sigs]) for i, sigs in enumerate(signatures)] + async def step7_finish( + self, signatures: List[List[Tuple[bytes, int | None]]] + ) -> None: + sigs = [ + MintlayerTxRequestSerializedType( + signature_index=i, + signatures=[ + MintlayerSignature(signature=s[0], multisig_idx=s[1]) for s in sigs + ], + ) + for i, sigs in enumerate(signatures) + ] self.tx_req.serialized = sigs await helpers.request_tx_finish(self.tx_req) + def update_totals(totals: Dict[str, int], txo: MintlayerTxOutput): def update(value: MintlayerOutputValue): - amount = int.from_bytes(value.amount, 'big') - token_or_coin = str(value.token.token_ticker.decode('utf-8')) if value.token else ML_COIN + amount = int.from_bytes(value.amount, "big") + token_or_coin = ( + str(value.token.token_ticker.decode("utf-8")) if value.token else ML_COIN + ) if token_or_coin in totals: totals[token_or_coin] += amount else: @@ -400,12 +501,12 @@ def update(value: MintlayerOutputValue): elif txo.burn: update(txo.burn.value) elif txo.issue_nft: - totals[txo.issue_nft.ticker.decode('utf-8')] += 1 + totals[txo.issue_nft.ticker.decode("utf-8")] += 1 elif txo.create_stake_pool: - amount = int.from_bytes(txo.create_stake_pool.pledge, 'big') + amount = int.from_bytes(txo.create_stake_pool.pledge, "big") totals[ML_COIN] += amount elif txo.delegate_staking: - amount = int.from_bytes(txo.delegate_staking.amount, 'big') + amount = int.from_bytes(txo.delegate_staking.amount, "big") totals[ML_COIN] += amount elif txo.htlc: update(txo.htlc.value) diff --git a/core/src/apps/mintlayer/writers.py b/core/src/apps/mintlayer/writers.py deleted file mode 100644 index 13f89e63c..000000000 --- a/core/src/apps/mintlayer/writers.py +++ /dev/null @@ -1,110 +0,0 @@ -from micropython import const -from typing import TYPE_CHECKING - -from trezor.utils import ensure - -from apps.common.writers import ( # noqa: F401 - write_bytes_fixed, - write_bytes_reversed, - write_bytes_unchecked, - write_compact_size, - write_uint8, - write_uint16_le, - write_uint32_le, - write_uint64_le, -) - -if TYPE_CHECKING: - from trezor.messages import PrevInput, PrevOutput, TxInput, TxOutput - from trezor.utils import HashWriter - - from apps.common.writers import Writer - -write_uint16 = write_uint16_le -write_uint32 = write_uint32_le -write_uint64 = write_uint64_le - -TX_HASH_SIZE = const(32) - - -def write_bytes_prefixed(w: Writer, b: bytes) -> None: - write_compact_size(w, len(b)) - write_bytes_unchecked(w, b) - - -def write_tx_input(w: Writer, i: TxInput | PrevInput, script: bytes) -> None: - write_bytes_reversed(w, i.prev_hash, TX_HASH_SIZE) - write_uint32(w, i.prev_index) - write_bytes_prefixed(w, script) - write_uint32(w, i.sequence) - - -def write_tx_input_check(w: Writer, i: TxInput) -> None: - from .multisig import multisig_fingerprint - - write_uint32(w, len(i.address_n)) - for n in i.address_n: - write_uint32(w, n) - write_bytes_fixed(w, i.prev_hash, TX_HASH_SIZE) - write_uint32(w, i.prev_index) - write_bytes_prefixed(w, i.script_sig or b"") - write_uint32(w, i.sequence) - write_uint32(w, i.script_type) - multisig_fp = multisig_fingerprint(i.multisig) if i.multisig else b"" - write_bytes_prefixed(w, multisig_fp) - write_uint64(w, i.amount or 0) - write_bytes_prefixed(w, i.witness or b"") - write_bytes_prefixed(w, i.ownership_proof or b"") - write_bytes_prefixed(w, i.orig_hash or b"") - write_uint32(w, i.orig_index or 0) - write_bytes_prefixed(w, i.script_pubkey or b"") - - -def write_tx_output(w: Writer, o: TxOutput | PrevOutput, script_pubkey: bytes) -> None: - write_uint64(w, o.amount) - write_bytes_prefixed(w, script_pubkey) - - -def write_op_push(w: Writer, n: int) -> None: - append = w.append # local_cache_attribute - - ensure(0 <= n <= 0xFFFF_FFFF) - if n < 0x4C: - append(n & 0xFF) - elif n < 0x100: - append(0x4C) - append(n & 0xFF) - elif n < 0x1_0000: - append(0x4D) - append(n & 0xFF) - append((n >> 8) & 0xFF) - else: - append(0x4E) - append(n & 0xFF) - append((n >> 8) & 0xFF) - append((n >> 16) & 0xFF) - append((n >> 24) & 0xFF) - - -def op_push_length(n: int) -> int: - ensure(0 <= n <= 0xFFFF_FFFF) - if n < 0x4C: - return 1 - elif n < 0x100: - return 2 - elif n < 0x1_0000: - return 3 - else: - return 4 - - -def get_tx_hash(w: HashWriter, double: bool = False, reverse: bool = False) -> bytes: - from trezor.crypto.hashlib import sha256 - - d = w.get_digest() - if double: - d = sha256(d).digest() - if reverse: - d = bytes(reversed(d)) - return d - diff --git a/core/src/apps/workflow_handlers.py b/core/src/apps/workflow_handlers.py index 014a3a479..cf55a7e9e 100644 --- a/core/src/apps/workflow_handlers.py +++ b/core/src/apps/workflow_handlers.py @@ -24,7 +24,7 @@ def _find_message_handler_module(msg_type: int) -> str: - collecting everything as strings instead of importing directly means that we don't need to load any of the modules into memory until we actually need them """ - from trezor import utils, log + from trezor import log, utils from trezor.enums import MessageType # debug @@ -211,7 +211,10 @@ def _find_message_handler_module(msg_type: int) -> str: return "apps.mintlayer.sign_tx" if __debug__: - log.debug(__name__, f"msg type not found {msg_type}, {MessageType.MintlayerGetPublicKey}") + log.debug( + __name__, + f"msg type not found {msg_type}, {MessageType.MintlayerGetPublicKey}", + ) raise ValueError diff --git a/core/src/trezor/crypto/__init__.py b/core/src/trezor/crypto/__init__.py index 7f7756fbd..a2348431d 100644 --- a/core/src/trezor/crypto/__init__.py +++ b/core/src/trezor/crypto/__init__.py @@ -18,7 +18,8 @@ if not utils.BITCOIN_ONLY: from trezorcrypto import cardano, monero, nem # noqa: F401 - from trezormintlayer import utils as mintlayer_utils + + import trezormintlayer as mintlayer_utils # noqa: F401 if utils.USE_OPTIGA: from trezorcrypto import optiga # noqa: F401 diff --git a/core/src/trezor/crypto/bech32.py b/core/src/trezor/crypto/bech32.py index fa2368ef9..17a7382dc 100644 --- a/core/src/trezor/crypto/bech32.py +++ b/core/src/trezor/crypto/bech32.py @@ -126,9 +126,8 @@ def convertbits( return ret -def reverse_convertbits( - data: Sequence[int], frombits: int, tobits: int -) -> list[int]: + +def reverse_convertbits(data: Sequence[int], frombits: int, tobits: int) -> list[int]: acc = 0 bits = 0 ret = [] @@ -145,7 +144,7 @@ def reverse_convertbits( def mintlayer_bech32_decode(bech32_str): - if not (1 <= len(bech32_str) <= 90): + if not 1 <= len(bech32_str) <= 90: raise ValueError("Invalid length of Bech32 string") if not (bech32_str.lower() == bech32_str or bech32_str.upper() == bech32_str): @@ -174,6 +173,7 @@ def mintlayer_bech32_decode(bech32_str): return hrp, decoded[:-6] + def mintlayer_decode_address_to_bytes(address: str | None) -> bytes: if address is None: return bytes() diff --git a/python/src/trezorlib/mintlayer.py b/python/src/trezorlib/mintlayer.py index a37153f7d..7163aee80 100644 --- a/python/src/trezorlib/mintlayer.py +++ b/python/src/trezorlib/mintlayer.py @@ -18,7 +18,6 @@ from typing import TYPE_CHECKING, Dict, List, Optional from . import messages -from .protobuf import dict_to_proto from .tools import expect, session if TYPE_CHECKING: @@ -49,6 +48,7 @@ def get_public_key( messages.MintlayerGetPublicKey(address_n=address_n, show_display=show_display) ) + def sign_message( client: "TrezorClient", address_n: "Address", @@ -56,41 +56,40 @@ def sign_message( ) -> bytes: try: resp = client.call( - messages.MintlayerSignMessage( - address_n=address_n, - message=message - ) + messages.MintlayerSignMessage(address_n=address_n, message=message) ) if isinstance(resp, messages.MessageSignature): return resp.signature - return b'' + return b"" # TODO: add exceptions like btc # except exceptions.TrezorFailure: except: print("got exception in verify sig Mintlayer") - return b'' + return b"" Input = messages.MintlayerTxInput Output = messages.MintlayerTxOutput TxHash = bytes + @dataclass class Tx: inputs: List[Input] outputs: List[Output] + @session def sign_tx( - client: "TrezorClient", - inputs: List[Input], - outputs: List[Output], - prev_txs: Dict[TxHash, Tx], - version: Optional["int"] = 1, - serialize: Optional["bool"] = True, - chunkify: Optional["bool"] = None, + client: "TrezorClient", + inputs: List[Input], + outputs: List[Output], + prev_txs: Dict[TxHash, Tx], + version: Optional["int"] = 1, + serialize: Optional["bool"] = True, + chunkify: Optional["bool"] = None, ): res = client.call( messages.MintlayerSignTx( @@ -108,7 +107,9 @@ def sign_tx( return res if res.request_type == R.TXINPUT: - msg = messages.MintlayerTxAckInputWrapper(input=inputs[res.details.request_index]) + msg = messages.MintlayerTxAckInputWrapper( + input=inputs[res.details.request_index] + ) msg = messages.MintlayerTxAckUtxoInput(tx=msg) res = client.call(msg) elif res.request_type == R.TXOUTPUT: @@ -117,7 +118,9 @@ def sign_tx( outs = prev_txs[res.details.tx_hash].outputs else: outs = outputs - msg = messages.MintlayerTxAckOutputWrapper(output=outs[res.details.request_index]) + msg = messages.MintlayerTxAckOutputWrapper( + output=outs[res.details.request_index] + ) msg = messages.MintlayerTxAckOutput(tx=msg) res = client.call(msg) diff --git a/rust/trezor-client/src/error.rs b/rust/trezor-client/src/error.rs index 18c273ab5..e38c90d9e 100644 --- a/rust/trezor-client/src/error.rs +++ b/rust/trezor-client/src/error.rs @@ -103,11 +103,3 @@ pub enum Error { #[error("malformed MintlayerTxRequest: {0:?}")] MalformedMintlayerTxRequest(protos::MintlayerTxRequest), } - -impl PartialEq for Error { - fn eq(&self, _other: &Self) -> bool { - false - } -} - -impl Eq for Error {}