Exemple #1
0
 def check_bip143_tx(self, tx_u_hex, tx_s_hex, txs_out_value_scripthex_pair, tx_in_count, tx_out_count, version, lock_time):
     tx_u = Tx.from_hex(tx_u_hex)
     tx_s = Tx.from_hex(tx_s_hex)
     txs_out = [
         TxOut(int(coin_value * 1e8), h2b(script_hex)) for coin_value, script_hex in txs_out_value_scripthex_pair
     ]
     for tx in (tx_u, tx_s):
         self.assertEqual(len(tx.txs_in), tx_in_count)
         self.assertEqual(len(tx.txs_out), tx_out_count)
         self.assertEqual(tx.version, version)
         self.assertEqual(tx.lock_time, lock_time)
         tx.set_unspents(txs_out)
     self.check_unsigned(tx_u)
     self.check_signed(tx_s)
     tx_hex = tx_u.as_hex()
     self.assertEqual(tx_hex, tx_u_hex)
     tx_hex = tx_s.as_hex()
     self.assertEqual(tx_hex, tx_s_hex)
     tx_u_prime = self.unsigned_copy(tx_s)
     tx_hex = tx_u_prime.as_hex()
     self.assertEqual(tx_hex, tx_u_hex)
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_s_hex))), tx_s.w_id())
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_u_hex))), tx_u.w_id())
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_u_hex))), tx_u.id())
     return tx_u, tx_s
Exemple #2
0
 def check_bip143_tx(self, tx_u_hex, tx_s_hex, txs_out_value_scripthex_pair,
                     tx_in_count, tx_out_count, version, lock_time):
     tx_u = Tx.from_hex(tx_u_hex)
     tx_s = Tx.from_hex(tx_s_hex)
     txs_out = [
         TxOut(int(coin_value * 1e8), h2b(script_hex))
         for coin_value, script_hex in txs_out_value_scripthex_pair
     ]
     for tx in (tx_u, tx_s):
         self.assertEqual(len(tx.txs_in), tx_in_count)
         self.assertEqual(len(tx.txs_out), tx_out_count)
         self.assertEqual(tx.version, version)
         self.assertEqual(tx.lock_time, lock_time)
         tx.set_unspents(txs_out)
     self.check_unsigned(tx_u)
     self.check_signed(tx_s)
     tx_hex = tx_u.as_hex()
     self.assertEqual(tx_hex, tx_u_hex)
     tx_hex = tx_s.as_hex()
     self.assertEqual(tx_hex, tx_s_hex)
     tx_u_prime = self.unsigned_copy(tx_s)
     tx_hex = tx_u_prime.as_hex()
     self.assertEqual(tx_hex, tx_u_hex)
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_s_hex))), tx_s.w_id())
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_u_hex))), tx_u.w_id())
     self.assertEqual(b2h_rev(double_sha256(h2b(tx_u_hex))), tx_u.id())
     return tx_u, tx_s
Exemple #3
0
 def test_issue_224(self):
     RAWTX = (
         "010000000002145fea0b000000001976a9144838d8b3588c4c7ba7c1d06f866e9b3739"
         "c6303788ac0000000000000000346a32544553540000000a0000000000000001000000"
         "0005f5e1000000000000000000000000000bebc2000032000000000000271000000000"
     )
     Tx.from_hex(RAWTX)
Exemple #4
0
def main():
    if len(sys.argv) != 4:
        print("usage: %s tx-hex-file-path wif-file-path p2sh-file-path" % sys.argv[0])
        sys.exit(-1)

    # get the tx
    with open(sys.argv[1], "r") as f:
        tx_hex = f.readline().strip()
    tx = Tx.from_hex(tx_hex)

    # get the WIF
    with open(sys.argv[2], "r") as f:
        wif = f.readline().strip()
    assert is_wif_valid(wif)

    # create the p2sh_lookup
    with open(sys.argv[3], "r") as f:
        p2sh_script_hex = f.readline().strip()
    p2sh_script = h2b(p2sh_script_hex)

    # build a dictionary of script hashes to scripts
    p2sh_lookup = build_p2sh_lookup([p2sh_script])

    # sign the transaction with the given WIF
    sign_tx(tx, wifs=[wif], p2sh_lookup=p2sh_lookup)

    bad_signature_count = tx.bad_signature_count()
    print("tx %s now has %d bad signature(s)" % (tx.id(), bad_signature_count))

    include_unspents = (bad_signature_count > 0)
    print("Here is the tx as hex:\n%s" % tx.as_hex(include_unspents=include_unspents))
Exemple #5
0
 def test_sign_bitcoind_partially_signed_2_of_2(self):
     # Finish signing a 2 of 2 transaction, that already has one signature signed by bitcoind
     # This tx can be found on testnet3 blockchain
     # txid: 9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2
     raw_script = (
         "522103e33b41f5ed67a77d4c4c54b3e946bd30d15b8f66e42cb29fde059c168851165521"
         "02b92cb20a9fb1eb9656a74eeb7387636cf64cdf502ff50511830328c1b479986452ae"
     )
     p2sh_lookup = build_p2sh_lookup([h2b(raw_script)])
     partially_signed_raw_tx = (
         "010000000196238f11a5fd3ceef4efd5a186a7e6b9217d900418e72aca917cd6a6e634"
         "e74100000000910047304402201b41b471d9dd93cf97eed7cfc39a5767a546f6bfbf3e"
         "0c91ff9ad23ab9770f1f02205ce565666271d055be1f25a7e52e34cbf659f6c70770ff"
         "59bd783a6fcd1be3dd0147522103e33b41f5ed67a77d4c4c54b3e946bd30d15b8f66e4"
         "2cb29fde059c16885116552102b92cb20a9fb1eb9656a74eeb7387636cf64cdf502ff5"
         "0511830328c1b479986452aeffffffff01a0bb0d00000000001976a9143b3beefd6f78"
         "02fa8706983a76a51467bfa36f8b88ac00000000")
     tx = Tx.from_hex(partially_signed_raw_tx)
     tx_out = TxOut(1000000,
                    h2b("a914a10dfa21ee8c33b028b92562f6fe04e60563d3c087"))
     tx.set_unspents([tx_out])
     key = key_from_text(
         "cThRBRu2jAeshWL3sH3qbqdq9f4jDiDbd1SVz4qjTZD2xL1pdbsx")
     hash160_lookup = build_hash160_lookup([key.secret_exponent()],
                                           [secp256k1_generator])
     self.assertEqual(tx.bad_signature_count(), 1)
     tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
     self.assertEqual(tx.bad_signature_count(), 0)
     self.assertEqual(
         tx.id(),
         "9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2")
