示例#1
0
    def test_signtransaction_with_wallet(self, mock_save_db):
        wallet = restore_wallet_from_text(
            'bitter grass shiver impose acquire brush forget axis eager alone wine silver',
            gap_limit=2,
            path='if_this_exists_mocking_failed_648151893',
            config=self.config)['wallet']

        # bootstrap wallet1
        funding_tx = Transaction(
            '01000000014576dacce264c24d81887642b726f5d64aa7825b21b350c7b75a57f337da6845010000006b483045022100a3f8b6155c71a98ad9986edd6161b20d24fad99b6463c23b463856c0ee54826d02200f606017fd987696ebbe5200daedde922eee264325a184d5bbda965ba5160821012102e5c473c051dae31043c335266d0ef89c1daab2f34d885cc7706b267f3269c609ffffffff0240420f00000000001600148a28bddb7f61864bdcf58b2ad13d5aeb3abc3c42a2ddb90e000000001976a914c384950342cb6f8df55175b48586838b03130fad88ac00000000'
        )
        funding_txid = funding_tx.txid()
        funding_output_value = 1000000
        self.assertEqual(
            'add2535aedcbb5ba79cc2260868bb9e57f328738ca192937f2c92e0e94c19203',
            funding_txid)
        wallet.receive_tx_callback(funding_txid, funding_tx,
                                   TX_HEIGHT_UNCONFIRMED)

        cmds = Commands(config=self.config)

        unsigned_tx = "cHNidP8BAHECAAAAAQOSwZQOLsnyNykZyjiHMn/luYuGYCLMebq1y+1aU9KtAAAAAAD+////AigjAAAAAAAAFgAUaQtZqBQGAvsjzCkE7OnMTa82EFIwGw8AAAAAABYAFKwOLSKSAL/7IWftb9GWrvnWh9i7AAAAAAABAN8BAAAAAUV22sziZMJNgYh2Qrcm9dZKp4JbIbNQx7daV/M32mhFAQAAAGtIMEUCIQCj+LYVXHGpitmYbt1hYbINJPrZm2RjwjtGOFbA7lSCbQIgD2BgF/2YdpbrvlIA2u3eki7uJkMloYTVu9qWW6UWCCEBIQLlxHPAUdrjEEPDNSZtDvicHaqy802IXMdwayZ/MmnGCf////8CQEIPAAAAAAAWABSKKL3bf2GGS9z1iyrRPVrrOrw8QqLduQ4AAAAAGXapFMOElQNCy2+N9VF1tIWGg4sDEw+tiKwAAAAAIgYDD67ptKJbfbggI8qYkZJxLN1MtT09kzhZHHkJ5YGuHAwQsuNafQAAAIAAAAAAAAAAAAAiAgKFhOeJ459BORsvJ4UsoYq+wGpUEcIb41D+1h7scSDeUxCy41p9AAAAgAEAAAAAAAAAAAA="

        self.assertEqual(
            "020000000001010392c1940e2ec9f2372919ca3887327fe5b98b866022cc79bab5cbed5a53d2ad0000000000feffffff022823000000000000160014690b59a8140602fb23cc2904ece9cc4daf361052301b0f0000000000160014ac0e2d229200bffb2167ed6fd196aef9d687d8bb02473044022027e1e37172e52b2d84106663cff5bcf6e447dcb41f6483f99584cfb4de2785f4022005c72f6324ad130c78fca43fe5fc565526d1723f2c9dc3efea78f66d7ae9d4360121030faee9b4a25b7db82023ca989192712cdd4cb53d3d9338591c7909e581ae1c0c00000000",
            cmds._run('signtransaction', (), tx=unsigned_tx, wallet=wallet))
