コード例 #1
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")
コード例 #2
0
def parse_scripts(args):
    scripts = []
    warnings = []

    for p2s in args.pay_to_script or []:
        try:
            scripts.append(h2b(p2s))
        except Exception:
            warnings.append("warning: error parsing pay-to-script value %s" %
                            p2s)

    hex_re = re.compile(r"[0-9a-fA-F]+")
    for f in args.pay_to_script_file or []:
        count = 0
        for l in f:
            try:
                m = hex_re.search(l)
                if m:
                    p2s = m.group(0)
                    scripts.append(h2b(p2s))
                    count += 1
            except Exception:
                warnings.append(
                    "warning: error parsing pay-to-script file %s" % f.name)
        if count == 0:
            warnings.append("warning: no scripts found in %s" % f.name)
    return scripts, warnings
コード例 #3
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
コード例 #4
0
def tx_from_json_dict(r):
    version = r.get("version")
    lock_time = r.get("locktime")
    txs_in = []
    for vin in r.get("vin"):
        if "coinbase" in vin:
            previous_hash = b'\0' * 32
            script = h2b(vin.get("coinbase"))
            previous_index = 4294967295
        else:
            previous_hash = h2b_rev(vin.get("txid"))
            scriptSig = vin.get("scriptSig")
            if "hex" in scriptSig:
                script = h2b(scriptSig.get("hex"))
            else:
                script = tools.compile(scriptSig.get("asm"))
            previous_index = vin.get("vout")
        sequence = vin.get("sequence")
        txs_in.append(TxIn(previous_hash, previous_index, script, sequence))
    txs_out = []
    for vout in r.get("vout"):
        coin_value = btc_to_satoshi(decimal.Decimal(vout.get("value")))
        script = tools.compile(vout.get("scriptPubKey").get("asm"))
        txs_out.append(TxOut(coin_value, script))
    tx = Tx(version, txs_in, txs_out, lock_time)
    bh = r.get("blockhash")
    if bh:
        bh = h2b_rev(bh)
    tx.confirmation_block_hash = bh
    return tx
コード例 #5
0
ファイル: key_test.py プロジェクト: mewald55/pycoin_ypub-zpub
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec,
                    address_b58, c_address_b58):

            secret_exponent = int(exp_hex, 16)
            sec = h2b(public_pair_sec)
            c_sec = h2b(c_public_pair_sec)

            keys_wif = [
                Key(secret_exponent=secret_exponent),
                Key.from_text(wif),
                Key.from_text(c_wif),
            ]

            key_sec = Key.from_sec(sec)
            key_sec_c = Key.from_sec(c_sec)
            keys_sec = [key_sec, key_sec_c]

            for key in keys_wif:
                self.assertEqual(key.secret_exponent(), secret_exponent)
                self.assertEqual(key.public_copy().secret_exponent(), None)
                repr(key)
                if key._prefer_uncompressed:
                    self.assertEqual(key.wif(), wif)
                else:
                    self.assertEqual(key.wif(), c_wif)
                self.assertEqual(key.wif(use_uncompressed=True), wif)
                self.assertEqual(key.wif(use_uncompressed=False), c_wif)

            for key in keys_wif + keys_sec:
                if key._prefer_uncompressed:
                    self.assertEqual(key.sec(), sec)
                else:
                    self.assertEqual(key.sec(), c_sec)
                self.assertEqual(key.sec(use_uncompressed=True), sec)
                self.assertEqual(key.sec(use_uncompressed=False), c_sec)
                if key._prefer_uncompressed:
                    self.assertEqual(key.address(), address_b58)
                else:
                    self.assertEqual(key.address(), c_address_b58)
                self.assertEqual(key.address(use_uncompressed=False),
                                 c_address_b58)
                self.assertEqual(key.address(use_uncompressed=True),
                                 address_b58)

            key_pub = Key.from_text(address_b58, is_compressed=False)
            key_pub_c = Key.from_text(c_address_b58, is_compressed=True)

            self.assertEqual(key_pub.address(), address_b58)
            self.assertEqual(key_pub.address(use_uncompressed=True),
                             address_b58)
            self.assertEqual(key_pub.address(use_uncompressed=False), None)

            self.assertEqual(key_pub_c.address(), c_address_b58)
            self.assertEqual(key_pub_c.address(use_uncompressed=True), None)
            self.assertEqual(key_pub_c.address(use_uncompressed=False),
                             c_address_b58)
