Пример #1
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 = BitcoinScriptTools.compile(scriptSig.get("asm"))
            previous_index = vin.get("vout")
        sequence = vin.get("sequence")
        txs_in.append(Tx.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 = BitcoinScriptTools.compile(vout.get("scriptPubKey").get("asm"))
        txs_out.append(Tx.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
Пример #2
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_solution_count(), 1)
     tx.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
     self.assertEqual(tx.bad_solution_count(), 0)
     self.assertEqual(
         tx.id(),
         "9618820d7037d2f32db798c92665231cd4599326f5bd99cb59d0b723be2a13a2")
Пример #3
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 = BitcoinScriptTools.compile(scriptSig.get("asm"))
            previous_index = vin.get("vout")
        sequence = vin.get("sequence")
        txs_in.append(Tx.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 = BitcoinScriptTools.compile(
            vout.get("scriptPubKey").get("asm"))
        txs_out.append(Tx.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
Пример #4
0
def parse_scripts(args, keychain):
    warnings = []

    for p2s in args.pay_to_script or []:
        try:
            keychain.add_p2s_script(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)
                    keychain.add_p2s_script(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)
    keychain.commit()
    return warnings
Пример #5
0
def parse_key(item, networks):
    default_network = networks[0]
    Key = default_network.extras.Key
    generator = Key._default_generator
    if item == 'create':
        return None, _create_bip32(default_network)

    for network, key_info in key_info_from_text(item, networks=networks):
        return network, key_info["create_f"]()

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

    secret_exponent = parse_as_secret_exponent(item, generator)
    if secret_exponent:
        return None, Key(secret_exponent=secret_exponent)

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

    public_pair = parse_as_public_pair(item, generator)
    if public_pair:
        return None, Key(public_pair=public_pair)

    return None, None
Пример #6
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
Пример #7
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
Пример #8
0
def parse_scripts(args, keychain):
    warnings = []

    for p2s in args.pay_to_script or []:
        try:
            keychain.add_p2s_script(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)
                    keychain.add_p2s_script(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)
    keychain.commit()
    return warnings
Пример #9
0
    def test_hash160(self):
        def do_test(blob, expected_hash):
            self.assertEqual(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"))
Пример #10
0
def tx(args, parser):
    (network, txs, spendables, payables, keychain, tx_db,
     warning_spendables) = parse_context(args, parser)

    for tx in txs:
        if tx.missing_unspents() and (args.augment or tx_db):
            if tx_db is None:
                tx_db = create_tx_db(network)
            tx.unspents_from_db(tx_db, ignore_missing=True)

    # build p2sh_lookup
    warnings = parse_scripts(args, keychain)
    for w in warnings:
        print(w)

    tx = generate_tx(network, txs, spendables, payables, args)

    signature_hints = [h2b(sig) for sig in (args.signature or [])]
    sec_hints = network.tx.solve.build_sec_lookup(
        [h2b(sec) for sec in (args.sec or [])])

    is_fully_signed = do_signing(tx, keychain, keychain, sec_hints,
                                 signature_hints, network)

    include_unspents = not is_fully_signed

    if args.dump_signatures or args.dump_secs:
        if args.dump_signatures:
            dump_signatures_hex(tx, network)

        if args.dump_secs:
            dump_secs_hex(tx, network)

        return

    print_output(tx, include_unspents, args.output_file, args.show_unspents,
                 network, args.verbose_signature, args.disassemble, args.trace,
                 args.pdb)

    tx_db = cache_result(tx, tx_db, args.cache, network)

    tx_db = validate_against_bitcoind(tx, tx_db, args.network,
                                      args.bitcoind_url)

    if args.dump_inputs:
        dump_inputs(tx, network)

    if not args.show_unspents:
        tx_db = validate_tx(tx, tx_db, network)

    # print warnings
    if tx_db:
        for m in [tx_db.warning_tx_cache, tx_db.warning_tx_for_tx_hash]:
            if m:
                print("warning: %s" % m, file=sys.stderr)
    if warning_spendables:
        print("warning: %s" % warning_spendables, file=sys.stderr)
Пример #11
0
    def test_to_from_long(self):
        def do_test(as_int, prefix, as_rep, base):
            self.assertEqual((as_int, prefix), to_long(base, lambda v: v, iterbytes(as_rep)))
            self.assertEqual(as_rep, 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)
Пример #12
0
    def test_p2sh(self):
        def do_test(h160, redeem_script, address):
            self.assertEqual(GroestlcoinMainnet.contract.for_p2sh(h160), redeem_script)
            self.assertEqual(GroestlcoinMainnet.address.for_p2sh(h160), address)
            self.assertEqual(GroestlcoinMainnet.parse.p2sh(address).address(), address)

        do_test(
            h2b('2a84cf00d47f699ee7bbc1dea5ec1bdecb4ac154'),
            h2b('a9142a84cf00d47f699ee7bbc1dea5ec1bdecb4ac15487'), '35ZqQJcBQMZ1rsv8aSuJ2wkC7ohUFNJZ77')
Пример #13
0
    def test_double_sha256(self):
        def do_test(blob, expected_hash):
            self.assertEqual(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"))
Пример #14
0
    def test_hash160(self):
        def do_test(blob, expected_hash):
            self.assertEqual(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"))
Пример #15
0
    def test_to_from_long(self):
        def do_test(as_int, prefix, as_rep, base):
            self.assertEqual((as_int, prefix),
                             to_long(base, lambda v: v, iterbytes(as_rep)))
            self.assertEqual(as_rep,
                             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)
Пример #16
0
    def test_p2sh_multisig_sequential_signing(self):
        raw_scripts = [
            h2b("52210234abcffd2e80ad01c2ec0276ad02682808169c6fafdd25ebfb60703df272b461"
                "2102e5baaafff8094e4d77ce8b009d5ebc3de9110085ebd3d96e50cc7ce70faf175221"
                "0316ee25e80eb6e6fc734d9c86fa580cbb9c4bfd94a19f0373a22353ececd4db6853ae"
                )
        ]
        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'
        }

        key_1 = network.parse.wif(
            'Kz6pytJCigYHeMsGLmfHQPJhN5og2wpeSVrU43xWwgHLCAvpsprh')
        key_2 = network.parse.wif(
            'Kz7NHgX7MBySA3RSKj9GexUSN6NepEDoPNugSPr5absRDoKgn2dT')
        for ordered_keys in [(key_1, key_2), (key_2, key_1)]:
            txs_in = [
                TxIn(previous_hash=h2b(
                    '43c95d14724437bccc102ccf86aba1ac02415524fd1aefa787db886bba52a10c'
                ),
                     previous_index=0)
            ]
            txs_out = [
                TxOut(
                    10000,
                    network.contract.for_address(
                        '3KeGeLFmsbmbVdeMLrWp7WYKcA3tdsB4AR'))
            ]
            unspents = [Spendable.from_dict(spendable)]
            tx = Tx(version=DEFAULT_VERSION,
                    txs_in=txs_in,
                    txs_out=txs_out,
                    unspents=unspents)
            for key in ordered_keys:
                self.assertEqual(tx.bad_solution_count(), 1)
                p2sh_lookup = network.tx.solve.build_p2sh_lookup(raw_scripts)
                tx.sign(network.tx.solve.build_hash160_lookup(
                    [key.secret_exponent()]),
                        p2sh_lookup=p2sh_lookup)
            self.assertEqual(tx.bad_solution_count(), 0)
Пример #17
0
    def test_p2sh(self):
        def do_test(h160, redeem_script, address):
            self.assertEqual(GroestlcoinMainnet.contract.for_p2sh(h160),
                             redeem_script)
            self.assertEqual(GroestlcoinMainnet.address.for_p2sh(h160),
                             address)
            self.assertEqual(
                GroestlcoinMainnet.parse.p2sh(address).address(), address)

        do_test(h2b('2a84cf00d47f699ee7bbc1dea5ec1bdecb4ac154'),
                h2b('a9142a84cf00d47f699ee7bbc1dea5ec1bdecb4ac15487'),
                '35ZqQJcBQMZ1rsv8aSuJ2wkC7ohUFNJZ77')
Пример #18
0
def tx(args, parser):
    (network, txs, spendables, payables, keychain, tx_db, warning_spendables) = parse_context(args, parser)

    for tx in txs:
        if tx.missing_unspents() and (args.augment or tx_db):
            if tx_db is None:
                tx_db = create_tx_db(network)
            tx.unspents_from_db(tx_db, ignore_missing=True)

    # build p2sh_lookup
    warnings = parse_scripts(args, keychain)
    for w in warnings:
        print(w)

    tx = generate_tx(network, txs, spendables, payables, args)

    signature_hints = [h2b(sig) for sig in (args.signature or [])]
    sec_hints = network.tx.solve.build_sec_lookup([h2b(sec) for sec in (args.sec or [])])

    is_fully_signed = do_signing(tx, keychain, keychain, sec_hints, signature_hints, network)

    include_unspents = not is_fully_signed

    if args.dump_signatures or args.dump_secs:
        if args.dump_signatures:
            dump_signatures_hex(tx, network)

        if args.dump_secs:
            dump_secs_hex(tx, network)

        return

    print_output(tx, include_unspents, args.output_file, args.show_unspents, network,
                 args.verbose_signature, args.disassemble, args.trace, args.pdb)

    tx_db = cache_result(tx, tx_db, args.cache, network)

    tx_db = validate_against_bitcoind(tx, tx_db, args.network, args.bitcoind_url)

    if args.dump_inputs:
        dump_inputs(tx, network)

    if not args.show_unspents:
        tx_db = validate_tx(tx, tx_db, network)

    # print warnings
    if tx_db:
        for m in [tx_db.warning_tx_cache, tx_db.warning_tx_for_tx_hash]:
            if m:
                print("warning: %s" % m, file=sys.stderr)
    if warning_spendables:
        print("warning: %s" % warning_spendables, file=sys.stderr)
Пример #19
0
    def test_to_from_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_bin, a2b_base58(as_text))
            self.assertEqual(as_text, 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"))
Пример #20
0
    def test_wif(self):
        def do_test(sec_bytes, wif, address):
            parsed = GroestlcoinMainnet.parse.wif(wif)
            self.assertEqual(to_bytes_32(parsed.secret_exponent()), sec_bytes)
            self.assertEqual(parsed.wif(), wif)
            self.assertEqual(parsed.address(), address)

        do_test(
            h2b('0000000000000000000000000000000000000000000000000000000000000001'),
            '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAmVmAPb', 'FiT6218RsUiTMyG5DA8bDjrNNuofYV2MdF')
        do_test(
            h2b('0000000000000000000000000000000000000000000000000000000000000001'),
            'KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sX6ptSt', 'Ffqz14cyvZYJavD76t6oHNDJnGiWcZMVxR')
Пример #21
0
    def test_to_from_hashed_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_text, b2a_hashed_base58(as_bin))
            self.assertEqual(as_bin, a2b_hashed_base58(as_text))
            self.assertTrue(is_hashed_base58_valid(as_text))
            bogus_text = as_text[:-1] + chr(1+ord(as_text[-1]))
            self.assertFalse(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"))
Пример #22
0
    def test_to_from_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_bin, a2b_base58(as_text))
            self.assertEqual(as_text, 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"))
Пример #23
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)

            keys_wif = [
                Key(secret_exponent=secret_exponent,
                    generator=secp256k1_generator),
                key_from_text(wif),
                key_from_text(c_wif),
            ]

            key_sec = Key.from_sec(sec, secp256k1_generator)
            key_sec_c = Key.from_sec(c_sec, secp256k1_generator)
            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)

            self.assertEqual(key_pub.address(), address_b58)
            self.assertEqual(key_pub.address(use_uncompressed=True), None)
            self.assertEqual(key_pub.address(use_uncompressed=False), None)
Пример #24
0
 def spendables_for_address(self, address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = self.api_domain + "/unspent?active=%s" % 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(Tx.Spendable(coin_value, script, previous_hash, previous_index))
     return spendables
Пример #25
0
    def test_wif(self):
        def do_test(sec_bytes, wif, address):
            parsed = GroestlcoinMainnet.parse.wif(wif)
            self.assertEqual(to_bytes_32(parsed.secret_exponent()), sec_bytes)
            self.assertEqual(parsed.wif(), wif)
            self.assertEqual(parsed.address(), address)

        do_test(
            h2b('0000000000000000000000000000000000000000000000000000000000000001'
                ), '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAmVmAPb',
            'FiT6218RsUiTMyG5DA8bDjrNNuofYV2MdF')
        do_test(
            h2b('0000000000000000000000000000000000000000000000000000000000000001'
                ), 'KwDiBf89QgGbjEhKnhXJuH7LrciVrZi3qYjgd9M7rFU73sX6ptSt',
            'Ffqz14cyvZYJavD76t6oHNDJnGiWcZMVxR')
Пример #26
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")
Пример #27
0
    def test_block(self):
        expected_checksum = '0000000000089F7910F6755C10EA2795EC368A29B435D80770AD78493A6FECF1'.lower()

        block_data = h2b(
            "010000007480150B299A16BBCE5CCDB1D1BBC65CFC5893B01E6619107C552000000000"
            "007900A2B203D24C69710AB6A94BEB937E1B1ADD64C2327E268D8C3E5F8B41DBED8796"
            "974CED66471B204C324703010000000100000000000000000000000000000000000000"
            "00000000000000000000000000FFFFFFFF0804ED66471B024001FFFFFFFF0100F2052A"
            "010000004341045FEE68BAB9915C4EDCA4C680420ED28BBC369ED84D48AC178E1F5F7E"
            "EAC455BBE270DABA06802145854B5E29F0A7F816E2DF906E0FE4F6D5B4C9B92940E4F0"
            "EDAC000000000100000001F7B30415D1A7BF6DB91CB2A272767C6799D721A4178AA328"
            "E0D77C199CB3B57F010000008A4730440220556F61B84F16E637836D2E74B8CB784DE4"
            "0C28FE3EF93CCB7406504EE9C7CAA5022043BD4749D4F3F7F831AC696748AD8D8E79AE"
            "B4A1C539E742AA3256910FC88E170141049A414D94345712893A828DE57B4C2054E2F5"
            "96CDCA9D0B4451BA1CA5F8847830B9BE6E196450E6ABB21C540EA31BE310271AA00A49"
            "ED0BA930743D1ED465BAD0FFFFFFFF0200E1F505000000001976A914529A63393D63E9"
            "80ACE6FA885C5A89E4F27AA08988ACC0ADA41A000000001976A9145D17976537F30886"
            "5ED533CCCFDD76558CA3C8F088AC00000000010000000165148D894D3922EF5FFDA962"
            "BE26016635C933D470C8B0AB7618E869E3F70E3C000000008B48304502207F5779EBF4"
            "834FEAEFF4D250898324EB5C0833B16D7AF4C1CB0F66F50FCF6E85022100B78A65377F"
            "D018281E77285EFC31E5B9BA7CB7E20E015CF6B7FA3E4A466DD195014104072AD79E0A"
            "A38C05FA33DD185F84C17F611E58A8658CE996D8B04395B99C7BE36529CAB7606900A0"
            "CD5A7AEBC6B233EA8E0FE60943054C63620E05E5B85F0426FFFFFFFF02404B4C000000"
            "00001976A914D4CAA8447532CA8EE4C80A1AE1D230A01E22BFDB88AC8013A0DE010000"
            "001976A9149661A79AE1F6D487AF3420C13E649D6DF3747FC288AC00000000")

        # try to parse a block

        block = Block.parse(io.BytesIO(block_data))
        assert b2h_rev(block.hash()) == expected_checksum
        block.check_merkle_hash()

        # parse already validated block
        block = Block.parse(io.BytesIO(block_data), check_merkle_hash=False)
        assert block.as_bin() == block_data
Пример #28
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))
Пример #29
0
def make_script_test(script_in, script_out, flags_string, comment, expected, coin_value, script_witness):
    script_in_bin = network.script.compile(script_in)
    script_out_bin = network.script.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 = ''
            spend_tx.check_solution(tx_in_idx=0, flags=flags)
            r = 0
        except ScriptError as se:
            r = se.error_code()
            msg = se.args[0]
        except Exception:
            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
Пример #30
0
 def info_for_sec(self, prefix, text):
     sec = h2b(text)
     public_pair = sec_to_public_pair(sec, self._generator)
     is_compressed = is_sec_compressed(sec)
     kwargs = dict(public_pair=public_pair, is_compressed=is_compressed)
     return dict(type="key", key_type="sec", is_private=False, kwargs=kwargs,
                 key_class=self._key_class, create_f=lambda: self._key_class(**kwargs))
Пример #31
0
def make_script_test(script_in, script_out, flags_string, comment, expected,
                     coin_value, script_witness):
    script_in_bin = network.script.compile(script_in)
    script_out_bin = network.script.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 = ''
            spend_tx.check_solution(tx_in_idx=0, flags=flags)
            r = 0
        except ScriptError as se:
            r = se.error_code()
            msg = se.args[0]
        except Exception:
            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
Пример #32
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))
Пример #33
0
    def info_for_E(self, prefix, data):
        bin_data = h2b(data)

        size = len(bin_data)
        if size not in (16, 32, 64):
            return

        is_private = (size != 64)

        if size == 16:
            kwargs = dict(initial_key=data, generator=self._generator)
            electrum_type = "seed"

        if size == 32:
            kwargs = dict(master_private_key=from_bytes_32(bin_data),
                          generator=self._generator)
            electrum_type = "private"

        if size == 64:
            kwargs = dict(master_public_key=bin_data,
                          generator=self._generator)
            electrum_type = "public"

        return dict(type="key",
                    key_type="electrum",
                    electrum_type=electrum_type,
                    is_private=is_private,
                    key_class=self._electrum_class,
                    kwargs=kwargs,
                    create_f=lambda: self._electrum_class(**kwargs))