示例#2
0
    def test_bumpfee(self, mock_save_db):
        wallet = restore_wallet_from_text(
            'right nominee cheese afford exotic pilot mask illness rug fringe degree pottery',
            gap_limit=2,
            path='if_this_exists_mocking_failed_648151893',
            config=self.config)['wallet']

        funding_tx = Transaction(
            "02000000000102789e8aa8caa79d87241ff9df0e3fd757a07c85a30195d76e8efced1d57c56b670000000000fdffffff7ee2b6abd52b332f797718ae582f8d3b979b83b1799e0a3bfb2c90c6e070c29e0100000000fdffffff020820000000000000160014c0eb720c93a61615d2d66542d381be8943ca553950c3000000000000160014d7dbd0196a2cbd76420f14a19377096cf6cddb75024730440220485b491ad8d3ce3b4da034a851882da84a06ec9800edff0d3fd6aa42eeba3b440220359ea85d32a05932ac417125e133fa54e54e7e9cd20ebc54b883576b8603fd65012103860f1fbf8a482b9d35d7d4d04be8fb33d856a514117cd8b73e372d36895feec60247304402206c2ca56cc030853fa59b4b3cb293f69a3378ead0f10cb76f640f8c2888773461022079b7055d0f6af6952a48e5b97218015b0723462d667765c142b41bd35e3d9c0a01210359e303f57647094a668d69e8ff0bd46c356d00aa7da6dc533c438e71c057f0793e721f00"
        )
        funding_txid = funding_tx.txid()
        wallet.receive_tx_callback(funding_txid, funding_tx,
                                   TX_HEIGHT_UNCONFIRMED)

        cmds = Commands(config=self.config)
        tx = "02000000000101b9723dfc69af058ef6613539a000d2cd098a2c8a74e802b6d8739db708ba8c9a0100000000fdffffff02a00f00000000000016001429e1fd187f0cac845946ae1b11dc136c536bfc0fe8b2000000000000160014100611bcb3aee7aad176936cf4ed56ade03027aa02473044022063c05e2347f16251922830ccc757231247b3c2970c225f988e9204844a1ab7b802204652d2c4816707e3d3bea2609b83b079001a435bad2a99cc2e730f276d07070c012102ee3f00141178006c78b0b458aab21588388335078c655459afe544211f15aee050721f00"
        self.assertEqual(
            "02000000000101b9723dfc69af058ef6613539a000d2cd098a2c8a74e802b6d8739db708ba8c9a0100000000fdffffff02a00f00000000000016001429e1fd187f0cac845946ae1b11dc136c536bfc0f84b2000000000000160014100611bcb3aee7aad176936cf4ed56ade03027aa0247304402203aa63539b673a3bd70a76482b17f35f8843974fab28f84143a00450789010bc40220779c2ce2d0217f973f1f6c9f718e19fc7ebd14dd8821a962f002437cda3082ec012102ee3f00141178006c78b0b458aab21588388335078c655459afe544211f15aee000000000",
            cmds._run('bumpfee', (), tx=tx, new_fee_rate='1.6', wallet=wallet))

        self.assertEqual(
            "02000000000101b9723dfc69af058ef6613539a000d2cd098a2c8a74e802b6d8739db708ba8c9a0100000000fdffffff02a00f00000000000016001429e1fd187f0cac845946ae1b11dc136c536bfc0f84b2000000000000160014100611bcb3aee7aad176936cf4ed56ade03027aa0247304402203aa63539b673a3bd70a76482b17f35f8843974fab28f84143a00450789010bc40220779c2ce2d0217f973f1f6c9f718e19fc7ebd14dd8821a962f002437cda3082ec012102ee3f00141178006c78b0b458aab21588388335078c655459afe544211f15aee000000000",
            cmds._run(
                'bumpfee', (),
                tx=tx,
                new_fee_rate='1.6',
                from_coins=
                "9a8cba08b79d73d8b602e8748a2c8a09cdd200a0393561f68e05af69fc3d72b9:1",
                wallet=wallet))
示例#3
0
    def test_payto(self, mock_save_db):
        wallet = restore_wallet_from_text(
            'disagree rug lemon bean unaware square alone beach tennis exhibit fix mimic',
            gap_limit=2,
            path='if_this_exists_mocking_failed_648151893',
            config=self.config)['wallet']
        # bootstrap wallet
        funding_tx = Transaction(
            '0200000000010165806607dd458280cb57bf64a16cf4be85d053145227b98c28932e953076b8e20000000000fdffffff02ac150700000000001600147e3ddfe6232e448a8390f3073c7a3b2044fd17eb102908000000000016001427fbe3707bc57e5bb63d6f15733ec88626d8188a02473044022049ce9efbab88808720aa563e2d9bc40226389ab459c4390ea3e89465665d593502206c1c7c30a2f640af1e463e5107ee4cfc0ee22664cfae3f2606a95303b54cdef80121026269e54d06f7070c1f967eb2874ba60de550dfc327a945c98eb773672d9411fd77181e00'
        )
        funding_txid = funding_tx.txid()
        self.assertEqual(
            'ede61d39e501d65ccf34e6300da439419c43393f793bb9a8a4b06b2d0d80a8a0',
            funding_txid)
        wallet.receive_tx_callback(funding_txid, funding_tx,
                                   TX_HEIGHT_UNCONFIRMED)

        cmds = Commands(config=self.config)
        tx_str = cmds._run(
            'payto', (),
            destination="tltc1qsyzgpwa0vg2940u5t6l97etuvedr5dejcp84ad",
            amount="0.00123456",
            feerate=50,
            locktime=1972344,
            wallet=wallet)

        tx = tx_from_any(tx_str)
        self.assertEqual(2, len(tx.outputs()))
        txout = TxOutput.from_address_and_value(
            "tltc1qsyzgpwa0vg2940u5t6l97etuvedr5dejcp84ad", 123456)
        self.assertTrue(txout in tx.outputs())
        self.assertEqual(
            "02000000000101a0a8800d2d6bb0a4a8b93b793f39439c4139a40d30e634cf5cd601e5391de6ed0100000000fdffffff0240e2010000000000160014810480bbaf62145abf945ebe5f657c665a3a3732462b060000000000160014a5103285eb519f826520a9f7d3227e1eaa7ec5f802473044022057a6f4b1ec63336c7d0ba233e785ec9f2e2d9c2d67617a50e069f4498ee6a3b7022032fb331e0bef06f46e9cb77bfe94413142653c4912516835e941fa7f170c1a53012103001b55f19541faaf7e6d57dd1bdb9fdc37725fc500e12f2418cc11e0aed4154978181e00",
            tx_str)