Exemple #6
0
 def test_blanked_hash(self):
     tx = Tx.from_hex(
         TX_E1A18B843FC420734DEEB68FF6DF041A2585E1A0D7DBF3B82AAB98291A6D9952_HEX
     )
     self.assertEqual(
         tx.id(),
         "e1a18b843fc420734deeb68ff6df041a2585e1a0d7dbf3b82aab98291a6d9952")
     self.assertEqual(
         b2h(tx.blanked_hash()),
         "909579526c4c2c441687c7478d3f96249724d2ff071d2272b44500d6cf70d5d6")
     tx.txs_in[0].script = b"foo"
     self.assertEqual(
         b2h(tx.blanked_hash()),
         "909579526c4c2c441687c7478d3f96249724d2ff071d2272b44500d6cf70d5d6")
     tx.txs_out[0].coin_value += 1
     self.assertEqual(
         b2h(tx.blanked_hash()),
         "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b"bar"
     self.assertEqual(
         b2h(tx.blanked_hash()),
         "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b""
     self.assertEqual(
         b2h(tx.hash()),
         "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b"foo"
     self.assertEqual(
         b2h(tx.hash()),
         "c91910058722f1c0f52fc5c734939053c9b87882a9c72b609f21632e0bd13751")
Exemple #7
0
 def test_pay_to_script_file(self):
     the_dir = self.set_cache_dir()
     p2sh_file = tempfile.NamedTemporaryFile()
     p2sh_file.write(
         "52210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102c60"
         "47f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee52102f9308a019258"
         "c31049344f85f89d5229b531c845836f99b08601f113bce036f953ae\n".encode("utf8"))
     p2sh_file.write(
         "53210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102c60"
         "47f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee52102f9308a019258"
         "c31049344f85f89d5229b531c845836f99b08601f113bce036f953ae\n".encode("utf8"))
     p2sh_file.flush()
     tx_source_hex = (
         "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0"
         "0ffffffff0200f902950000000017a91415fc0754e73eb85d1cbce08786fadb7320ecb8dc8700f90295"
         "0000000017a914594f349df0bac3084ffea8a477bba5f03dcd45078700000000")
     self.launch_tool("tx -C %s" % tx_source_hex)
     tx_to_sign = (
         "01000000020a316ea8980ef9ba02f4e6637c88229bf059f39b06238d48d06a8e"
         "f672aea2bb0000000000ffffffff0a316ea8980ef9ba02f4e6637c88229bf059"
         "f39b06238d48d06a8ef672aea2bb0100000000ffffffff01f0ca052a01000000"
         "1976a914751e76e8199196d454941c45d1b3a323f1433bd688ac0000000000f9"
         "02950000000017a91415fc0754e73eb85d1cbce08786fadb7320ecb8dc8700f9"
         "02950000000017a914594f349df0bac3084ffea8a477bba5f03dcd450787")
     wifs = ' '.join(Key(_).wif() for _ in (1, 2, 3))
     signed = tempfile.mktemp(suffix=".hex")
     self.launch_tool("tx -a -P %s --db %s %s %s -o %s" % (
         p2sh_file.name, tx_source_hex, tx_to_sign, wifs, signed), env=dict(PYCOIN_CACHE_DIR=the_dir))
     tx = Tx.from_hex(open(signed).read())
     self.assertEqual(tx.id(), "9d991ddccf77e33cb4584e4fc061a36da0da43589232b2e78a1aa0748ac3254b")
Exemple #8
0
def parse_tx(arg, parser, tx_db, network):
    # hex transaction id
    tx = None

    if TX_ID_RE.match(arg):
        if tx_db is None:
            tx_db = create_tx_db(network)
        tx = tx_db.get(h2b_rev(arg))
        if not tx:
            parser.error("can't find Tx with id %s" % arg)
        return tx, tx_db

    # hex transaction data
    try:
        return Tx.from_hex(arg), tx_db
    except Exception:
        pass

    if os.path.exists(arg):
        try:
            with open(arg, "rb") as f:
                if f.name.endswith("hex"):
                    f = io.BytesIO(codecs.getreader("hex_codec")(f).read())
                tx = Tx.parse(f)
                tx.parse_unspents(f)
        except Exception:
            pass

    return tx, tx_db
    def get_transactions(self):
        # Get a list of utxos by scanning the blockchain
        self.utxos = self.rescan(clargs.args.key_search_depth,
                                 clargs.args.search_subaccounts or 0)

        raw_txs = self.sign_utxos()
        return [Tx.from_hex(raw_tx) for raw_tx in raw_txs]
Exemple #10
0
    def get_transactions(self):
        # Get a list of utxos by scanning the blockchain
        keysets = []
        for subaccount in clargs.args.subaccounts2of2:
            user_key = derive_user_key(self.wallets[0], subaccount)
            xpubs = ga_xpub.xpubs_from_mnemonic(self.mnemonic, subaccount,
                                                self.is_testnet)
            addrs = clargs.args.conn.call("addressbook.get_my_addresses",
                                          subaccount)
            pointer = 0
            while len(addrs):
                for a in addrs:
                    pointer = a["pointer"]
                    if a["addr_type"] == "p2sh":
                        a["subaccount"] = subaccount
                        keysets.append(
                            DerivedKeySet2Of2Scan(user_key, xpubs, a,
                                                  self.is_testnet))
                if pointer:
                    addrs = clargs.args.conn.call(
                        "addressbook.get_my_addresses", subaccount, pointer)
                else:
                    addrs = []

        utxos = self.scan_blockchain(keysets, https=True)
        raw_txs = []
        for utxo in utxos:
            tx = utxo.sign(twooftwo=True)
            if tx is not None:
                raw_txs.append(tx)

        return [Tx.from_hex(raw_tx) for raw_tx in raw_txs]
Exemple #11
0
    async def _get_utxos(self, address: str) -> List[Spendable]:
        """ Coroutine. Returns a list of pycoin.tx.Spendable objects for all
        UTXOS associated with the given address

        :param address: an address string to retrieve a balance for
        :returns: Future, a list of pycoin Spendable objects.
        """
        logging.debug("Retrieving utxos for address %s", address)

        result = await self.connection.listen_rpc(self.methods["listunspent"],
                                                  [address])  # type: Dict
        pos_map = {
            unspent["tx_hash"]: unspent["tx_pos"]
            for unspent in result
        }  # type: Dict[str, int]
        futures = [
            self.connection.listen_rpc(self.methods["get"],
                                       [unspent["tx_hash"]])
            for unspent in result
        ]  # type: List[asyncio.Future]
        txs = await asyncio.gather(*futures, loop=self.loop)  # type: List[str]

        utxos = []  # type: List[Spendable]
        for tx_hex in txs:
            tx = Tx.from_hex(tx_hex)  # type: Tx
            vout = pos_map[tx.id()]  # type: int
            spendable = tx.tx_outs_as_spendable()[vout]  # type: Spendable
            utxos.append(spendable)
            logging.debug("Retrieved utxo: %s", spendable)
        return utxos
Exemple #12
0
def test_set_nlocktime(mock_bitcoincore):
    """Test that newly created recovery transactions have nlocktime = current blockheight + 1"""
    mock_bitcoincore.return_value = AuthServiceProxy('testnet_txs')
    estimate = {
        'blocks': 3,
        'feerate': 1,
    }
    mock_bitcoincore.return_value.estimatesmartfee.return_value = estimate

    current_blockheight = 123
    mock_bitcoincore.return_value.getblockcount.return_value = current_blockheight

    destination_address = 'mynHfTyTWyGGB76NBFbfUrTnn8YWQkTJVs'
    args = [
        '--mnemonic-file={}'.format(datafile('mnemonic_6.txt')),
        '--rpcuser=abc',
        '--rpcpassword=abc',
        '2of3',
        '--recovery-mnemonic-file={}'.format(datafile('mnemonic_7.txt')),
        '--rescan',
        '--key-search-depth={}'.format(key_depth),
        '--search-subaccounts={}'.format(sub_depth),
        '--destination-address={}'.format(destination_address),
    ]

    output = get_output(args).strip()
    tx = Tx.from_hex(output)
    assert tx.lock_time == current_blockheight
Exemple #13
0
def parse_tx(arg, parser, tx_db, network):
    # hex transaction id
    tx = None

    if TX_ID_RE.match(arg):
        if tx_db is None:
            tx_db = create_tx_db(network)
        tx = tx_db.get(h2b_rev(arg))
        if not tx:
            parser.error("can't find Tx with id %s" % arg)
        return tx, tx_db

    # hex transaction data
    try:
        return Tx.from_hex(arg), tx_db
    except Exception:
        pass

    if os.path.exists(arg):
        try:
            with open(arg, "rb") as f:
                if f.name.endswith("hex"):
                    f = io.BytesIO(codecs.getreader("hex_codec")(f).read())
                tx = Tx.parse(f)
                tx.parse_unspents(f)
        except Exception:
            pass

    return tx, tx_db
Exemple #14
0
 def test_pay_to_script_file(self):
     the_dir = self.set_cache_dir()
     p2sh_file = tempfile.NamedTemporaryFile()
     p2sh_file.write(
         "52210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102c60"
         "47f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee52102f9308a019258"
         "c31049344f85f89d5229b531c845836f99b08601f113bce036f953ae\n".encode("utf8"))
     p2sh_file.write(
         "53210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817982102c60"
         "47f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee52102f9308a019258"
         "c31049344f85f89d5229b531c845836f99b08601f113bce036f953ae\n".encode("utf8"))
     p2sh_file.flush()
     tx_source_hex = (
         "01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0"
         "0ffffffff0200f902950000000017a91415fc0754e73eb85d1cbce08786fadb7320ecb8dc8700f90295"
         "0000000017a914594f349df0bac3084ffea8a477bba5f03dcd45078700000000")
     self.launch_tool("tx -C %s" % tx_source_hex)
     tx_to_sign = ( "01000000020a316ea8980ef9ba02f4e6637c88229bf059f39b06238d48d06a8e"
         "f672aea2bb0000000000ffffffff0a316ea8980ef9ba02f4e6637c88229bf059"
         "f39b06238d48d06a8ef672aea2bb0100000000ffffffff01f0ca052a01000000"
         "1976a914751e76e8199196d454941c45d1b3a323f1433bd688ac0000000000f9"
         "02950000000017a91415fc0754e73eb85d1cbce08786fadb7320ecb8dc8700f9"
         "02950000000017a914594f349df0bac3084ffea8a477bba5f03dcd450787")
     wifs = ' '.join(Key(_).wif() for _ in (1, 2, 3))
     signed = tempfile.mktemp(suffix=".hex")
     self.launch_tool("tx -a -P %s --db %s %s %s -o %s" % (
         p2sh_file.name, tx_source_hex, tx_to_sign, wifs, signed), env=dict(PYCOIN_CACHE_DIR=the_dir))
     tx = Tx.from_hex(open(signed).read())
     self.assertEqual(tx.id(), "9d991ddccf77e33cb4584e4fc061a36da0da43589232b2e78a1aa0748ac3254b")
Exemple #15
0
def sign(txdata, signatories):
    tx = Tx.from_hex(txdata['tx'])
    for prevout_index, txin in enumerate(tx.txs_in):

        script = hex_to_bytes(txdata['prevout_scripts'][prevout_index])
        script_type = txdata['prevout_script_types'][prevout_index]

        if script_type == SEGWIT:
            value = int(txdata['prevout_values'][prevout_index])
            sighash = tx_segwit_hash(tx, prevout_index, script, value)
        else:
            sighash = to_bytes_32(
                tx.signature_hash(script, prevout_index, SIGHASH_ALL))

        signatures = [
            signatory.get_signature(sighash) for signatory in signatories
        ]

        if script_type == SEGWIT:
            tx.set_witness(prevout_index, [
                b'',
            ] + signatures + [
                script,
            ])
            txin.script = inscript.witness(script)
        else:
            txin.script = inscript.multisig(script, signatures)

    return tx
Exemple #16
0
def main():
    if len(sys.argv) != 4:
        print("usage: %s tx-hex-file-path wif-file-path p2sh-file-path" %
              sys.argv[0])
        sys.exit(-1)

    # get the tx
    with open(sys.argv[1], "r") as f:
        tx_hex = f.readline().strip()
    tx = Tx.from_hex(tx_hex)

    # get the WIF
    with open(sys.argv[2], "r") as f:
        wif = f.readline().strip()
    assert is_wif_valid(wif)

    # create the p2sh_lookup
    with open(sys.argv[3], "r") as f:
        p2sh_script_hex = f.readline().strip()
    p2sh_script = h2b(p2sh_script_hex)

    # build a dictionary of script hashes to scripts
    p2sh_lookup = build_p2sh_lookup([p2sh_script])

    # sign the transaction with the given WIF
    sign_tx(tx, wifs=[wif], p2sh_lookup=p2sh_lookup)

    bad_signature_count = tx.bad_signature_count()
    print("tx %s now has %d bad signature(s)" % (tx.id(), bad_signature_count))

    include_unspents = (bad_signature_count > 0)
    print("Here is the tx as hex:\n%s" %
          tx.as_hex(include_unspents=include_unspents))
Exemple #17
0
 def test_tx_api(self):
     tx = Tx.from_hex(TX_E1A18B843FC420734DEEB68FF6DF041A2585E1A0D7DBF3B82AAB98291A6D9952_HEX)
     # this transaction is a pay-to-hash transaction
     self.assertEqual(tx.id(), "e1a18b843fc420734deeb68ff6df041a2585e1a0d7dbf3b82aab98291a6d9952")
     address = address_for_script(tx.txs_out[0].puzzle_script())
     self.assertEqual(address, "19LemzJ3XPdUxp113uynqCAivDbXZBdBy3")
     address = address_for_script(tx.txs_out[1].puzzle_script())
     self.assertEqual(address, "3KmkA7hvqG2wKkWUGz1BySioUywvcmdPLR")
Exemple #18
0
def prepare_tx_for_signing(hex_tx, tx_inputs):
    logging.info('Preparing tx for signing')
    transaction = Tx.from_hex(hex_tx)
    unspents = [
        TxOut(coin_value=tx_input.coin_value, script=tx_input.script)
        for tx_input in tx_inputs
    ]
    transaction.set_unspents(unspents)
    return transaction
Exemple #19
0
 def test_tx_with_gpg(self):
     gpg_wif = tempfile.NamedTemporaryFile(suffix=".gpg")
     gpg_wif.write(WIF_1_GPG)
     gpg_wif.flush()
     output_file = tempfile.NamedTemporaryFile(suffix=".hex")
     self.launch_tool(args=["tx.py", "5564224b6c01dbc2bfad89bfd8038bc2f4ca6c55eb660511d7151d71e4b94b6d/0/210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac/5000000000", "1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T", "-f", gpg_wif.name, "-g", "--batch --passphrase=foo", "-o", output_file.name])
     d = open(output_file.name).read()
     tx = Tx.from_hex(d)
     self.assertEqual(tx.id(), "c52b0c66cff6147b99acb29389343f6eae68c29faf2186fa8c1613d615b217e8")
Exemple #20
0
    async def do_broadcast(self, obj):
        tx_hex, chg_vout = obj.get("tx_hex"), obj.get("vout")
        if not tx_hex or not chg_vout:
            self.print_json({"error": "Command parameters are not correct"})
            return

        chg_out = Tx.from_hex(tx_hex).txs_out[chg_vout]
        txid = await self.wallet.broadcast(tx_hex, chg_out)
        self.print_json({"txid": txid})
Exemple #21
0
 def test_cache_tx(self):
     the_dir = self.set_cache_dir()
     tx = Tx.from_hex(
         "01000000010000000000000000000000000000000000000000000000000000000000000000"
         "ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a"
         "2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781"
         "e62294721166bf621e73a82cbf2342c858eeac00000000")
     self.launch_tool("tx -C %s --db %s" % (tx.id(), tx.as_hex()), env=dict(PYCOIN_CACHE_DIR=the_dir))
     self.assertTrue(os.path.exists(os.path.join(the_dir, "txs", "%s_tx.bin" % tx.id())))
Exemple #22
0
    def test_mempool_observer(self):
        connection = Mock()
        from pycoin.tx.Tx import Tx
        tx = Tx.from_hex(
            '01000000000101112a649fd72656cf572259cb7cb61bd31ccdbdf0944070e73401565affbe629d0100000000ffffffff02608'
            'de2110000000017a914d52b516c1a094462959ed6facebb94429d2cebf487d3135b0b00000000220020701a8d401c84fb13e6'
            'baf169d59684e17abd9fa216c8cc5b9fc63d622ff8c58d0400473044022006b149e0cf031f57fd443bd1210b381e9b1b15094'
            '57ba1f49e48b803696f56e802203d66bd974ad3ac5b7591cc84e706b78d139c61e2bf1995a89c4dc0758984a2b70148304502'
            '2100fe7275d601080e1870517774a3ad6accaa7f8ad144addec3251e98685d4fefad02207792c2b0ed6ab42ed2ba6d12e6bd3'
            '4db8c6f4ac6f15e604f70ea85a735c450b1016952210375e00eb72e29da82b89367947f29ef34afb75e8654f6ea368e0acdfd'
            '92976b7c2103a1b26313f430c4b15bb1fdce663207659d8cac749a0e53d70eff01874496feff2103c96d495bfdd5ba4145e3e'
            '046fee45e84a8a48ad05bd8dbb395c011a32cf9f88053ae00000000')
        self.loop.run_until_complete(
            self.sut.on_transaction(connection, {'tx': tx}))
        self.assertEqual(tx.w_id(),
                         [x for x in self.mempool_repository.get_txids()][0])
        self.repository.blockchain.get_transactions_by_block_hash.return_value = [], None

        block = Block(1,
                      b'0' * 32,
                      merkle_root=merkle([tx.hash()]),
                      timestamp=123456789,
                      difficulty=3000000,
                      nonce=1 * 137)
        block.txs.append(tx)
        as_bin = block.as_bin()
        Block.from_bin(as_bin)
        block_header = {'block_hash': block.id()}
        self.batcher_factory.add_peer.return_value = async_coro(True)
        self.batcher_factory.inv_item_to_future.return_value = block.as_bin()
        mempool_response = self.mempool_repository.get_raw_mempool(True)

        self.assertEqual(
            {
                '41867301a6cff5c47951aa1a4eef0be910db0cb5f154eaeb469732e1f9b54548':
                {
                    'size': 381,
                    'fee': 0,
                    'modifiedfee': 0,
                    'time': ANY,
                    'height': 0,
                    'descendantcount': 0,
                    'descendantsize': 0,
                    'descendantfees': 0,
                    'ancestorcount': 0,
                    'ancestorsize': 0,
                    'ancestorfees': 0,
                    'depends': []
                }
            }, mempool_response)
        self.repository.blockchain.save_block.side_effect = lambda a: {
            'block_object': Block.from_bin(a['block_bytes'])
        }
        self.repository.blockchain.get_transactions_by_block_hash.return_value = [], None
        self.loop.run_until_complete(self.sut.on_block_header(block_header))
        self.assertEqual(self.mempool_repository.get_raw_mempool(True), {})
        self.assertEqual([x for x in self.mempool_repository.get_txids()], [])
Exemple #23
0
def tx_to_b64(tx_hex):
    # use this to dump raw transactions in the data above
    import io
    tx = Tx.from_hex(tx_hex)
    f = io.BytesIO()
    tx.stream(f)
    d = f.getvalue()
    for idx in range(0, len(d), 45):
        print('"%s"' % binascii.b2a_base64(d[idx:idx+45]).decode("utf8")[:-1])
Exemple #24
0
def tx_to_b64(tx_hex):
    # use this to dump raw transactions in the data above
    import io
    tx = Tx.from_hex(tx_hex)
    f = io.BytesIO()
    tx.stream(f)
    d = f.getvalue()
    for idx in range(0, len(d), 45):
        print('"%s"' % binascii.b2a_base64(d[idx:idx+45]).decode("utf8")[:-1])
    def load_tx(self, txid):
        p = subprocess.Popen(['electrum', 'gettransaction', txid], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        raw_data = p.communicate()[0]

        data = json.loads(raw_data)
        txhex = data['hex']
        tx = Tx.from_hex(txhex)

        return tx
Exemple #26
0
 def tx_for_tx_hash(self, tx_hash):
     """
     Get a Tx by its hash.
     """
     url = "%s/rawtx/%s" % (self.url, b2h_rev(tx_hash))
     d = urlopen(url).read()
     j = json.loads(d.decode("utf8"))
     tx = Tx.from_hex(j.get("rawtx", ""))
     if tx.hash() == tx_hash:
         return tx
Exemple #27
0
    def load_tx(self, txid):
        p = subprocess.Popen(['electrum', 'gettransaction', txid],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        raw_data = p.communicate()[0]

        data = json.loads(raw_data)
        txhex = data['hex']
        tx = Tx.from_hex(txhex)

        return tx
Exemple #28
0
 def test_cache_tx(self):
     the_dir = self.set_cache_dir()
     tx = Tx.from_hex(
         "01000000010000000000000000000000000000000000000000000000000000000000000000"
         "ffffffff0704ffff001d0104ffffffff0100f2052a0100000043410496b538e853519c726a"
         "2c91e61ec11600ae1390813a627c66fb8be7947be63c52da7589379515d4e0a604f8141781"
         "e62294721166bf621e73a82cbf2342c858eeac00000000")
     self.launch_tool("tx -C %s --db %s" % (tx.id(), tx.as_hex()),
                      env=dict(PYCOIN_CACHE_DIR=the_dir))
     self.assertTrue(
         os.path.exists(os.path.join(the_dir, "txs",
                                     "%s_tx.bin" % tx.id())))
Exemple #29
0
def dump_txos(hx, out_num=0):
    from binascii import b2a_hex
    from helpers import into_hex
    from pycoin.tx.Tx import Tx

    t = Tx.from_hex(hx)
    with into_hex() as fd:
        t.txs_out[out_num].stream(fd)

    print('hash160: %s' % b2a_hex(t.txs_out[out_num].hash160()))

    return t
Exemple #30
0
 def test_disassemble(self):
     input_tx = Tx.from_hex(
         "01000000010000000000000000000000000000000000000000000000000000000000000000"
         "ffffffff0704ffff001d0134ffffffff0100f2052a0100000043410411db93e1dcdb8a016b"
         "49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0eaddfb84ccf9744464f82e16"
         "0bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000")
     tx_db = {tx.hash(): tx for tx in [input_tx]}
     tx_to_validate = Tx.from_hex(
         "0100000001c997a5e56e104102fa209c6a852dd90660a20b2d9c352423edce25857fcd3704000000004847304402"
         "204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181522ec8eca07de4860a4"
         "acdd12909d831cc56cbbac4622082221a8768d1d0901ffffffff0200ca9a3b00000000434104ae1a62fe09c5f51b"
         "13905f07f06b99a2f7159b2225f374cd378d71302fa28414e7aab37397f554a7df5f142c21c1b7303b8a0626f1ba"
         "ded5c72a704f7e6cd84cac00286bee0000000043410411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482e"
         "cad7b148a6909a5cb2e0eaddfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3ac00000000")
     tx_to_validate.unspents_from_db(tx_db)
     self.assertEqual(tx_to_validate.id(), "f4184fc596403b9d638783cf57adfe4c75c605f6356fbc91338530e9831e9e16")
     r = annotate_scripts(tx_to_validate, 0)
     EXPECTED = [
         (
             ['--- SIGNATURE SCRIPT START'], 0, 0x47,
             ('[PUSH_71] 304402204e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd410220'
              '181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d0901'),
             [
                 'r: 0x4e45e16932b8af514961a1d3a1a25fdf3f4f7732e9d624c6c61548ab5fb8cd41',
                 's: 0x181522ec8eca07de4860a4acdd12909d831cc56cbbac4622082221a8768d1d09',
                 'z: 0x7a05c6145f10101e9d6325494245adf1297d80f8f38d4d576d57cdba220bcb19',
                 'signature type SIGHASH_ALL',
                 (' sig for 1M6HTkQf7RhsrDLDX7Q6GJkxXbTz8VWxMx 1E5CDVQrLjSqTeqfN5zT2X2DoeYS7od2Mi '
                  '13KiMqUJ7xD6MhUD2k7mKEoZMHDP9HdWwW 12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S')
             ]
         ),
         (
             ['--- PUBLIC KEY SCRIPT START'], 0, 0x41,
             ('[PUSH_65] 0411db93e1dcdb8a016b49840f8c53bc1eb68a382e97b1482ecad7b148a6909a5cb2e0ead'
              'dfb84ccf9744464f82e160bfa9b8b64f9d4c03f999b8643f656b412a3'),
             ['SEC for uncompressed 12cbQLTFMXRnSzktFkuoG3eHoMeFtpTu3S']
         ),
         ([], 0x42, 0xac, 'OP_CHECKSIG', [])]
     self.assertEqual(r, EXPECTED)
Exemple #31
0
 def test_validate(self):
     input_tx = Tx.from_hex(
         "01000000019c97afdf6c9a31ffa86d71ea79a079001e2b59ee408fd418498219400639ac0a01"
         "0000008b4830450220363cffae09599397b21e6d8a8073fb1dfbe06b6acdd0f2f7d3fea86ca9"
         "c3f605022100fa255a6ed23fd825c759ef1a885a31cad0989606ca8a3a16657d50fe3cef5828"
         "014104ff444bac08308b9ec97f56a652ad8866e0ba804da97868909999566cb377f4a2c8f100"
         "0e83b496868f3a282e1a34df78565b65c15c3fa21a0763fd81a3dfbbb6ffffffff02c05eecde"
         "010000001976a914588554e6cc64e7343d77117da7e01357a6111b7988ac404b4c0000000000"
         "1976a914ca6eb218592f289999f13916ee32829ad587dbc588ac00000000")
     tx_to_validate = Tx.from_hex(
         "010000000165148d894d3922ef5ffda962be26016635c933d470c8b0ab7618e869e3f70e3c00"
         "0000008b48304502207f5779ebf4834feaeff4d250898324eb5c0833b16d7af4c1cb0f66f50f"
         "cf6e85022100b78a65377fd018281e77285efc31e5b9ba7cb7e20e015cf6b7fa3e4a466dd195"
         "014104072ad79e0aa38c05fa33dd185f84c17f611e58a8658ce996d8b04395b99c7be36529ca"
         "b7606900a0cd5a7aebc6b233ea8e0fe60943054c63620e05e5b85f0426ffffffff02404b4c00"
         "000000001976a914d4caa8447532ca8ee4c80a1ae1d230a01e22bfdb88ac8013a0de01000000"
         "1976a9149661a79ae1f6d487af3420c13e649d6df3747fc288ac00000000")
     tx_db = {tx.hash(): tx for tx in [input_tx]}
     tx_to_validate.unspents_from_db(tx_db)
     self.assertEqual("OP_DUP OP_HASH160 [d4caa8447532ca8ee4c80a1ae1d230a01e22bfdb] OP_EQUALVERIFY OP_CHECKSIG",
                      BitcoinScriptTools.disassemble(tx_to_validate.txs_out[0].script))
     self.assertEqual(tx_to_validate.id(), "7c4f5385050c18aa8df2ba50da566bbab68635999cc99b75124863da1594195b")
     annotate_scripts(tx_to_validate, 0)
Exemple #32
0
def pycoin_verify_txs(txs, utxos, expect_witness):

    txs = [Tx.from_hex(tx) for tx in txs]

    for tx in txs:
        txs_in = tx.txs_in
        assert len(txs_in) == 1
        txin = txs_in[0]
        if expect_witness:
            assert len(txin.witness) > 1
            assert tx.has_witness_data()
        else:
            assert txin.witness == ()
            assert not tx.has_witness_data()

    assert len(utxos) > 0
    for idx, utxo in enumerate(utxos):
        utxo = ''.join(utxo.split())
        tx = txs[idx]
        txout = Tx.from_hex(utxo).txs_out[:1]
        tx.set_unspents(txout)
        tx.check()
        assert tx.bad_signature_count() == 0
Exemple #33
0
    def __init__(self, txfile):
        self.tx_by_id = {}
        self.txout_by_address = {}
        for line in open(datafile(txfile)).readlines():
            tx = Tx.from_hex(line.strip())
            self.tx_by_id[tx.id()] = tx
            for vout, txout in enumerate(tx.txs_out):
                self.txout_by_address[txout.address('XTN')] = (tx, vout, txout)
        self.imported = {}

        # This is something of a workaround because all the existing tests are based on generating
        # txs where nlocktime was fixed as 0. The code changed to use current blockheight , so by
        # fudging this value to 0 the existing tests don't notice the difference
        self.getblockcount.return_value = 0
Exemple #34
0
 def test_tx_with_gpg(self):
     # binary data with GPG-encrypted WIF KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn for secret exponent 1
     WIF_1_GPG = h2b(
         "8c0d040303026c3030b7518a94eb60c950bc87ab26f0604a37f247f74f88deda10b180bb807"
         "2879b728b8f056808baea0c8e511e7cf2eba77cce937d2f69a67a79e163bf70b57113d27cb6"
         "a1c2390a1e8069b447c34a7c9b5ba268c2beedd85b50")
     gpg_wif = tempfile.NamedTemporaryFile(suffix=".gpg")
     gpg_wif.write(WIF_1_GPG)
     gpg_wif.flush()
     output_file = tempfile.NamedTemporaryFile(suffix=".hex")
     self.launch_tool(args=["tx", "5564224b6c01dbc2bfad89bfd8038bc2f4ca6c55eb660511d7151d71e4b94b6d/0/210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac/5000000000", "1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T", "-f", gpg_wif.name, "-g", "--batch --passphrase=foo", "-o", output_file.name])
     d = open(output_file.name).read()
     tx = Tx.from_hex(d)
     self.assertEqual(tx.id(), "c52b0c66cff6147b99acb29389343f6eae68c29faf2186fa8c1613d615b217e8")
Exemple #35
0
    async def _get_history(self, txids: List[str]) -> List[Tx]:
        """ Coroutine. Returns a list of pycoin.tx.Tx objects
        associated with the given txids.

        :param txids: a list of txid strings to retrieve tx histories for
        :returns: Future, a list of Tx objects
        """
        futures = [
            self.connection.listen_rpc(self.methods["get"], [txid])
            for txid in txids
        ]  # type: str
        results = await asyncio.gather(*futures, loop=self.loop)
        txs = [Tx.from_hex(tx_hex) for tx_hex in results]  # type: List[Tx]
        logging.debug("Retrieved Txs: %s", txs)
        return txs
def txs_from_json(path):
    """
    Read tests from ./data/tx_??valid.json
    Format is an array of arrays
    Inner arrays are either [ "comment" ]
    or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...], serializedTransaction, verifyFlags]
    ... where all scripts are stringified scripts.

    verifyFlags is a comma separated list of script verification flags to apply, or "NONE"
    """
    comments = None
    with open(path, 'r') as f:
        for tvec in json.load(f):
            if len(tvec) == 1:
                comments = tvec[0]
                continue
            assert len(tvec) == 3
            prevouts = tvec[0]
            for prevout in prevouts:
                assert len(prevout) in (3, 4)

            tx_hex = tvec[1]

            flags = parse_flags(tvec[2])
            try:
                tx = Tx.from_hex(tx_hex)
            except:
                print("Cannot parse tx_hex: %s" % tx_hex)
                raise

            spendable_db = {}
            blank_spendable = Spendable(0, b'', b'\0' * 32, 0)
            for prevout in prevouts:
                coin_value = 1000000
                if len(prevout) == 4:
                    coin_value = prevout[3]
                spendable = Spendable(coin_value=coin_value,
                                      script=compile(prevout[2]),
                                      tx_hash=h2b_rev(prevout[0]),
                                      tx_out_index=prevout[1])
                spendable_db[(spendable.tx_hash,
                              spendable.tx_out_index)] = spendable
            unspents = [
                spendable_db.get((tx_in.previous_hash, tx_in.previous_index),
                                 blank_spendable) for tx_in in tx.txs_in
            ]
            tx.set_unspents(unspents)
            yield (tx, flags, comments)
Exemple #37
0
    async def _get_history(self, txids: List[str]) -> List[Tx]:
        """
        Coroutine. Returns a list of pycoin.tx.Tx objects associated
                    with the given txids

        :param txids: a list of txid strings to retrieve tx histories for
        :returns: Future, a list of Tx objects
        """
        results = list()  # type: List[str]
        for txid in txids:
            hex_ = await self.connection.listen_rpc(
                self.methods["get"], [txid])  # type: str
            results.append(hex_)
            logging.debug("Retrieved Tx hex: %s", hex_)
        txs = [Tx.from_hex(tx_hex) for tx_hex in results]  # type: List[Tx]
        return txs
Exemple #38
0
 def test_blanked_hash(self):
     tx = Tx.from_hex(TX_E1A18B843FC420734DEEB68FF6DF041A2585E1A0D7DBF3B82AAB98291A6D9952_HEX)
     self.assertEqual(tx.id(), "e1a18b843fc420734deeb68ff6df041a2585e1a0d7dbf3b82aab98291a6d9952")
     self.assertEqual(
         b2h(tx.blanked_hash()), "909579526c4c2c441687c7478d3f96249724d2ff071d2272b44500d6cf70d5d6")
     tx.txs_in[0].script = b"foo"
     self.assertEqual(
         b2h(tx.blanked_hash()), "909579526c4c2c441687c7478d3f96249724d2ff071d2272b44500d6cf70d5d6")
     tx.txs_out[0].coin_value += 1
     self.assertEqual(
         b2h(tx.blanked_hash()), "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b"bar"
     self.assertEqual(
         b2h(tx.blanked_hash()), "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b""
     self.assertEqual(b2h(tx.hash()), "10d4e87f7bf35f2949e7693e7a4a84189aad8631f0b2b0999e88f7261066cbe5")
     tx.txs_in[0].script = b"foo"
     self.assertEqual(b2h(tx.hash()), "c91910058722f1c0f52fc5c734939053c9b87882a9c72b609f21632e0bd13751")
    def test_compare_cost(self):
        """
        Compare our size estimation with a known transaction. The transaction contains 1 input, 6 outputs, and 1
        OP_RETURN

        Note that the estimation may be off +/- the number of inputs, which is why the estimate was off by 1 in this
        case.
        :return:
        """

        tx = Tx.from_hex(
            '0100000001ae17c5db3174b46ae2bdc911c25df6bc3ce88092256b6f6e564989693ecf67fc030000006b483045022100b0cfd576dd30bbdf6fd11e0d6118c59b6c6f8e7bf6513d323c7f9f5f8296bef102200174a28e28c792425b71155df99ea6110cdb67d3567792f1696e61424c1f67400121037175dfbeecd8b5a54eb5ad9a696f15b7b39da2ea7d67b4cd7a3299bb95e28884ffffffff07be0a0000000000001976a91481c706f7e6b2d9546169c1e76f50a3ee18e1e1d788acbe0a0000000000001976a914c2b9a62457e35bef48ef350a00622b1e63394d4588acbe0a0000000000001976a91481c706f7e6b2d9546169c1e76f50a3ee18e1e1d788acbe0a0000000000001976a914c2b9a62457e35bef48ef350a00622b1e63394d4588acbe0a0000000000001976a914cc0a909c4c83068be8b45d69b60a6f09c2be0fda88ac5627cb1d000000001976a9144103222e7c72b869c5e47bfe86702684531f2c9088ac0000000000000000226a206f308c70afcfcb0311ad0de989b80904fb54d9131fd3ab2187b89ca9601adab000000000')
        s = io.BytesIO()
        tx.stream(s)
        tx_byte_count = len(s.getvalue())

        estimated_byte_count = tx_utils.calculate_raw_tx_size_with_op_return(num_inputs=1, num_outputs=6)
        self.assertEquals(estimated_byte_count, tx_byte_count + 1)
def txs_from_json(path):
    """
    Read tests from ./data/tx_??valid.json
    Format is an array of arrays
    Inner arrays are either [ "comment" ]
    or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...], serializedTransaction, verifyFlags]
    ... where all scripts are stringified scripts.

    verifyFlags is a comma separated list of script verification flags to apply, or "NONE"
    """
    comments = None
    with open(path, 'r') as f:
        for tvec in json.load(f):
            if len(tvec) == 1:
                comments = tvec[0]
                continue
            assert len(tvec) == 3
            prevouts = tvec[0]
            for prevout in prevouts:
                assert len(prevout) in (3, 4)

            tx_hex = tvec[1]

            flag_mask = parse_flags(tvec[2])
            try:
                tx = Tx.from_hex(tx_hex)
            except:
                print("Cannot parse tx_hex: %s" % tx_hex)
                raise

            spendable_db = {}
            blank_spendable = Spendable(0, b'', b'\0' * 32, 0)
            for prevout in prevouts:
                coin_value = 1000000
                if len(prevout) == 4:
                    coin_value = prevout[3]
                spendable = Spendable(coin_value=coin_value,
                                      script=compile(prevout[2]),
                                      tx_hash=h2b_rev(prevout[0]), tx_out_index=prevout[1])
                spendable_db[(spendable.tx_hash, spendable.tx_out_index)] = spendable
            unspents = [
                spendable_db.get((tx_in.previous_hash, tx_in.previous_index), blank_spendable) for tx_in in tx.txs_in]
            tx.set_unspents(unspents)
            yield (tx, flag_mask, comments)
    def test_is_invalid(self):
        for (prevouts, tx_hex, flags) in txs_from_json(TX_INVALID_JSON):
            try:
                tx = Tx.from_hex(tx_hex)
                if not check_transaction(tx):
                    continue
                unspents = [Spendable(coin_value=1000000,
                                  script=compile_script(prevout[2]),
                                  tx_hash=prevout[0], tx_out_index=prevout[1])
                        for prevout in prevouts]
                tx.set_unspents(unspents)

                bs = tx.bad_signature_count()
                self.assertEqual(bs, 0)
            except:
                continue

            self.fail("Invalid transaction: " + tx.id() +
                      " appears to be valid.")
Exemple #42
0
 def test_tx_with_gpg(self):
     # binary data with GPG-encrypted WIF KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sVHnoWn for secret exponent 1
     WIF_1_GPG = h2b(
         "8c0d040303026c3030b7518a94eb60c950bc87ab26f0604a37f247f74f88deda10b180bb807"
         "2879b728b8f056808baea0c8e511e7cf2eba77cce937d2f69a67a79e163bf70b57113d27cb6"
         "a1c2390a1e8069b447c34a7c9b5ba268c2beedd85b50")
     gpg_wif = tempfile.NamedTemporaryFile(suffix=".gpg")
     gpg_wif.write(WIF_1_GPG)
     gpg_wif.flush()
     output_file = tempfile.NamedTemporaryFile(suffix=".hex")
     self.launch_tool(
         args=["tx",
               "5564224b6c01dbc2bfad89bfd8038bc2f4ca6c55eb660511d7151d71e4b94b6d/0/"
               "210279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798ac/5000000000",
               "1KissFDVu2wAYWPRm4UGh5ZCDU9sE9an8T", "-f", gpg_wif.name, "-g", "--batch --passphrase=foo",
               "-o", output_file.name])
     d = open(output_file.name).read()
     tx = Tx.from_hex(d)
     self.assertEqual(tx.id(), "c52b0c66cff6147b99acb29389343f6eae68c29faf2186fa8c1613d615b217e8")
def main():
    if len(sys.argv) != 4:
        print("usage: %s incoming_tx_hex_filename tx_out_index new_address" % sys.argv[0])
        sys.exit(-1)

    with open(sys.argv[1], "r") as f:
        tx_hex = f.readline().strip()

    # get the spendable from the prior transaction
    tx = Tx.from_hex(tx_hex)
    tx_out_index = int(sys.argv[2])
    spendable = tx.tx_outs_as_spendable()[tx_out_index]

    # make sure the address is valid
    payable = sys.argv[3]
    assert is_address_valid(payable)

    # create the unsigned transaction
    tx = create_tx([spendable], [payable])

    print("here is the transaction: %s" % tx.as_hex(include_unspents=True))
    def test_is_valid(self):
        for (prevouts, tx_hex, flags) in txs_from_json(TX_VALID_JSON):
            try:
                tx = Tx.from_hex(tx_hex)
            except:
                self.fail("Cannot parse tx_hex: " + tx_hex)

            if not check_transaction(tx):
                self.fail("check_transaction(tx) = False for valid tx: " +
                          tx_hex)

            unspents = [Spendable(coin_value=1000000,
                                  script=compile_script(prevout[2]),
                                  tx_hash=prevout[0], tx_out_index=prevout[1])
                        for prevout in prevouts]
            tx.set_unspents(unspents)

            bs = tx.bad_signature_count()
            if bs > 0:
                msg = str(tx_hex) + " bad_signature_count() = " + str(bs)
                self.fail(msg)
Exemple #45
0
 def test_sign_bitcoind_partially_signed_2_of_2(self):
     # Finish signing a 2 of 2 transaction, that already has one signature signed by bitcoind
     # This tx can be found on testnet3 blockchain
     # txid: 9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2
     raw_script = ("522103e33b41f5ed67a77d4c4c54b3e946bd30d15b8f66e42cb29fde059c168851165521"
                   "02b92cb20a9fb1eb9656a74eeb7387636cf64cdf502ff50511830328c1b479986452ae")
     p2sh_lookup = build_p2sh_lookup([h2b(raw_script)])
     partially_signed_raw_tx = (
         "010000000196238f11a5fd3ceef4efd5a186a7e6b9217d900418e72aca917cd6a6e634"
         "e74100000000910047304402201b41b471d9dd93cf97eed7cfc39a5767a546f6bfbf3e"
         "0c91ff9ad23ab9770f1f02205ce565666271d055be1f25a7e52e34cbf659f6c70770ff"
         "59bd783a6fcd1be3dd0147522103e33b41f5ed67a77d4c4c54b3e946bd30d15b8f66e4"
         "2cb29fde059c16885116552102b92cb20a9fb1eb9656a74eeb7387636cf64cdf502ff5"
         "0511830328c1b479986452aeffffffff01a0bb0d00000000001976a9143b3beefd6f78"
         "02fa8706983a76a51467bfa36f8b88ac00000000")
     tx = Tx.from_hex(partially_signed_raw_tx)
     tx_out = TxOut(1000000, h2b("a914a10dfa21ee8c33b028b92562f6fe04e60563d3c087"))
     tx.set_unspents([tx_out])
     key = Key.from_text("cThRBRu2jAeshWL3sH3qbqdq9f4jDiDbd1SVz4qjTZD2xL1pdbsx")
     hash160_lookup = build_hash160_lookup([key.secret_exponent()])
     self.assertEqual(tx.bad_signature_count(), 1)
     tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
     self.assertEqual(tx.bad_signature_count(), 0)
     self.assertEqual(tx.id(), "9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2")
Exemple #46
0
def unsignedtx(rawtx):
    # FIXME validate tx is unsigned
    return Tx.from_hex(rawtx)
Exemple #47
0
    def test_bip143_txs(self):
        # these five examples are from BIP 143 at
        # https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki

        tx_u1, tx_s1 = self.check_bip143_tx(
            '0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac11000000',
            '01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3bebf337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede944ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c4518331561406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368da1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000',
            [
                (6.25, "2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac"),
                (6, "00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1")
            ],
            2,
            2,
            1,
            17
        )

        self.assertEqual(b2h(tx_s1.hash_prevouts(SIGHASH_ALL)),
                         "96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37")
        self.assertEqual(b2h(tx_s1.hash_sequence(SIGHASH_ALL)),
                         "52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b")
        self.assertEqual(b2h(tx_s1.hash_outputs(SIGHASH_ALL, 0)),
                         "863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5")

        script = tools.compile("OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG" % b2h(tx_s1.unspents[1].script[2:]))
        self.assertEqual(b2h(tx_s1.segwit_signature_preimage(script=script, tx_in_idx=1, hash_type=SIGHASH_ALL)),
                         "0100000096b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd3752b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3bef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a010000001976a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac0046c32300000000ffffffff863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e51100000001000000")

        self.assertEqual(b2h(to_bytes_32(tx_s1.signature_for_hash_type_segwit(script, 1, 1))),
                         "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670")
        self.check_tx_can_be_signed(tx_u1, tx_s1, [
            0xbbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866,
            0x619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9
        ])

        tx_u2, tx_s2 = self.check_bip143_tx(
            "0100000001db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a54770100000000feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac92040000",
            "01000000000101db6b1b20aa0fd7b23880be2ecbd4a98130974cf4748fb66092ac4d3ceb1a5477010000001716001479091972186c449eb1ded22b78e40d009bdf0089feffffff02b8b4eb0b000000001976a914a457b684d7f0d539a46a45bbc043f35b59d0d96388ac0008af2f000000001976a914fd270b1ee6abcaea97fea7ad0402e8bd8ad6d77c88ac02473044022047ac8e878352d3ebbde1c94ce3a10d057c24175747116f8288e5d794d12d482f0220217f36a485cae903c713331d877c1f64677e3622ad4010726870540656fe9dcb012103ad1d8e89212f0b92c74d23bb710c00662ad1470198ac48c43f7d6f93a2a2687392040000",
            [(10, "a9144733f37cf4db86fbc2efed2500b4f4e49f31202387")],
            1,
            2,
            1,
            1170
        )
        self.check_tx_can_be_signed(
            tx_u2, tx_s2, [0xeb696a065ef48a2192da5b28b694f87544b30fae8327c4510137a922f32c6dcf],
            ["001479091972186c449eb1ded22b78e40d009bdf0089"])

        tx_u3, tx_s3 = self.check_bip143_tx(
            "0100000002fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e0000000000ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac00000000",
            "01000000000102fe3dc9208094f3ffd12645477b3dc56f60ec4fa8e6f5d67c565d1c6b9216b36e000000004847304402200af4e47c9b9629dbecc21f73af989bdaa911f7e6f6c2e9394588a3aa68f81e9902204f3fcf6ade7e5abb1295b6774c8e0abd94ae62217367096bc02ee5e435b67da201ffffffff0815cf020f013ed6cf91d29f4202e8a58726b1ac6c79da47c23d1bee0a6925f80000000000ffffffff0100f2052a010000001976a914a30741f8145e5acadf23f751864167f32e0963f788ac000347304402200de66acf4527789bfda55fc5459e214fa6083f936b430a762c629656216805ac0220396f550692cd347171cbc1ef1f51e15282e837bb2b30860dc77c8f78bc8501e503473044022027dc95ad6b740fe5129e7e62a75dd00f291a2aeb1200b84b09d9e3789406b6c002201a9ecd315dd6a0e632ab20bbb98948bc0c6fb204f2c286963bb48517a7058e27034721026dccc749adc2a9d0d89497ac511f760f45c47dc5ed9cf352a58ac706453880aeadab210255a9626aebf5e29c0e6538428ba0d1dcf6ca98ffdf086aa8ced5e0d0215ea465ac00000000",
            [
                (1.5625, "21036d5c20fa14fb2f635474c1dc4ef5909d4568e5569b79fc94d3448486e14685f8ac"),
                (49, "00205d1b56b63d714eebe542309525f484b7e9d6f686b3781b6f61ef925d66d6f6a0")
            ],
            2,
            1,
            1,
            0
        )

        tx_u4, tx_s4 = self.check_bip143_tx(
            "0100000002e9b542c5176808107ff1df906f46bb1f2583b16112b95ee5380665ba7fcfc0010000000000ffffffff80e68831516392fcd100d186b3c2c7b95c80b53c77e77c35ba03a66b429a2a1b0000000000ffffffff0280969800000000001976a914de4b231626ef508c9a74a8517e6783c0546d6b2888ac80969800000000001976a9146648a8cd4531e1ec47f35916de8e259237294d1e88ac00000000",
            "01000000000102e9b542c5176808107ff1df906f46bb1f2583b16112b95ee5380665ba7fcfc0010000000000ffffffff80e68831516392fcd100d186b3c2c7b95c80b53c77e77c35ba03a66b429a2a1b0000000000ffffffff0280969800000000001976a914de4b231626ef508c9a74a8517e6783c0546d6b2888ac80969800000000001976a9146648a8cd4531e1ec47f35916de8e259237294d1e88ac02483045022100f6a10b8604e6dc910194b79ccfc93e1bc0ec7c03453caaa8987f7d6c3413566002206216229ede9b4d6ec2d325be245c5b508ff0339bf1794078e20bfe0babc7ffe683270063ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac024730440220032521802a76ad7bf74d0e2c218b72cf0cbc867066e2e53db905ba37f130397e02207709e2188ed7f08f4c952d9d13986da504502b8c3be59617e043552f506c46ff83275163ab68210392972e2eb617b2388771abe27235fd5ac44af8e61693261550447a4c3e39da98ac00000000",
            [
                (0.16777215, "0020ba468eea561b26301e4cf69fa34bde4ad60c81e70f059f045ca9a79931004a4d"),
                (0.16777215, "0020d9bbfbe56af7c4b7f960a70d7ea107156913d9e5a26b0a71429df5e097ca6537"),
            ],
            2,
            2,
            1,
            0
        )

        tx_u5, tx_s5 = self.check_bip143_tx(
            "010000000136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e0100000000ffffffff0200e9a435000000001976a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac00000000",
            "0100000000010136641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e0100000023220020a16b5755f7f6f96dbd65f5f0d6ab9418b89af4b1f14a1bb8a09062c35f0dcb54ffffffff0200e9a435000000001976a914389ffce9cd9ae88dcc0631e88a821ffdbe9bfe2688acc0832f05000000001976a9147480a33f950689af511e6e84c138dbbd3c3ee41588ac080047304402206ac44d672dac41f9b00e28f4df20c52eeb087207e8d758d76d92c6fab3b73e2b0220367750dbbe19290069cba53d096f44530e4f98acaa594810388cf7409a1870ce01473044022068c7946a43232757cbdf9176f009a928e1cd9a1a8c212f15c1e11ac9f2925d9002205b75f937ff2f9f3c1246e547e54f62e027f64eefa2695578cc6432cdabce271502473044022059ebf56d98010a932cf8ecfec54c48e6139ed6adb0728c09cbe1e4fa0915302e022007cd986c8fa870ff5d2b3a89139c9fe7e499259875357e20fcbb15571c76795403483045022100fbefd94bd0a488d50b79102b5dad4ab6ced30c4069f1eaa69a4b5a763414067e02203156c6a5c9cf88f91265f5a942e96213afae16d83321c8b31bb342142a14d16381483045022100a5263ea0553ba89221984bd7f0b13613db16e7a70c549a86de0cc0444141a407022005c360ef0ae5a5d4f9f2f87a56c1546cc8268cab08c73501d6b3be2e1e1a8a08824730440220525406a1482936d5a21888260dc165497a90a15669636d8edca6b9fe490d309c022032af0c646a34a44d1f4576bf6a4a74b67940f8faa84c7df9abe12a01a11e2b4783cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae00000000",
            [(9.87654321, "a9149993a429037b5d912407a71c252019287b8d27a587")],
            1,
            2,
            1,
            0
        )

        tx_u5prime = self.unsigned_copy(tx_s5)
        tx_s_hex = tx_s5.as_hex()
        tx_u5prime.set_unspents(tx_s5.unspents)

        ss = ["56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56ae", "0020a16b5755f7f6f96dbd65f5f0d6ab9418b89af4b1f14a1bb8a09062c35f0dcb54"]
        p2sh_lookup = build_p2sh_lookup([h2b(x) for x in ss])
        for se, sighash_type in [
            (0x730fff80e1413068a05b57d6a58261f07551163369787f349438ea38ca80fac6, SIGHASH_ALL),
            (0x11fa3d25a17cbc22b29c44a484ba552b5a53149d106d3d853e22fdd05a2d8bb3, SIGHASH_NONE),
            (0x77bf4141a87d55bdd7f3cd0bdccf6e9e642935fec45f2f30047be7b799120661, SIGHASH_SINGLE),
            (0x14af36970f5025ea3e8b5542c0f8ebe7763e674838d08808896b63c3351ffe49, SIGHASH_ANYONECANPAY|SIGHASH_ALL),
            (0xfe9a95c19eef81dde2b95c1284ef39be497d128e2aa46916fb02d552485e0323, SIGHASH_ANYONECANPAY|SIGHASH_NONE),
            (0x428a7aee9f0c2af0cd19af3cf1c78149951ea528726989b2e83e4778d2c3f890, SIGHASH_ANYONECANPAY|SIGHASH_SINGLE),
        ]:
            tx_u5prime.sign(hash_type=sighash_type, hash160_lookup=build_hash160_lookup([se]), p2sh_lookup=p2sh_lookup)

        self.check_signed(tx_u5prime)
        tx_hex = tx_u5prime.as_hex()
        self.assertEqual(tx_hex, tx_s_hex)

        self.assertEqual(b2h(tx_s5.hash_prevouts(SIGHASH_ALL)),
                         "74afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0")
        self.assertEqual(b2h(tx_s5.hash_sequence(SIGHASH_ALL)),
                         "3bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e70665044")
        self.assertEqual(b2h(tx_s5.hash_outputs(SIGHASH_ALL, 0)),
                         "bc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc")
        self.assertEqual(b2h(tx_s5.hash_outputs(SIGHASH_SINGLE, 0)),
                         "9efe0c13a6b16c14a41b04ebe6a63f419bdacb2f8705b494a43063ca3cd4f708")
        script = tx_s5.txs_in[0].witness[-1]
        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_ALL)),
                         "0100000074afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa03bb13029ce7b1f559ef5e747fcac439f1455a2ec7c5f09b72290795e7066504436641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffffbc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc0000000001000000")

        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_NONE)),
                         "0100000074afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0000000000000000000000000000000000000000000000000000000000000000036641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffff00000000000000000000000000000000000000000000000000000000000000000000000002000000")

        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_SINGLE)),
                         "0100000074afdc312af5183c4198a40ca3c1a275b485496dd3929bca388c4b5e31f7aaa0000000000000000000000000000000000000000000000000000000000000000036641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffff9efe0c13a6b16c14a41b04ebe6a63f419bdacb2f8705b494a43063ca3cd4f7080000000003000000")

        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_ALL | SIGHASH_ANYONECANPAY)),
                         "010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000036641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffffbc4d309071414bed932f98832b27b4d76dad7e6c1346f487a8fdbb8eb90307cc0000000081000000")

        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_NONE | SIGHASH_ANYONECANPAY)),
                         "010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000036641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffff00000000000000000000000000000000000000000000000000000000000000000000000082000000")

        self.assertEqual(b2h(tx_s5.segwit_signature_preimage(script=script, tx_in_idx=0, hash_type=SIGHASH_SINGLE | SIGHASH_ANYONECANPAY)),
                         "010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000036641869ca081e70f394c6948e8af409e18b619df2ed74aa106c1ca29787b96e01000000cf56210307b8ae49ac90a048e9b53357a2354b3334e9c8bee813ecb98e99a7e07e8c3ba32103b28f0c28bfab54554ae8c658ac5c3e0ce6e79ad336331f78c428dd43eea8449b21034b8113d703413d57761b8b9781957b8c0ac1dfe69f492580ca4195f50376ba4a21033400f6afecb833092a9a21cfdf1ed1376e58c5d1f47de74683123987e967a8f42103a6d48b1131e94ba04d9737d61acdaa1322008af9602b3b14862c07a1789aac162102d8b661b0b3302ee2f162b09e07a55ad5dfbe673a9f01d9f0c19617681024306b56aeb168de3a00000000ffffffff9efe0c13a6b16c14a41b04ebe6a63f419bdacb2f8705b494a43063ca3cd4f7080000000083000000")

        tx = Tx.from_hex("010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff0101000000000000000000000000")
        tx.set_witness(0, [h2b(x) for x in [
            "30450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01",
            "02a9781d66b61fb5a7ef00ac5ad5bc6ffc78be7b44a566e3c87870e1079368df4c",
            "ad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e01"
        ]])
        tx = Tx.from_hex("0100000000010169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff01010000000000000000034830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012102a9781d66b61fb5a7ef00ac5ad5bc6ffc78be7b44a566e3c87870e1079368df4c4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0100000000")
        tx_hex = tx.as_hex()
        print(tx)
        print(tx_hex)
        tx = Tx.from_hex("010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff0101000000000000000000000000")
        self.assertEqual(tx_hex, "0100000000010169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff01010000000000000000034830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012102a9781d66b61fb5a7ef00ac5ad5bc6ffc78be7b44a566e3c87870e1079368df4c4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0100000000")

        tx_u6, tx_s6 = self.check_bip143_tx(
            "010000000169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff0101000000000000000000000000",
            "0100000000010169c12106097dc2e0526493ef67f21269fe888ef05c7a3a5dacab38e1ac8387f14c1d000000ffffffff01010000000000000000034830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e012102a9781d66b61fb5a7ef00ac5ad5bc6ffc78be7b44a566e3c87870e1079368df4c4aad4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0100000000",
            [(0.002, "00209e1be07558ea5cc8e02ed1d80c0911048afad949affa36d5c3951e3159dbea19")],
            1,
            1,
            1,
            0
        )

        tx_u7, tx_s7 = self.check_bip143_tx(
            "01000000019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a6628964c1d000000ffffffff0101000000000000000000000000",
            "010000000001019275cb8d4a485ce95741c013f7c0d28722160008021bb469a11982d47a6628964c1d000000ffffffff0101000000000000000007004830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c0395960101022102966f109c54e85d3aee8321301136cedeb9fc710fdef58a9de8a73942f8e567c021034ffc99dd9a79dd3cb31e2ab3e0b09e0e67db41ac068c625cd1f491576016c84e9552af4830450220487fb382c4974de3f7d834c1b617fe15860828c7f96454490edd6d891556dcc9022100baf95feb48f845d5bfc9882eb6aeefa1bc3790e39f59eaa46ff7f15ae626c53e0148304502205286f726690b2e9b0207f0345711e63fa7012045b9eb0f19c2458ce1db90cf43022100e89f17f86abc5b149eba4115d4f128bcf45d77fb3ecdd34f594091340c039596017500000000",
            [(0.002, "00209b66c15b4e0b4eb49fa877982cafded24859fe5b0e2dbfbe4f0df1de7743fd52")],
            1,
            1,
            1,
            0
        )
        print(tx_s7.txs_in[0])
