1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2025-06-03 22:58:46 +00:00

chore(core): use more const to decrease space

This commit is contained in:
grdddj 2022-09-15 12:45:30 +02:00 committed by matejcik
parent 49765830de
commit 52558c7b96
21 changed files with 142 additions and 121 deletions

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import utils, wire from trezor import utils, wire
@ -28,8 +29,8 @@ if TYPE_CHECKING:
_VERSION_MAGIC = b"SL\x00\x19" _VERSION_MAGIC = b"SL\x00\x19"
_FLAG_USER_CONFIRMED = 0x01 _FLAG_USER_CONFIRMED = const(0x01)
_OWNERSHIP_ID_LEN = 32 _OWNERSHIP_ID_LEN = const(32)
_OWNERSHIP_ID_KEY_PATH = [b"SLIP-0019", b"Ownership identification key"] _OWNERSHIP_ID_KEY_PATH = [b"SLIP-0019", b"Ownership identification key"]

View File

@ -53,7 +53,7 @@ _TXSIZE_DECRED_SCRIPT_VERSION = const(2)
_TXSIZE_DECRED_EXPIRY = const(4) _TXSIZE_DECRED_EXPIRY = const(4)
# Decred witness size (without script): 8 byte amount, 4 byte block height, 4 byte block index # Decred witness size (without script): 8 byte amount, 4 byte block height, 4 byte block index
_TXSIZE_DECRED_WITNESS = 16 _TXSIZE_DECRED_WITNESS = const(16)
class DecredTxWeightCalculator(TxWeightCalculator): class DecredTxWeightCalculator(TxWeightCalculator):

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import Any from typing import Any
from trezor import messages, wire from trezor import messages, wire
@ -37,8 +38,8 @@ ADDRESS_TYPES_PAYMENT_SCRIPT = (
CardanoAddressType.ENTERPRISE_SCRIPT, CardanoAddressType.ENTERPRISE_SCRIPT,
) )
MIN_ADDRESS_BYTES_LENGTH = 29 _MIN_ADDRESS_BYTES_LENGTH = const(29)
MAX_ADDRESS_BYTES_LENGTH = 65 _MAX_ADDRESS_BYTES_LENGTH = const(65)
def assert_params_cond(condition: bool) -> None: def assert_params_cond(condition: bool) -> None:
@ -282,7 +283,7 @@ def _validate_shelley_address(
def _validate_size(address_bytes: bytes) -> None: def _validate_size(address_bytes: bytes) -> None:
assert_cond( assert_cond(
MIN_ADDRESS_BYTES_LENGTH <= len(address_bytes) <= MAX_ADDRESS_BYTES_LENGTH _MIN_ADDRESS_BYTES_LENGTH <= len(address_bytes) <= _MAX_ADDRESS_BYTES_LENGTH
) )

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import messages, wire from trezor import messages, wire
@ -27,15 +28,15 @@ if TYPE_CHECKING:
from . import seed from . import seed
AUXILIARY_DATA_HASH_SIZE = 32 _AUXILIARY_DATA_HASH_SIZE = const(32)
GOVERNANCE_VOTING_PUBLIC_KEY_LENGTH = 32 _GOVERNANCE_VOTING_PUBLIC_KEY_LENGTH = const(32)
GOVERNANCE_REGISTRATION_HASH_SIZE = 32 _GOVERNANCE_REGISTRATION_HASH_SIZE = const(32)
METADATA_KEY_GOVERNANCE_REGISTRATION = 61284 _METADATA_KEY_GOVERNANCE_REGISTRATION = const(61284)
METADATA_KEY_GOVERNANCE_REGISTRATION_SIGNATURE = 61285 _METADATA_KEY_GOVERNANCE_REGISTRATION_SIGNATURE = const(61285)
MAX_DELEGATION_COUNT = 32 _MAX_DELEGATION_COUNT = const(32)
DEFAULT_VOTING_PURPOSE = 0 _DEFAULT_VOTING_PURPOSE = const(0)
def assert_cond(condition: bool) -> None: def assert_cond(condition: bool) -> None:
@ -57,7 +58,7 @@ def validate(auxiliary_data: messages.CardanoTxAuxiliaryData) -> None:
def _validate_hash(auxiliary_data_hash: bytes) -> None: def _validate_hash(auxiliary_data_hash: bytes) -> None:
assert_cond(len(auxiliary_data_hash) == AUXILIARY_DATA_HASH_SIZE) assert_cond(len(auxiliary_data_hash) == _AUXILIARY_DATA_HASH_SIZE)
def _validate_governance_registration_parameters( def _validate_governance_registration_parameters(
@ -84,13 +85,13 @@ def _validate_governance_registration_parameters(
def _validate_voting_public_key(key: bytes) -> None: def _validate_voting_public_key(key: bytes) -> None:
assert_cond(len(key) == GOVERNANCE_VOTING_PUBLIC_KEY_LENGTH) assert_cond(len(key) == _GOVERNANCE_VOTING_PUBLIC_KEY_LENGTH)
def _validate_delegations( def _validate_delegations(
delegations: list[messages.CardanoGovernanceDelegation], delegations: list[messages.CardanoGovernanceDelegation],
) -> None: ) -> None:
assert_cond(len(delegations) <= MAX_DELEGATION_COUNT) assert_cond(len(delegations) <= _MAX_DELEGATION_COUNT)
for delegation in delegations: for delegation in delegations:
_validate_voting_public_key(delegation.voting_public_key) _validate_voting_public_key(delegation.voting_public_key)
@ -101,7 +102,7 @@ def _get_voting_purpose_to_serialize(
if parameters.format == CardanoGovernanceRegistrationFormat.CIP15: if parameters.format == CardanoGovernanceRegistrationFormat.CIP15:
return None return None
if parameters.voting_purpose is None: if parameters.voting_purpose is None:
return DEFAULT_VOTING_PURPOSE return _DEFAULT_VOTING_PURPOSE
return parameters.voting_purpose return parameters.voting_purpose
@ -218,8 +219,8 @@ def _cborize_governance_registration(
governance_registration_signature = {1: governance_registration_payload_signature} governance_registration_signature = {1: governance_registration_payload_signature}
return { return {
METADATA_KEY_GOVERNANCE_REGISTRATION: governance_registration_payload, _METADATA_KEY_GOVERNANCE_REGISTRATION: governance_registration_payload,
METADATA_KEY_GOVERNANCE_REGISTRATION_SIGNATURE: governance_registration_signature, _METADATA_KEY_GOVERNANCE_REGISTRATION_SIGNATURE: governance_registration_signature,
} }
@ -277,12 +278,12 @@ def _create_governance_registration_payload_signature(
node = keychain.derive(path) node = keychain.derive(path)
encoded_governance_registration = cbor.encode( encoded_governance_registration = cbor.encode(
{METADATA_KEY_GOVERNANCE_REGISTRATION: governance_registration_payload} {_METADATA_KEY_GOVERNANCE_REGISTRATION: governance_registration_payload}
) )
governance_registration_hash = hashlib.blake2b( governance_registration_hash = hashlib.blake2b(
data=encoded_governance_registration, data=encoded_governance_registration,
outlen=GOVERNANCE_REGISTRATION_HASH_SIZE, outlen=_GOVERNANCE_REGISTRATION_HASH_SIZE,
).digest() ).digest()
return ed25519.sign_ext( return ed25519.sign_ext(
@ -304,5 +305,5 @@ def _wrap_metadata(metadata: dict) -> tuple[dict, tuple]:
def _get_hash(auxiliary_data: bytes) -> bytes: def _get_hash(auxiliary_data: bytes) -> bytes:
return hashlib.blake2b( return hashlib.blake2b(
data=auxiliary_data, outlen=AUXILIARY_DATA_HASH_SIZE data=auxiliary_data, outlen=_AUXILIARY_DATA_HASH_SIZE
).digest() ).digest()

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import log, wire from trezor import log, wire
@ -11,7 +12,7 @@ from .helpers.utils import derive_public_key
if TYPE_CHECKING: if TYPE_CHECKING:
from . import seed from . import seed
PROTOCOL_MAGIC_KEY = 2 _PROTOCOL_MAGIC_KEY = const(2)
""" """
@ -44,7 +45,7 @@ def get_address_attributes(protocol_magic: int) -> dict:
if protocol_magics.is_mainnet(protocol_magic): if protocol_magics.is_mainnet(protocol_magic):
address_attributes = {} address_attributes = {}
else: else:
address_attributes = {PROTOCOL_MAGIC_KEY: cbor.encode(protocol_magic)} address_attributes = {_PROTOCOL_MAGIC_KEY: cbor.encode(protocol_magic)}
return address_attributes return address_attributes
@ -91,13 +92,13 @@ def _validate_protocol_magic(address_data_encoded: bytes, protocol_magic: int) -
attributes = address_data[1] attributes = address_data[1]
if protocol_magics.is_mainnet(protocol_magic): if protocol_magics.is_mainnet(protocol_magic):
if PROTOCOL_MAGIC_KEY in attributes: if _PROTOCOL_MAGIC_KEY in attributes:
raise wire.ProcessError("Output address network mismatch") raise wire.ProcessError("Output address network mismatch")
else: # testnet else: # testnet
if len(attributes) == 0 or PROTOCOL_MAGIC_KEY not in attributes: if len(attributes) == 0 or _PROTOCOL_MAGIC_KEY not in attributes:
raise wire.ProcessError("Output address network mismatch") raise wire.ProcessError("Output address network mismatch")
protocol_magic_cbor = attributes[PROTOCOL_MAGIC_KEY] protocol_magic_cbor = attributes[_PROTOCOL_MAGIC_KEY]
address_protocol_magic = cbor.decode(protocol_magic_cbor) address_protocol_magic = cbor.decode(protocol_magic_cbor)
if not isinstance(address_protocol_magic, int): if not isinstance(address_protocol_magic, int):

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import wire from trezor import wire
@ -19,14 +20,14 @@ if TYPE_CHECKING:
from . import seed from . import seed
from .helpers.account_path_check import AccountPathChecker from .helpers.account_path_check import AccountPathChecker
POOL_HASH_SIZE = 28 _POOL_HASH_SIZE = const(28)
VRF_KEY_HASH_SIZE = 32 _VRF_KEY_HASH_SIZE = const(32)
POOL_METADATA_HASH_SIZE = 32 _POOL_METADATA_HASH_SIZE = const(32)
IPV4_ADDRESS_SIZE = 4 _IPV4_ADDRESS_SIZE = const(4)
IPV6_ADDRESS_SIZE = 16 _IPV6_ADDRESS_SIZE = const(16)
MAX_URL_LENGTH = 64 _MAX_URL_LENGTH = const(64)
MAX_PORT_NUMBER = 65535 _MAX_PORT_NUMBER = const(65535)
def validate( def validate(
@ -50,7 +51,7 @@ def validate(
) )
if certificate.type == CardanoCertificateType.STAKE_DELEGATION: if certificate.type == CardanoCertificateType.STAKE_DELEGATION:
if not certificate.pool or len(certificate.pool) != POOL_HASH_SIZE: if not certificate.pool or len(certificate.pool) != _POOL_HASH_SIZE:
raise wire.ProcessError("Invalid certificate") raise wire.ProcessError("Invalid certificate")
if certificate.type == CardanoCertificateType.STAKE_POOL_REGISTRATION: if certificate.type == CardanoCertificateType.STAKE_POOL_REGISTRATION:
@ -169,8 +170,8 @@ def _validate_pool_parameters(
protocol_magic: int, protocol_magic: int,
network_id: int, network_id: int,
) -> None: ) -> None:
assert_cond(len(pool_parameters.pool_id) == POOL_HASH_SIZE) assert_cond(len(pool_parameters.pool_id) == _POOL_HASH_SIZE)
assert_cond(len(pool_parameters.vrf_key_hash) == VRF_KEY_HASH_SIZE) assert_cond(len(pool_parameters.vrf_key_hash) == _VRF_KEY_HASH_SIZE)
assert_cond(0 <= pool_parameters.pledge <= LOVELACE_MAX_SUPPLY) assert_cond(0 <= pool_parameters.pledge <= LOVELACE_MAX_SUPPLY)
assert_cond(0 <= pool_parameters.cost <= LOVELACE_MAX_SUPPLY) assert_cond(0 <= pool_parameters.cost <= LOVELACE_MAX_SUPPLY)
assert_cond(pool_parameters.margin_numerator >= 0) assert_cond(pool_parameters.margin_numerator >= 0)
@ -206,32 +207,32 @@ def validate_pool_relay(pool_relay: messages.CardanoPoolRelayParameters) -> None
pool_relay.ipv4_address is not None or pool_relay.ipv6_address is not None pool_relay.ipv4_address is not None or pool_relay.ipv6_address is not None
) )
if pool_relay.ipv4_address is not None: if pool_relay.ipv4_address is not None:
assert_cond(len(pool_relay.ipv4_address) == IPV4_ADDRESS_SIZE) assert_cond(len(pool_relay.ipv4_address) == _IPV4_ADDRESS_SIZE)
if pool_relay.ipv6_address is not None: if pool_relay.ipv6_address is not None:
assert_cond(len(pool_relay.ipv6_address) == IPV6_ADDRESS_SIZE) assert_cond(len(pool_relay.ipv6_address) == _IPV6_ADDRESS_SIZE)
assert_cond( assert_cond(
pool_relay.port is not None and 0 <= pool_relay.port <= MAX_PORT_NUMBER pool_relay.port is not None and 0 <= pool_relay.port <= _MAX_PORT_NUMBER
) )
elif pool_relay.type == CardanoPoolRelayType.SINGLE_HOST_NAME: elif pool_relay.type == CardanoPoolRelayType.SINGLE_HOST_NAME:
assert_cond( assert_cond(
pool_relay.host_name is not None pool_relay.host_name is not None
and len(pool_relay.host_name) <= MAX_URL_LENGTH and len(pool_relay.host_name) <= _MAX_URL_LENGTH
) )
assert_cond( assert_cond(
pool_relay.port is not None and 0 <= pool_relay.port <= MAX_PORT_NUMBER pool_relay.port is not None and 0 <= pool_relay.port <= _MAX_PORT_NUMBER
) )
elif pool_relay.type == CardanoPoolRelayType.MULTIPLE_HOST_NAME: elif pool_relay.type == CardanoPoolRelayType.MULTIPLE_HOST_NAME:
assert_cond( assert_cond(
pool_relay.host_name is not None pool_relay.host_name is not None
and len(pool_relay.host_name) <= MAX_URL_LENGTH and len(pool_relay.host_name) <= _MAX_URL_LENGTH
) )
else: else:
raise RuntimeError # should be unreachable raise RuntimeError # should be unreachable
def _validate_pool_metadata(pool_metadata: messages.CardanoPoolMetadataType) -> None: def _validate_pool_metadata(pool_metadata: messages.CardanoPoolMetadataType) -> None:
assert_cond(len(pool_metadata.url) <= MAX_URL_LENGTH) assert_cond(len(pool_metadata.url) <= _MAX_URL_LENGTH)
assert_cond(len(pool_metadata.hash) == POOL_METADATA_HASH_SIZE) assert_cond(len(pool_metadata.hash) == _POOL_METADATA_HASH_SIZE)
assert_cond(all((32 <= ord(c) < 127) for c in pool_metadata.url)) assert_cond(all((32 <= ord(c) < 127) for c in pool_metadata.url))
@ -251,7 +252,7 @@ def _cborize_ipv6_address(ipv6_address: bytes | None) -> bytes | None:
return None return None
# ipv6 addresses are serialized to CBOR as uint_32[4] little endian # ipv6 addresses are serialized to CBOR as uint_32[4] little endian
assert len(ipv6_address) == IPV6_ADDRESS_SIZE assert len(ipv6_address) == _IPV6_ADDRESS_SIZE
result = b"" result = b""
for i in range(0, 4): for i in range(0, 4):

View File

@ -1,6 +1,8 @@
LOVELACE_MAX_SUPPLY = 45_000_000_000 * 1_000_000 from micropython import const
INPUT_PREV_HASH_SIZE = 32
ADDRESS_KEY_HASH_SIZE = 28 LOVELACE_MAX_SUPPLY = const(45_000_000_000 * 1_000_000)
SCRIPT_HASH_SIZE = 28 INPUT_PREV_HASH_SIZE = const(32)
OUTPUT_DATUM_HASH_SIZE = 32 ADDRESS_KEY_HASH_SIZE = const(28)
SCRIPT_DATA_HASH_SIZE = 32 SCRIPT_HASH_SIZE = const(28)
OUTPUT_DATUM_HASH_SIZE = const(32)
SCRIPT_DATA_HASH_SIZE = const(32)

View File

@ -1,5 +1,7 @@
MAINNET = 1 from micropython import const
TESTNET = 0
MAINNET = const(1)
TESTNET = const(0)
def is_mainnet(network_id: int) -> bool: def is_mainnet(network_id: int) -> bool:

View File

@ -1,8 +1,10 @@
from micropython import const
# https://book.world.dev.cardano.org/environments.html # https://book.world.dev.cardano.org/environments.html
MAINNET = 764824073 MAINNET = const(764824073)
TESTNET_PREPROD = 1 TESTNET_PREPROD = const(1)
TESTNET_PREVIEW = 2 TESTNET_PREVIEW = const(2)
TESTNET_LEGACY = 1097911063 TESTNET_LEGACY = const(1097911063)
NAMES = { NAMES = {
MAINNET: "Mainnet", MAINNET: "Mainnet",

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import wire from trezor import wire
@ -23,7 +24,7 @@ if TYPE_CHECKING:
from apps.common.keychain import Keychain from apps.common.keychain import Keychain
TX_TYPE = 2 _TX_TYPE = const(2)
def access_list_item_length(item: EthereumAccessList) -> int: def access_list_item_length(item: EthereumAccessList) -> int:
@ -86,7 +87,7 @@ async def sign_tx_eip1559(
sha = HashWriter(sha3_256(keccak=True)) sha = HashWriter(sha3_256(keccak=True))
rlp.write(sha, TX_TYPE) rlp.write(sha, _TX_TYPE)
rlp.write_header(sha, total_length, rlp.LIST_HEADER_BYTE) rlp.write_header(sha, total_length, rlp.LIST_HEADER_BYTE)

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import wire from trezor import wire
@ -34,7 +35,7 @@ if TYPE_CHECKING:
# Maximum data size we support # Maximum data size we support
MAX_VALUE_BYTE_SIZE = 1024 _MAX_VALUE_BYTE_SIZE = const(1024)
@with_keychain_from_path(*PATTERNS_ADDRESS) @with_keychain_from_path(*PATTERNS_ADDRESS)
@ -423,8 +424,8 @@ def validate_value(field: EthereumFieldType, value: bytes) -> None:
if len(value) != field.size: if len(value) != field.size:
raise wire.DataError("Invalid length") raise wire.DataError("Invalid length")
else: else:
if len(value) > MAX_VALUE_BYTE_SIZE: if len(value) > _MAX_VALUE_BYTE_SIZE:
raise wire.DataError(f"Invalid length, bigger than {MAX_VALUE_BYTE_SIZE}") raise wire.DataError(f"Invalid length, bigger than {_MAX_VALUE_BYTE_SIZE}")
# Specific tests for some data types # Specific tests for some data types
if field.data_type == EthereumDataType.BOOL: if field.data_type == EthereumDataType.BOOL:

View File

@ -1,3 +1,4 @@
from micropython import const
from typing import Sequence from typing import Sequence
from trezor import ui, utils, wire from trezor import ui, utils, wire
@ -18,7 +19,7 @@ from trezor.ui.layouts.reset import ( # noqa: F401
if __debug__: if __debug__:
from apps import debug from apps import debug
NUM_OF_CHOICES = 3 _NUM_OF_CHOICES = const(3)
async def show_internal_entropy(ctx: wire.GenericContext, entropy: bytes) -> None: async def show_internal_entropy(ctx: wire.GenericContext, entropy: bytes) -> None:
@ -45,8 +46,8 @@ async def _confirm_word(
non_duplicates = list(set(share_words)) non_duplicates = list(set(share_words))
# shuffle list # shuffle list
random.shuffle(non_duplicates) random.shuffle(non_duplicates)
# take top NUM_OF_CHOICES words # take top _NUM_OF_CHOICES words
choices = non_duplicates[:NUM_OF_CHOICES] choices = non_duplicates[:_NUM_OF_CHOICES]
# select first of them # select first of them
checked_word = choices[0] checked_word = choices[0]
# find its index # find its index

View File

@ -14,6 +14,7 @@ encrypted using the private spend key. Here the host sends it back
in `MoneroGetTxKeyRequest.tx_enc_keys` to be decrypted and yet again encrypted in `MoneroGetTxKeyRequest.tx_enc_keys` to be decrypted and yet again encrypted
using the view key, which the host possess. using the view key, which the host possess.
""" """
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor import utils, wire from trezor import utils, wire
@ -24,7 +25,7 @@ from apps.common.keychain import auto_keychain
from apps.monero import layout, misc from apps.monero import layout, misc
from apps.monero.xmr import chacha_poly, crypto, crypto_helpers from apps.monero.xmr import chacha_poly, crypto, crypto_helpers
_GET_TX_KEY_REASON_TX_DERIVATION = 1 _GET_TX_KEY_REASON_TX_DERIVATION = const(1)
if TYPE_CHECKING: if TYPE_CHECKING:
from apps.common.keychain import Keychain from apps.common.keychain import Keychain

View File

@ -19,7 +19,7 @@ MAX_FEE = const(1_000_000) # equals 1 XRP
# the value in docs is in XRP, we declare it here in drops # the value in docs is in XRP, we declare it here in drops
MAX_ALLOWED_AMOUNT = const(100_000_000_000_000_000) MAX_ALLOWED_AMOUNT = const(100_000_000_000_000_000)
FLAG_FULLY_CANONICAL = 0x8000_0000 FLAG_FULLY_CANONICAL = const(0x8000_0000)
def address_from_public_key(pubkey: bytes) -> str: def address_from_public_key(pubkey: bytes) -> str:

View File

@ -8,6 +8,7 @@
# the actual data follow. This currently only supports the Payment # the actual data follow. This currently only supports the Payment
# transaction type and the fields that are required for it. # transaction type and the fields that are required for it.
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from trezor.messages import RippleSignTx from trezor.messages import RippleSignTx
@ -24,24 +25,24 @@ class RippleField:
self.key: int = key self.key: int = key
FIELD_TYPE_INT16 = 1 _FIELD_TYPE_INT16 = const(1)
FIELD_TYPE_INT32 = 2 _FIELD_TYPE_INT32 = const(2)
FIELD_TYPE_AMOUNT = 6 _FIELD_TYPE_AMOUNT = const(6)
FIELD_TYPE_VL = 7 _FIELD_TYPE_VL = const(7)
FIELD_TYPE_ACCOUNT = 8 _FIELD_TYPE_ACCOUNT = const(8)
FIELDS_MAP: dict[str, RippleField] = { FIELDS_MAP: dict[str, RippleField] = {
"account": RippleField(type=FIELD_TYPE_ACCOUNT, key=1), "account": RippleField(type=_FIELD_TYPE_ACCOUNT, key=1),
"amount": RippleField(type=FIELD_TYPE_AMOUNT, key=1), "amount": RippleField(type=_FIELD_TYPE_AMOUNT, key=1),
"destination": RippleField(type=FIELD_TYPE_ACCOUNT, key=3), "destination": RippleField(type=_FIELD_TYPE_ACCOUNT, key=3),
"fee": RippleField(type=FIELD_TYPE_AMOUNT, key=8), "fee": RippleField(type=_FIELD_TYPE_AMOUNT, key=8),
"sequence": RippleField(type=FIELD_TYPE_INT32, key=4), "sequence": RippleField(type=_FIELD_TYPE_INT32, key=4),
"type": RippleField(type=FIELD_TYPE_INT16, key=2), "type": RippleField(type=_FIELD_TYPE_INT16, key=2),
"signingPubKey": RippleField(type=FIELD_TYPE_VL, key=3), "signingPubKey": RippleField(type=_FIELD_TYPE_VL, key=3),
"flags": RippleField(type=FIELD_TYPE_INT32, key=2), "flags": RippleField(type=_FIELD_TYPE_INT32, key=2),
"txnSignature": RippleField(type=FIELD_TYPE_VL, key=4), "txnSignature": RippleField(type=_FIELD_TYPE_VL, key=4),
"lastLedgerSequence": RippleField(type=FIELD_TYPE_INT32, key=27), "lastLedgerSequence": RippleField(type=_FIELD_TYPE_INT32, key=27),
"destinationTag": RippleField(type=FIELD_TYPE_INT32, key=14), "destinationTag": RippleField(type=_FIELD_TYPE_INT32, key=14),
} }
TRANSACTION_TYPES = {"Payment": 0} TRANSACTION_TYPES = {"Payment": 0}
@ -73,19 +74,19 @@ def write(w: Writer, field: RippleField, value: int | bytes | str | None) -> Non
if value is None: if value is None:
return return
write_type(w, field) write_type(w, field)
if field.type == FIELD_TYPE_INT16: if field.type == _FIELD_TYPE_INT16:
assert isinstance(value, int) assert isinstance(value, int)
w.extend(value.to_bytes(2, "big")) w.extend(value.to_bytes(2, "big"))
elif field.type == FIELD_TYPE_INT32: elif field.type == _FIELD_TYPE_INT32:
assert isinstance(value, int) assert isinstance(value, int)
w.extend(value.to_bytes(4, "big")) w.extend(value.to_bytes(4, "big"))
elif field.type == FIELD_TYPE_AMOUNT: elif field.type == _FIELD_TYPE_AMOUNT:
assert isinstance(value, int) assert isinstance(value, int)
w.extend(serialize_amount(value)) w.extend(serialize_amount(value))
elif field.type == FIELD_TYPE_ACCOUNT: elif field.type == _FIELD_TYPE_ACCOUNT:
assert isinstance(value, str) assert isinstance(value, str)
write_bytes_varint(w, helpers.decode_address(value)) write_bytes_varint(w, helpers.decode_address(value))
elif field.type == FIELD_TYPE_VL: elif field.type == _FIELD_TYPE_VL:
assert isinstance(value, (bytes, bytearray)) assert isinstance(value, (bytes, bytearray))
write_bytes_varint(w, value) write_bytes_varint(w, value)
else: else:

View File

@ -60,7 +60,7 @@ MICHELSON_SEQUENCE_TAG = const(2)
BRANCH_HASH_SIZE = const(32) BRANCH_HASH_SIZE = const(32)
PROPOSAL_HASH_SIZE = const(32) PROPOSAL_HASH_SIZE = const(32)
PUBLIC_KEY_HASH_SIZE = const(20) PUBLIC_KEY_HASH_SIZE = const(20)
TAGGED_PUBKEY_HASH_SIZE = 1 + PUBLIC_KEY_HASH_SIZE TAGGED_PUBKEY_HASH_SIZE = const(1 + PUBLIC_KEY_HASH_SIZE)
CONTRACT_ID_SIZE = const(22) CONTRACT_ID_SIZE = const(22)
_ED25519_PUBLIC_KEY_SIZE = const(32) _ED25519_PUBLIC_KEY_SIZE = const(32)
_SECP256K1_PUBLIC_KEY_SIZE = const(33) _SECP256K1_PUBLIC_KEY_SIZE = const(33)

View File

@ -1,4 +1,5 @@
import gc import gc
from micropython import const
from trezorcrypto import random # avoid pulling in trezor.crypto from trezorcrypto import random # avoid pulling in trezor.crypto
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
@ -10,27 +11,27 @@ if TYPE_CHECKING:
T = TypeVar("T") T = TypeVar("T")
_MAX_SESSIONS_COUNT = 10 _MAX_SESSIONS_COUNT = const(10)
_SESSIONLESS_FLAG = 128 _SESSIONLESS_FLAG = const(128)
_SESSION_ID_LENGTH = 32 _SESSION_ID_LENGTH = const(32)
# Traditional cache keys # Traditional cache keys
APP_COMMON_SEED = 0 APP_COMMON_SEED = const(0)
APP_COMMON_AUTHORIZATION_TYPE = 1 APP_COMMON_AUTHORIZATION_TYPE = const(1)
APP_COMMON_AUTHORIZATION_DATA = 2 APP_COMMON_AUTHORIZATION_DATA = const(2)
APP_COMMON_NONCE = 3 APP_COMMON_NONCE = const(3)
if not utils.BITCOIN_ONLY: if not utils.BITCOIN_ONLY:
APP_COMMON_DERIVE_CARDANO = 4 APP_COMMON_DERIVE_CARDANO = const(4)
APP_CARDANO_ICARUS_SECRET = 5 APP_CARDANO_ICARUS_SECRET = const(5)
APP_CARDANO_ICARUS_TREZOR_SECRET = 6 APP_CARDANO_ICARUS_TREZOR_SECRET = const(6)
APP_MONERO_LIVE_REFRESH = 7 APP_MONERO_LIVE_REFRESH = const(7)
# Keys that are valid across sessions # Keys that are valid across sessions
APP_COMMON_SEED_WITHOUT_PASSPHRASE = 0 | _SESSIONLESS_FLAG APP_COMMON_SEED_WITHOUT_PASSPHRASE = const(0 | _SESSIONLESS_FLAG)
APP_COMMON_SAFETY_CHECKS_TEMPORARY = 1 | _SESSIONLESS_FLAG APP_COMMON_SAFETY_CHECKS_TEMPORARY = const(1 | _SESSIONLESS_FLAG)
STORAGE_DEVICE_EXPERIMENTAL_FEATURES = 2 | _SESSIONLESS_FLAG STORAGE_DEVICE_EXPERIMENTAL_FEATURES = const(2 | _SESSIONLESS_FLAG)
APP_COMMON_REQUEST_PIN_LAST_UNLOCK = 3 | _SESSIONLESS_FLAG APP_COMMON_REQUEST_PIN_LAST_UNLOCK = const(3 | _SESSIONLESS_FLAG)
APP_COMMON_BUSY_DEADLINE_MS = 4 | _SESSIONLESS_FLAG APP_COMMON_BUSY_DEADLINE_MS = const(4 | _SESSIONLESS_FLAG)
# === Homescreen storage === # === Homescreen storage ===

View File

@ -45,16 +45,16 @@ if TYPE_CHECKING:
StorageSafetyCheckLevel = Literal[0, 1] StorageSafetyCheckLevel = Literal[0, 1]
# fmt: on # fmt: on
HOMESCREEN_MAXSIZE = 16384 HOMESCREEN_MAXSIZE = const(16384)
LABEL_MAXLENGTH = 32 LABEL_MAXLENGTH = const(32)
if __debug__: if __debug__:
AUTOLOCK_DELAY_MINIMUM = 10 * 1000 # 10 seconds AUTOLOCK_DELAY_MINIMUM = 10 * 1000 # 10 seconds
else: else:
AUTOLOCK_DELAY_MINIMUM = 60 * 1000 # 1 minute AUTOLOCK_DELAY_MINIMUM = 60 * 1000 # 1 minute
AUTOLOCK_DELAY_DEFAULT = 10 * 60 * 1000 # 10 minutes AUTOLOCK_DELAY_DEFAULT = const(10 * 60 * 1000) # 10 minutes
# autolock intervals larger than AUTOLOCK_DELAY_MAXIMUM cause issues in the scheduler # autolock intervals larger than AUTOLOCK_DELAY_MAXIMUM cause issues in the scheduler
AUTOLOCK_DELAY_MAXIMUM = 0x2000_0000 # ~6 days AUTOLOCK_DELAY_MAXIMUM = const(0x2000_0000) # ~6 days
# Length of SD salt auth tag. # Length of SD salt auth tag.
# Other SD-salt-related constants are in sd_salt.py # Other SD-salt-related constants are in sd_salt.py

View File

@ -20,10 +20,9 @@
"""Reference implementation for Bech32/Bech32m and segwit addresses.""" """Reference implementation for Bech32/Bech32m and segwit addresses."""
from trezorcrypto import bech32
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
bech32_decode = bech32.decode from micropython import const
if TYPE_CHECKING: if TYPE_CHECKING:
@ -43,12 +42,12 @@ else:
class Encoding(IntEnum): class Encoding(IntEnum):
"""Enumeration type to list the various supported encodings.""" """Enumeration type to list the various supported encodings."""
BECH32 = 1 BECH32 = const(1)
BECH32M = 2 BECH32M = const(2)
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
BECH32M_CONST = 0x2BC830A3 _BECH32M_CONST = const(0x2BC830A3)
def bech32_polymod(values: list[int]) -> int: def bech32_polymod(values: list[int]) -> int:
@ -71,7 +70,7 @@ def bech32_hrp_expand(hrp: str) -> list[int]:
def bech32_create_checksum(hrp: str, data: list[int], spec: Encoding) -> list[int]: def bech32_create_checksum(hrp: str, data: list[int], spec: Encoding) -> list[int]:
"""Compute the checksum values given HRP and data.""" """Compute the checksum values given HRP and data."""
values = bech32_hrp_expand(hrp) + data values = bech32_hrp_expand(hrp) + data
const = BECH32M_CONST if spec == Encoding.BECH32M else 1 const = _BECH32M_CONST if spec == Encoding.BECH32M else 1
polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const polymod = bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const
return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)] return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]
@ -127,8 +126,10 @@ def convertbits(
def decode(hrp: str, addr: str) -> OptionalTuple2[int, bytes]: def decode(hrp: str, addr: str) -> OptionalTuple2[int, bytes]:
"""Decode a segwit address.""" """Decode a segwit address."""
from trezorcrypto import bech32
try: try:
hrpgot, data, spec = bech32_decode(addr) hrpgot, data, spec = bech32.decode(addr)
decoded = bytes(convertbits(data[1:], 5, 8, False)) decoded = bytes(convertbits(data[1:], 5, 8, False))
except ValueError: except ValueError:
return (None, None) return (None, None)

View File

@ -20,11 +20,13 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
from micropython import const
from .bech32 import convertbits from .bech32 import convertbits
CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
ADDRESS_TYPE_P2KH = 0 ADDRESS_TYPE_P2KH = const(0)
ADDRESS_TYPE_P2SH = 8 ADDRESS_TYPE_P2SH = const(8)
def cashaddr_polymod(values: list[int]) -> int: def cashaddr_polymod(values: list[int]) -> int:

View File

@ -35,6 +35,7 @@ reads the message's header. When the message type is known the first handler is
""" """
from micropython import const
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from storage.cache import InvalidSessionError from storage.cache import InvalidSessionError
@ -132,9 +133,9 @@ class DummyContext:
DUMMY_CONTEXT = DummyContext() DUMMY_CONTEXT = DummyContext()
PROTOBUF_BUFFER_SIZE = 8192 _PROTOBUF_BUFFER_SIZE = const(8192)
WIRE_BUFFER = bytearray(PROTOBUF_BUFFER_SIZE) WIRE_BUFFER = bytearray(_PROTOBUF_BUFFER_SIZE)
if __debug__: if __debug__:
PROTOBUF_BUFFER_SIZE_DEBUG = 1024 PROTOBUF_BUFFER_SIZE_DEBUG = 1024