示例#4
0
    def test_paytomany_multiple_max_spends(self, mock_save_db):
        wallet = restore_wallet_from_text(
            'kit virtual quantum festival fortune inform ladder saddle filter soldier start ghost',
            gap_limit=2,
            path='if_this_exists_mocking_failed_648151893',
            config=self.config)['wallet']
        # bootstrap wallet
        funding_tx = Transaction(
            '02000000000101f59876b1c65bbe3e182ccc7ea7224fe397bb9b70aadcbbf4f4074c75c8a074840000000000fdffffff021f351f00000000001600144eec851dd980cc36af1f629a32325f511604d6af56732d000000000016001439267bc7f3e3fabeae3bc3f73880de22d8b01ba50247304402207eac5f639806a00878488d58ca651d690292145bca5511531845ae21fab309d102207162708bd344840cc1bacff1092e426eb8484f83f5c068ba4ca579813de324540121020e0798c267ff06ee8b838cd465f3cfa6c843a122a04917364ce000c29ca205cae5f31f00'
        )
        funding_txid = funding_tx.txid()
        self.assertEqual(
            'e8e977bd9c857d84ec1b8f154ae2ee5dfa49fffb7688942a586196c1ad15de15',
            funding_txid)
        wallet.receive_tx_callback(funding_txid, funding_tx,
                                   TX_HEIGHT_UNCONFIRMED)

        cmds = Commands(config=self.config)
        tx_str = cmds._run(
            'paytomany', (),
            outputs=[["tltc1qk3g0t9pw5wctkzz7gh6k3ljfuukn729srkx29s", 0.002],
                     ["tltc1qr7evucrllljtryam6y2k3ntmlptq208p3lzp67", "2!"],
                     ["tltc1qs3msqp0n0qade2haanjw2dkaa5lm77vw4sm3l7", 0.003],
                     ["tltc1qar4ye43tdfj6y5n3yndp9adhs2wuz2v0hqzdyk", "3!"]],
            fee="0.00005000",
            locktime=2094054,
            wallet=wallet)

        tx = tx_from_any(tx_str)
        self.assertEqual(4, len(tx.outputs()))
        self.assertEqual(
            "0200000000010115de15adc19661582a948876fbff49fa5deee24a158f1bec847d859cbd77e9e80100000000fdffffff04400d030000000000160014b450f5942ea3b0bb085e45f568fe49e72d3f28b0e09304000000000016001484770005f3783adcaafdece4e536dded3fbf798e12190f00000000001600141fb2ce607fffe4b193bbd11568cd7bf856053ce19ca5160000000000160014e8ea4cd62b6a65a2527124da12f5b7829dc1298f02473044022079570c62352d7c462ee50851d27f829f7ea5757d258b6b38a6b377a4910ba597022056653f1b15a9693ba790e89ebac60e33b7a1d8357e05cd3d7ecc1ae00e9ab4a8012102eed460ead0cbaa71ad52b70899acf4ea12682ab237207b045c5cf9c6d11c2bcfe6f31f00",
            tx_str)
示例#5
0
def merge_sigs_from_psbt(tx: Transaction, psbt: BasicPSBT):
    # Take new signatures from PSBT, and merge into in-memory transaction object.
    # - "we trust everyone here" ... no validation/checks

    count = 0
    for inp_idx, inp in enumerate(psbt.inputs):
        if not inp.part_sigs:
            continue

        scr = inp.redeem_script or inp.witness_script

        # need to map from pubkey to signing position in redeem script
        M, N, _, pubkeys, _ = parse_redeemScript_multisig(scr)
        #assert (M, N) == (wallet.m, wallet.n)

        for sig_pk in inp.part_sigs:
            pk_pos = pubkeys.index(sig_pk.hex())
            tx.add_signature_to_txin(inp_idx, pk_pos, inp.part_sigs[sig_pk].hex())
            count += 1

        #print("#%d: sigs = %r" % (inp_idx, tx.inputs()[inp_idx]['signatures']))
    
    # reset serialization of TX
    tx.raw = tx.serialize()
    tx.raw_psbt = None

    return count
示例#6
0
    def parse(self, raw, filename=None):
        # auto-detect and decode Base64 and Hex.
        if raw[0:10].lower() == b'70736274ff':
            raw = a2b_hex(raw.strip())
        if raw[0:6] == b'cHNidP':
            raw = b64decode(raw)
        assert raw[0:5] == b'psbt\xff', "bad magic"

        self.filename = filename

        with io.BytesIO(raw[5:]) as fd:

            # globals
            while 1:
                ks = deser_compact_size(fd)
                if ks is None: break

                if ks == 0: break

                key = fd.read(ks)
                vs = deser_compact_size(fd)
                val = fd.read(vs)

                kt = key[0]
                if kt == PSBT_GLOBAL_UNSIGNED_TX:
                    self.txn = val

                    self.parsed_txn = Transaction(val.hex())
                    num_ins = len(self.parsed_txn.inputs())
                    num_outs = len(self.parsed_txn.outputs())

                elif kt == PSBT_GLOBAL_XPUB:
                    # key=(xpub) => val=(path)
                    self.xpubs.append((key, val))
                else:
                    raise ValueError('unknown global key type: 0x%02x' % kt)

            assert self.txn, 'missing reqd section'

            self.inputs = [BasicPSBTInput(fd, idx) for idx in range(num_ins)]
            self.outputs = [
                BasicPSBTOutput(fd, idx) for idx in range(num_outs)
            ]

            sep = fd.read(1)
            assert sep == b''

        return self
 def input_script(self,
                  txin: PartialTxInput,
                  *,
                  estimate_size=False):
     if txin.script_type == 'p2pkh':
         return Transaction.get_preimage_script(txin)
     raise Exception("unsupported type %s" % txin.script_type)