Exemple #48
0
 def unsigned_copy(self, tx):
     tx = Tx.from_hex(tx.as_hex())
     for tx_in in tx.txs_in:
         tx_in.script = b''
         tx_in.witness = []
     return tx
Exemple #49
0
def prepare_tx_for_signing(hex_tx, tx_inputs):
    logging.info('Preparing tx for signing')
    transaction = Tx.from_hex(hex_tx)
    unspents = [TxOut(coin_value=tx_input.coin_value, script=tx_input.script) for tx_input in tx_inputs]
    transaction.set_unspents(unspents)
    return transaction
Exemple #50
0
 def test_tx_api(self):
     tx = Tx.from_hex(TX_E1A18B843FC420734DEEB68FF6DF041A2585E1A0D7DBF3B82AAB98291A6D9952_HEX)
     # this transaction is a pay-to-hash transaction
     self.assertEqual(tx.id(), "e1a18b843fc420734deeb68ff6df041a2585e1a0d7dbf3b82aab98291a6d9952")
     self.assertEqual(tx.txs_out[0].bitcoin_address(), "19LemzJ3XPdUxp113uynqCAivDbXZBdBy3")
     self.assertEqual(tx.txs_out[1].bitcoin_address(), "3KmkA7hvqG2wKkWUGz1BySioUywvcmdPLR")