Пример #34
0
 def test_recognize_multisig(self):
     h = (
         "010000000139c92b102879eb95f14e7344e4dd7d481e1238b1bfb1fa0f735068d2927b"
         "231400000000910047304402208fc06d216ebb4b6a3a3e0f906e1512c372fa8a9c2a92"
         "505d04e9b451ea7acd0c0220764303bb7e514ddd77855949d941c934e9cbda8e3c3827"
         "bfdb5777477e73885b014730440220569ec6d2e81625dd18c73920e0079cdb4c1d67d3"
         "d7616759eb0c18cf566b3d3402201c60318f0a62e3ba85ca0f158d4dfe63c0779269eb"
         "6765b6fc939fc51e7a8ea901ffffffff0140787d01000000001976a914641ad5051edd"
         "97029a003fe9efb29359fcee409d88ac0000000040787d0100000000c952410496ec45"
         "f878b62c46c4be8e336dff7cc58df9b502178cc240eb3d31b1266f69f5767071aa3e01"
         "7d1b82a0bb28dab5e27d4d8e9725b3e68ed5f8a2d45c730621e34104cc71eb30d653c0"
         "c3163990c47b976f3fb3f37cccdcbedb169a1dfef58bbfbfaff7d8a473e7e2e6d317b8"
         "7bafe8bde97e3cf8f065dec022b51d11fcdd0d348ac4410461cbdcc5409fb4b4d42b51"
         "d33381354d80e550078cb532a34bfa2fcfdeb7d76519aecc62770f5b0e4ef8551946d8"
         "a540911abe3e7854a26f39f58b25c15342af53ae")
     f = io.BytesIO(h2b(h))
     tx = Tx.parse(f)
     tx.parse_unspents(f)
     self.assertEqual(
         tx.id(),
         "10c61e258e0a2b19b245a96a2d0a1538fe81cd4ecd547e0a3df7ed6fd3761ada")
     script = tx.unspents[0].script
     multisig_info = script_info_for_script(script)
     del multisig_info["type"]
     s = script_for_multisig(**multisig_info)
     self.assertEqual(s, script)
