def f(key_data, network, subkey_path, add_output): if len(key_data) == 74: key = network.extras.BIP32Node.deserialize(b'0000' + key_data) elif len(key_data) in (32, 64): key = network.extras.ElectrumWallet.deserialize(key_data) else: return yield ("wallet_key", key.hwif(as_private=key.is_private()), None) if key.is_private(): yield ("public_version", key.hwif(as_private=False), None) child_number = key.child_index() if child_number >= 0x80000000: wc = child_number - 0x80000000 child_index = "%dH (%d)" % (wc, child_number) else: child_index = "%d" % child_number yield ("tree_depth", "%d" % key.tree_depth(), None) yield ("fingerprint", b2h(key.fingerprint()), None) yield ("parent_fingerprint", b2h(key.parent_fingerprint()), "parent f'print") yield ("child_index", child_index, None) yield ("chain_code", b2h(key.chain_code()), None) yield ("private_key", "yes" if key.is_private() else "no", None)
def f(public_pair): yield ("public_pair_x", '%d' % public_pair[0], None) yield ("public_pair_y", '%d' % public_pair[1], None) yield ("public_pair_x_hex", '%x' % public_pair[0], " x as hex") yield ("public_pair_y_hex", '%x' % public_pair[1], " y as hex") yield ("y_parity", "odd" if (public_pair[1] & 1) else "even", None) key = Key(public_pair=public_pair) yield ("key_pair_as_sec", b2h(key.sec(use_uncompressed=False)), None) yield ("key_pair_as_sec_uncompressed", b2h(key.sec(use_uncompressed=True)), " uncompressed") ui_context = network.ui network_name = network.network_name hash160_c = key.hash160(use_uncompressed=False) hash160_u = key.hash160(use_uncompressed=True) hash160 = None if hash160_c is None and hash160_u is None: hash160 = key.hash160() yield ("hash160", b2h(hash160 or hash160_c), None) if hash160_c and hash160_u: yield ("hash160_uncompressed", b2h(hash160_u), " uncompressed") address = ui_context.address_for_p2pkh(hash160 or hash160_c) yield ("address", address, "%s address" % network_name) yield ("%s_address" % network.symbol, address, "legacy") if hash160_c and hash160_u: address = key.address(use_uncompressed=True) yield ("address_uncompressed", address, "%s address uncompressed" % network_name) yield ("%s_address_uncompressed" % network.symbol, address, "legacy") # don't print segwit addresses unless we're sure we have a compressed key if hash160_c and hasattr(network, "ui") and getattr( network.ui, "_bech32_hrp"): address_segwit = network.ui.address_for_p2pkh_wit(hash160_c) if address_segwit: # this network seems to support segwit yield ("address_segwit", address_segwit, "%s segwit address" % network_name) yield ("%s_address_segwit" % network.symbol, address_segwit, "legacy") p2sh_script = network.script_info.script_for_p2pkh_wit( hash160_c) p2s_address = network.ui.address_for_p2s(p2sh_script) if p2s_address: yield ("p2sh_segwit", p2s_address, None) p2sh_script_hex = b2h(p2sh_script) yield ("p2sh_segwit_script", p2sh_script_hex, " corresponding p2sh script")
def determine_constraints(self, tx_in_idx, p2sh_lookup={}): tx_context = self.solution_checker.tx_context_for_idx(tx_in_idx) tx_context.witness_solution_stack = DynamicStack( [Atom("w_%d" % (1 - _)) for _ in range(2)], fill_template="w_%d") script_hash = self.solution_checker.script_hash_from_script( tx_context.puzzle_script) witness_version = self.solution_checker._witness_program_version( tx_context.puzzle_script) tx_context.solution_script = b'' solution_reserve_count = 0 fill_template = "x_%d" if script_hash: underlying_script = p2sh_lookup.get(script_hash, None) if underlying_script is None: raise ValueError( "p2sh_lookup not set or does not have script hash for %s" % b2h(script_hash)) tx_context.solution_script = self.ScriptTools.compile_push_data_list( [underlying_script]) solution_reserve_count = 1 witness_version = self.solution_checker._witness_program_version( underlying_script) if witness_version == 0: witness_program = (underlying_script if script_hash else tx_context.puzzle_script)[2:] if len(witness_program) == 32: underlying_script_wit = p2sh_lookup.get(witness_program, None) if underlying_script_wit is None: raise ValueError( "p2sh_lookup not set or does not have script hash for %s" % b2h(witness_program)) fill_template = "w_%d" solution_reserve_count = 1 tx_context.witness_solution_stack = [underlying_script_wit] constraints = [] def reset_stack_f(stack): return DynamicStack(stack, solution_reserve_count, fill_template) try: traceback_f = make_traceback_f(constraints, self.ScriptTools.int_for_opcode, reset_stack_f) self.solution_checker.check_solution(tx_context, traceback_f=traceback_f) except ScriptError: pass if script_hash: constraints.append( Operator('EQUAL', Atom("x_0"), underlying_script)) if witness_version == 0: if len(witness_program) == 32: constraints.append( Operator('EQUAL', Atom("w_0"), underlying_script_wit)) return constraints
def __repr__(self): r = self.public_copy() if r._network: s = r.as_text() elif r.sec(): s = b2h(r.sec()) else: s = b2h(r.hash160()) if self.is_private(): return "private_for <%s>" % s return "<%s>" % s
def __repr__(self): r = self.public_copy() if r._ui_context: s = r.as_text() elif r.sec(): s = b2h(r.sec()) else: s = b2h(r.hash160()) if self.is_private(): return "private_for <%s>" % s return "<%s>" % s
def test_bip143_tx_1(self): tx_u1, tx_s1 = self.check_bip143_tx( "0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad" "969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9" "b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df3" "78db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e" "4dbe6a21b2d50ce2f0167faa815988ac11000000", "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4" "e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3beb" "f337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede9" "44ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b" "309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a914" "8280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143b" "de42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7" "d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c45183315" "61406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368d" "a1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000", [(6.25, "2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac" ), (6, "00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1")], 2, 2, 1, 17) sc = tx_s1.SolutionChecker(tx_s1) self.assertEqual( b2h(sc._hash_prevouts(SIGHASH_ALL)), "96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37") self.assertEqual( b2h(sc._hash_sequence(SIGHASH_ALL)), "52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b") self.assertEqual( b2h(sc._hash_outputs(SIGHASH_ALL, 0)), "863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5") script = BitcoinMainnet.ui._script_info.script_for_p2pkh( tx_s1.unspents[1].script[2:]) self.assertEqual( b2h( sc._segwit_signature_preimage(script=script, tx_in_idx=1, hash_type=SIGHASH_ALL)), "0100000096b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd" "3752b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3bef51" "e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000019" "76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac0046c32300000000ffff" "ffff863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e511" "00000001000000") self.assertEqual( b2h(to_bytes_32(sc._signature_for_hash_type_segwit(script, 1, 1))), "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670") self.check_tx_can_be_signed(tx_u1, tx_s1, [ 0xbbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866, 0x619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9 ])
def create_public_pair_output(key, add_output): public_pair = key.public_pair() if public_pair: add_output("public_pair_x", '%d' % public_pair[0]) add_output("public_pair_y", '%d' % public_pair[1]) add_output("public_pair_x_hex", '%x' % public_pair[0], " x as hex") add_output("public_pair_y_hex", '%x' % public_pair[1], " y as hex") add_output("y_parity", "odd" if (public_pair[1] & 1) else "even") add_output("key_pair_as_sec", b2h(key.sec(use_uncompressed=False))) add_output("key_pair_as_sec_uncompressed", b2h(key.sec(use_uncompressed=True)), " uncompressed")
def test_bip143_tx_1(self): tx_u1, tx_s1 = self.check_bip143_tx( "0100000002fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4e4ad" "969f0000000000eeffffffef51e1b804cc89d182d279655c3aa89e815b1b309fe287d9" "b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a9148280b37df3" "78db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143bde42dbee7e" "4dbe6a21b2d50ce2f0167faa815988ac11000000", "01000000000102fff7f7881a8099afa6940d42d1e7f6362bec38171ea3edf433541db4" "e4ad969f00000000494830450221008b9d1dc26ba6a9cb62127b02742fa9d754cd3beb" "f337f7a55d114c8e5cdd30be022040529b194ba3f9281a99f2b1c0a19c0489bc22ede9" "44ccf4ecbab4cc618ef3ed01eeffffffef51e1b804cc89d182d279655c3aa89e815b1b" "309fe287d9b2b55d57b90ec68a0100000000ffffffff02202cb206000000001976a914" "8280b37df378db99f66f85c95a783a76ac7a6d5988ac9093510d000000001976a9143b" "de42dbee7e4dbe6a21b2d50ce2f0167faa815988ac000247304402203609e17b84f6a7" "d30c80bfa610b5b4542f32a8a0d5447a12fb1366d7f01cc44a0220573a954c45183315" "61406f90300e8f3358f51928d43c212a8caed02de67eebee0121025476c2e83188368d" "a1ff3e292e7acafcdb3566bb0ad253f62fc70f07aeee635711000000", [ (6.25, "2103c9f4836b9a4f77fc0d81f7bcb01b7f1b35916864b9476c241ce9fc198bd25432ac"), (6, "00141d0f172a0ecb48aee1be1f2687d2963ae33f71a1") ], 2, 2, 1, 17 ) sc = tx_s1.SolutionChecker(tx_s1) self.assertEqual(b2h(sc._hash_prevouts(SIGHASH_ALL)), "96b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd37") self.assertEqual(b2h(sc._hash_sequence(SIGHASH_ALL)), "52b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3b") self.assertEqual(b2h(sc._hash_outputs(SIGHASH_ALL, 0)), "863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e5") script = BitcoinMainnet.ui._script_info.script_for_p2pkh(tx_s1.unspents[1].script[2:]) self.assertEqual( b2h(sc._segwit_signature_preimage(script=script, tx_in_idx=1, hash_type=SIGHASH_ALL)), "0100000096b827c8483d4e9b96712b6713a7b68d6e8003a781feba36c31143470b4efd" "3752b0a642eea2fb7ae638c36f6252b6750293dbe574a806984b8e4d8548339a3bef51" "e1b804cc89d182d279655c3aa89e815b1b309fe287d9b2b55d57b90ec68a0100000019" "76a9141d0f172a0ecb48aee1be1f2687d2963ae33f71a188ac0046c32300000000ffff" "ffff863ef3e1a92afbfdb97f31ad0fc7683ee943e9abcf2501590ff8f6551f47e5e511" "00000001000000") self.assertEqual(b2h(to_bytes_32(sc._signature_for_hash_type_segwit(script, 1, 1))), "c37af31116d1b27caf68aae9e3ac82f1477929014d5b917657d0eb49478cb670") self.check_tx_can_be_signed(tx_u1, tx_s1, [ 0xbbc27228ddcb9209d7fd6f36b02f7dfa6252af40bb2f1cbc7a557da8027ff866, 0x619c335025c7f4012e556c2a58b2506e30b8511b53ade95ea316fd8c3286feb9 ])
def ku_output_for_public_pair(self): if self._public_pair: yield ("public_pair_x", '%d' % self._public_pair[0], None) yield ("public_pair_y", '%d' % self._public_pair[1], None) yield ("public_pair_x_hex", '%x' % self._public_pair[0], " x as hex") yield ("public_pair_y_hex", '%x' % self._public_pair[1], " y as hex") yield ("y_parity", "odd" if (self._public_pair[1] & 1) else "even", None) yield ("key_pair_as_sec", b2h(self.sec(is_compressed=True)), None) yield ("key_pair_as_sec_uncompressed", b2h(self.sec(is_compressed=False)), " uncompressed")
def info_for_arg(arg, network): d = {} compiled_script = network.script.compile(arg) d["compiled_script_hex"] = "0x%s" % b2h(compiled_script) address_p2s = network.address.for_p2s(compiled_script) d["address_p2s"] = address_p2s d["preimage_p2s_hex"] = b2h(network.contract.for_address(address_p2s)) address_p2s_wit = network.address.for_p2s_wit(compiled_script) d["address_p2s_wit"] = address_p2s_wit d["underlying_script"] = b2h(network.contract.for_address(address_p2s_wit)) d["disassembled_script"] = network.script.disassemble(compiled_script) return d
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")
def test_p2multisig_wit(self): keys = [Key(i, generator=secp256k1_generator) for i in (1, 2, 3)] secs = [k.sec() for k in keys] underlying_script = script_for_multisig(2, secs) p2sh_script = BitcoinScriptTools.compile("OP_0 [%s]" % b2h(hashlib.sha256(underlying_script).digest())) script = script_for_address(address_for_p2s(p2sh_script)) self.do_test_tx(script, p2sh_lookup=build_p2sh_lookup([underlying_script, p2sh_script]))
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
def test_sign_verify_mutual_compatability(self): if libsecp256k1 is None: raise unittest.SkipTest("no libsecp256k1") ctx = libsecp256k1.ctx signature = create_string_buffer(64) sighash = to_bytes_32(1000) secret_key = to_bytes_32(100) public_key = create_string_buffer(64) r = libsecp256k1.secp256k1_ec_pubkey_create(ctx, public_key, secret_key) self.assertEqual(r, 1) self.assertEqual( b2h(public_key), '880f50f7ceb4210289266a40b306e33ef52bb75f834c172e65175e3ce2ac3bed' '6e2835e3d57ae1fcd0954808be17bd97bf871f7a8a5edadcffcc8812576f7ae5') r = libsecp256k1.secp256k1_ecdsa_sign(ctx, signature, sighash, secret_key, None, None) self.assertEqual(r, 1) r = libsecp256k1.secp256k1_ecdsa_verify(ctx, signature, sighash, public_key) self.assertEqual(r, 1) signature1 = signature[:-1] + int2byte(byte2int(signature[-1]) ^ 1) r = libsecp256k1.secp256k1_ecdsa_verify(ctx, signature1, sighash, public_key) self.assertEqual(r, 0)
def test_sign_verify_mutual_compatability(self): if libsecp256k1 is None: raise unittest.SkipTest("no libsecp256k1") ctx = libsecp256k1.ctx signature = create_string_buffer(64) sighash = to_bytes_32(1000) secret_key = to_bytes_32(100) public_key = create_string_buffer(64) r = libsecp256k1.secp256k1_ec_pubkey_create(ctx, public_key, secret_key) self.assertEqual(r, 1) self.assertEqual( b2h(public_key), '880f50f7ceb4210289266a40b306e33ef52bb75f834c172e65175e3ce2ac3bed' '6e2835e3d57ae1fcd0954808be17bd97bf871f7a8a5edadcffcc8812576f7ae5' ) r = libsecp256k1.secp256k1_ecdsa_sign(ctx, signature, sighash, secret_key, None, None) self.assertEqual(r, 1) r = libsecp256k1.secp256k1_ecdsa_verify(ctx, signature, sighash, public_key) self.assertEqual(r, 1) signature1 = signature[:-1] + int2byte(byte2int(signature[-1]) ^ 1) r = libsecp256k1.secp256k1_ecdsa_verify(ctx, signature1, sighash, public_key) self.assertEqual(r, 0)
def test_sign(self): if libsecp256k1 is None: raise unittest.SkipTest("no libsecp256k1") ctx = libsecp256k1.ctx sighash = to_bytes_32(1000) secret_key = to_bytes_32(100) public_key = create_string_buffer(64) r = libsecp256k1.secp256k1_ec_pubkey_create(ctx, public_key, secret_key) self.assertEqual(r, 1) self.assertEqual( b2h(public_key), '880f50f7ceb4210289266a40b306e33ef52bb75f834c172e65175e3ce2ac3bed' '6e2835e3d57ae1fcd0954808be17bd97bf871f7a8a5edadcffcc8812576f7ae5' ) signature = create_string_buffer(64) r = libsecp256k1.secp256k1_ecdsa_sign(ctx, signature, sighash, secret_key, None, None) self.assertEqual(r, 1) compact_signature = create_string_buffer(64) libsecp256k1.secp256k1_ecdsa_signature_serialize_compact(ctx, compact_signature, signature) r = from_bytes_32(compact_signature[:32]) s = from_bytes_32(compact_signature[32:]) signature = (r, s) pubkey_size = c_size_t(65) pubkey_serialized = create_string_buffer(65) libsecp256k1.secp256k1_ec_pubkey_serialize( ctx, pubkey_serialized, byref(pubkey_size), public_key, SECP256K1_EC_UNCOMPRESSED) x = from_bytes_32(pubkey_serialized[1:33]) y = from_bytes_32(pubkey_serialized[33:]) legacy_secp256k1_group.verify((x, y), 1000, signature)
def create_hash160_output(key, network, add_output, output_dict): ui_context = network.ui network_name = network.network_name hash160_c = key.hash160(use_uncompressed=False) hash160_u = key.hash160(use_uncompressed=True) hash160 = None if hash160_c is None and hash160_u is None: hash160 = key.hash160() add_output("hash160", b2h(hash160 or hash160_c)) if hash160_c and hash160_u: add_output("hash160_uncompressed", b2h(hash160_u), " uncompressed") address = ui_context.address_for_p2pkh(hash160 or hash160_c) add_output("address", address, "%s address" % network_name) add_output("%s_address" % network.code, address, is_legacy_key=True) if hash160_c and hash160_u: address = key.address(use_uncompressed=True) add_output("address_uncompressed", address, "%s address uncompressed" % network_name) add_output("%s_address_uncompressed" % network.code, address, is_legacy_key=True) # don't print segwit addresses unless we're sure we have a compressed key if hash160_c and hasattr(network, "ui") and getattr( network.ui, "_bech32_hrp"): address_segwit = network.ui.address_for_p2pkh_wit(hash160_c) if address_segwit: # this network seems to support segwit add_output("address_segwit", address_segwit, "%s segwit address" % network_name) add_output("%s_address_segwit" % network.code, address_segwit, is_legacy_key=True) p2sh_script = network.ui._script_info.script_for_p2pkh_wit( hash160_c) p2s_address = network.ui.address_for_p2s(p2sh_script) if p2s_address: add_output("p2sh_segwit", p2s_address) p2sh_script_hex = b2h(p2sh_script) add_output("p2sh_segwit_script", p2sh_script_hex, " corresponding p2sh script")
def dump_secs_hex(tx, network): sec_key_list = [] for _, tx_in in enumerate(tx.txs_in): sec_key_list.extend(network.who_signed.extract_secs(tx, _)) if len(sec_key_list): print("SECS") for sec in sec_key_list: print(b2h(sec))
def test_p2sh_wit(self): keys = [Key(i) for i in (1, 2, 3)] secs = [k.sec() for k in keys] underlying_script = script_for_multisig(2, secs) script = network.script_tools.compile( "OP_0 [%s]" % b2h(hashlib.sha256(underlying_script).digest())) self.do_test_tx(script, p2sh_lookup=build_p2sh_lookup([underlying_script]))
def save_spendable(self, spendable): tx_hash = b2h_rev(spendable.tx_hash) script = b2h(spendable.script) self._exec_sql( "insert or replace into Spendable values (?, ?, ?, ?, ?, ?, ?)", tx_hash, spendable.tx_out_index, spendable.coin_value, script, spendable.block_index_available, spendable.does_seem_spent, spendable.block_index_spent)
def as_hex(self, *args, **kwargs): """Returns a text string containing the streamed transaction encoded as hex. For information about the parameters, see :func:`Tx.stream <stream>` :return: hex string that would parse to the given transaction """ return b2h(self.as_bin(*args, **kwargs))
def dump_signatures_hex(tx, network): sigs = [] for _, tx_in in enumerate(tx.txs_in): sigs.extend(network.who_signed.extract_signatures(tx, _)) if len(sigs): print("SIGNATURES") for sig in sigs: print(b2h(sig[0]))
def coinc(args, parser): network = network_for_netcode(args.network) script_tools = network.extras.ScriptTools for arg in args.argument: compiled_script = script_tools.compile(arg) print(b2h(compiled_script)) address_p2s = network.ui.address_for_p2s(compiled_script) print(address_p2s) print(b2h(network.ui.script_for_address(address_p2s))) address_p2s_wit = network.ui.address_for_p2s_wit(compiled_script) print(address_p2s_wit) print(b2h(network.ui.script_for_address(address_p2s_wit))) print(script_tools.disassemble(compiled_script))
def coinbase_tx(cls, public_key_sec, coin_value, coinbase_bytes=b'', version=1, lock_time=0): """Create the special "first in block" transaction that includes the mining fees.""" tx_in = cls.TxIn.coinbase_tx_in(script=coinbase_bytes) COINBASE_SCRIPT_OUT = "%s OP_CHECKSIG" script_text = COINBASE_SCRIPT_OUT % b2h(public_key_sec) script_bin = BitcoinScriptTools.compile(script_text) tx_out = cls.TxOut(coin_value, script_bin) return cls(version, [tx_in], [tx_out], lock_time)
def b58(args, parser): for arg in args.input: blob, is_hex_input = parse_arg(arg, args.b) if is_hex_input: print(b2h(blob)) print(b2a_base58(blob)) print(b2a_hashed_base58(blob)) else: print(b2h(blob)) print(b2a_base58(blob)) try: blob = a2b_hashed_base58(arg) print("valid hashed b58") print("contents: ", b2h(blob)) except Exception: print("not hashed b58")
def dump_secs_hex(tx, network): sec_key_list = [] for _, tx_in in enumerate(tx.txs_in): sec_key_list.extend(network.extras.extract_secs(tx, _)) if len(sec_key_list): print("SECS") for sec in sec_key_list: print(b2h(sec))
def dump_signatures_hex(tx, network): sigs = [] for _, tx_in in enumerate(tx.txs_in): sigs.extend(network.extras.extract_signatures(tx, _)) if len(sigs): print("SIGNATURES") for sig in sigs: print(b2h(sig[0]))
def solve_old(self, hash160_lookup, tx_in_idx, hash_type=None, **kwargs): """ Sign a standard transaction. hash160_lookup: An object with a get method that accepts a hash160 and returns the corresponding (secret exponent, public_pair, is_compressed) tuple or None if it's unknown (in which case the script will obviously not be signed). A standard dictionary will do nicely here. tx_in_idx: the index of the tx_in we are currently signing """ from ...tx.pay_to import script_obj_from_script, ScriptPayToScript tx_out_script = self.tx.unspents[tx_in_idx].script if hash_type is None: hash_type = SIGHASH_ALL tx_in = self.tx.txs_in[tx_in_idx] is_p2h = self.solution_checker.is_pay_to_script_hash(tx_out_script) if is_p2h: hash160 = ScriptPayToScript.from_script(tx_out_script).hash160 p2sh_lookup = kwargs.get("p2sh_lookup") if p2sh_lookup is None: raise ValueError("p2sh_lookup not set") if hash160 not in p2sh_lookup: raise ValueError("hash160=%s not found in p2sh_lookup" % b2h(hash160)) script_to_hash = p2sh_lookup[hash160] else: script_to_hash = tx_out_script # Leave out the signature from the hash, since a signature can't sign itself. # The checksig op will also drop the signatures from its hash. def signature_for_hash_type_f(hash_type, script): return self.solution_checker.signature_hash( script, tx_in_idx, hash_type) def witness_signature_for_hash_type(hash_type, script): return self.solution_checker.signature_for_hash_type_segwit( script, tx_in_idx, hash_type) witness_signature_for_hash_type.skip_delete = True signature_for_hash_type_f.witness = witness_signature_for_hash_type the_script = script_obj_from_script(tx_out_script) kwargs[ "generator_for_signature_type_f"] = self.SolutionChecker.VM.generator_for_signature_type solution = the_script.solve( hash160_lookup=hash160_lookup, signature_type=hash_type, existing_script=self.tx.txs_in[tx_in_idx].script, existing_witness=tx_in.witness, script_to_hash=script_to_hash, signature_for_hash_type_f=signature_for_hash_type_f, **kwargs) return solution
def as_dict(self): # for use with JSON return dict(coin_value=self.coin_value, script_hex=b2h(self.script), tx_hash_hex=b2h_rev(self.tx_hash), tx_out_index=self.tx_out_index, block_index_available=self.block_index_available, does_seem_spent=int(self.does_seem_spent), block_index_spent=self.block_index_spent)
def test_p2sh_wit(self): keys = [network.keys.private(i) for i in (1, 2, 3)] secs = [k.sec() for k in keys] underlying_script = network.contract.for_multisig(2, secs) script = network.script.compile( "OP_0 [%s]" % b2h(hashlib.sha256(underlying_script).digest())) self.do_test_tx(script, p2sh_lookup=network.tx.solve.build_p2sh_lookup( [underlying_script]))
def test_p2multisig_wit(self): keys = [Key(i, generator=secp256k1_generator) for i in (1, 2, 3)] secs = [k.sec() for k in keys] underlying_script = script_for_multisig(2, secs) p2sh_script = BitcoinScriptTools.compile( "OP_0 [%s]" % b2h(hashlib.sha256(underlying_script).digest())) script = script_for_address(address_for_p2s(p2sh_script)) self.do_test_tx(script, p2sh_lookup=build_p2sh_lookup( [underlying_script, p2sh_script]))
def as_text(self): return "/".join([ b2h_rev(self.tx_hash), str(self.tx_out_index), b2h(self.script), str(self.coin_value), str(self.block_index_available), "%d" % self.does_seem_spent, str(self.block_index_spent) ])
def check_balance(private_key): address = b2h(ethereum.utils.privtoaddr(private_key)) print("address: 0x%s" % address) checksum_address = w3.toChecksumAddress(address) balance = w3.fromWei(w3.eth.getBalance(checksum_address), 'ether') return balance
def electrum_seed(self, s): """ Parse an electrum key from a text string in seed form ("E:xxx" where xxx is a 32-character hex string). Return a :class:`ElectrumWallet <pycoin.key.electrum.ElectrumWallet>` or None. """ blob = self._electrum_to_blob(s) if blob and len(blob) == 16: blob = b2h(blob) return self._network.keys.electrum_seed(seed=blob)
def output(self): """ Return a 20-byte hash corresponding to this script (or None if not applicable). """ hash160 = self._script_info.get("hash160", None) if hash160: yield ("hash160", b2h(hash160), None) address = self.address() yield ("address", address, "%s address" % self._network.network_name) yield ("%s_address" % self._network.symbol, address, "legacy")
def as_dict(self): # for use with JSON return dict( coin_value=self.coin_value, script_hex=b2h(self.script), tx_hash_hex=b2h_rev(self.tx_hash), tx_out_index=self.tx_out_index, block_index_available=self.block_index_available, does_seem_spent=int(self.does_seem_spent), block_index_spent=self.block_index_spent )
def ku_output(self): """ Return a 20-byte hash corresponding to this script (or None if not applicable). """ hash160 = self._script_info.get("hash160", None) if hash160: yield ("hash160", b2h(hash160), None) address = self.address() yield ("address", address, "%s address" % self._network.network_name) yield ("%s_address" % self._network.symbol, address, "legacy")
def f(solved_values, **kwargs): the_hash = m["the_hash"] db = kwargs.get("hash160_lookup", {}) result = db.get(the_hash) if result is None: result = kwargs.get("sec_hints", {}).get(the_hash) if result: return {m["1"]: result} if result is None: raise SolvingError("can't find public pair for %s" % b2h(the_hash)) sec = public_pair_to_sec(result[1], compressed=result[2]) return {m["1"]: sec}
def trace_script(opcode, data, pc, vmc): output.append("stack: [%s]" % ' '.join(b2h(s) for s in vmc.stack)) if len(vmc.altstack) > 0: output.append("altstack: %s" % vmc.altstack) output.append("condition stack: %s" % vmc.conditional_stack) output.append("%3d : %02x %s" % (vmc.pc, opcode, BitcoinScriptTools.disassemble_for_opcode_data(opcode, data))) if use_pdb: for line in output: print(line) output[:] = [] import pdb pdb.set_trace()
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 send_tx(self, tx): s = io.BytesIO() tx.stream(s) tx_as_hex = b2h(s.getvalue()) data = urlencode(dict(rawtx=tx_as_hex)).encode("utf8") URL = "%s/tx/send" % self.base_url try: d = urlopen(URL, data=data).read() return d except request.HTTPError as err: if err.code == 400: raise ValueError(err.readline()) raise err
def broadcast_tx(self, tx): s = io.BytesIO() tx.stream(s) tx_as_hex = b2h(s.getvalue()) data = urlencode(dict(tx=tx_as_hex)).encode("utf8") URL = self.api_domain + "/pushtx" try: d = urlopen(URL, data=data).read() return d except request.HTTPError as ex: try: d = ex.read() ex.message = d except Exception: pass raise ex
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 address_for_script_info(self, script_info): type = script_info.get("type") if type == "p2pkh": return self.address_for_p2pkh(script_info["hash160"]) if type == "p2pkh_wit": return self.address_for_p2pkh_wit(script_info["hash160"]) if type == "p2sh_wit": return self.address_for_p2sh_wit(script_info["hash256"]) if type == "p2pk": h160 = hash160(script_info["sec"]) # BRAIN DAMAGE: this isn't really a p2pkh return self.address_for_p2pkh(h160) if type == "p2sh": return self.address_for_p2sh(script_info["hash160"]) if type == "nulldata": return "(nulldata %s)" % b2h(script_info["data"]) return "???"
def main(): if len(sys.argv) != 2: print("usage: %s bip32_key_file" % sys.argv[0]) sys.exit(-1) with open(sys.argv[1], "r") as f: hwif = f.readline().strip() # turn the bip32 text into a BIP32Node object BIP32_KEY = BIP32Node.from_hwif(hwif) # create three sec_keys (these are public keys, streamed using the SEC format) SEC_0 = BIP32_KEY.subkey_for_path("0/0/0").sec() SEC_1 = BIP32_KEY.subkey_for_path("0/1/0").sec() SEC_2 = BIP32_KEY.subkey_for_path("0/2/0").sec() public_key_sec_list = [SEC_0, SEC_1, SEC_2] # create the 2-of-3 multisig script # any 2 signatures can release the funds pay_to_multisig_script = script_for_multisig(2, public_key_sec_list) # create a "2-of-3" multisig address_for_multisig the_address = address_for_p2s(pay_to_multisig_script) print("Here is your pay 2-of-3 address: %s" % the_address) print("Here is the pay 2-of-3 script: %s" % b2h(pay_to_multisig_script)) print("The hex script should go into p2sh_lookup.hex") base_dir = os.path.dirname(sys.argv[1]) print("The three WIFs are written into %s as wif0, wif1 and wif2" % base_dir) for i in range(3): wif = BIP32_KEY.subkey_for_path("0/%d/0" % i).wif() with open(os.path.join(base_dir, "wif%d" % i), "w") as f: f.write(wif)
def script_for_nulldata_push(self, data): # BRAIN DAMAGE return self._scriptTools.compile("OP_RETURN [%s]" % b2h(data))
def test_p2pkh_wit(self): key = Key(1, generator=secp256k1_generator) script = BitcoinScriptTools.compile("OP_0 [%s]" % b2h(key.hash160())) self.do_test_tx(script)
def instruction_for_opcode(self, opcode, data): if data is None or len(data) == 0: return self._script_tools.disassemble_for_opcode_data(opcode, data) return "[PUSH_%d] %s" % (opcode, b2h(data))
def unspent_to_bitcoind_dict(tx_in, tx_out): return dict( txid=b2h_rev(tx_in.previous_hash), vout=tx_in.previous_index, scriptPubKey=b2h(tx_out.script) )
def secret_exponent(self): if self._secret_exponent is None and self._initial_key: self._secret_exponent = initial_key_to_master_key(b2h(self._initial_key)) return self._secret_exponent
def __repr__(self): return "Electrum<E:%s>" % b2h(self.master_public_key())
def as_text(self): return "/".join([b2h_rev(self.tx_hash), str(self.tx_out_index), b2h(self.script), str(self.coin_value), str(self.block_index_available), "%d" % self.does_seem_spent, str(self.block_index_spent)])
def __str__(self): if self.is_coinbase(): return 'TxIn<COINBASE: %s>' % b2h(self.script) return 'TxIn<%s[%d] "%s">' % ( b2h_rev(self.previous_hash), self.previous_index, ScriptTools.disassemble(self.script))