Exemple #51
0
    def test_issue_39(self):
        """
        See https://github.com/richardkiss/pycoin/issues/39 and
        https://github.com/richardkiss/pycoin/pull/40

        There was a problem validating the following transactions:

        315ac7d4c26d69668129cc352851d9389b4a6868f1509c6c8b66bead11e2619f
        dbf38261224ebff0c455c405e2435cfc69adb6b8a42d7b10674d9a4eb0464dca
        de744408e4198c0a39310c8106d1830206e8d8a5392bcf715c9b5ec97d784edd

        This codes tests this.
        """
        TX_B64_LIST = [
            # some encoded transactions (the three listed above and the three
            # that they depend upon)
            (
                "AQAAAALcOOk1m9faO1g4YgThhtlAhoX0J/XlE2ZttzWqimshaQAAAABqRzBE"
                "AiBdj+6zEkeORo0LUU5j4ROVjXIU+lcqzYcHmn8MwCb8XAIgD6duoFvyQ69t"
                "D5F38kHK9gbQH8/V5i1r77yiTlaeXCcDIQIQChqcosGJMtZXfFjyJVgBhNDg"
                "gibUGVmHSslj48Gy/v/////cOOk1m9faO1g4YgThhtlAhoX0J/XlE2ZttzWq"
                "imshaQEAAABrSDBFAiAIft44cp5tNeT1FVBQGOZZIiAxJztzZpIPOT7jqxe8"
                "HgIhAMpDFkt1fRptEjXxMgDUtfdt2P2k7J/ChUay31sSEejfAyECdZg5E+YA"
                "k7dn6FWXypOX+y9Bjlf5mNavu8U2EWCFscv/////AUCJlQAAAAAAGXapFPzJ"
                "s204z1XX1bTuTd22ssF2EvSMiKwAAAAA"
            ),
            (
                "AQAAAAEtUf3HWib/PGE4Ag4am7QPH6tuOc6W/q4yGMmuA14AqwEAAABrSDBF"
                "AiEA5PGlIZB+UPxE0zEy7pjJcVpk350sKGDj4EdMUhq4U34CIDCvjTUGpTUu"
                "KwVkRazYVaQtNycOlKYpp7KLIYcOxtdhASEDgIxJPwYZkNK+AB5A8EiuiHAy"
                "C3SJXOLZZS88HHPNbyz/////AvCHSwAAAAAAGXapFPzJs204z1XX1bTuTd22"
                "ssF2EvSMiKzwh0sAAAAAABl2qRQzzvYXSdEboq3wkaXgRWeBd/46bYisAAAA"
                "AA=="
            ),
            (
                "AQAAAAJa+fLO2OCiRk98qhSvobvRyPsY3qrl0QEZa1jcIn70rgAAAABqRzBE"
                "AiANKFITbLHEu93eBOx29YHRsyockZFIyF+8D9BWXTWK8wIgNvKqF87Ind6w"
                "A3aigYv3KMRHmSgLnyBExWkad7Dc2WwDIQIQChqcosGJMtZXfFjyJVgBhNDg"
                "gibUGVmHSslj48Gy/v////9a+fLO2OCiRk98qhSvobvRyPsY3qrl0QEZa1jc"
                "In70rgEAAABrSDBFAiEA9APIYMTjztPlIyyzWCXnk3It+vCsLwGWGpN4K0kG"
                "qWMCIGLdifJz5mvPrW8FqLDNJrp7Bma+/Qw9pF2feVcX2lBKAyECdZg5E+YA"
                "k7dn6FWXypOX+y9Bjlf5mNavu8U2EWCFscv/////AaAClAAAAAAAGXapFOUK"
                "XY2jOZUbBAutBFPXxAz9dNPciKwAAAAA"
            ),
            (
                "AQAAAAGfYeIRrb5mi2ycUPFoaEqbONlRKDXMKYFmaW3C1MdaMQAAAABsSTBG"
                "AiEAhIisrGQ/6Sa7DAJtv+pa9nMiHuBTLNAkxlyzDjYvGEQCIQCFH27K+zjJ"
                "ItZHnrCORpOhrBnHvPnUX8mqXy1pGB/4ngEhAhAKGpyiwYky1ld8WPIlWAGE"
                "0OCCJtQZWYdKyWPjwbL+/////wKgxEoAAAAAABl2qRT8ybNtOM9V19W07k3d"
                "trLBdhL0jIisoMRKAAAAAAAZdqkUM872F0nRG6Kt8JGl4EVngXf+Om2IrAAA"
                "AAA="
            ),
            (
                "AQAAAALCBkSoNGHOnUgtcCy8I87ODdMmW1WL56GNNOIWvaccAAAAAABrSDBF"
                "AiAxKffbGKLs4sDhPFwLZvQlHX+Q20uxr0hFzQqtnSQZQAIhAImY0R1z7HrT"
                "Tt4hR0R/3n3eS8LXk14G94/O8Pc7LDlmAyECE2UQ39BTBuo0mCvz395yuOSd"
                "QyqYBb9kUtOZTnkvnRn/////yRF9O6xy+bn8PWf3KNM1uywKHCYWOL0bgEe1"
                "Zd1jGaIAAAAAakcwRAIgRQ7h/BpT6uurhfpEmEE/Xx5OAZdUohj+Euzr3Zg8"
                "mbkCIDxIakZ02TMLAtt5OHKyy0VQw7uywxjyis6540zeNZdJAyED78tvrsro"
                "6386Jta3YJd/I64guTuYS8oof9K4PDGZeHD/////AeD9HAAAAAAAGXapFB0x"
                "6lo758/yr1vtc3EOtvXV9n1wiKwAAAAA"
            ),
            (
                "AQAAAAKerCh2TFeXmFaXU1qdQUucoCL5WRFVNZdvNt1FZgp5XQAAAACMSTBG"
                "AiEAvLz97Qz/zSlKSDrllLRwj73G2B7RfaiR1ZspOG5Ae3kCIQD5ATZgiNvH"
                "X8Tn8Ib8RohgW0HGbPRi00XUcvxCTmybGgFBBCsXId9LDBz91gENMCmVXxRE"
                "ZI+E6QOSkToVTtny7tiOJhmHy/jci4KzQmucvUBotsK5r4CiwjhjOkAAXRD6"
                "SWD/////6864dM1/4fxjvltUc0HJ1da9agsSw4LV3KYhGR7FJ+MBAAAAi0gw"
                "RQIhAJIopjUy7dPOHa+LGTvgM4jfZ8pA522/Jx3+uFC4Lz5IAiBzLNoxejaa"
                "dw1CXwOUuzI4rMl0xsuYC5XQaxZNT2TFzwFBBBPpriULEjb9VdVoC8v3E4is"
                "RMmfQByPCJYadSwK/ZZg9TTFGyDXUwW+dQ9tScDzhMWfdLK9DyV4iAbnYh/S"
                "2cr/////A0BCDwAAAAAAGXapFFzGycfh13x6rrUPhNJNj2ViE7xbiKwACT0A"
                "AAAAABl2qRQhQVEH8cwnc3//rGPcfvakBANJxIistBcsAAAAAAAZdqkUMQV+"
                "QpfDgBAsCQ+ixaUK5Kgl0kOIrAAAAAA="
            ),
            (
                "AQAAAAO1CFlm1mEB3fjCtilQEH+6TbR3UzdJyqafj3mab9Mc6gAAAACKRzBE"
                "AiA8rWZ4BB8YYJp3xtx8jAZdrfQ6B0zjYRdgTS7I5LZF7gIgabCjn9iu9L3n"
                "YvKrdXFJJygtbg6V8iMTLrPh8ghdGvwBQQQrFyHfSwwc/dYBDTAplV8URGSP"
                "hOkDkpE6FU7Z8u7YjiYZh8v43IuCs0JrnL1AaLbCua+AosI4YzpAAF0Q+klg"
                "/////8IGRKg0Yc6dSC1wLLwjzs4N0yZbVYvnoY004ha9pxwAAQAAAItIMEUC"
                "IDNZYWLuCV0nJL6CCGgUfQfNoh0oAACd2lMZn+zJdJCDAiEAqZafa18G1K1x"
                "/6yOvj8h1uAGSM8UjSJJ6479li5sos4BQQTswrqYR5m+x0vFTzgGrrM2k+Gx"
                "gX+hDBAvN8Kq9RRuWdqC4jVNGhGdFD63Ev1TQYXMqvp6b9ztbAZ3ED8i6sFo"
                "/////0Vf19DzvUs2DvFwlVW9viTF+YlXCNYNMD6yUXK9I9RBAgAAAItIMEUC"
                "IQCKbaQY2eH1fsXZFksstrP4B+uxPBwGRe2Wxl7rW5sYGwIgVvVEPdnJNvVj"
                "rh0XZdhqnOAA0Sw39Upqkejrm+yXWnwBQQQ1hDJBuzoTc1ZJ8zyVQjEfRcjW"
                "o8rq3lE+3x3rYZ3Q/9xBEBtsnkFAzps/N8n6C5cK2QAmRGxeGFmbYaGFT5RP"
                "/////wNAQg8AAAAAABl2qRSU70Qwi2d2bI+nKnCP19XGsbSnWoisVEkwAAAA"
                "AAAZdqkUgroT7ai54LzKPXVnWJsPoV6lJ0yIrHjrFQAAAAAAGXapFEFyZV9I"
                "izJXnWmTivO2n9OKDWCdiKwAAAAA"
            ),
            (
                "AQAAAAHBHumhtHyFj2ma501AFchO/RrrfkY1sYTKsJiYe6i5pAEAAADaAEcw"
                "RAIgJQsMj5xe4yyGSQOseNBu7zuQNbdwYRpmu4tyOeVrDhoCIHTRJ5lHr5OH"
                "JsmDYl4nTEMhT2TeEN8tMNtrt/rFLMaHAUgwRQIhAObKZ2o5NubR2aoXKP7q"
                "oNMI3sv4u33Hnxcu1NBCilhoAiAH5OaEGAC5snVQDIWgXXVWICosFmTHHjXg"
                "y5fNwAO5gAFHUiECzr9qtYCUjRRrfMdx2OZGl0NJ09exHz4DKH0Jl6R307kh"
                "A3umUUhbeiyyIhketkpVkm5iu6v+m17SqUiKrVR7IEKCUq7/////An1KDwAA"
                "AAAAGXapFNxnIa33YyARGtMFwzhMdn1LmeGViKxllyYPAAAAABepFNsSg3N8"
                "2T68HrEpjWRKeEbFWm2WhwAAAAA="
            ),
            (
                "AQAAAAHZI2Rm7Gvz7UMEKi20P7AIT5AOxlhwW29S0uFz9EPz1QEAAADaAEgw"
                "RQIhAIX1NZuYzrKUHFAxUNYI6yWMUuzCEapuZOUY6TdCspWaAiAchzgPP6if"
                "WNh0cmVkyW1UpygM/eVa1XrtHepCMhvArAFHMEQCIGLJtKtbyJEaH6iQS+hK"
                "xUlGrWwmqdJScz/JfSZ1Qln6AiBNRC+gswEEMjTNR5uVetqCGJkNL2m6fDfk"
                "DyICU/otoQFHUiECzr9qtYCUjRRrfMdx2OZGl0NJ09exHz4DKH0Jl6R307kh"
                "A3umUUhbeiyyIhketkpVkm5iu6v+m17SqUiKrVR7IEKCUq7/////Aux5CAAA"
                "AAAAGXapFDIKbLrYWAn/2ZTB7ToisbIaZ5DoiKzL5TUPAAAAABepFNsSg3N8"
                "2T68HrEpjWRKeEbFWm2WhwAAAAA="
            ),
            (# 837dea37ddc8b1e3ce646f1a656e79bbd8cc7f558ac56a169626d649ebe2a3ba
                "AQAAAAGsp/O0VlTCMOCIalf7mIwwRO9ej385cm0wXGHV6BiQPAAAAAD9XQEAS"
                "DBFAiABh6+Sjp0VXEsaycHJEYFTI5q6dndPd118H5w+EG/zPAIhAIgisPZY7e"
                "wiJ00LauneEOvy2gaxu9qrpOUOsHjznj14AUcwRAIgeV8PT1lBp3rgMuy54zd"
                "TeI1+tcsMeNgFV11rAKHZv+0CID4fStkzLRQWrgHicDjpRbydtZxzJyijg6bx"
                "7S+5naekAUzJUkEEkbuiUQkSpb032h+1sWcwEOQ9LG2BLFFOkb+p8usSnhwYM"
                "ynbVb2GjiCarC+8Assz2Y/nS/I/DCNdYSax2DNPhkEEhlxAKTpoDLnAIOex4Q"
                "bYwZFtPO+ZqkMaVtJT5pJW2sCe8SKxqYaBiny2JFMvBiwdH4ciCEhhxcMpHM/"
                "+9OxodEEEjSRV0kA+CHCPwfVWAC8bbNg/mS0IUJf5l0qwiiiDjweJb7qwjzlJ"
                "XhX6b61u2/sedU41+hx4RMQfMioYY9RiE1Ou/////wFAQg8AAAAAABl2qRSuV"
                "rTbE1VNMhxALbOWEYeu0bvtW4isAAAAAA=="
            ),
            (# 3c9018e8d5615c306d72397f8f5eef44308c98fb576a88e030c25456b4f3a7ac
             # input of
             # 837dea37ddc8b1e3ce646f1a656e79bbd8cc7f558ac56a169626d649ebe2a3ba
                "AQAAAAGJYyhI+ZcikVcnxcddqNstvxlDQqBCmCj2b/iPqyr31gAAAACLSDBFA"
                "iEAq7yKc/4gVEgL2j8ygdotDFHihBORq9TAn0+QiiA0wY0CIFvJ5NaOr7kY8+"
                "lmIzhkekQZwN4aZQq4mD8dIW4qMdjjAUEEb1XXre/2ARx+rClP5UDFeDC+gOk"
                "1XIOGnJJgpLi/R2ema6y9cLgE3GPVvusUGAKSrX87CDNysdAtejfdl/9cnv//"
                "//8BQEIPAAAAAAAXqRT4FbA22bu85enyoAq9G/PckelVEIcAAAAA"
            )
        ]

        TX_LIST = [Tx.from_hex(b2h(binascii.a2b_base64(b64.encode("utf8")))) for b64 in TX_B64_LIST]
        TX_DB = dict((tx.hash(), tx) for tx in TX_LIST)
        for h in ["315ac7d4c26d69668129cc352851d9389b4a6868f1509c6c8b66bead11e2619f",
                  "dbf38261224ebff0c455c405e2435cfc69adb6b8a42d7b10674d9a4eb0464dca",
                  "de744408e4198c0a39310c8106d1830206e8d8a5392bcf715c9b5ec97d784edd",
                  "485716e53b422aca0fe5b1ded21360695ce5f49255d80e10db56458ed6962ff3",
                  "837dea37ddc8b1e3ce646f1a656e79bbd8cc7f558ac56a169626d649ebe2a3ba"]:
            tx = TX_DB.get(h2b_rev(h))
            self.assertNotEqual(tx, None)
            tx.unspents_from_db(TX_DB)
            for idx, tx_in in enumerate(tx.txs_in):
                self.assertTrue(tx.is_signature_ok(tx_in_idx=idx))
 def tx_for_tx_hash(self, tx_hash):
     "Get a Tx by its hash."
     URL = "https://blockchain.info/rawtx/%s?format=hex" % b2h_rev(tx_hash)
     tx = Tx.from_hex(urlopen(URL).read().decode("utf8"))
     return tx
Exemple #53
0
def tx(rawtx):
    return Tx.from_hex(rawtx)