Пример #35
0
    def test_double_sha256(self):
        def do_test(blob, expected_hash):
            self.assertEqual(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"
                ))
Пример #36
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")
Пример #37
0
 def spendables_for_address(self, address):
     """
     Return a list of Spendable objects for the
     given bitcoin address.
     """
     URL = "https://blockchain.info/unspent?active=%s" % 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(
             Tx.Spendable(coin_value, script, previous_hash,
                          previous_index))
     return spendables
Пример #38
0
 def _electrum_to_blob(self, s):
     pair = parse_colon_prefix(s)
     if pair is None or pair[0] != "E":
         return None
     try:
         return h2b(pair[1])
     except ValueError:
         return None
Пример #39
0
 def _electrum_to_blob(self, s):
     pair = parse_colon_prefix(s)
     if pair is None or pair[0] != "E":
         return None
     try:
         return h2b(pair[1])
     except ValueError:
         return None
Пример #40
0
class Ripple:

    _wif_prefix = h2b("21")
    _privkey_prefix = h2b("00")

    @classmethod
    def create_seed_from_mnemonic(cls, words):
        m = mnemonic.Mnemonic.normalize_string(words)
        passphrase = mnemonic.Mnemonic.normalize_string("")
        seed = PBKDF2(m,
                      u'mnemonic' + passphrase,
                      iterations=mnemonic.mnemonic.PBKDF2_ROUNDS,
                      macmodule=hmac,
                      digestmodule=hashlib.sha512).read(16)
        return seed

    @classmethod
    def secret_from_seed(cls, seed):
        # get first 16 bytes even if the seed is bigger
        secret = b2a_hashed_base58(cls._wif_prefix + seed[:16])
        return secret

    @classmethod
    def address_from_seed(cls, seed):
        secret = cls.secret_from_seed(seed)
        return get_ripple_from_secret(secret)

    @classmethod
    def address_from_pubkey(cls, pubkey):
        return get_ripple_from_pubkey(h2b(pubkey))

    @classmethod
    def pubkey_from_seed(cls, seed):
        print("seed", b2h(seed))
        root_key = root_key_from_seed(seed[:16])
        pubkey = fmt_hex(
            ecc_point_to_bytes_compressed(root_key.privkey.public_key.point,
                                          pad=True))
        return pubkey

    @classmethod
    def privkey_from_seed(cls, seed):
        root_key = root_key_from_seed(seed[:16])
        privkey = fmt_hex(cls._privkey_prefix +
                          to_bytes(root_key.privkey.secret_multiplier))
        return privkey
