refactor(core): simplify Bitcoin signer machinery
What changed, and why it matters
This is a code cleanup (refactor) of the Bitcoin signing workflow inside Trezor firmware. It replaces a custom hand-rolled event loop and a pile of UI wrapper objects with ordinary async/await calls. The commit message and diff show no change to the actual signing algorithm or security checks; it only rewrites the surrounding machinery to make the code easier to maintain. Tests were updated to match the new calling style.
No security action required. Treat as normal code-quality/maintenance review. If auditing, verify that the new async flow preserves the same order of TxRequest/TxAck exchanges and UI confirmations as the old generator loop, which the updated unit tests assert.
Security signals we found
Refactor only: commit message explicitly states it does not touch the signing algorithm
No changes to input/output validation, fee checks, address derivation, or signature generation
No new dependencies, network calls, or external interfaces introduced
No privilege changes or secret-handling modifications
Test expectations updated to match new async harness, preserving prior behavior
Evidence from the diff
The commit converts the Bitcoin sign_tx harness from a generator-based coroutine driver (using signer.send(), yielded TxRequest tuples, and UiConfirm wrapper classes) to native async def/await. helpers.py drops the UiConfirm* classes and turns request_tx_* helpers into real async functions that await trezor.wire.context.call(). layout.py functions now return awaitable layouts instead of awaiting them. progress.py removes the global progress singleton in favor of per-signer Progress() instances. __init__.py no longer loops over signer.send(res); it simply await signer.signer() and returns signer.tx_req. Test files replace generator-driven scripts with a new ScriptedContext/run_signer helper. No cryptographic or authorization logic is altered.
Changed components
core/src/apps/bitcoin/sign_tx/__init__.pycore/src/apps/bitcoin/sign_tx/approvers.pycore/src/apps/bitcoin/sign_tx/bitcoin.pycore/src/apps/bitcoin/sign_tx/decred.pycore/src/apps/bitcoin/sign_tx/helpers.pycore/src/apps/bitcoin/sign_tx/layout.pycore/src/apps/bitcoin/sign_tx/progress.pycore/src/apps/bitcoin/sign_tx/zcash_v4.pycore/tests/common.pycore/tests/test_apps.bitcoin.*.pyInspect captured patch +376 / −822
### core/src/apps/bitcoin/sign_tx/__init__.py
@@ -7,33 +7,17 @@
if TYPE_CHECKING:
from typing import Protocol
- from trezor.messages import (
- SignTx,
- TxAckInput,
- TxAckOutput,
- TxAckPrevExtraData,
- TxAckPrevInput,
- TxAckPrevMeta,
- TxAckPrevOutput,
- TxRequest,
- )
+ from trezor.messages import SignTx, TxRequest
from apps.common.coininfo import CoinInfo
from apps.common.keychain import Keychain
from ..authorization import CoinJoinAuthorization
from . import approvers
- TxAckType = (
- TxAckInput
- | TxAckOutput
- | TxAckPrevMeta
- | TxAckPrevInput
- | TxAckPrevOutput
- | TxAckPrevExtraData
- )
-
class SignerClass(Protocol):
+ tx_req: TxRequest
+
def __init__( # pylint: disable=super-init-not-called
self,
tx: SignTx,
@@ -53,13 +37,10 @@ async def sign_tx(
authorization: CoinJoinAuthorization | None = None,
) -> TxRequest:
from trezor import TR
- from trezor.enums import RequestType
- from trezor.messages import TxRequest
from trezor.ui.layouts import show_continue_in_app
- from trezor.wire.context import call
from ..common import BITCOIN_NAMES
- from . import approvers, bitcoin, helpers, progress
+ from . import approvers, bitcoin
approver: approvers.Approver | None = None
if authorization:
@@ -86,20 +67,7 @@ async def sign_tx(
signer_class = bitcoinlike.Bitcoinlike
- signer = signer_class(msg, keychain, coin, approver).signer()
-
- res: TxAckType | bool | None = None
- while True:
- req = signer.send(res)
- if isinstance(req, tuple):
- request_class, req = req
- assert TxRequest.is_type_of(req)
- if req.request_type == RequestType.TXFINISHED:
- show_continue_in_app(TR.send__transaction_signed)
- return req
- res = await call(req, request_class)
- elif isinstance(req, helpers.UiConfirm):
- res = await req.confirm_dialog()
- progress.progress.report_init()
- else:
- raise TypeError("Invalid signing instruction")
+ signer = signer_class(msg, keychain, coin, approver)
+ await signer.signer()
+ show_continue_in_app(TR.send__transaction_signed)
+ return signer.tx_req
### core/src/apps/bitcoin/sign_tx/approvers.py
@@ -8,7 +8,7 @@
from ..common import CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES, input_is_external_unverified
from ..keychain import validate_path_against_script_type
-from . import helpers, tx_weight
+from . import layout, tx_weight
from .tx_info import OriginalTxInfo
if TYPE_CHECKING:
@@ -161,7 +161,7 @@ def __init__(self, tx: SignTx, coin: CoinInfo) -> None:
async def add_internal_input(self, txi: TxInput, node: bip32.HDNode) -> None:
if not validate_path_against_script_type(self.coin, txi):
- await helpers.confirm_foreign_address(txi.address_n)
+ await layout.confirm_foreign_address(txi.address_n)
self.foreign_address_confirmed = True
await super().add_internal_input(txi, node)
@@ -184,7 +184,7 @@ async def _add_output(self, txo: TxOutput, script_pubkey: AnyBytes) -> None:
script_type=CHANGE_OUTPUT_TO_INPUT_SCRIPT_TYPES[txo.script_type],
multisig=bool(txo.multisig),
):
- await helpers.confirm_foreign_address(txo.address_n)
+ await layout.confirm_foreign_address(txo.address_n)
await super()._add_output(txo, script_pubkey)
@@ -230,7 +230,7 @@ async def add_external_output(
# Non-payjoin replacement transactions are allowed to decrease external outputs
# upon user confirmation. See top comment.
- await helpers.confirm_modify_output(
+ await layout.confirm_modify_output(
txo, orig_txo, self.coin, self.amount_unit
)
elif txo.amount > orig_txo.amount:
@@ -257,7 +257,7 @@ async def add_external_output(
source_path = (
tx_info.change_detector.wallet_path.get_path() if tx_info else None
)
- await helpers.confirm_output(
+ await layout.confirm_output(
txo,
self.coin,
self.amount_unit,
@@ -288,7 +288,7 @@ async def add_payment_request(
assert txo.address
- await helpers.show_payment_request_details(
+ await layout.show_payment_request_details(
txo.address,
payment_request,
self.coin,
@@ -304,7 +304,7 @@ async def approve_orig_txids(
title = self._replacement_title(tx_info, orig_txs)
for orig in orig_txs:
- await helpers.confirm_replacement(title, orig.orig_hash)
+ await layout.confirm_replacement(title, orig.orig_hash)
def _replacement_title(
self, tx_info: TxInfo, orig_txs: list[OriginalTxInfo]
@@ -336,10 +336,10 @@ async def approve_tx(
await super().approve_tx(tx_info, orig_txs, signer)
if self.has_unverified_external_input:
- await helpers.confirm_unverified_external_input()
+ await layout.confirm_unverified_external_input()
if tx_info.change_detector.wallet_path.get_path() is None:
- await helpers.confirm_multiple_accounts()
+ await layout.confirm_multiple_accounts()
fee = self.total_in - self.total_out
@@ -358,10 +358,10 @@ async def approve_tx(
if fee > fee_threshold:
if fee > 10 * fee_threshold and safety_checks.is_strict():
raise DataError("The fee is unexpectedly large")
- await helpers.confirm_feeoverthreshold(fee, coin, amount_unit)
+ await layout.confirm_feeoverthreshold(fee, coin, amount_unit)
if self.change_count > self.MAX_SILENT_CHANGE_COUNT:
- await helpers.confirm_change_count_over_threshold(self.change_count)
+ await layout.confirm_change_count_over_threshold(self.change_count)
if orig_txs:
# Replacement transaction.
@@ -399,7 +399,7 @@ async def approve_tx(
# Not a PayJoin: Show the actual fee difference, since any difference in the fee is
# coming entirely from the user's own funds and from decreases of external outputs.
# We consider the decreases as belonging to the user.
- await helpers.confirm_modify_fee(
+ await layout.confirm_modify_fee(
title, fee - orig_fee, fee, fee_rate, coin, amount_unit
)
elif spending > orig_spending:
@@ -409,7 +409,7 @@ async def approve_tx(
# PayJoin and user is spending more: Show the increase in the user's contribution
# to the fee, ignoring any contribution from external inputs. Decreasing of
# external outputs is not allowed in PayJoin, so there is no need to handle those.
- await helpers.confirm_modify_fee(
+ await layout.confirm_modify_fee(
title, spending - orig_spending, fee, fee_rate, coin, amount_unit
)
else:
@@ -420,15 +420,15 @@ async def approve_tx(
else:
# Standard transaction.
if tx_info.tx.lock_time > 0:
- await helpers.confirm_nondefault_locktime(
+ await layout.confirm_nondefault_locktime(
tx_info.tx.lock_time, tx_info.lock_time_disabled()
)
if signer is not None:
signer.init_signing()
if not self.external_in:
- await helpers.confirm_total(
+ await layout.confirm_total(
total,
fee,
fee_rate,
@@ -437,7 +437,7 @@ async def approve_tx(
tx_info.change_detector.wallet_path.get_path(),
)
else:
- await helpers.confirm_joint_total(spending, total, coin, amount_unit)
+ await layout.confirm_joint_total(spending, total, coin, amount_unit)
class CoinJoinApprover(Approver):
### core/src/apps/bitcoin/sign_tx/bitcoin.py
@@ -16,7 +16,7 @@
from . import helpers
from .approvers import CoinJoinApprover
from .helpers import request_tx_input, request_tx_output
-from .progress import progress
+from .progress import Progress
from .tx_info import OriginalTxInfo
if TYPE_CHECKING:
@@ -42,8 +42,9 @@
class Bitcoin:
def init_signing(self) -> None:
- # Next shown progress bar is already signing progress, but it isn't shown until approval from next dialog
- progress.init_signing(
+ # Step counts for the signing phase. The "Signing transaction" progress
+ # layout is created after the last approval dialog, in signer().
+ self.progress.init_signing(
len(self.external),
len(self.segwit),
len(self.presigned),
@@ -56,7 +57,7 @@ def init_signing(self) -> None:
self.signing = True
async def signer(self) -> None:
- progress.init(
+ self.progress.init(
self.tx_info.tx, is_coinjoin=isinstance(self.approver, CoinJoinApprover)
)
@@ -73,11 +74,10 @@ async def signer(self) -> None:
# Check fee, approve lock_time and total.
await self.approver.approve_tx(self.tx_info, self.orig_txs, self)
- # Make sure proper progress is shown, in case dialog was not required
if not self.signing:
self.init_signing()
- progress.report_init()
- progress.report()
+ self.progress.report_init()
+ self.progress.report()
# Following steps can take a long time, make sure autolock doesn't kick in.
# This is set to True again after workflow is finished in start_default().
@@ -119,6 +119,7 @@ def __init__(
self.tx_info = TxInfo(self, helpers.sanitize_sign_tx(tx, coin))
self.keychain = keychain
self.coin = coin
+ self.progress = Progress()
if approver is not None:
self.approver = approver
@@ -179,7 +180,7 @@ async def step1_process_inputs(self) -> None:
for i in range(tx_info.tx.inputs_count):
# STAGE_REQUEST_1_INPUT in legacy
- progress.advance()
+ self.progress.advance()
txi = await request_tx_input(self.tx_req, i, self.coin)
if txi.script_type not in (
InputScriptType.SPENDTAPROOT,
@@ -218,7 +219,7 @@ async def step1_process_inputs(self) -> None:
async def step2_approve_outputs(self) -> None:
for i in range(self.tx_info.tx.outputs_count):
# STAGE_REQUEST_2_OUTPUT in legacy
- progress.advance()
+ self.progress.advance()
txo = await request_tx_output(self.tx_req, i, self.coin)
script_pubkey = self.output_derive_script(txo)
orig_txo: TxOutput | None = None
@@ -245,7 +246,7 @@ async def step3_verify_inputs(self) -> None:
expected_digest = self.h_presigned_inputs
for i in range(self.tx_info.tx.inputs_count):
if i in self.presigned:
- progress.advance()
+ self.progress.advance()
txi = await request_tx_input(self.tx_req, i, self.coin)
writers.write_tx_input_check(h_check, txi)
@@ -295,14 +296,14 @@ async def step4_serialize_inputs(self) -> None:
for i in range(self.tx_info.tx.inputs_count):
if i in self.external:
if self.serialize:
- progress.advance()
+ self.progress.advance()
await self.serialize_external_input(i)
elif i in self.segwit:
if self.serialize:
- progress.advance()
+ self.progress.advance()
await self.serialize_segwit_input(i)
else:
- progress.advance()
+ self.progress.advance()
await self.sign_nonsegwit_input(i)
async def step5_serialize_outputs(self) -> None:
@@ -311,7 +312,7 @@ async def step5_serialize_outputs(self) -> None:
write_compact_size(self.serialized_tx, self.tx_info.tx.outputs_count)
for i in range(self.tx_info.tx.outputs_count):
- progress.advance()
+ self.progress.advance()
await self.serialize_output(i)
async def step6_sign_segwit_inputs(self) -> None:
@@ -323,13 +324,13 @@ async def step6_sign_segwit_inputs(self) -> None:
if i in self.external:
if self.serialize:
if i in self.presigned:
- progress.advance()
+ self.progress.advance()
txi = await request_tx_input(self.tx_req, i, self.coin)
self.serialized_tx.extend(txi.witness or b"\0")
else:
self.serialized_tx.append(0)
else:
- progress.advance()
+ self.progress.advance()
await self.sign_segwit_input(i)
else:
# add empty witness for non-segwit inputs
@@ -340,8 +341,8 @@ async def step7_finish(self) -> None:
if self.serialize:
self.write_tx_footer(self.serialized_tx, self.tx_info.tx)
if __debug__:
- progress.assert_finished()
- await helpers.request_tx_finish(self.tx_req)
+ self.progress.assert_finished()
+ helpers.request_tx_finish(self.tx_req)
async def process_internal_input(self, txi: TxInput, node: bip32.HDNode) -> None:
if txi.script_type not in common.INTERNAL_INPUT_SCRIPT_TYPES:
@@ -495,7 +496,7 @@ async def verify_original_txs(self) -> None:
h_check = HashWriter(sha256())
for i in range(orig.tx.inputs_count):
- progress.advance()
+ self.progress.advance()
txi = await request_tx_input(self.tx_req, i, self.coin, orig.orig_hash)
writers.write_tx_input_check(h_check, txi)
script_pubkey = self.input_derive_script(txi)
@@ -727,7 +728,7 @@ async def get_legacy_tx_digest(
node = None
for i in range(tx.inputs_count):
# STAGE_REQUEST_4_INPUT in legacy
- progress.advance()
+ self.progress.advance()
txi = await request_tx_input(self.tx_req, i, coin, tx_hash)
writers.write_tx_input_check(h_check, txi)
# Only the previous UTXO's scriptPubKey is included in h_sign.
@@ -765,7 +766,7 @@ async def get_legacy_tx_digest(
for i in range(tx.outputs_count):
# STAGE_REQUEST_4_OUTPUT in legacy
- progress.advance()
+ self.progress.advance()
txo = await request_tx_output(self.tx_req, i, coin, tx_hash)
script_pubkey = self.output_derive_script(txo)
self.write_tx_output(h_check, txo, script_pubkey)
@@ -815,7 +816,7 @@ async def get_prevtx_output(
# STAGE_REQUEST_3_PREV_META in legacy
tx = await helpers.request_tx_meta(self.tx_req, coin, prev_hash)
- progress.init_prev_tx(tx.inputs_count, tx.outputs_count)
+ self.progress.init_prev_tx(tx.inputs_count, tx.outputs_count)
if tx.outputs_count <= prev_index:
raise ProcessError("Not enough outputs in previous transaction.")
@@ -828,7 +829,7 @@ async def get_prevtx_output(
for i in range(tx.inputs_count):
# STAGE_REQUEST_3_PREV_INPUT in legacy
- progress.advance_prev_tx()
+ self.progress.advance_prev_tx()
txi = await helpers.request_tx_prev_input(self.tx_req, i, coin, prev_hash)
self.write_tx_input(txh, txi, txi.script_sig)
@@ -837,7 +838,7 @@ async def get_prevtx_output(
script_pubkey: AnyBytes | None = None
for i in range(tx.outputs_count):
# STAGE_REQUEST_3_PREV_OUTPUT in legacy
- progress.advance_prev_tx()
+ self.progress.advance_prev_tx()
txo_bin = await helpers.request_tx_prev_output(
self.tx_req, i, coin, prev_hash
)
### core/src/apps/bitcoin/sign_tx/decred.py
@@ -15,7 +15,6 @@
from . import helpers
from .approvers import BasicApprover
from .bitcoin import Bitcoin
-from .progress import progress
_DECRED_SERIALIZE_FULL = const(0 << 16)
_DECRED_SERIALIZE_NO_WITNESS = const(1 << 16)
@@ -91,12 +90,14 @@ def __init__(self, tx: SignTx, coin: CoinInfo) -> None:
async def add_decred_sstx_submission(
self, txo: TxOutput, script_pubkey: AnyBytes
) -> None:
+ from .layout import confirm_decred_sstx_submission
+
# NOTE: The following calls Approver.add_external_output(), not BasicApprover.add_external_output().
- # This is needed to skip calling helpers.confirm_output(), which is what BasicApprover would do.
+ # This is needed to skip calling layout.confirm_output(), which is what BasicApprover would do.
await super(BasicApprover, self).add_external_output(
txo, script_pubkey, None, None
)
- await helpers.confirm_decred_sstx_submission(txo, self.coin, self.amount_unit)
+ await confirm_decred_sstx_submission(txo, self.coin, self.amount_unit)
class DecredSigHasher:
@@ -212,7 +213,6 @@ async def step4_serialize_inputs(self) -> None:
from .. import multisig
from ..common import SigHashType, ecdsa_sign
- from .progress import progress
inputs_count = self.tx_info.tx.inputs_count # local_cache_attribute
coin = self.coin # local_cache_attribute
@@ -223,7 +223,7 @@ async def step4_serialize_inputs(self) -> None:
prefix_hash = self.h_prefix.get_digest()
for i_sign in range(inputs_count):
- progress.advance()
+ self.progress.advance()
txi_sign = await helpers.request_tx_input(self.tx_req, i_sign, coin)
@@ -294,9 +294,9 @@ async def step6_sign_segwit_inputs(self) -> None:
async def step7_finish(self) -> None:
if __debug__:
- progress.assert_finished()
+ self.progress.assert_finished()
- await helpers.request_tx_finish(self.tx_req)
+ helpers.request_tx_finish(self.tx_req)
def check_prevtx_output(self, txo_bin: PrevOutput) -> None:
if txo_bin.decred_script_version != 0:
@@ -349,7 +349,7 @@ async def approve_staking_ticket(self) -> None:
raise DataError("Ticket has wrong number of outputs.")
# SSTX submission
- progress.advance()
+ self.progress.advance()
txo = await helpers.request_tx_output(self.tx_req, 0, self.coin)
if txo.address is None:
raise DataError("Missing address.")
@@ -360,7 +360,7 @@ async def approve_staking_ticket(self) -> None:
self.write_tx_output(self.serialized_tx, txo, script_pubkey)
# SSTX commitment
- progress.advance()
+ self.progress.advance()
txo = await helpers.request_tx_output(self.tx_req, 1, self.coin)
if txo.amount != approver.total_in:
raise DataError("Wrong sstxcommitment amount.")
@@ -371,7 +371,7 @@ async def approve_staking_ticket(self) -> None:
self.write_tx_output(self.serialized_tx, txo, script_pubkey)
# SSTX change
- progress.advance()
+ self.progress.advance()
txo = await helpers.request_tx_output(self.tx_req, 2, self.coin)
if txo.address is None:
raise DataError("Missing address.")
### core/src/apps/bitcoin/sign_tx/helpers.py
@@ -1,6 +1,5 @@
from typing import TYPE_CHECKING
-from trezor import utils
from trezor.enums import InputScriptType, OutputScriptType, RequestType
from trezor.messages import (
PaymentRequest,
@@ -15,14 +14,11 @@
from .. import common
from ..writers import TX_HASH_SIZE
-from . import layout
if TYPE_CHECKING:
from buffer_types import AnyBytes
- from collections.abc import Awaitable
from typing import Any
- from trezor.enums import AmountUnit
from trezor.messages import (
PrevInput,
PrevOutput,
@@ -34,435 +30,102 @@
)
from apps.common.coininfo import CoinInfo
- from apps.common.paths import Bip32Path
-
-# Machine instructions
-# ===
-
-
-class UiConfirm:
- def confirm_dialog(self) -> Awaitable[Any]:
- raise NotImplementedError
-
- __eq__ = utils.obj_eq
-
-
-class UiConfirmOutput(UiConfirm):
- def __init__(
- self,
- output: TxOutput,
- coin: CoinInfo,
- amount_unit: AmountUnit,
- output_index: int,
- chunkify: bool,
- address_n: Bip32Path | None,
- ) -> None:
- self.output = output
- self.coin = coin
- self.amount_unit = amount_unit
- self.output_index = output_index
- self.chunkify = chunkify
- self.address_n = address_n
-
- def confirm_dialog(self) -> Awaitable[Any]:
- return layout.confirm_output(
- self.output,
- self.coin,
- self.amount_unit,
- self.output_index,
- self.chunkify,
- self.address_n,
- )
-
-
-class UiConfirmDecredSSTXSubmission(UiConfirm):
- def __init__(
- self, output: TxOutput, coin: CoinInfo, amount_unit: AmountUnit
- ) -> None:
- 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,
- provider_address: str,
- payment_req: PaymentRequest,
- coin: CoinInfo,
- amount_unit: AmountUnit,
- address_n: Bip32Path | None,
- ) -> None:
- self.provider_address = provider_address
- self.payment_req = payment_req
- self.amount_unit = amount_unit
- self.coin = coin
- self.address_n = address_n
-
- def confirm_dialog(self) -> Awaitable[None]:
- return layout.show_payment_request_details(
- self.provider_address,
- self.payment_req,
- self.coin,
- self.amount_unit,
- self.address_n,
- )
-
- __eq__ = utils.obj_eq
-
-
-class UiConfirmReplacement(UiConfirm):
- def __init__(self, title: str, txid: AnyBytes) -> None:
- 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,
- ) -> None:
- 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,
- ) -> None:
- 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,
- spending: int,
- fee: int,
- fee_rate: float,
- coin: CoinInfo,
- amount_unit: AmountUnit,
- address_n: Bip32Path | None,
- ) -> 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]:
- return layout.confirm_total(
- self.spending,
- 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
- ) -> None:
- 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) -> None:
- 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) -> None:
- self.change_count = change_count
-
- def confirm_dialog(self) -> Awaitable[Any]:
- return layout.confirm_change_count_over_threshold(self.change_count)
-
-
-class UiConfirmUnverifiedExternalInput(UiConfirm):
- def confirm_dialog(self) -> Awaitable[Any]:
- return layout.confirm_unverified_external_input()
-
-
-class UiConfirmForeignAddress(UiConfirm):
- def __init__(self, address_n: list) -> None:
- self.address_n = address_n
-
- def confirm_dialog(self) -> Awaitable[Any]:
- from apps.common import paths
-
- return paths.show_path_warning(self.address_n)
-
-
-class UiConfirmNonDefaultLocktime(UiConfirm):
- def __init__(self, lock_time: int, lock_time_disabled: bool) -> None:
- 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,
- amount_unit: AmountUnit,
- output_index: int,
- chunkify: bool,
- address_n: Bip32Path | None,
-) -> Awaitable[None]: # type: ignore [awaitable-return-type]
- return (
- yield UiConfirmOutput( # type: ignore [awaitable-return-type]
- output, coin, amount_unit, output_index, chunkify, address_n
- )
- )
-
-
-def confirm_decred_sstx_submission(
- output: TxOutput, coin: CoinInfo, amount_unit: AmountUnit
-) -> Awaitable[None]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmDecredSSTXSubmission(output, coin, amount_unit)) # type: ignore [awaitable-return-type]
-
-
-def show_payment_request_details(
- provider_address: str,
- payment_req: PaymentRequest,
- coin: CoinInfo,
- amount_unit: AmountUnit,
- address_n: Bip32Path | None,
-) -> Awaitable[bool]: # type: ignore [awaitable-return-type]
- return (
- yield UiConfirmPaymentRequest( # type: ignore [awaitable-return-type]
- provider_address, payment_req, coin, amount_unit, address_n
- )
- )
-
-
-def confirm_replacement(description: str, txid: AnyBytes) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmReplacement(description, txid)) # type: ignore [awaitable-return-type]
-
-
-def confirm_modify_output(
- txo: TxOutput, orig_txo: TxOutput, coin: CoinInfo, amount_unit: AmountUnit
-) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmModifyOutput(txo, orig_txo, coin, amount_unit)) # type: ignore [awaitable-return-type]
-
-
-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-return-type]
- return (
- yield UiConfirmModifyFee( # type: ignore [awaitable-return-type]
- 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-return-type]
- return (yield UiConfirmTotal(spending, fee, fee_rate, coin, amount_unit, address_n)) # type: ignore [awaitable-return-type]
-
-
-def confirm_joint_total(
- spending: int, total: int, coin: CoinInfo, amount_unit: AmountUnit
-) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmJointTotal(spending, total, coin, amount_unit)) # type: ignore [awaitable-return-type]
-
-
-def confirm_feeoverthreshold(
- fee: int, coin: CoinInfo, amount_unit: AmountUnit
-) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmFeeOverThreshold(fee, coin, amount_unit)) # type: ignore [awaitable-return-type]
-def confirm_change_count_over_threshold(change_count: int) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmChangeCountOverThreshold(change_count)) # type: ignore [awaitable-return-type]
-
-
-def confirm_unverified_external_input() -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmUnverifiedExternalInput()) # type: ignore [awaitable-return-type]
-
-
-def confirm_foreign_address(address_n: list) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmForeignAddress(address_n)) # type: ignore [awaitable-return-type]
-
-
-def confirm_nondefault_locktime(
- lock_time: int, lock_time_disabled: bool
-) -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmNonDefaultLocktime(lock_time, lock_time_disabled)) # type: ignore [awaitable-return-type]
-
-
-def confirm_multiple_accounts() -> Awaitable[Any]: # type: ignore [awaitable-return-type]
- return (yield UiConfirmMultipleAccounts()) # type: ignore [awaitable-return-type]
-
-
-def request_tx_meta(
+async def request_tx_meta(
tx_req: TxRequest, coin: CoinInfo, tx_hash: AnyBytes | None = None
-) -> Awaitable[PrevTx]: # type: ignore [awaitable-return-type]
+) -> PrevTx:
assert tx_req.details is not None
tx_req.request_type = RequestType.TXMETA
tx_req.details.tx_hash = tx_hash
- ack = yield TxAckPrevMeta, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
+ ack = await _call_tx_request(tx_req, TxAckPrevMeta)
return _sanitize_tx_meta(ack.tx, coin)
-def request_tx_extra_data(
+async def request_tx_extra_data(
tx_req: TxRequest, offset: int, size: int, tx_hash: AnyBytes | None = None
-) -> Awaitable[bytearray]: # type: ignore [awaitable-return-type]
+) -> AnyBytes:
details = tx_req.details # local_cache_attribute
assert details is not None
tx_req.request_type = RequestType.TXEXTRADATA
details.extra_data_offset = offset
details.extra_data_len = size
details.tx_hash = tx_hash
- ack = yield TxAckPrevExtraData, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
- return ack.tx.extra_data_chunk
+ ack = await _call_tx_request(tx_req, TxAckPrevExtraData)
+ extra_data_chunk = ack.tx.extra_data_chunk
+ assert extra_data_chunk is not None
+ return extra_data_chunk
-def request_tx_input(
+async def request_tx_input(
tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None
-) -> Awaitable[TxInput]: # type: ignore [awaitable-return-type]
+) -> TxInput:
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = RequestType.TXORIGINPUT
tx_req.details.tx_hash = tx_hash
else:
tx_req.request_type = RequestType.TXINPUT
tx_req.details.request_index = i
- ack = yield TxAckInput, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
+ ack = await _call_tx_request(tx_req, TxAckInput)
return _sanitize_tx_input(ack.tx.input, coin)
-def request_tx_prev_input(
+async def request_tx_prev_input(
tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None
-) -> Awaitable[PrevInput]: # type: ignore [awaitable-return-type]
+) -> PrevInput:
assert tx_req.details is not None
tx_req.request_type = RequestType.TXINPUT
tx_req.details.request_index = i
tx_req.details.tx_hash = tx_hash
- ack = yield TxAckPrevInput, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
+ ack = await _call_tx_request(tx_req, TxAckPrevInput)
return _sanitize_tx_prev_input(ack.tx.input, coin)
-def request_tx_output(
+async def request_tx_output(
tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None
-) -> Awaitable[TxOutput]: # type: ignore [awaitable-return-type]
+) -> TxOutput:
assert tx_req.details is not None
if tx_hash:
tx_req.request_type = RequestType.TXORIGOUTPUT
tx_req.details.tx_hash = tx_hash
else:
tx_req.request_type = RequestType.TXOUTPUT
tx_req.details.request_index = i
- ack = yield TxAckOutput, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
+ ack = await _call_tx_request(tx_req, TxAckOutput)
return _sanitize_tx_output(ack.tx.output, coin)
-def request_tx_prev_output(
+async def request_tx_prev_output(
tx_req: TxRequest, i: int, coin: CoinInfo, tx_hash: AnyBytes | None = None
-) -> Awaitable[PrevOutput]: # type: ignore [awaitable-return-type]
+) -> PrevOutput:
assert tx_req.details is not None
tx_req.request_type = RequestType.TXOUTPUT
tx_req.details.request_index = i
tx_req.details.tx_hash = tx_hash
- ack = yield TxAckPrevOutput, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
+ ack = await _call_tx_request(tx_req, TxAckPrevOutput)
# return sanitize_tx_prev_output(ack.tx, coin) # no sanitize is required
return ack.tx.output
-def request_payment_req(tx_req: TxRequest, i: int) -> Awaitable[PaymentRequest]: # type: ignore [awaitable-return-type]
+async def request_payment_req(tx_req: TxRequest, i: int) -> PaymentRequest:
assert tx_req.details is not None
tx_req.request_type = RequestType.TXPAYMENTREQ
tx_req.details.request_index = i
- ack = yield PaymentRequest, tx_req # type: ignore [awaitable-return-type]
- _clear_tx_request(tx_req)
- return ack
+ return await _call_tx_request(tx_req, PaymentRequest)
-def request_tx_finish(tx_req: TxRequest) -> Awaitable[None]: # type: ignore [awaitable-return-type]
+def request_tx_finish(tx_req: TxRequest) -> None:
tx_req.request_type = RequestType.TXFINISHED
- yield None, tx_req # type: ignore [awaitable-return-type]
+
+
+async def _call_tx_request(tx_req: TxRequest, expected_type: type[Any]) -> Any:
+ from trezor.wire.context import call
+
+ ack = await call(tx_req, expected_type)
_clear_tx_request(tx_req)
+ return ack
def _clear_tx_request(tx_req: TxRequest) -> None:
### core/src/apps/bitcoin/sign_tx/layout.py
@@ -18,6 +18,8 @@
if TYPE_CHECKING:
from buffer_types import AnyBytes
+ from collections.abc import Awaitable
+ from typing import Any
from trezor.enums import AmountUnit
from trezor.messages import PaymentRequest, TxOutput
@@ -57,14 +59,14 @@ def account_label(coin: CoinInfo, address_n: Bip32Path | None) -> str:
) or address_n_to_str(address_n)
-async def confirm_output(
+def confirm_output(
output: TxOutput,
coin: CoinInfo,
amount_unit: AmountUnit,
output_index: int,
chunkify: bool,
address_n: Bip32Path | None,
-) -> None:
+) -> Awaitable[None]:
from trezor.enums import OutputScriptType
if output.script_type == OutputScriptType.PAYTOOPRETURN:
@@ -112,7 +114,7 @@ async def confirm_output(
source_account_path=address_n_to_str(address_n) if address_n else None,
)
- await layout
+ return layout
async def confirm_decred_sstx_submission(
@@ -141,13 +143,13 @@ async def confirm_decred_sstx_submission(
)
-async def show_payment_request_details(
+def show_payment_request_details(
provider_address: str,
payment_request: PaymentRequest,
coin: CoinInfo,
amount_unit: AmountUnit,
address_n: Bip32Path | None,
-) -> None:
+) -> Awaitable[None]:
from trezor import wire
from trezor.ui.layouts.slip24 import Refund, Trade
@@ -200,7 +202,7 @@ async def show_payment_request_details(
if account_path:
account_items.append((TR.address_details__derivation_path, account_path, True))
- await layouts.confirm_payment_request(
+ return layouts.confirm_payment_request(
payment_request.recipient_name,
provider_address,
texts,
@@ -212,39 +214,39 @@ async def show_payment_request_details(
)
-async def confirm_replacement(title: str, txid: AnyBytes) -> None:
- await layouts.confirm_replacement(
+def confirm_replacement(title: str, txid: AnyBytes) -> Awaitable[None]:
+ return layouts.confirm_replacement(
title,
txid.hex(),
)
-async def confirm_modify_output(
+def confirm_modify_output(
txo: TxOutput,
orig_txo: TxOutput,
coin: CoinInfo,
amount_unit: AmountUnit,
-) -> None:
+) -> Awaitable[None]:
assert txo.address is not None
address_short = addresses.address_short(coin, txo.address)
amount_change = txo.amount - orig_txo.amount
- await layouts.confirm_modify_output(
+ return layouts.confirm_modify_output(
address_short,
amount_change,
format_coin_amount(abs(amount_change), coin, amount_unit),
format_coin_amount(txo.amount, coin, amount_unit),
)
-async def confirm_modify_fee(
+def confirm_modify_fee(
title: str,
user_fee_change: int,
total_fee_new: int,
fee_rate: float,
coin: CoinInfo,
amount_unit: AmountUnit,
-) -> None:
- await layouts.confirm_modify_fee(
+) -> Awaitable[None]:
+ return layouts.confirm_modify_fee(
title,
user_fee_change,
format_coin_amount(abs(user_fee_change), coin, amount_unit),
@@ -253,33 +255,30 @@ async def confirm_modify_fee(
)
-async def confirm_joint_total(
- spending: int,
- total: int,
- coin: CoinInfo,
- amount_unit: AmountUnit,
-) -> None:
- await layouts.confirm_joint_total(
+def confirm_joint_total(
+ spending: int, total: int, coin: CoinInfo, amount_unit: AmountUnit
+) -> Awaitable[None]:
+ return layouts.confirm_joint_total(
spending_amount=format_coin_amount(spending, coin, amount_unit),
total_amount=format_coin_amount(total, coin, amount_unit),
)
-async def confirm_total(
+def confirm_total(
spending: int,
fee: int,
fee_rate: float,
coin: CoinInfo,
amount_unit: AmountUnit,
address_n: Bip32Path | None,
-) -> None:
+) -> Awaitable[Any]:
account = account_label(coin, address_n)
account_path = address_n_to_str(address_n) if address_n else None
account_items: list[StrPropertyType] = [(TR.words__account, account, None)]
if account_path and account_path != account:
account_items.append((TR.address_details__derivation_path, account_path, None))
- await layouts.confirm_total(
+ return layouts.confirm_total(
format_coin_amount(spending, coin, amount_unit),
format_coin_amount(fee, coin, amount_unit),
account_items=account_items,
@@ -291,29 +290,29 @@ async def confirm_total(
)
-async def confirm_feeoverthreshold(
+def confirm_feeoverthreshold(
fee: int, coin: CoinInfo, amount_unit: AmountUnit
-) -> None:
+) -> Awaitable[None]:
fee_amount = format_coin_amount(fee, coin, amount_unit)
- await layouts.show_warning(
+ return layouts.show_warning(
"fee_over_threshold",
TR.bitcoin__unusually_high_fee,
fee_amount,
br_code=ButtonRequestType.FeeOverThreshold,
)
-async def confirm_change_count_over_threshold(change_count: int) -> None:
- await layouts.show_warning(
+def confirm_change_count_over_threshold(change_count: int) -> Awaitable[None]:
+ return layouts.show_warning(
"change_count_over_threshold",
TR.bitcoin__lot_of_change_outputs,
f"{str(change_count)} {TR.words__outputs}",
br_code=ButtonRequestType.SignTx,
)
-async def confirm_unverified_external_input() -> None:
- await layouts.show_warning(
+def confirm_unverified_external_input() -> Awaitable[None]:
+ return layouts.show_warning(
"unverified_external_input",
TR.bitcoin__unverified_external_inputs,
TR.words__continue_anyway_question,
@@ -322,15 +321,17 @@ async def confirm_unverified_external_input() -> None:
)
-async def confirm_multiple_accounts() -> None:
- await layouts.confirm_multiple_accounts_warning()
+def confirm_multiple_accounts() -> Awaitable[None]:
+ return layouts.confirm_multiple_accounts_warning()
-async def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool) -> None:
+def confirm_nondefault_locktime(
+ lock_time: int, lock_time_disabled: bool
+) -> Awaitable[None]:
from trezor.strings import format_timestamp
if lock_time_disabled:
- await layouts.lock_time_disabled_warning()
+ return layouts.lock_time_disabled_warning()
else:
if lock_time < _LOCKTIME_TIMESTAMP_MIN_VALUE:
text = TR.bitcoin__locktime_set_to_blockheight
@@ -340,7 +341,7 @@ async def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool)
text = TR.bitcoin__locktime_set_to
value = format_timestamp(lock_time)
is_data = False
- await layouts.confirm_value(
+ return layouts.confirm_value(
TR.bitcoin__confirm_locktime,
value,
text,
@@ -349,3 +350,9 @@ async def confirm_nondefault_locktime(lock_time: int, lock_time_disabled: bool)
br_code=ButtonRequestType.SignTx,
verb=TR.buttons__confirm,
)
+
+
+def confirm_foreign_address(address_n: list) -> Awaitable[None]:
+ from apps.common import paths
+
+ return paths.show_path_warning(address_n)
### core/src/apps/bitcoin/sign_tx/progress.py
@@ -134,6 +134,3 @@ def assert_finished(self) -> None:
raise wire.FirmwareError(
f"Transaction {operation} progress finished at {self.progress}/{self.steps}."
)
-
-
-progress = Progress()
### core/src/apps/bitcoin/sign_tx/zcash_v4.py
@@ -153,7 +153,7 @@ async def step7_finish(self) -> None:
write_compact_size(serialized_tx, 0) # nShieldedOutput
write_compact_size(serialized_tx, 0) # nJoinSplit
- await helpers.request_tx_finish(self.tx_req)
+ helpers.request_tx_finish(self.tx_req)
async def sign_nonsegwit_input(self, i_sign: int) -> None:
await self.sign_nonsegwit_bip143_input(i_sign)
### core/tests/common.py
@@ -9,6 +9,11 @@
if TYPE_CHECKING:
from collections.abc import Awaitable
+ from trezor.messages import TxRequest
+ from trezor.protobuf import MessageType
+
+ from apps.bitcoin.sign_tx.bitcoin import Bitcoin
+
def H_(x: int) -> int:
"""
@@ -65,3 +70,158 @@ def setUpClass(self):
def tearDownClass(self):
self._seed_patch.__exit__(None, None, None)
super().tearDownClass()
+
+
+class _ScriptEnded(Exception):
+ pass
+
+
+_SIGNING_UI_STUBS = (
+ "confirm_output",
+ "confirm_decred_sstx_submission",
+ "show_payment_request_details",
+ "confirm_replacement",
+ "confirm_modify_output",
+ "confirm_modify_fee",
+ "confirm_total",
+ "confirm_joint_total",
+ "confirm_feeoverthreshold",
+ "confirm_change_count_over_threshold",
+ "confirm_unverified_external_input",
+ "confirm_foreign_address",
+ "confirm_nondefault_locktime",
+ "confirm_multiple_accounts",
+)
+
+
+class UiCall:
+ """Expected (or recorded) call of a `apps.bitcoin.sign_tx.layout` function."""
+
+ def __init__(
+ self, name: str, args: tuple[Any, ...], kwargs: dict[str, Any]
+ ) -> None:
+ self.name = name
+ self.args = args
+ self.kwargs = kwargs
+
+ def __eq__(self, other: Any) -> bool:
+ return (
+ isinstance(other, UiCall)
+ and self.name == other.name
+ and self.args == other.args
+ and self.kwargs == other.kwargs
+ )
+
+ def __repr__(self) -> str:
+ return f"<UiCall {self.name} args={self.args} kwargs={self.kwargs}>"
+
+
+class _UiExpectations:
+ """`ui.confirm_output(...)` builds the expected `UiCall` for `layout.confirm_output(...)`."""
+
+ def __getattr__(self, name: str):
+ if name not in _SIGNING_UI_STUBS:
+ raise AttributeError(name)
+
+ def expect(*args, **kwargs) -> UiCall:
+ return UiCall(name, args, kwargs)
+
+ return expect
+
+
+ui = _UiExpectations()
+
+
+class ScriptedContext:
+ """Fake wire context that asserts TxRequests and returns scripted acknowledgements.
+
+ Expected signing UI calls (`UiCall`s) are interleaved with the TxRequests in the
+ same script, so their relative order is asserted as well.
+ """
+
+ def __init__(self, script: list, testcase: unittest.TestCase) -> None:
+ self._script = script
+ self._index = 0
+ self._tc = testcase
+
+ def _next_expected(self, actual) -> None:
+ if self._index >= len(self._script):
+ self._tc.fail(f"unexpected {actual} after end of script")
+ expected = self._script[self._index]
+ self._index += 1
+ if isinstance(expected, UiCall) != isinstance(actual, UiCall):
+ self._tc.fail(f"expected {expected}, got {actual}")
+ self._tc.assertEqual(actual, expected)
+
+ async def call(self, msg, expected_type: MessageType):
+ self._next_expected(msg)
+ if self._index >= len(self._script):
+ raise _ScriptEnded
+ ack = self._script[self._index]
+ self._index += 1
+ if not expected_type.is_type_of(ack):
+ self._tc.fail(
+ f"expected {expected_type.MESSAGE_NAME}, got {ack.MESSAGE_NAME}"
+ )
+ return ack
+
+ def ui_call(self, name: str, args: tuple, kwargs: dict) -> bool:
+ self._next_expected(UiCall(name, args, kwargs))
+ if self._index >= len(self._script):
+ raise _ScriptEnded
+ return True # auto-confirm
+
+
+def stub_signing_ui(ctx: ScriptedContext) -> None:
+ from apps.bitcoin.sign_tx import layout
+
+ def make_confirm_fn(name: str):
+ async def confirm_fn(*args, **kwargs) -> bool:
+ # make sure confirmation call matches the expected UiCall.
+ return ctx.ui_call(name, args, kwargs)
+
+ return confirm_fn
+
+ for name in _SIGNING_UI_STUBS:
+ assert hasattr(layout, name)
+ setattr(layout, name, make_confirm_fn(name))
+
+
+def run_signer(
+ testcase: unittest.TestCase, signer: Bitcoin, messages: list
+) -> TxRequest | None:
+ """Drive a bitcoin signer against a TxRequest / TxAck / UiCall script.
+
+ `messages` is a flat list of expected `TxRequest`s interleaved with the
+ corresponding acknowledgements, and expected signing UI calls (built via
+ `ui.<layout function>(...)`), which are auto-confirmed. A trailing
+ `TxRequest` with `request_type=TXFINISHED` is asserted against
+ `signer.tx_req` after the signer returns, and is not treated as a
+ `context.call()`.
+ """
+ from trezor.enums import RequestType
+ from trezor.messages import TxRequest
+
+ finished = None
+ if messages:
+ last = messages[-1]
+ if TxRequest.is_type_of(last) and last.request_type == RequestType.TXFINISHED:
+ finished = last
+ messages = messages[:-1]
+
+ ctx = ScriptedContext(messages, testcase)
+ stub_signing_ui(ctx)
+ try:
+ await_result(context.with_context(ctx, signer.signer()))
+ except _ScriptEnded:
+ if finished is not None:
+ testcase.fail("signer stopped before TXFINISHED")
+ if ctx._index != len(ctx._script):
+ testcase.fail("script not fully consumed")
+ return None
+
+ if ctx._index != len(ctx._script):
+ testcase.fail("script not fully consumed")
+ if finished is not None:
+ testcase.assertEqual(signer.tx_req, finished)
+ return signer.tx_req
### core/tests/test_apps.bitcoin.segwit.signtx.native_p2wpkh.py
@@ -25,10 +25,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoin, helpers
+from apps.bitcoin.sign_tx import bitcoin
from apps.common import coins
from apps.common.keychain import Keychain
@@ -99,40 +98,35 @@ def test_send_native_p2wpkh(self):
fee_rate = 11000 / 142
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckInput(tx=TxAckInputWrapper(input=inp1)),
- helpers.UiConfirmForeignAddress(address_n=inp1.address_n),
- True,
+ ui.confirm_foreign_address(inp1.address_n),
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out2, coin, AmountUnit.BITCOIN, 1, False, [H_(49), H_(1), H_(0)]
),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_total(
12300000, 11000, fee_rate, coin, AmountUnit.BITCOIN, inp1.address_n[:3]
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -231,14 +225,8 @@ def test_send_native_p2wpkh(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- for request, response in chunks(messages, 2):
- res = signer.send(request)
- if isinstance(res, tuple):
- _, res = res
- self.assertEqual(res, response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_native_p2wpkh_change(self):
@@ -302,43 +290,38 @@ def test_send_native_p2wpkh_change(self):
fee_rate = 11000 / 142
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckInput(tx=TxAckInputWrapper(input=inp1)),
- helpers.UiConfirmForeignAddress(address_n=inp1.address_n),
- True,
+ ui.confirm_foreign_address(inp1.address_n),
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmForeignAddress(address_n=out2.address_n),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_foreign_address(out2.address_n),
+ ui.confirm_total(
5000000 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -438,14 +421,8 @@ def test_send_native_p2wpkh_change(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_native_invalid_address(self):
@@ -476,37 +453,27 @@ def test_send_native_invalid_address(self):
)
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckInput(tx=TxAckInputWrapper(input=inp1)),
- helpers.UiConfirmForeignAddress(address_n=inp1.address_n),
- True,
+ ui.confirm_foreign_address(inp1.address_n),
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- None,
]
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- if expected_response is None:
- with self.assertRaises(wire.DataError):
- signer.send(request)
- else:
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ with self.assertRaises(wire.DataError):
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.segwit.signtx.native_p2wpkh_grs.py
@@ -24,10 +24,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoinlike, helpers
+from apps.bitcoin.sign_tx import bitcoinlike
from apps.common import coins
from apps.common.keychain import Keychain
@@ -110,7 +109,6 @@ def test_send_native_p2wpkh(self):
fee_rate = 11000 / 142
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -124,26 +122,22 @@ def test_send_native_p2wpkh(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(84), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out2, coin, AmountUnit.BITCOIN, 1, False, [H_(84), H_(1), H_(0)]
),
- True,
- helpers.UiConfirmNonDefaultLocktime(tx.lock_time, lock_time_disabled=False),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_nondefault_locktime(tx.lock_time, False),
+ ui.confirm_total(
12300000, 11000, fee_rate, coin, AmountUnit.BITCOIN, inp1.address_n[:3]
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -242,14 +236,8 @@ def test_send_native_p2wpkh(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_native_p2wpkh_change(self):
@@ -323,7 +311,6 @@ def test_send_native_p2wpkh_change(self):
fee_rate = 11000 / 142
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -337,27 +324,24 @@ def test_send_native_p2wpkh_change(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(84), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmNonDefaultLocktime(tx.lock_time, lock_time_disabled=False),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_nondefault_locktime(tx.lock_time, False),
+ ui.confirm_total(
5000000 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -457,14 +441,8 @@ def test_send_native_p2wpkh_change(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.segwit.signtx.p2wpkh_in_p2sh.py
@@ -25,10 +25,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoin, helpers
+from apps.bitcoin.sign_tx import bitcoin
from apps.common import coins
from apps.common.keychain import Keychain
@@ -103,7 +102,6 @@ def test_send_p2wpkh_in_p2sh(self):
fee_rate = 11000 / 168
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -117,29 +115,26 @@ def test_send_p2wpkh_in_p2sh(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out2, coin, AmountUnit.BITCOIN, 1, False, [H_(49), H_(1), H_(0)]
),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_total(
123445789 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -238,14 +233,8 @@ def test_send_p2wpkh_in_p2sh(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_p2wpkh_in_p2sh_change(self):
@@ -312,7 +301,6 @@ def test_send_p2wpkh_in_p2sh_change(self):
fee_rate = 11000 / 168
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -326,25 +314,23 @@ def test_send_p2wpkh_in_p2sh_change(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmTotal(
+ ui.confirm_total(
12300000 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -444,14 +430,8 @@ def test_send_p2wpkh_in_p2sh_change(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_p2wpkh_in_p2sh_attack_amount(self):
@@ -530,7 +510,6 @@ def test_send_p2wpkh_in_p2sh_attack_amount(self):
fee_rate = (9 - 8 - 1) / 168
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -544,20 +523,18 @@ def test_send_p2wpkh_in_p2sh_attack_amount(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmTotal(
+ ui.confirm_total(
9 - 1, 9 - 8 - 1, fee_rate, coin, AmountUnit.BITCOIN, inp1.address_n[:3]
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -591,33 +568,13 @@ def test_send_p2wpkh_in_p2sh_attack_amount(self):
serialized=EMPTY_SERIALIZED,
),
TxAckPrevOutput(tx=TxAckPrevOutputWrapper(output=pout2)),
- # sign tx
- TxRequest(
- request_type=TXINPUT,
- details=TxRequestDetailsType(request_index=0, tx_hash=None),
- serialized=TxRequestSerializedType(
- # returned serialized header
- serialized_tx=bytes.fromhex("01000000000101"),
- ),
- ),
]
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin, None).signer()
- i = 0
- messages_count = int(len(messages) / 2)
- for request, expected_response in chunks(messages, 2):
- if i == messages_count - 1: # last message should throw wire.Error
- self.assertRaises(wire.DataError, signer.send, request)
- else:
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- i += 1
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoin.Bitcoin(tx, keychain, coin, None)
+ with self.assertRaises(wire.DataError):
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.segwit.signtx.p2wpkh_in_p2sh_grs.py
@@ -24,10 +24,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoinlike, helpers
+from apps.bitcoin.sign_tx import bitcoinlike
from apps.common import coins
from apps.common.keychain import Keychain
@@ -112,7 +111,6 @@ def test_send_p2wpkh_in_p2sh(self):
fee_rate = 11000 / 168
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -126,31 +124,27 @@ def test_send_p2wpkh_in_p2sh(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out2, coin, AmountUnit.BITCOIN, 1, False, [H_(49), H_(1), H_(0)]
),
- True,
- helpers.UiConfirmNonDefaultLocktime(tx.lock_time, lock_time_disabled=False),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_nondefault_locktime(tx.lock_time, False),
+ ui.confirm_total(
123445789 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -249,14 +243,8 @@ def test_send_p2wpkh_in_p2sh(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
def test_send_p2wpkh_in_p2sh_change(self):
@@ -331,7 +319,6 @@ def test_send_p2wpkh_in_p2sh_change(self):
fee_rate = 11000 / 168
messages = [
- None,
# check fee
TxRequest(
request_type=TXINPUT,
@@ -345,27 +332,24 @@ def test_send_p2wpkh_in_p2sh_change(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(49), H_(1), H_(0)]
),
- True,
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out2)),
- helpers.UiConfirmNonDefaultLocktime(tx.lock_time, lock_time_disabled=False),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_nondefault_locktime(tx.lock_time, False),
+ ui.confirm_total(
12300000 + 11000,
11000,
fee_rate,
coin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# check prev tx
TxRequest(
request_type=TXINPUT,
@@ -465,14 +449,8 @@ def test_send_p2wpkh_in_p2sh_change(self):
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.signtx.fee_threshold.py
@@ -24,9 +24,8 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
-from apps.bitcoin.sign_tx import bitcoin, helpers
+from apps.bitcoin.sign_tx import bitcoin
from apps.common import coins
from apps.common.keychain import Keychain
from apps.common.paths import AlwaysMatchingSchema
@@ -43,70 +42,6 @@ class TestSignTxFeeThreshold(unittest.TestCase):
# this is being tested in the device test:
# test_msg_signtx.test_testnet_fee_too_high
- """
- def test_over_fee_threshold(self):
- coin_bitcoin = coins.by_name('Bitcoin')
-
- ptx1 = PrevTx(version=1, lock_time=0, inputs_count=2, outputs_count=1, extra_data_len=0)
- pinp1 = PrevInput(script_sig=bytes.fromhex('483045022072ba61305fe7cb542d142b8f3299a7b10f9ea61f6ffaab5dca8142601869d53c0221009a8027ed79eb3b9bc13577ac2853269323434558528c6b6a7e542be46e7e9a820141047a2d177c0f3626fc68c53610b0270fa6156181f46586c679ba6a88b34c6f4874686390b4d92e5769fbb89c8050b984f4ec0b257a0e5c4ff8bd3b035a51709503'),
- prev_hash=bytes.fromhex('c16a03f1cf8f99f6b5297ab614586cacec784c2d259af245909dedb0e39eddcf'),
- prev_index=1)
- pinp2 = PrevInput(script_sig=bytes.fromhex('48304502200fd63adc8f6cb34359dc6cca9e5458d7ea50376cbd0a74514880735e6d1b8a4c0221008b6ead7fe5fbdab7319d6dfede3a0bc8e2a7c5b5a9301636d1de4aa31a3ee9b101410486ad608470d796236b003635718dfc07c0cac0cfc3bfc3079e4f491b0426f0676e6643a39198e8e7bdaffb94f4b49ea21baa107ec2e237368872836073668214'),
- prev_hash=bytes.fromhex('1ae39a2f8d59670c8fc61179148a8e61e039d0d9e8ab08610cb69b4a19453eaf'),
- prev_index=1)
- pout1 = PrevOutput(script_pubkey=bytes.fromhex('76a91424a56db43cf6f2b02e838ea493f95d8d6047423188ac'),
- amount=390000)
-
- inp1 = TxInput(address_n=[0], # 14LmW5k4ssUrtbAB4255zdqv3b4w1TuX9e
- # amount=390000,
- prev_hash=bytes.fromhex('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882'),
- prev_index=0,
- amount=None)
- out1 = TxOutput(address='1MJ2tj2ThBE62zXbBYA5ZaN3fdve5CPAz1',
- amount=390000 - 100000, # fee increased to 100000 => too high
- multisig=None,
- script_type=OutputScriptType.PAYTOADDRESS,
- address_n=[])
- tx = SignTx(coin_name=None, version=1, lock_time=0, inputs_count=1, outputs_count=1)
-
- messages = [
- None,
-
- TxRequest(request_type=TXINPUT, details=TxRequestDetailsType(request_index=0, tx_hash=None)),
- TxAckInput(tx=TxAckInputWrapper(input=inp1)),
- helpers.UiConfirmForeignAddress(address_n=inp1.address_n),
- True,
- TxRequest(request_type=TXMETA, details=TxRequestDetailsType(request_index=None, tx_hash=bytes.fromhex('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882')), serialized=None),
- TxAckPrevMeta(tx=ptx1),
- TxRequest(request_type=TXINPUT, details=TxRequestDetailsType(request_index=0, tx_hash=bytes.fromhex('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882')), serialized=None),
- TxAckPrevInput(tx=TxAckPrevInputWrapper(input=pinp1)),
- TxRequest(request_type=TXINPUT, details=TxRequestDetailsType(request_index=1, tx_hash=bytes.fromhex('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882')), serialized=None),
- TxAckPrevInput(tx=TxAckPrevInputWrapper(input=pinp2)),
- TxRequest(request_type=TXOUTPUT, details=TxRequestDetailsType(request_index=0, tx_hash=bytes.fromhex('d5f65ee80147b4bcc70b75e4bbf2d7382021b871bd8867ef8fa525ef50864882')), serialized=None),
- TxAckPrevOutput(tx=TxAckPrevOutputWrapper(output=pout1)),
- TxRequest(request_type=TXOUTPUT, details=TxRequestDetailsType(request_index=0, tx_hash=None), serialized=None),
- TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(out1, coin_bitcoin, AmountUnit.BITCOIN, 0, False),
- True,
- helpers.UiConfirmFeeOverThreshold(100000, coin_bitcoin),
- True,
- helpers.UiConfirmTotal(290000 + 100000, 100000, coin_bitcoin, AmountUnit.BITCOIN),
- True,
- TxRequest(request_type=TXINPUT, details=TxRequestDetailsType(request_index=0, tx_hash=None), serialized=None),
- ]
-
- seed = bip39.seed('alcohol woman abuse must during monitor noble actual mixed trade anger aisle', '')
- root = bip32.from_seed(seed, 'secp256k1')
-
- keychain = Keychain([[coin_bitcoin.curve_name]], [root])
- signer = signing.sign_tx(tx, keychain)
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- """
-
def test_under_threshold(self):
coin_bitcoin = coins.by_name("Bitcoin")
@@ -166,31 +101,24 @@ def test_under_threshold(self):
fee_rate = 90000 / (768 / 4)
messages = [
- None,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckInput(tx=TxAckInputWrapper(input=inp1)),
- helpers.UiConfirmForeignAddress(address_n=inp1.address_n),
- True,
+ ui.confirm_foreign_address(inp1.address_n),
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
- out1, coin_bitcoin, AmountUnit.BITCOIN, 0, False, None
- ),
- True,
- helpers.UiConfirmMultipleAccounts(),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_output(out1, coin_bitcoin, AmountUnit.BITCOIN, 0, False, None),
+ ui.confirm_multiple_accounts(),
+ ui.confirm_total(
300000 + 90000, 90000, fee_rate, coin_bitcoin, AmountUnit.BITCOIN, None
),
- True,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -256,12 +184,8 @@ def test_under_threshold(self):
)
keychain = Keychain(seed, coin_bitcoin.curve_name, [AlwaysMatchingSchema])
- signer = bitcoin.Bitcoin(tx, keychain, coin_bitcoin, None).signer()
- for request, response in chunks(messages, 2):
- res = signer.send(request)
- if isinstance(res, tuple):
- _, res = res
- self.assertEqual(res, response)
+ signer = bitcoin.Bitcoin(tx, keychain, coin_bitcoin, None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.signtx.py
@@ -24,10 +24,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoin, helpers
+from apps.bitcoin.sign_tx import bitcoin
from apps.common import coins
from apps.common.keychain import Keychain
@@ -99,7 +98,6 @@ def test_one_one_fee(self):
fee_rate = 50_000 / (768 / 4)
messages = [
- None,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -112,19 +110,17 @@ def test_one_one_fee(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin_bitcoin, AmountUnit.BITCOIN, 0, False, [H_(44), H_(0), H_(0)]
),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_total(
3_801_747,
50_000,
fee_rate,
coin_bitcoin,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
# ButtonRequest(code=ButtonRequest_ConfirmOutput),
# ButtonRequest(code=ButtonRequest_SignTx),
TxRequest(
@@ -224,16 +220,9 @@ def test_one_one_fee(self):
)
ns = _get_schemas_for_coin(coin_bitcoin)
keychain = Keychain(seed, coin_bitcoin.curve_name, ns)
- signer = bitcoin.Bitcoin(tx, keychain, coin_bitcoin, None).signer()
+ signer = bitcoin.Bitcoin(tx, keychain, coin_bitcoin, None)
- for request, response in chunks(messages, 2):
- res = signer.send(request)
- if isinstance(res, tuple):
- _, res = res
- self.assertEqual(res, response)
-
- with self.assertRaises(StopIteration):
- signer.send(None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.signtx_decred.py
@@ -28,10 +28,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
- from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
- from apps.bitcoin.sign_tx import decred, helpers
+ from apps.bitcoin.sign_tx import decred
from apps.common import coins
from apps.common.keychain import Keychain
@@ -102,7 +101,6 @@ def test_one_one_fee(self):
fee_rate = 100_000 / (864 / 4)
messages = [
- None,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -121,19 +119,17 @@ def test_one_one_fee(self):
),
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin_decred, AmountUnit.BITCOIN, 0, False, [H_(44), H_(1), H_(0)]
),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_total(
200_000_000,
100_000,
fee_rate,
coin_decred,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -215,17 +211,9 @@ def test_one_one_fee(self):
)
ns = _get_schemas_for_coin(coin_decred)
keychain = Keychain(seed, coin_decred.curve_name, ns)
- signer = decred.Decred(tx, keychain, coin_decred, None).signer()
+ signer = decred.Decred(tx, keychain, coin_decred, None)
- for request, response in chunks(messages, 2):
- res = signer.send(request)
- if isinstance(res, tuple):
- _, res = res
-
- self.assertEqual(res, response)
-
- with self.assertRaises(StopIteration):
- signer.send(None)
+ run_signer(self, signer, messages)
def test_purchase_ticket(self):
inp1 = TxInput(
@@ -269,7 +257,6 @@ def test_purchase_ticket(self):
fee_rate = 100_000 / (1188 / 4)
messages = [
- None,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -288,10 +275,7 @@ def test_purchase_ticket(self):
),
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmDecredSSTXSubmission(
- out1, coin_decred, AmountUnit.BITCOIN
- ),
- True,
+ ui.confirm_decred_sstx_submission(out1, coin_decred, AmountUnit.BITCOIN),
TxRequest(
request_type=TXOUTPUT,
details=TxRequestDetailsType(request_index=1, tx_hash=None),
@@ -312,15 +296,14 @@ def test_purchase_ticket(self):
),
),
TxAckOutput(tx=TxAckOutputWrapper(output=out3)),
- helpers.UiConfirmTotal(
+ ui.confirm_total(
200_000_000,
100_000,
fee_rate,
coin_decred,
AmountUnit.BITCOIN,
inp1.address_n[:3],
),
- True,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -402,17 +385,9 @@ def test_purchase_ticket(self):
)
ns = _get_schemas_for_coin(coin_decred)
keychain = Keychain(seed, coin_decred.curve_name, ns)
- signer = decred.Decred(tx, keychain, coin_decred, None).signer()
-
- for request, response in chunks(messages, 2):
- res = signer.send(request)
- if isinstance(res, tuple):
- _, res = res
-
- self.assertEqual(res, response)
+ signer = decred.Decred(tx, keychain, coin_decred, None)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":
### core/tests/test_apps.bitcoin.signtx_grs.py
@@ -24,10 +24,9 @@
TxRequestDetailsType,
TxRequestSerializedType,
)
-from trezor.utils import chunks
from apps.bitcoin.keychain import _get_schemas_for_coin
-from apps.bitcoin.sign_tx import bitcoinlike, helpers
+from apps.bitcoin.sign_tx import bitcoinlike
from apps.common import coins
from apps.common.keychain import Keychain
@@ -100,7 +99,6 @@ def test_one_one_fee(self):
fee_rate = 192 / (768 / 4)
messages = [
- None,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -113,14 +111,12 @@ def test_one_one_fee(self):
serialized=EMPTY_SERIALIZED,
),
TxAckOutput(tx=TxAckOutputWrapper(output=out1)),
- helpers.UiConfirmOutput(
+ ui.confirm_output(
out1, coin, AmountUnit.BITCOIN, 0, False, [H_(44), H_(17), H_(0)]
),
- True,
- helpers.UiConfirmTotal(
+ ui.confirm_total(
210016, 192, fee_rate, coin, AmountUnit.BITCOIN, inp1.address_n[:3]
),
- True,
TxRequest(
request_type=TXINPUT,
details=TxRequestDetailsType(request_index=0, tx_hash=None),
@@ -208,14 +204,8 @@ def test_one_one_fee(self):
seed = bip39.seed(" ".join(["all"] * 12), "")
ns = _get_schemas_for_coin(coin)
keychain = Keychain(seed, coin.curve_name, ns)
- signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None).signer()
- for request, expected_response in chunks(messages, 2):
- response = signer.send(request)
- if isinstance(response, tuple):
- _, response = response
- self.assertEqual(response, expected_response)
- with self.assertRaises(StopIteration):
- signer.send(None)
+ signer = bitcoinlike.Bitcoinlike(tx, keychain, coin, None)
+ run_signer(self, signer, messages)
if __name__ == "__main__":Why this scored 12/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.