def input_script(self, txin, estimate_size=False, sign_schnorr=False): if txin['type'] == 'p2pkh': return Transaction.get_preimage_script(txin) if txin['type'] == 'p2sh': # Multisig verification has partial support, but is disabled. This is the # expected serialization though, so we leave it here until we activate it. return '00' + push_script(Transaction.get_preimage_script(txin)) raise Exception("unsupported type %s" % txin['type'])
def sign_transaction(self, tx, password, *, use_cache=False): if tx.is_complete(): return client = self.get_client() inputs = [] inputsPaths = [] pubKeys = [] chipInputs = [] redeemScripts = [] signatures = [] preparedTrustedInputs = [] changePath = "" output = None p2shTransaction = False pin = "" self.get_client( ) # prompt for the PIN before displaying the dialog if necessary self.cashaddr_alert() # Fetch inputs of the transaction to sign derivations = self.get_tx_derivations(tx) for txin in tx.inputs(): if txin['type'] == 'coinbase': self.give_error( _('Coinbase not supported')) # should never happen if txin['type'] in ['p2sh']: p2shTransaction = True pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin) for i, x_pubkey in enumerate(x_pubkeys): if x_pubkey in derivations: signingPos = i s = derivations.get(x_pubkey) hwAddress = "{:s}/{:d}/{:d}".format( self.get_derivation()[2:], s[0], s[1]) break else: self.give_error(_('No matching x_key for sign_transaction') ) # should never happen redeemScript = Transaction.get_preimage_script(txin) inputs.append([ txin['prev_tx'].raw, txin['prevout_n'], redeemScript, txin['prevout_hash'], signingPos, txin.get('sequence', 0xffffffff - 1) ]) inputsPaths.append(hwAddress) pubKeys.append(pubkeys) # Sanity check if p2shTransaction: for txin in tx.inputs(): if txin['type'] != 'p2sh': self.give_error( _('P2SH / regular input mixed in same transaction not supported' )) # should never happen txOutput = var_int(len(tx.outputs())) for txout in tx.outputs(): output_type, addr, amount = txout txOutput += int_to_hex(amount, 8) script = tx.pay_script(addr) txOutput += var_int(len(script) // 2) txOutput += script txOutput = bfh(txOutput) # Recognize outputs # - only one output and one change is authorized (for hw.1 and nano) # - at most one output can bypass confirmation (~change) (for all) if not p2shTransaction: if not self.get_client_electrum().supports_multi_output(): if len(tx.outputs()) > 2: self.give_error( _('Transaction with more than 2 outputs not supported by {}' ).format(self.device)) has_change = False any_output_on_change_branch = is_any_tx_output_on_change_branch(tx) for o in tx.outputs(): _type, address, amount = o if self.get_client_electrum().is_hw1(): if not _type == TYPE_ADDRESS: self.give_error( _('Only address outputs are supported by {}'). format(self.device)) else: if not _type in [TYPE_ADDRESS, TYPE_SCRIPT]: self.give_error( _('Only address and script outputs are supported by {}' ).format(self.device)) if _type == TYPE_SCRIPT: try: # Ledger has a maximum output size of 200 bytes: # https://github.com/LedgerHQ/ledger-app-btc/commit/3a78dee9c0484821df58975803e40d58fbfc2c38#diff-c61ccd96a6d8b54d48f54a3bc4dfa7e2R26 # which gives us a maximum OP_RETURN payload size of # 187 bytes. It also apparently has no limit on # max_pushes, so we specify max_pushes=None so as # to bypass that check. validate_op_return_output_and_get_data( o, max_size=187, max_pushes=None) except RuntimeError as e: self.give_error('{}: {}'.format( self.device, str(e))) info = tx.output_info.get(address) if (info is not None) and len(tx.outputs()) > 1 \ and not has_change: index, xpubs, m, script_type = info on_change_branch = index[0] == 1 # prioritise hiding outputs on the 'change' branch from user # because no more than one change address allowed if on_change_branch == any_output_on_change_branch: changePath = self.get_derivation( )[2:] + "/{:d}/{:d}".format(*index) has_change = True else: output = address else: output = address self.handler.show_message( _('Confirm Transaction on your {}...').format(self.device)) try: # Get trusted inputs from the original transactions for utxo in inputs: sequence = int_to_hex(utxo[5], 4) if not self.get_client_electrum().requires_trusted_inputs(): txtmp = bitcoinTransaction(bfh(utxo[0])) tmp = bfh(utxo[3])[::-1] tmp += bfh(int_to_hex(utxo[1], 4)) tmp += txtmp.outputs[utxo[1]].amount chipInputs.append({ 'value': tmp, 'witness': True, 'sequence': sequence }) redeemScripts.append(bfh(utxo[2])) else: txtmp = bitcoinTransaction(bfh(utxo[0])) trustedInput = self.get_client().getTrustedInput( txtmp, utxo[1]) trustedInput['sequence'] = sequence trustedInput['witness'] = True chipInputs.append(trustedInput) if p2shTransaction: redeemScripts.append(bfh(utxo[2])) else: redeemScripts.append(txtmp.outputs[utxo[1]].script) # Sign all inputs inputIndex = 0 self.get_client().enableAlternate2fa(False) cashaddr = Address.FMT_UI == Address.FMT_CASHADDR if cashaddr and self.get_client_electrum().supports_cashaddr(): self.get_client().startUntrustedTransaction( True, inputIndex, chipInputs, redeemScripts[inputIndex], cashAddr=True) else: self.get_client().startUntrustedTransaction( True, inputIndex, chipInputs, redeemScripts[inputIndex]) # we don't set meaningful outputAddress, amount and fees # as we only care about the alternateEncoding==True branch outputData = self.get_client().finalizeInput( b'', 0, 0, changePath, bfh(tx.serialize(True))) outputData['outputData'] = txOutput transactionOutput = outputData['outputData'] if outputData['confirmationNeeded']: outputData['address'] = output self.handler.finished() pin = self.handler.get_auth( outputData) # does the authenticate dialog and returns pin if not pin: raise UserWarning() self.handler.show_message( _('Confirmed. Signing Transaction...')) while inputIndex < len(inputs): singleInput = [chipInputs[inputIndex]] if cashaddr and self.get_client_electrum().supports_cashaddr(): self.get_client().startUntrustedTransaction( False, 0, singleInput, redeemScripts[inputIndex], cashAddr=True) else: self.get_client().startUntrustedTransaction( False, 0, singleInput, redeemScripts[inputIndex]) inputSignature = self.get_client().untrustedHashSign( inputsPaths[inputIndex], pin, lockTime=tx.locktime, sighashType=0x41) inputSignature[0] = 0x30 # force for 1.4.9+ signatures.append(inputSignature) inputIndex = inputIndex + 1 except UserWarning: self.handler.show_error(_('Cancelled by user')) return except BTChipException as e: if e.sw in (0x6985, 0x6d00): # cancelled by user return elif e.sw == 0x6982: raise # pin lock. decorator will catch it else: traceback.print_exc(file=sys.stderr) self.give_error(e, True) except BaseException as e: traceback.print_exc(file=sys.stdout) self.give_error(e, True) finally: self.handler.finished() for i, txin in enumerate(tx.inputs()): signingPos = inputs[i][4] txin['signatures'][signingPos] = bh2u(signatures[i]) tx.raw = tx.serialize()