示例#8
0
 def __init__(self, chan: Channel, app: 'ElectrumWindow', **kwargs):
     Popup.__init__(self, **kwargs)
     Logger.__init__(self)
     self.is_closed = chan.is_closed()
     self.can_be_deleted = chan.can_be_deleted()
     self.app = app
     self.chan = chan
     self.title = _('Channel details')
     self.node_id = bh2u(chan.node_id)
     self.channel_id = bh2u(chan.channel_id)
     self.funding_txid = chan.funding_outpoint.txid
     self.short_id = format_short_channel_id(chan.short_channel_id)
     self.capacity = self.app.format_amount_and_units(chan.get_capacity())
     self.state = chan.get_state_for_GUI()
     self.local_ctn = chan.get_latest_ctn(LOCAL)
     self.remote_ctn = chan.get_latest_ctn(REMOTE)
     self.local_csv = chan.config[LOCAL].to_self_delay
     self.remote_csv = chan.config[REMOTE].to_self_delay
     self.initiator = 'Local' if chan.constraints.is_initiator else 'Remote'
     feerate_kw = chan.get_latest_feerate(LOCAL)
     self.feerate = str(quantize_feerate(Transaction.satperbyte_from_satperkw(feerate_kw)))
     self.can_send = self.app.format_amount_and_units(chan.available_to_spend(LOCAL) // 1000)
     self.can_receive = self.app.format_amount_and_units(chan.available_to_spend(REMOTE) // 1000)
     self.is_open = chan.is_open()
     closed = chan.get_closing_height()
     if closed:
         self.closing_txid, closing_height, closing_timestamp = closed
     msg = messages.MSG_NON_TRAMPOLINE_CHANNEL_FROZEN_WITHOUT_GOSSIP
     self.warning = '' if self.app.wallet.lnworker.channel_db or self.app.wallet.lnworker.is_trampoline_peer(chan.node_id) else _('Warning') + ': ' + msg
     self.is_frozen_for_sending = chan.is_frozen_for_sending()
     self.is_frozen_for_receiving = chan.is_frozen_for_receiving()
     self.update_action_dropdown()
示例#9
0
    def tx_inputs(self, tx: Transaction, *, for_sig=False, keystore: 'SafeTKeyStore' = None):
        inputs = []
        for txin in tx.inputs():
            txinputtype = self.types.TxInputType()
            if txin.is_coinbase_input():
                prev_hash = b"\x00"*32
                prev_index = 0xffffffff  # signed int -1
            else:
                if for_sig:
                    assert isinstance(tx, PartialTransaction)
                    assert isinstance(txin, PartialTxInput)
                    assert keystore
                    if len(txin.pubkeys) > 1:
                        xpubs_and_deriv_suffixes = get_xpubs_and_der_suffixes_from_txinout(tx, txin)
                        multisig = self._make_multisig(txin.num_sig, xpubs_and_deriv_suffixes)
                    else:
                        multisig = None
                    script_type = self.get_safet_input_script_type(txin.script_type)
                    txinputtype = self.types.TxInputType(
                        script_type=script_type,
                        multisig=multisig)
                    my_pubkey, full_path = keystore.find_my_pubkey_in_txinout(txin)
                    if full_path:
                        txinputtype._extend_address_n(full_path)

                prev_hash = txin.prevout.txid
                prev_index = txin.prevout.out_idx

            if txin.value_sats() is not None:
                txinputtype.amount = txin.value_sats()
            txinputtype.prev_hash = prev_hash
            txinputtype.prev_index = prev_index

            if txin.script_sig is not None:
                txinputtype.script_sig = txin.script_sig

            txinputtype.sequence = txin.nsequence

            inputs.append(txinputtype)

        return inputs
示例#10
0
    def tx_inputs(self,
                  tx: Transaction,
                  *,
                  for_sig=False,
                  keystore: 'TrezorKeyStore' = None):
        inputs = []
        for txin in tx.inputs():
            if txin.is_coinbase_input():
                txinputtype = TxInputType(
                    prev_hash=b"\x00" * 32,
                    prev_index=0xffffffff,  # signed int -1
                )
            else:
                txinputtype = TxInputType(
                    prev_hash=txin.prevout.txid,
                    prev_index=txin.prevout.out_idx,
                )
                if for_sig:
                    assert isinstance(tx, PartialTransaction)
                    assert isinstance(txin, PartialTxInput)
                    assert keystore
                    if len(txin.pubkeys) > 1:
                        xpubs_and_deriv_suffixes = get_xpubs_and_der_suffixes_from_txinout(
                            tx, txin)
                        txinputtype.multisig = self._make_multisig(
                            txin.num_sig, xpubs_and_deriv_suffixes)
                    txinputtype.script_type = self.get_trezor_input_script_type(
                        txin.script_type)
                    my_pubkey, full_path = keystore.find_my_pubkey_in_txinout(
                        txin)
                    if full_path:
                        txinputtype.address_n = full_path

            txinputtype.amount = txin.value_sats()
            txinputtype.script_sig = txin.script_sig
            txinputtype.sequence = txin.nsequence

            inputs.append(txinputtype)

        return inputs
示例#11
0
def recover_tx_from_psbt(first: BasicPSBT, wallet: Abstract_Wallet) -> Transaction:
    # Take a PSBT object and re-construct the Electrum transaction object.
    # - does not include signatures, see merge_sigs_from_psbt
    # - any PSBT in the group could be used for this purpose; all must share tx details
    
    tx = Transaction(first.txn.hex())
    tx.deserialize(force_full_parse=True)

    # .. add back some data that's been preserved in the PSBT, but isn't part of
    # of the unsigned bitcoin txn
    tx.is_partial_originally = True

    for idx, inp in enumerate(tx.inputs()):
        scr = first.inputs[idx].redeem_script or first.inputs[idx].witness_script

        # XXX should use transaction.py parse_scriptSig() here!
        if scr:
            try:
                M, N, __, pubkeys, __ = parse_redeemScript_multisig(scr)
            except NotRecognizedRedeemScript:
                # limitation: we can only handle M-of-N multisig here
                raise ValueError("Cannot handle non M-of-N multisig input")

            inp['pubkeys'] = pubkeys
            inp['x_pubkeys'] = pubkeys
            inp['num_sig'] = M
            inp['type'] = 'p2wsh' if first.inputs[idx].witness_script else 'p2sh'

            # bugfix: transaction.py:parse_input() puts empty dict here, but need a list
            inp['signatures'] = [None] * N

        if 'prev_tx' not in inp:
            # fetch info about inputs' previous txn
            wallet.add_hw_info(tx)

        if 'value' not in inp:
            # we'll need to know the value of the outpts used as part
            # of the witness data, much later...
            inp['value'] = inp['prev_tx'].outputs()[inp['prevout_n']].value

    return tx
示例#12
0
 def test_verify_ok_t_tx(self):
     """Actually mined 64 byte tx should not raise."""
     t_tx = Transaction(VALID_64_BYTE_TX)
     t_tx_hash = t_tx.txid()
     self.assertEqual(MERKLE_ROOT,
                      SPV.hash_merkle_root(MERKLE_BRANCH, t_tx_hash, 3))
示例#13
0
class BasicPSBT:
    "Just? parse and store"

    def __init__(self):

        self.txn = None
        self.filename = None
        self.parsed_txn = None
        self.xpubs = []

        self.inputs = []
        self.outputs = []

    def __eq__(a, b):
        return a.txn == b.txn and \
            len(a.inputs) == len(b.inputs) and \
            len(a.outputs) == len(b.outputs) and \
            all(a.inputs[i] == b.inputs[i] for i in range(len(a.inputs))) and \
            all(a.outputs[i] == b.outputs[i] for i in range(len(a.outputs))) and \
            sorted(a.xpubs) == sorted(b.xpubs)

    def parse(self, raw, filename=None):
        # auto-detect and decode Base64 and Hex.
        if raw[0:10].lower() == b'70736274ff':
            raw = a2b_hex(raw.strip())
        if raw[0:6] == b'cHNidP':
            raw = b64decode(raw)
        assert raw[0:5] == b'psbt\xff', "bad magic"

        self.filename = filename

        with io.BytesIO(raw[5:]) as fd:

            # globals
            while 1:
                ks = deser_compact_size(fd)
                if ks is None: break

                if ks == 0: break

                key = fd.read(ks)
                vs = deser_compact_size(fd)
                val = fd.read(vs)

                kt = key[0]
                if kt == PSBT_GLOBAL_UNSIGNED_TX:
                    self.txn = val

                    self.parsed_txn = Transaction(val.hex())
                    num_ins = len(self.parsed_txn.inputs())
                    num_outs = len(self.parsed_txn.outputs())

                elif kt == PSBT_GLOBAL_XPUB:
                    # key=(xpub) => val=(path)
                    self.xpubs.append((key, val))
                else:
                    raise ValueError('unknown global key type: 0x%02x' % kt)

            assert self.txn, 'missing reqd section'

            self.inputs = [BasicPSBTInput(fd, idx) for idx in range(num_ins)]
            self.outputs = [
                BasicPSBTOutput(fd, idx) for idx in range(num_outs)
            ]

            sep = fd.read(1)
            assert sep == b''

        return self

    def serialize(self, fd):
        def wr(ktype, val, key=b''):
            fd.write(ser_compact_size(1 + len(key)))
            fd.write(bytes([ktype]) + key)
            fd.write(ser_compact_size(len(val)))
            fd.write(val)

        fd.write(b'psbt\xff')

        wr(PSBT_GLOBAL_UNSIGNED_TX, self.txn)

        for k, v in self.xpubs:
            wr(PSBT_GLOBAL_XPUB, v, key=k)

        # sep
        fd.write(b'\0')

        for idx, inp in enumerate(self.inputs):
            inp.serialize(fd, idx)

        for idx, outp in enumerate(self.outputs):
            outp.serialize(fd, idx)

    def as_bytes(self):
        with io.BytesIO() as fd:
            self.serialize(fd)
            return fd.getvalue()
示例#14
0
    def sign_transaction(self, tx, password):
        if tx.is_complete():
            return
        inputs = []
        inputsPaths = []
        chipInputs = []
        redeemScripts = []
        changePath = ""
        output = None
        p2shTransaction = False
        segwitTransaction = False
        pin = ""
        client_ledger = self.get_client(
        )  # prompt for the PIN before displaying the dialog if necessary
        client_electrum = self.get_client_electrum()
        assert client_electrum

        # Fetch inputs of the transaction to sign
        for txin in tx.inputs():
            if txin.is_coinbase_input():
                self.give_error(
                    "Coinbase not supported")  # should never happen

            if txin.script_type in ['p2sh']:
                p2shTransaction = True

            if txin.script_type in ['p2wpkh-p2sh', 'p2wsh-p2sh']:
                if not client_electrum.supports_segwit():
                    self.give_error(MSG_NEEDS_FW_UPDATE_SEGWIT)
                segwitTransaction = True

            if txin.script_type in ['p2wpkh', 'p2wsh']:
                if not client_electrum.supports_native_segwit():
                    self.give_error(MSG_NEEDS_FW_UPDATE_SEGWIT)
                segwitTransaction = True

            my_pubkey, full_path = self.find_my_pubkey_in_txinout(txin)
            if not full_path:
                self.give_error("No matching pubkey for sign_transaction"
                                )  # should never happen
            full_path = convert_bip32_intpath_to_strpath(full_path)[2:]

            redeemScript = Transaction.get_preimage_script(txin)
            txin_prev_tx = txin.utxo
            if txin_prev_tx is None and not txin.is_segwit():
                raise UserFacingException(
                    _('Missing previous tx for legacy input.'))
            txin_prev_tx_raw = txin_prev_tx.serialize(
            ) if txin_prev_tx else None
            inputs.append([
                txin_prev_tx_raw, txin.prevout.out_idx, redeemScript,
                txin.prevout.txid.hex(), my_pubkey, txin.nsequence,
                txin.value_sats()
            ])
            inputsPaths.append(full_path)

        # Sanity check
        if p2shTransaction:
            for txin in tx.inputs():
                if txin.script_type != 'p2sh':
                    self.give_error(
                        "P2SH / regular input mixed in same transaction not supported"
                    )  # should never happen

        txOutput = var_int(len(tx.outputs()))
        for o in tx.outputs():
            txOutput += int_to_hex(o.value, 8)
            script = o.scriptpubkey.hex()
            txOutput += var_int(len(script) // 2)
            txOutput += script
        txOutput = bfh(txOutput)

        if not client_electrum.supports_multi_output():
            if len(tx.outputs()) > 2:
                self.give_error(
                    "Transaction with more than 2 outputs not supported")
        for txout in tx.outputs():
            if client_electrum.is_hw1(
            ) and txout.address and not is_b58_address(txout.address):
                self.give_error(
                    _("This {} device can only send to base58 addresses.").
                    format(self.device))
            if not txout.address:
                if client_electrum.is_hw1():
                    self.give_error(
                        _("Only address outputs are supported by {}").format(
                            self.device))
                # note: max_size based on https://github.com/LedgerHQ/ledger-app-btc/commit/3a78dee9c0484821df58975803e40d58fbfc2c38#diff-c61ccd96a6d8b54d48f54a3bc4dfa7e2R26
                validate_op_return_output(txout, max_size=190)

        # Output "change" detection
        # - 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:
            has_change = False
            any_output_on_change_branch = is_any_tx_output_on_change_branch(tx)
            for txout in tx.outputs():
                if txout.is_mine and len(tx.outputs()) > 1 \
                        and not has_change:
                    # prioritise hiding outputs on the 'change' branch from user
                    # because no more than one change address allowed
                    if txout.is_change == any_output_on_change_branch:
                        my_pubkey, changePath = self.find_my_pubkey_in_txinout(
                            txout)
                        assert changePath
                        changePath = convert_bip32_intpath_to_strpath(
                            changePath)[2:]
                        has_change = True
                    else:
                        output = txout.address
                else:
                    output = txout.address

        self.handler.show_message(
            _("Confirm Transaction on your Ledger device..."))
        try:
            # Get trusted inputs from the original transactions
            for utxo in inputs:
                sequence = int_to_hex(utxo[5], 4)
                if segwitTransaction and not client_electrum.supports_segwit_trustedInputs(
                ):
                    tmp = bfh(utxo[3])[::-1]
                    tmp += bfh(int_to_hex(utxo[1], 4))
                    tmp += bfh(int_to_hex(utxo[6], 8))  # txin['value']
                    chipInputs.append({
                        'value': tmp,
                        'witness': True,
                        'sequence': sequence
                    })
                    redeemScripts.append(bfh(utxo[2]))
                elif (not p2shTransaction
                      ) or client_electrum.supports_multi_output():
                    txtmp = bitcoinTransaction(bfh(utxo[0]))
                    trustedInput = client_ledger.getTrustedInput(
                        txtmp, utxo[1])
                    trustedInput['sequence'] = sequence
                    if segwitTransaction:
                        trustedInput['witness'] = True
                    chipInputs.append(trustedInput)
                    if p2shTransaction or segwitTransaction:
                        redeemScripts.append(bfh(utxo[2]))
                    else:
                        redeemScripts.append(txtmp.outputs[utxo[1]].script)
                else:
                    tmp = bfh(utxo[3])[::-1]
                    tmp += bfh(int_to_hex(utxo[1], 4))
                    chipInputs.append({'value': tmp, 'sequence': sequence})
                    redeemScripts.append(bfh(utxo[2]))

            # Sign all inputs
            firstTransaction = True
            inputIndex = 0
            rawTx = tx.serialize_to_network()
            client_ledger.enableAlternate2fa(False)
            if segwitTransaction:
                client_ledger.startUntrustedTransaction(
                    True,
                    inputIndex,
                    chipInputs,
                    redeemScripts[inputIndex],
                    version=tx.version)
                # we don't set meaningful outputAddress, amount and fees
                # as we only care about the alternateEncoding==True branch
                outputData = client_ledger.finalizeInput(
                    b'', 0, 0, changePath, bfh(rawTx))
                outputData['outputData'] = txOutput
                if outputData['confirmationNeeded']:
                    outputData['address'] = output
                    self.handler.finished()
                    # do the authenticate dialog and get pin:
                    pin = self.handler.get_auth(outputData,
                                                client=client_electrum)
                    if not pin:
                        raise UserWarning()
                    self.handler.show_message(
                        _("Confirmed. Signing Transaction..."))
                while inputIndex < len(inputs):
                    singleInput = [chipInputs[inputIndex]]
                    client_ledger.startUntrustedTransaction(
                        False,
                        0,
                        singleInput,
                        redeemScripts[inputIndex],
                        version=tx.version)
                    inputSignature = client_ledger.untrustedHashSign(
                        inputsPaths[inputIndex], pin, lockTime=tx.locktime)
                    inputSignature[0] = 0x30  # force for 1.4.9+
                    my_pubkey = inputs[inputIndex][4]
                    tx.add_signature_to_txin(txin_idx=inputIndex,
                                             signing_pubkey=my_pubkey.hex(),
                                             sig=inputSignature.hex())
                    inputIndex = inputIndex + 1
            else:
                while inputIndex < len(inputs):
                    client_ledger.startUntrustedTransaction(
                        firstTransaction,
                        inputIndex,
                        chipInputs,
                        redeemScripts[inputIndex],
                        version=tx.version)
                    # we don't set meaningful outputAddress, amount and fees
                    # as we only care about the alternateEncoding==True branch
                    outputData = client_ledger.finalizeInput(
                        b'', 0, 0, changePath, bfh(rawTx))
                    outputData['outputData'] = txOutput
                    if outputData['confirmationNeeded']:
                        outputData['address'] = output
                        self.handler.finished()
                        # do the authenticate dialog and get pin:
                        pin = self.handler.get_auth(outputData,
                                                    client=client_electrum)
                        if not pin:
                            raise UserWarning()
                        self.handler.show_message(
                            _("Confirmed. Signing Transaction..."))
                    else:
                        # Sign input with the provided PIN
                        inputSignature = client_ledger.untrustedHashSign(
                            inputsPaths[inputIndex], pin, lockTime=tx.locktime)
                        inputSignature[0] = 0x30  # force for 1.4.9+
                        my_pubkey = inputs[inputIndex][4]
                        tx.add_signature_to_txin(
                            txin_idx=inputIndex,
                            signing_pubkey=my_pubkey.hex(),
                            sig=inputSignature.hex())
                        inputIndex = inputIndex + 1
                    firstTransaction = False
        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:
                self.logger.exception('')
                self.give_error(e, True)
        except BaseException as e:
            self.logger.exception('')
            self.give_error(e, True)
        finally:
            self.handler.finished()
示例#15
0
def build_psbt(tx: Transaction, wallet: Abstract_Wallet):
    # Render a PSBT file, for possible upload to Coldcard.
    # 
    # TODO this should be part of Wallet object, or maybe Transaction?

    if getattr(tx, 'raw_psbt', False):
        _logger.info('PSBT cache hit')
        return tx.raw_psbt

    inputs = tx.inputs()
    if 'prev_tx' not in inputs[0]:
        # fetch info about inputs, if needed?
        # - needed during export PSBT flow, not normal online signing
        wallet.add_hw_info(tx)

    # wallet.add_hw_info installs this attr
    assert tx.output_info is not None, 'need data about outputs'

    # Build a map of all pubkeys needed as derivation from master XFP, in PSBT binary format
    # 1) binary version of the common subpath for all keys
    #       m/ => fingerprint LE32
    #       a/b/c => ints
    #
    # 2) all used keys in transaction:
    #    - for all inputs and outputs (when its change back)
    #    - for all keystores, if multisig
    #
    subkeys = {}
    for ks in wallet.get_keystores():

        # XFP + fixed prefix for this keystore
        ks_prefix = packed_xfp_path_for_keystore(ks)

        # all pubkeys needed for input signing
        for xpubkey, derivation in ks.get_tx_derivations(tx).items():
            pubkey = xpubkey_to_pubkey(xpubkey)

            # assuming depth two, non-harded: change + index
            aa, bb = derivation
            assert 0 <= aa < 0x80000000 and 0 <= bb < 0x80000000

            subkeys[bfh(pubkey)] = ks_prefix + pack('<II', aa, bb)

        # all keys related to change outputs
        for o in tx.outputs():
            if o.address in tx.output_info:
                # this address "is_mine" but might not be change (if I send funds to myself)
                output_info = tx.output_info.get(o.address)
                if not output_info.is_change:
                    continue
                chg_path = output_info.address_index
                assert chg_path[0] == 1 and len(chg_path) == 2, f"unexpected change path: {chg_path}"
                pubkey = ks.derive_pubkey(True, chg_path[1])
                subkeys[bfh(pubkey)] = ks_prefix + pack('<II', *chg_path)

    for txin in inputs:
        assert txin['type'] != 'coinbase', _("Coinbase not supported")

        if txin['type'] in ['p2sh', 'p2wsh-p2sh', 'p2wsh']:
            assert type(wallet) is Multisig_Wallet

    # Construct PSBT from start to finish.
    out_fd = io.BytesIO()
    out_fd.write(b'psbt\xff')

    def write_kv(ktype, val, key=b''):
        # serialize helper: write w/ size and key byte
        out_fd.write(my_var_int(1 + len(key)))
        out_fd.write(bytes([ktype]) + key)

        if isinstance(val, str):
            val = bfh(val)

        out_fd.write(my_var_int(len(val)))
        out_fd.write(val)


    # global section: just the unsigned txn
    class CustomTXSerialization(Transaction):
        @classmethod
        def input_script(cls, txin, estimate_size=False):
            return ''

    unsigned = bfh(CustomTXSerialization(tx.serialize()).serialize_to_network(witness=False))
    write_kv(PSBT_GLOBAL_UNSIGNED_TX, unsigned)

    if type(wallet) is Multisig_Wallet:

        # always put the xpubs into the PSBT, useful at least for checking
        for xp, ks in zip(wallet.get_master_public_keys(), wallet.get_keystores()):
            ks_prefix = packed_xfp_path_for_keystore(ks)

            write_kv(PSBT_GLOBAL_XPUB, ks_prefix, DecodeBase58Check(xp))

    # end globals section
    out_fd.write(b'\x00')

    # inputs section
    for txin in inputs:
        if Transaction.is_segwit_input(txin):
            utxo = txin['prev_tx'].outputs()[txin['prevout_n']]
            spendable = txin['prev_tx'].serialize_output(utxo)
            write_kv(PSBT_IN_WITNESS_UTXO, spendable)
        else:
            write_kv(PSBT_IN_NON_WITNESS_UTXO, str(txin['prev_tx']))

        pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin)

        pubkeys = [bfh(k) for k in pubkeys]

        if type(wallet) is Multisig_Wallet:
            # always need a redeem script for multisig
            scr = Transaction.get_preimage_script(txin)

            if Transaction.is_segwit_input(txin):
                # needed for both p2wsh-p2sh and p2wsh
                write_kv(PSBT_IN_WITNESS_SCRIPT, bfh(scr))
            else:
                write_kv(PSBT_IN_REDEEM_SCRIPT, bfh(scr))

        sigs = txin.get('signatures')

        for pk_pos, (pubkey, x_pubkey) in enumerate(zip(pubkeys, x_pubkeys)):
            if pubkey in subkeys:
                # faster? case ... calculated above
                write_kv(PSBT_IN_BIP32_DERIVATION, subkeys[pubkey], pubkey)
            else:
                # when an input is partly signed, tx.get_tx_derivations()
                # doesn't include that keystore's value and yet we need it
                # because we need to show a correct keypath... 
                assert x_pubkey[0:2] == 'ff', x_pubkey

                for ks in wallet.get_keystores():
                    d = ks.get_pubkey_derivation(x_pubkey)
                    if d is not None:
                        ks_path = packed_xfp_path_for_keystore(ks, d)
                        write_kv(PSBT_IN_BIP32_DERIVATION, ks_path, pubkey)
                        break
                else:
                    raise AssertionError("no keystore for: %s" % x_pubkey)

            if txin['type'] == 'p2wpkh-p2sh':
                assert len(pubkeys) == 1, 'can be only one redeem script per input'
                pa = hash_160(pubkey)
                assert len(pa) == 20
                write_kv(PSBT_IN_REDEEM_SCRIPT, b'\x00\x14'+pa)

            # optional? insert (partial) signatures that we already have
            if sigs and sigs[pk_pos]:
                write_kv(PSBT_IN_PARTIAL_SIG, bfh(sigs[pk_pos]), pubkey)

        out_fd.write(b'\x00')

    # outputs section
    for o in tx.outputs():
        # can be empty, but must be present, and helpful to show change inputs
        # wallet.add_hw_info() adds some data about change outputs into tx.output_info
        if o.address in tx.output_info:
            # this address "is_mine" but might not be change (if I send funds to myself)
            output_info = tx.output_info.get(o.address)
            if output_info.is_change:
                pubkeys = [bfh(i) for i in wallet.get_public_keys(o.address)]

                # Add redeem/witness script?
                if type(wallet) is Multisig_Wallet:
                    # always need a redeem script for multisig cases
                    scr = bfh(multisig_script([bh2u(i) for i in sorted(pubkeys)], wallet.m))

                    if output_info.script_type == 'p2wsh-p2sh':
                        write_kv(PSBT_OUT_WITNESS_SCRIPT, scr)
                        write_kv(PSBT_OUT_REDEEM_SCRIPT, b'\x00\x20' + sha256(scr))
                    elif output_info.script_type == 'p2wsh':
                        write_kv(PSBT_OUT_WITNESS_SCRIPT, scr)
                    elif output_info.script_type == 'p2sh':
                        write_kv(PSBT_OUT_REDEEM_SCRIPT, scr)
                    else:
                        raise ValueError(output_info.script_type)

                elif output_info.script_type == 'p2wpkh-p2sh':
                    # need a redeem script when P2SH is used to wrap p2wpkh
                    assert len(pubkeys) == 1
                    pa = hash_160(pubkeys[0])
                    write_kv(PSBT_OUT_REDEEM_SCRIPT, b'\x00\x14' + pa)

                # Document change output's bip32 derivation(s)
                for pubkey in pubkeys:
                    sk = subkeys[pubkey]
                    write_kv(PSBT_OUT_BIP32_DERIVATION, sk, pubkey)

        out_fd.write(b'\x00')

    # capture for later use
    tx.raw_psbt = out_fd.getvalue()

    return tx.raw_psbt