Пример #41
0
 def spendable_for_row(r, spendable_class):
     return spendable_class(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])
Пример #42
0
def is_pubkey_valid(pubkey):
    try:
        hpub = h2b(pubkey)
        k = network.keys.public(hpub)
        network.parse.address(k.address())
        return True
    except:
        return False
Пример #43
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)

            key = network.parse.wif(wif)
            exponent = key.secret_exponent()
            compressed = key.is_compressed()
            self.assertEqual(exponent, secret_exponent)
            self.assertFalse(compressed)

            key = network.parse.wif(c_wif)
            exponent = key.secret_exponent()
            compressed = key.is_compressed()
            self.assertEqual(exponent, secret_exponent)
            self.assertTrue(compressed)

            public_pair = secret_exponent * key._generator

            pk_public_pair = sec_to_public_pair(sec, key._generator)
            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, key._generator)
            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))
Пример #44
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)

            keys_wif = [
                Key(secret_exponent=secret_exponent, generator=secp256k1_generator),
                key_from_text(wif),
                key_from_text(c_wif),
            ]

            key_sec = Key.from_sec(sec, secp256k1_generator)
            key_sec_c = Key.from_sec(c_sec, secp256k1_generator)
            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)

            self.assertEqual(key_pub.address(), address_b58)
            self.assertEqual(key_pub.address(use_uncompressed=True), None)
            self.assertEqual(key_pub.address(use_uncompressed=False), None)