コード例 #6
0
    def test_hash160(self):
        def do_test(blob, expected_hash):
            self.assertEqual(encoding.hash160(blob), expected_hash)

        do_test(b"This is a test",
                h2b("18ac98fa2a2412ddb75de60459b52acd98f2d972"))
        do_test(b"The quick brown fox jumps over the lazy dogs",
                h2b("76c9d1f3aa5226554e20475f919aadd174f7e9b7"))
        do_test(b'\x74' * 10000,
                h2b("a961070296677401a57eae0d96d14d5a880a2c41"))
コード例 #7
0
        def do_test(exp_hex, wif, c_wif, public_pair_sec, c_public_pair_sec,
                    address_b58, c_address_b58):
            secret_exponent = int(exp_hex, 16)
            sec = h2b(public_pair_sec)
            c_sec = h2b(c_public_pair_sec)

            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=False), wif)
            self.assertEqual(
                secret_exponent_to_wif(secret_exponent, compressed=True),
                c_wif)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            exponent, compressed = wif_to_tuple_of_secret_exponent_compressed(
                c_wif)
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = secret_exponent * secp256k1_generator

            pk_public_pair = sec_to_public_pair(sec)
            compressed = is_sec_compressed(sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertFalse(is_sec_compressed(sec))
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=False), sec)

            pk_public_pair = sec_to_public_pair(c_sec)
            compressed = is_sec_compressed(c_sec)
            self.assertEqual(pk_public_pair, public_pair)
            self.assertTrue(compressed)
            self.assertEqual(
                public_pair_to_sec(pk_public_pair, compressed=True), c_sec)

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=True)
            self.assertEqual(bca, c_address_b58)

            self.assertEqual(
                bitcoin_address_to_hash160_sec(c_address_b58),
                public_pair_to_hash160_sec(pk_public_pair, compressed=True))

            bca = public_pair_to_bitcoin_address(pk_public_pair,
                                                 compressed=False)
            self.assertEqual(bca, address_b58)

            self.assertEqual(
                bitcoin_address_to_hash160_sec(address_b58),
                public_pair_to_hash160_sec(pk_public_pair, compressed=False))
コード例 #8
0
    def test_to_from_long(self):
        def do_test(as_int, prefix, as_rep, base):
            self.assertEqual((as_int, prefix),
                             encoding.to_long(base, lambda v: v,
                                              iterbytes(as_rep)))
            self.assertEqual(
                as_rep, encoding.from_long(as_int, prefix, base, lambda v: v))

        do_test(10000101, 2, h2b("00009896e5"), 256)
        do_test(10000101, 3, h2b("0000009896e5"), 256)
        do_test(1460765565493402645157733592332121663123460211377, 1,
                h2b("00ffdefe4f4875cf119fc3d8f4a09ae37ec4cc42b1"), 256)
コード例 #9
0
    def test_to_from_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_bin, encoding.a2b_base58(as_text))
            self.assertEqual(as_text, encoding.b2a_base58(as_bin))

        do_test("1abcdefghijkmnpqrst", h2b("0001935c7cf22ab9be1962aee48c7b"))
        do_test("1CASrvcpMMTa4dz4DmYtAqcegCtdkhjvdn",
                h2b("007a72b6fa63de36c4abc60a68b52d7f33e3d7cd3ec4babd39"))
        do_test("1111111111111111aaaa11aa",
                h2b("00000000000000000000000000000000436e7a51290b"))
        do_test(
            "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",
            h2b("000111d38e5fc9071ffcd20b4a763cc9ae4f252bb4e48fd66a835e252ada93ff480d6d"
                "d43dc62a641155a5"))