Пример #45
0
    def test_to_from_hashed_base58(self):
        def do_test(as_text, as_bin):
            self.assertEqual(as_text, b2a_hashed_base58(as_bin))
            self.assertEqual(as_bin, a2b_hashed_base58(as_text))
            self.assertTrue(is_hashed_base58_valid(as_text))
            bogus_text = as_text[:-1] + chr(1 + ord(as_text[-1]))
            self.assertFalse(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"
                ))
Пример #46
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")
Пример #47
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")
Пример #48
0
 def test_sec(self):
     pair_blob = h2b("0679be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483a"
                     "da7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
     sec_to_public_pair(pair_blob, secp256k1_generator, strict=False)
     try:
         sec_to_public_pair(pair_blob, secp256k1_generator, strict=True)
         self.fail("sec_to_public_pair unexpectedly succeeded")
     except EncodingError:
         pass
Пример #49
0
 def test_testnet(self):
     # WARNING: these values have not been verified independently. TODO: do so
     master = XTN.keys.bip32_seed(h2b("000102030405060708090a0b0c0d0e0f"))
     self.assertEqual(
         master.hwif(as_private=True),
         "tprv8ZgxMBicQKsPeDgjzdC36fs6bMjGApWDNLR9erAXMs5skhMv36j9MV5ecvfavji5kh"
         "qjWaWSFhN3YcCUUdiKH6isR4Pwy3U5y5egddBr16m")
     self.assertEqual(master.address(), "mkHGce7dctSxHgaWSSbmmrRWsZfzz7MxMk")
     self.assertEqual(master.wif(), "cVPXTF2TnozE1PenpP3x9huctiATZmp27T9Ue1d8nqLSExoPwfN5")
Пример #50
0
    def test_p2pkh(self):
        def do_test(h160, address):
            self.assertEqual(GroestlcoinMainnet.address.for_p2pkh(h160),
                             address)
            self.assertEqual(
                GroestlcoinMainnet.parse.p2pkh(address).address(), address)

        do_test(h2b('0000000000000000000000000000000000000000'),
                'FVAiSujNZVgYSc27t6zUTWoKfAGxer42D4')
Пример #51
0
 def test_sec(self):
     pair_blob = h2b(
         "0679be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483a"
         "da7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")
     sec_to_public_pair(pair_blob, secp256k1_generator, strict=False)
     try:
         sec_to_public_pair(pair_blob, secp256k1_generator, strict=True)
         self.fail("sec_to_public_pair unexpectedly succeeded")
     except EncodingError:
         pass
Пример #52
0
 def public_key_sec(self):
     """Return the public key as sec, or None in case of failure."""
     if self.is_coinbase():
         return None
     opcodes = ScriptTools.opcode_list(self.script)
     if len(opcodes) == 2 and opcodes[0].startswith("[30"):
         # the second opcode is probably the public key as sec
         sec = h2b(opcodes[1][1:-1])
         return sec
     return None
Пример #53
0
 def from_text(cls, text):
     the_tuple = (text.split("/") + [0, 0, 0])[:7]
     tx_hash_hex, tx_out_index_str, script_hex, coin_value, \
         block_index_available, does_seem_spent, block_index_spent = the_tuple
     tx_hash = h2b_rev(tx_hash_hex)
     tx_out_index = int(tx_out_index_str)
     script = h2b(script_hex)
     coin_value = int(coin_value)
     return cls(coin_value, script, tx_hash, tx_out_index, int(block_index_available),
                int(does_seem_spent), int(block_index_spent))
Пример #54
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)
     p2sh_lookup = build_p2sh_lookup([h2b(x) for x in p2sh_values])
     hash160_lookup = build_hash160_lookup(private_keys, [secp256k1_generator])
     tx_u_prime.sign(hash160_lookup=hash160_lookup, p2sh_lookup=p2sh_lookup)
     self.check_signed(tx_u_prime)
     tx_hex = tx_u_prime.as_hex()
     self.assertEqual(tx_hex, tx_s_hex)