コード例 #10
0
def dump_signatures(tx, tx_in, tx_out, idx, netcode, address_prefix,
                    traceback_f, disassembly_level):
    signatures = []
    for opcode in opcode_list(tx_in.script):
        if not opcode.startswith("OP_"):
            try:
                signatures.append(parse_signature_blob(h2b(opcode[1:-1])))
            except UnexpectedDER:
                pass
    if signatures:
        sig_types_identical = (tuple(zip(*signatures))[1].count(
            signatures[0][1]) == len(signatures))
        i = 1 if len(signatures) > 1 else ''
        for sig_pair, sig_type in signatures:
            print("      r{0}: {1:#x}\n      s{0}: {2:#x}".format(
                i, *sig_pair))
            if not sig_types_identical and tx_out:
                print("      z{}: {:#x} {}".format(
                    i, tx.signature_hash(tx_out.script, idx, sig_type),
                    sighash_type_to_string(sig_type)))
            if i:
                i += 1
        if sig_types_identical and tx_out:
            print("      z:{} {:#x} {}".format(
                ' ' if i else '',
                tx.signature_hash(tx_out.script, idx, sig_type),
                sighash_type_to_string(sig_type)))
コード例 #11
0
 def spendables_for_address(self, bitcoin_address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = "https://blockchain.info/unspent?active=%s" % bitcoin_address
     r = json.loads(urlopen(URL).read().decode("utf8"))
     spendables = []
     for u in r["unspent_outputs"]:
         coin_value = u["value"]
         script = h2b(u["script"])
         previous_hash = h2b(u["tx_hash"])
         previous_index = u["tx_output_n"]
         spendables.append(
             Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
コード例 #12
0
    def test_double_sha256(self):
        def do_test(blob, expected_hash):
            self.assertEqual(encoding.double_sha256(blob), expected_hash)

        do_test(
            b"This is a test",
            h2b("eac649d431aa3fc2d5749d1a5021bba7812ec83b8a59fa840bff75c17f8a665c"
                ))
        do_test(
            b"The quick brown fox jumps over the lazy dogs",
            h2b("8a356588797a901a11031779d4787ad0457eb082c56bd9b657157acf31bae6c4"
                ))
        do_test(
            b'\x74' * 10000,
            h2b("6e4d7736aa373c4718eef2b94528fed57519a0bdc3a8f4300aee372cbedea9a0"
                ))
コード例 #13
0
def make_script_test(script_in, script_out, flags_string, comment, expected,
                     coin_value, script_witness):
    script_in_bin = compile(script_in)
    script_out_bin = compile(script_out)
    script_witness_bin = [h2b(w) for w in script_witness]
    flags = parse_flags(flags_string)

    def f(self):
        try:
            credit_tx = build_credit_tx(script_out_bin, coin_value)
            spend_tx = build_spending_tx(script_in_bin, credit_tx)
            spend_tx.txs_in[0].witness = script_witness_bin
            msg = ''
            check_solution(spend_tx, tx_in_idx=0, flags=flags)
            r = 0
        except ScriptError as se:
            r = se.error_code()
            msg = se.args[0]
        except:
            r = -1
        # for now, just deal with 0 versus nonzero
        expect_error = getattr(errno, expected)
        if r != expect_error:
            dump_failure_info(spend_tx, script_in, script_out, flags,
                              flags_string, expected, r, msg, comment)
        self.assertEqual(r, expect_error)

    return f
コード例 #14
0
 def test_h2b(self):
     h = "000102"
     b = b"\x00\x01\x02"
     self.assertEqual(h2b(h), b)
     self.assertEqual(b2h(b), h)
     self.assertEqual(h2b_rev(h), b[::-1])
     self.assertEqual(b2h_rev(b), "020100")
コード例 #15
0
    def test_block_dump(self):
        block_hex = (
            '01000000bddd99ccfda39da1b108ce1a5d70038d0a967bacb68b6b63065f626a000000'
            '0044f672226090d85db9a9f2fbfe5f0f9609b387af7be5b7fbb7a1767c831c9e995dbe'
            '6649ffff001d05e0ed6d01010000000100000000000000000000000000000000000000'
            '00000000000000000000000000ffffffff0704ffff001d010effffffff0100f2052a01'
            '00000043410494b9d3e76c5b1629ecf97fff95d7a4bbdac87cc26099ada28066c6ff1e'
            'b9191223cd897194a08d0c2726c5747f1db49e8cf90e75dc3e3550ae9b30086f3cd5aa'
            'ac00000000')
        block_bin = h2b(block_hex)
        block_file = tempfile.NamedTemporaryFile()
        block_file.write(block_bin)
        block_file.flush()
        output = self.launch_tool("block %s" % block_file.name)
        self.assertEqual(output, """215 bytes   block hash 0000000082b5015589a3fdf2d4baff403e6f0be035a5d9742c1cae6295464449
version 1
prior block hash 000000006a625f06636b8bb6ac7b960a8d03705d1ace08b1a19da3fdcc99ddbd
merkle root 44f672226090d85db9a9f2fbfe5f0f9609b387af7be5b7fbb7a1767c831c9e99
timestamp 2009-01-09T03:02:53
difficulty 486604799
nonce 1844305925
1 transaction
Tx #0:
Version:  1  tx hash 999e1c837c76a1b7fbb7e57baf87b309960f5ffefbf2a9b95dd890602272f644  134 bytes
TxIn count: 1; TxOut count: 1
Lock time: 0 (valid anytime)
Input:
   0: COINBASE   50000.00000 mBTC
Output:
   0: 1FvzCLoTPGANNjWoUo6jUGuAG3wg1w4YjR receives  50000.00000 mBTC
Total input   50000.00000 mBTC
Total output  50000.00000 mBTC
Total fees        0.00000 mBTC

""")
コード例 #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))
コード例 #17
0
    def test_p2sh_multisig_sequential_signing(self):
        raw_scripts = [
            h2b("52210234abcffd2e80ad01c2ec0276ad02682808169c6fafdd25ebfb60703df272b461"
                "2102e5baaafff8094e4d77ce8b009d5ebc3de9110085ebd3d96e50cc7ce70faf175221"
                "0316ee25e80eb6e6fc734d9c86fa580cbb9c4bfd94a19f0373a22353ececd4db6853ae"
                )
        ]
        txs_in = [
            TxIn(previous_hash=h2b(
                '43c95d14724437bccc102ccf86aba1ac02415524fd1aefa787db886bba52a10c'
            ),
                 previous_index=0)
        ]
        txs_out = [
            TxOut(10000,
                  standard_tx_out_script('3KeGeLFmsbmbVdeMLrWp7WYKcA3tdsB4AR'))
        ]
        spendable = {
            'script_hex':
            'a914c4ed4de526461e3efbb79c8b688a6f9282c0464687',
            'does_seem_spent':
            0,
            'block_index_spent':
            0,
            'coin_value':
            10000,
            'block_index_available':
            0,
            'tx_out_index':
            0,
            'tx_hash_hex':
            '0ca152ba6b88db87a7ef1afd24554102aca1ab86cf2c10ccbc374472145dc943'
        }

        tx__prototype = Tx(version=DEFAULT_VERSION,
                           txs_in=txs_in,
                           txs_out=txs_out,
                           unspents=[Spendable.from_dict(spendable)])
        key_1 = 'Kz6pytJCigYHeMsGLmfHQPJhN5og2wpeSVrU43xWwgHLCAvpsprh'
        key_2 = 'Kz7NHgX7MBySA3RSKj9GexUSN6NepEDoPNugSPr5absRDoKgn2dT'
        for ordered_keys in [(key_1, key_2), (key_2, key_1)]:
            tx = copy.deepcopy(tx__prototype)
            for key in ordered_keys:
                self.assertEqual(tx.bad_signature_count(), 1)
                tx.sign(LazySecretExponentDB([key], {}),
                        p2sh_lookup=build_p2sh_lookup(raw_scripts))
            self.assertEqual(tx.bad_signature_count(), 0)
コード例 #18
0
 def spendable_for_row(r):
     return Spendable(coin_value=r[2],
                      script=h2b(r[3]),
                      tx_hash=h2b_rev(r[0]),
                      tx_out_index=r[1],
                      block_index_available=r[4],
                      does_seem_spent=r[5],
                      block_index_spent=r[6])
コード例 #19
0
    def test_to_from_hashed_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_text, encoding.b2a_hashed_base58(as_bin))
            self.assertEqual(as_bin, encoding.a2b_hashed_base58(as_text))
            self.assertTrue(encoding.is_hashed_base58_valid(as_text))
            bogus_text = as_text[:-1] + chr(1 + ord(as_text[-1]))
            self.assertFalse(encoding.is_hashed_base58_valid(bogus_text))

        do_test("14nr3dMd4VwNpFhFECU1A6imi",
                h2b("0001935c7cf22ab9be1962aee48c7b"))
        do_test("1CASrvcpMMTa4dz4DmYtAqcegCtdkhjvdn",
                h2b("007a72b6fa63de36c4abc60a68b52d7f33e3d7cd3e"))
        do_test("11111111111111114njGbaozZJui9o",
                h2b("00000000000000000000000000000000436e7a51290b"))
        do_test(
            "1mLRia5CbfDB9752zxvtrpnkigecaYWUSQNLJGECA8641ywusqomjhfdb6EM7bXGj1Gb",
            h2b("000111d38e5fc9071ffcd20b4a763cc9ae4f252bb4e48fd66a835e252ada93ff480d6dd43dc62a641155a561616161"
                ))
コード例 #20
0
    def test_PeerAddress(self):
        pa = PeerAddress(188, IP4_HEADER + h2b("c0a80163"), 8333)
        pa_bytes = to_bin(pa)
        pa1 = from_bin(PeerAddress, pa_bytes)
        self.assertEqual(pa, pa1)

        pa2 = PeerAddress(188, IP4_HEADER + h2b("c0a80162"), 8333)
        self.assertTrue(pa1 > pa2)
        self.assertTrue(pa1 >= pa2)
        self.assertTrue(pa2 < pa1)
        self.assertTrue(pa2 <= pa1)
        self.assertNotEqual(pa2, pa1)
        self.assertNotEqual(pa1, pa2)
        self.assertEqual(pa1.host(), "192.168.1.99")
        self.assertEqual(repr(pa1), "192.168.1.99/8333")

        pa_v6 = PeerAddress(945, h2b("2607f8b04006080a000000000000200e"), 8333)
        self.assertEqual(pa_v6.host(), "2607:f8b0:4006:80a:0:0:0:200e")
コード例 #21
0
 def test_sec(self):
     pair_blob = h2b(
         "0679be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483a"
         "da7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
     encoding.sec_to_public_pair(pair_blob, strict=False)
     try:
         encoding.sec_to_public_pair(pair_blob, strict=True)
         self.fail("sec_to_public_pair unexpectedly succeeded")
     except encoding.EncodingError:
         pass
コード例 #22
0
def parse_key(item, PREFIX_TRANSFORMS, network):

    key = parse_prefixes(item, PREFIX_TRANSFORMS)
    if key:
        return key

    if HASH160_RE.match(item):
        return Key(hash160=h2b(item), netcode=network)

    secret_exponent = parse_as_secret_exponent(item)
    if secret_exponent:
        return Key(secret_exponent=secret_exponent, netcode=network)

    if SEC_RE.match(item):
        return Key.from_sec(h2b(item))

    public_pair = parse_as_public_pair(item)
    if public_pair:
        return Key(public_pair=public_pair, netcode=network)

    return None
コード例 #23
0
 def tx_for_tx_hash(self, tx_hash):
     """
     returns the pycoin.tx object for tx_hash
     """
     try:
         url_append = "?token=%s&includeHex=true" % self.api_key
         url = self.base_url("txs/%s%s" % (b2h_rev(tx_hash), url_append))
         result = json.loads(urlopen(url).read().decode("utf8"))
         tx = Tx.parse(io.BytesIO(h2b(result.get("hex"))))
         return tx
     except:
         raise Exception
コード例 #24
0
 def test_testnet(self):
     # WARNING: these values have not been verified independently. TODO: do so
     master = BIP32Node.from_master_secret(
         h2b("000102030405060708090a0b0c0d0e0f"), netcode='XTN')
     self.assertEqual(
         master.wallet_key(as_private=True),
         "tprv8ZgxMBicQKsPeDgjzdC36fs6bMjGApWDNLR9erAXMs5skhMv36j9MV5ecvfavji5kh"
         "qjWaWSFhN3YcCUUdiKH6isR4Pwy3U5y5egddBr16m")
     self.assertEqual(master.bitcoin_address(),
                      "mkHGce7dctSxHgaWSSbmmrRWsZfzz7MxMk")
     self.assertEqual(
         master.wif(),
         "cVPXTF2TnozE1PenpP3x9huctiATZmp27T9Ue1d8nqLSExoPwfN5")
コード例 #25
0
 def check_tx_can_be_signed(self,
                            tx_u,
                            tx_s,
                            private_keys=[],
                            p2sh_values=[]):
     tx_u_prime = self.unsigned_copy(tx_s)
     tx_s_hex = tx_s.as_hex()
     tx_u_prime.set_unspents(tx_s.unspents)
     tx_u_prime.sign(hash160_lookup=LazySecretExponentDB(
         [Key(pk).wif() for pk in private_keys], {}),
                     p2sh_lookup=build_p2sh_lookup(
                         [h2b(x) for x in p2sh_values]))
     self.check_signed(tx_u_prime)
     tx_hex = tx_u_prime.as_hex()
     self.assertEqual(tx_hex, tx_s_hex)
コード例 #26
0
 def test_sign(self):
     sv = 33143560198659167577410026742586567991638126035902913554051654024377193788946
     tx_out_script = b'v\xa9\x14\x91\xb2K\xf9\xf5(\x852\x96\n\xc6\x87\xab\xb05\x12{\x1d(\xa5\x88\xac'
     st = script_obj_from_script(tx_out_script)
     hl = build_hash160_lookup([1])
     solution = st.solve(hash160_lookup=hl,
                         signature_for_hash_type_f=const_f(sv),
                         signature_type=SIGHASH_ALL)
     self.assertEqual(
         solution,
         h2b("47304402205e3df5b55be62140042c220b1fdf105cc85113af562a215c1fc5b5c522d1"
             "b3d3022038c9594b156faed7f37c30077affbf6acf42bf17b1e639a1fcc6c51a67aba2"
             "1601410479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f817"
             "98483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
             ))
コード例 #27
0
 def spendable_for_hash_index(self, tx_hash, tx_out_index):
     tx_hash_hex = b2h_rev(tx_hash)
     SQL = ("select coin_value, script, block_index_available, "
            "does_seem_spent, block_index_spent from Spendable where "
            "tx_hash = ? and tx_out_index = ?")
     c = self._exec_sql(SQL, tx_hash_hex, tx_out_index)
     r = c.fetchone()
     if r is None:
         return r
     return Spendable(coin_value=r[0],
                      script=h2b(r[1]),
                      tx_hash=tx_hash,
                      tx_out_index=tx_out_index,
                      block_index_available=r[2],
                      does_seem_spent=r[3],
                      block_index_spent=r[4])
コード例 #28
0
 def spendables_for_address(self, bitcoin_address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = "%s/addr/%s/utxo" % (self.base_url, bitcoin_address)
     r = json.loads(urlopen(URL).read().decode("utf8"))
     spendables = []
     for u in r:
         coin_value = btc_to_satoshi(str(u.get("amount")))
         script = h2b(u.get("scriptPubKey"))
         previous_hash = h2b_rev(u.get("txid"))
         previous_index = u.get("vout")
         spendables.append(
             Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
コード例 #29
0
ファイル: chain_so.py プロジェクト: mewald55/pycoin_ypub-zpub
    def spendables_for_address(self, address):
        """
        Return a list of Spendable objects for the
        given bitcoin address.
        """
        spendables = []
        r = json.loads(urlopen(self.base_url('get_tx_unspent', address)).read().decode("utf8"))

        for u in r['data']['txs']:
            coin_value = int(float(u['value']) * 100000000)
            script = h2b(u["script_hex"])
            previous_hash = h2b_rev(u["txid"])
            previous_index = u["output_no"]
            spendables.append(Spendable(coin_value, script, previous_hash, previous_index))

        return spendables
コード例 #30
0
 def spendables_for_address(self, address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     spendables = []
     url_append = "?unspentOnly=true&token=%s&includeScript=true" % self.api_key
     url = self.base_url("addrs/%s%s" % (address, url_append))
     result = json.loads(urlopen(url).read().decode("utf8"))
     for txn in result.get("txrefs", []):
         coin_value = txn.get("value")
         script = h2b(txn.get("script"))
         previous_hash = h2b_rev(txn.get("tx_hash"))
         previous_index = txn.get("tx_output_n")
         spendables.append(
             Spendable(coin_value, script, previous_hash, previous_index))
     return spendables