Пример #55
0
 def test_sign_p2sh(self):
     tx_out_script = h2b("76a91491b24bf9f5288532960ac687abb035127b1d28a588ac")
     script = script_for_address("1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm")
     self.assertEqual(tx_out_script, script)
     tx_out = TxOut(100, tx_out_script)
     tx = Tx(1, [TxIn(b'\1' * 32, 1)], [TxOut(100, tx_out_script)])
     tx.set_unspents([tx_out])
     hl = build_hash160_lookup([1], [secp256k1_generator])
     self.assertEqual(tx.bad_signature_count(), 1)
     tx.sign(hash160_lookup=hl)
     self.assertEqual(tx.bad_signature_count(), 0)
Пример #56
0
    def from_hex(class_, hex_string):
        """Return the Tx for the given hex string.

        :param hex_string: a hex string containing a transaction streamed in standard
            form. The blob may also include the unspents (a nonstandard extension,
            optionally written by :func:`Tx.stream <stream>`), and they will also be parsed.
        :return: :class:`Tx`

        If parsing fails, an exception is raised.
        """
        return class_.from_bin(h2b(hex_string))
Пример #57
0
 def test_sign_p2sh(self):
     tx_out_script = h2b("76a91491b24bf9f5288532960ac687abb035127b1d28a588ac")
     script = network.contract.for_address("1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm")
     self.assertEqual(tx_out_script, script)
     tx_out = TxOut(100, tx_out_script)
     tx = Tx(1, [TxIn(b'\1' * 32, 1)], [TxOut(100, tx_out_script)])
     tx.set_unspents([tx_out])
     hl = network.tx.solve.build_hash160_lookup([1])
     self.assertEqual(tx.bad_solution_count(), 1)
     tx.sign(hash160_lookup=hl)
     self.assertEqual(tx.bad_solution_count(), 0)
Пример #58
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 Exception:
         raise Exception