def make_transaction(src_priv_key, dst_address, value, data): src_address = b2h(utils.privtoaddr(src_priv_key)) nonce = get_num_transactions(src_address) gas_price = get_gas_price_in_wei() data_as_string = b2h(data) start_gas = eval_startgas(src_address, dst_address, value, data_as_string, gas_price) nonce = int(nonce, 16) gas_price = int(gas_price, 16) start_gas = int(start_gas, 16) + 100000 tx = transactions.Transaction(nonce, gas_price, start_gas, dst_address, value, data).sign(src_priv_key) tx_hex = b2h(rlp.encode(tx)) tx_hash = b2h(tx.hash) if use_ether_scan: params = [{"hex": "0x" + tx_hex}] else: params = ["0x" + tx_hex] return_value = json_call("eth_sendRawTransaction", params) if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000": print "Transaction failed" return False wait_for_confirmation(tx_hash) return return_value
def create_wallet_key_output(key, network, subkey_path, add_output): ui_context = network.ui if hasattr(key, "wallet_key"): if subkey_path: add_output("subkey_path", subkey_path) add_output( "wallet_key", key.hwif(ui_context=ui_context, as_private=key.is_private())) if key.is_private(): add_output("public_version", key.hwif(ui_context=ui_context, as_private=False)) 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 add_output("tree_depth", "%d" % key.tree_depth()) add_output("fingerprint", b2h(key.fingerprint())) add_output("parent_fingerprint", b2h(key.parent_fingerprint()), "parent f'print") add_output("child_index", child_index) add_output("chain_code", b2h(key.chain_code())) add_output("private_key", "yes" if key.is_private() else "no")
def __init__(self, payer_sec, payee_sec, spend_secret_hash, expire_time): self.payer_sec = payer_sec self.payee_sec = payee_sec self.spend_secret_hash = spend_secret_hash self.expire_time = expire_time self.script = compile_deposit_script(b2h(payer_sec), b2h(payee_sec), spend_secret_hash, expire_time)
def generate_feed(block_number, nonce, ask_for_1000, bid_for_1000, private_key): hexX = h2b("%0.64X" % block_number) hexY = h2b("%0.64X" % nonce) hexZ = h2b("%0.64X" % ask_for_1000) hexW = h2b("%0.64X" % bid_for_1000) msg = hexX + hexY + hexZ + hexW msghash = b2h(utils.sha3(msg)) V, R, S = bitcoin.ecdsa_raw_sign(msghash, private_key) # print("V R S") R = utils.int_to_hex(R) S = utils.int_to_hex(S) # print("0x%x" % V, R, S) dic = {} dic['status'] = "success" data = {} data['block_number'] = block_number data['nonce'] = nonce data['bid_for_1000'] = bid_for_1000 data['ask_for_1000'] = ask_for_1000 data['message'] = "0x" + b2h(msg) data['hash'] = "0x" + msghash data['signer'] = "0x" + b2h(utils.privtoaddr(private_key)) data['v'] = V data['r'] = R data['s'] = S dic['data'] = data print(json.dumps(dic, indent=4, sort_keys=True))
def make_transaction( src_priv_key, dst_address, value, data ): src_address = b2h( utils.privtoaddr(src_priv_key) ) nonce = get_num_transactions( src_address ) gas_price = get_gas_price_in_wei() data_as_string = b2h(data) start_gas = eval_startgas( src_address, dst_address, value, data_as_string, gas_price ) nonce = int( nonce, 16 ) gas_price = int( gas_price, 16 ) start_gas = int( start_gas, 16 ) + 100000 tx = transactions.Transaction( nonce, gas_price, start_gas, dst_address, value, data ).sign(src_priv_key) tx_hex = b2h(rlp.encode(tx)) tx_hash = b2h( tx.hash ) if use_ether_scan: params = [{"hex" : "0x" + tx_hex }] else: params = ["0x" + tx_hex] return_value = json_call( "eth_sendRawTransaction", params ) if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000": print "Transaction failed" return False wait_for_confirmation(tx_hash) return return_value
def _make_transaction(self, src_priv_key, dst_address, value, data, use_increased_gas_price): src_address = b2h(utils.privtoaddr(src_priv_key)) nonce_rs = self._get_num_transactions(src_address) nonce = int(nonce_rs, base=16) log.debug(f"Using nonce {nonce}.") gas_price_rs = self._get_gas_price_in_wei() gas_price = int(gas_price_rs, base=16) if use_increased_gas_price: log.debug(f"Using increased gas price.") gas_price = int(gas_price * INCREASED_GAS_PRICE_FACTOR) log.debug(f"gas price is {gas_price}") start_gas_rs = self._eval_startgas(src=src_address, dst=dst_address, value=value, data=b2h(data), gas_price=gas_price_rs) start_gas = int(start_gas_rs, base=16) + ADDITIONAL_START_GAS_TO_BE_ON_THE_SAFE_SIDE log.debug(f"Estimated start gas is {start_gas}") tx = transactions.Transaction(nonce, gas_price, start_gas, dst_address, value, data).sign(src_priv_key) tx_hex = b2h(rlp.encode(tx)) tx_hash = b2h(tx.hash) params = ["0x" + tx_hex] return_value = self._json_call("eth_sendRawTransaction", params) if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000": print("Transaction failed") return return_value return return_value
def solve_finalize_commit(self, **kwargs): hash160_lookup = kwargs.get("hash160_lookup") sign_value = kwargs.get("sign_value") signature_type = kwargs.get("signature_type") existing_script = kwargs.get("existing_script") # FIXME validate on receiving the commit # validate payer sig opcode, data, pc = tools.get_opcode(existing_script, 0) # OP_0 opcode, payer_sig, pc = tools.get_opcode(existing_script, pc) sig_pair, actual_signature_type = parse_signature_blob(payer_sig) try: public_pair = encoding.sec_to_public_pair(self.payer_sec) sig_pair, signature_type = parse_signature_blob(payer_sig) valid = ecdsa.verify(ecdsa.generator_secp256k1, public_pair, sign_value, sig_pair) if not valid: raise Exception("Invalid payer public_pair!") except (encoding.EncodingError, UnexpectedDER): raise Exception("Invalid payer public_pair!") # sign private_key = hash160_lookup.get(encoding.hash160(self.payee_sec)) secret_exponent, public_pair, compressed = private_key payee_sig = self._create_script_signature( secret_exponent, sign_value, signature_type ) script_text = "OP_0 {payer_sig} {payee_sig} OP_1".format( payer_sig=b2h(payer_sig), payee_sig=b2h(payee_sig) ) return tools.compile(script_text)
def call_const_function(priv_key, value, contract_hash, contract_abi, function_name, args): src_address = b2h(utils.privtoaddr(priv_key)) translator = ContractTranslator(contract_abi) call = translator.encode_function_call(function_name, args) nonce = get_num_transactions(src_address) gas_price = get_gas_price_in_wei() start_gas = eval_startgas(src_address, contract_hash, value, b2h(call), gas_price) nonce = int(nonce, 16) gas_price = int(gas_price, 16) start_gas = int(start_gas, 16) + 100000 params = { "from": "0x" + src_address, "to": "0x" + contract_hash, "gas": "0x" + str(start_gas), "gasPrice": "0x" + str(gas_price), "value": str(value), "data": "0x" + b2h(call) } return_value = json_call("eth_call", [params]) return_value = h2b(return_value[2:]) # remove 0x return translator.decode(function_name, return_value)
def set_identities(self, identities): calculated_hash = merkle.merkle([id.get_hash() for id in identities], merkle.double_sha256) if calculated_hash != self.header.merkle_root: raise block.BadMerkleRootError( "calculated %s but block contains %s" % (b2h(calculated_hash), b2h(self.header.merkle_root))) else: self.identities = identities
def set_auths(self, auths): calculated_hash = merkle.merkle([auth.get_hash() for auth in auths], merkle.double_sha256) if calculated_hash != self.header.merkle_root_auths: raise block.BadMerkleRootError( "calculated %s but block contains %s" % (b2h(calculated_hash), b2h(self.header.merkle_root_auths))) else: self.auths = auths
def main(): parser = argparse.ArgumentParser(description="Bitcoin utilities. WARNING: obsolete. Use ku instead.") parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true') parser.add_argument('-1', "--hash160", help='show as hash 160', action='store_true') parser.add_argument('-v', "--verbose", help='dump all information available', action='store_true') parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true') parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true') parser.add_argument('item', help='a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address', nargs="+") args = parser.parse_args() for c in args.item: # figure out what it is: # - secret exponent # - WIF # - X/Y public key (base 10 or hex) # - sec # - hash160 # - Bitcoin address secret_exponent = parse_as_private_key(c) if secret_exponent: public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent) print("secret exponent: %d" % secret_exponent) print(" hex: %x" % secret_exponent) print("WIF: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True)) print(" uncompressed: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False)) else: public_pair = parse_as_public_pair(c) if public_pair: bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False) bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True) print("public pair x: %d" % public_pair[0]) print("public pair y: %d" % public_pair[1]) print(" x as hex: %x" % public_pair[0]) print(" y as hex: %x" % public_pair[1]) print("y parity: %s" % "odd" if (public_pair[1] & 1) else "even") print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True))) s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False)) print(" uncompressed: %s\\\n %s" % (s[:66], s[66:])) hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True) hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False) myeccpoint = encoding.public_pair_to_sec(public_pair, compressed=True) myhash = encoding.ripemd160( myeccpoint ).digest( ) print("BTSX PubKey: %s" % BTS_ADDRESS_PREFIX + encoding.b2a_base58(myeccpoint + myhash[ :4 ])) else: hash160 = parse_as_address(c) hash160_unc = None if not hash160: sys.stderr.write("can't decode input %s\n" % c) sys.exit(1) print("hash160: %s" % b2h(hash160)) if hash160_unc: print(" uncompressed: %s" % b2h(hash160_unc)) print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160)) if hash160_unc: print(" uncompressed: %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
def solve_create_commit(self, **kwargs): hash160_lookup = kwargs["hash160_lookup"] private_key = hash160_lookup.get(encoding.hash160(self.payer_sec)) secret_exponent, public_pair, compressed = private_key sig = self._create_sig(secret_exponent, **kwargs) signature_placeholder = kwargs.get("signature_placeholder", DEFAULT_PLACEHOLDER_SIGNATURE) script_asm = COMMIT_SCRIPTSIG.format( payer_sig=b2h(sig), payee_sig=b2h(signature_placeholder)) return tools.compile(script_asm)
def upload_enc_secret_to_blockchain_and_send_keys_to_nodes( secret, secret_index, ethereum_key): key = utils.sha3("password") rand1 = utils.sha3("rand1") rand2 = utils.sha3("rand2") rand3 = utils.sha3("rand3") enc_secret = encrypt(secret, key) keys1 = CreateNodeKeys(key, rand1, rand2, rand3, 1) keys2 = CreateNodeKeys(key, rand1, rand2, rand3, 2) keys3 = CreateNodeKeys(key, rand1, rand2, rand3, 3) print "uploading encrypted secret to blockchain" newSecret(ethereum_key, enc_secret) # TODO - send to nodes keys1 = [b2h(keys1[0]), b2h(keys1[1]), b2h(keys1[2])] keys2 = [b2h(keys2[0]), b2h(keys2[1]), b2h(keys2[2])] keys3 = [b2h(keys3[0]), b2h(keys3[1]), b2h(keys3[2])] #print str(keys1) print "send key share 1 to server 1" sever1.submit_keys(secret_index, keys1, 1) print "send key share 2 to server 2" sever2.submit_keys(secret_index, keys2, 2) print "send key share 3 to server 3" sever3.submit_keys(secret_index, keys3, 3)
def create_output(item, key, subkey_path=None): output_dict = {} output_order = [] def add_output(json_key, value=None, human_readable_key=None): if human_readable_key is None: human_readable_key = json_key.replace("_", " ") if value: output_dict[json_key.strip().lower()] = value output_order.append((json_key.lower(), human_readable_key)) network_name = network_name_for_netcode(key._netcode) full_network_name = full_network_name_for_netcode(key._netcode) add_output("input", item) add_output("network", full_network_name) add_output("netcode", key._netcode) create_wallet_key_output(key, subkey_path, add_output) secret_exponent = key.secret_exponent() if secret_exponent: add_output("secret_exponent", '%d' % secret_exponent) add_output("secret_exponent_hex", '%x' % secret_exponent, " hex") add_output("wif", key.wif(use_uncompressed=False)) add_output("wif_uncompressed", key.wif(use_uncompressed=True), " uncompressed") create_public_pair_output(key, add_output) hash160_c = key.hash160(use_uncompressed=False) if hash160_c: add_output("hash160", b2h(hash160_c)) hash160_u = key.hash160(use_uncompressed=True) if hash160_u: add_output("hash160_uncompressed", b2h(hash160_u), " uncompressed") if hash160_c: address = key.address(use_uncompressed=False) add_output("address", address, "%s address" % network_name) output_dict["%s_address" % key._netcode] = address if hash160_u: address = key.address(use_uncompressed=True) add_output("address_uncompressed", address, "%s address uncompressed" % network_name) output_dict["%s_address_uncompressed" % key._netcode] = address if hash160_c and address_wit_prefix_for_netcode(key._netcode): address = ScriptPayToAddressWit(b'\0', hash160_c).info()["address_f"]( key._netcode) add_output("address segwit", address, "%s segwit address" % network_name) output_dict["%s_address_segwit" % key._netcode] = address return output_dict, output_order
def fix_input_script(inp, redeem_script): """replace dummy signatures with OP_0 and add redeem script for digitaloracle compatibility""" dummy = b2h(dummy_signature(1)) ops1 = [] for op in opcode_list(inp.script): if op == dummy: op = 'OP_0' ops1.append(op) # FIXME hack to add redeem script omitted by pycoin ops1.append(b2h(redeem_script)) inp.script = compile(' '.join(ops1))
def test_verify_transaction(self): SelectParams('testnet') b = h2b('8443b07464c762d7fb404ea918a5ac9b3618d5cd6a0c5ea6e4dd5d7bbe28b154') tx_input = Spendable(200, b'18eKkAWyU9kvRNHPKxnZb6wwtPMrNmRRRA', b, 0) tx_outs = [tx_utils.create_transaction_output('mgAqW5ZCnEp7fjvpj8RUL3WxsBy8rcDcCi', 0.0000275)] op_return_val = h2b('e9cee71ab932fde863338d08be4de9dfe39ea049bdafb342ce659ec5450b69ae') tx = tx_utils.create_trx(op_return_val, 3, 'mgAqW5ZCnEp7fjvpj8RUL3WxsBy8rcDcCi', tx_outs, [tx_input]) hextx = b2h(tx.serialize()) tx_utils.verify_transaction(hextx, b2h(op_return_val))
def _create_oracle_request(self, input_chain_paths, output_chain_paths, spend_id, tx, verifications=None, callback=None): """:nodoc:""" tx = deepcopy( tx ) # keep original Tx object intact, so that it is not mutated by fix_input_scripts below. # Have the Oracle sign the tx chain_paths = [] input_scripts = [] input_txs = [] for i, inp in enumerate(tx.txs_in): input_tx = self.tx_db.get(inp.previous_hash) if input_tx is None: raise Error("could not look up tx for %s" % (b2h(inp.previous_hash))) input_txs.append(input_tx) if input_chain_paths[i] is not None: redeem_script = self._account.script_for_path( input_chain_paths[i]).script() input_scripts.append(redeem_script) chain_paths.append(input_chain_paths[i]) fix_input_script(inp, redeem_script) else: input_scripts.append(None) chain_paths.append(None) req = { "walletAgent": self._wallet_agent, "transaction": { "bytes": b2h(stream_to_bytes(tx.stream)), "inputScripts": [(b2h(script) if script else None) for script in input_scripts], "inputTransactions": [b2h(stream_to_bytes(tx.stream)) for tx in input_txs], "chainPaths": chain_paths, "outputChainPaths": output_chain_paths, "masterKeys": self._account.public_keys[0:-self.num_oracle_keys], } } if spend_id: req['spendId'] = spend_id if callback: req['callback'] = callback if verifications: req['verifications'] = verifications return req
def test_verify_transaction(self): bitcoin.SelectParams('testnet') b = h2b('8443b07464c762d7fb404ea918a5ac9b3618d5cd6a0c5ea6e4dd5d7bbe28b154') tx_input = Spendable(200, b'18eKkAWyU9kvRNHPKxnZb6wwtPMrNmRRRA', b, 0) tx_outs = [tx_utils.create_transaction_output('mgAqW5ZCnEp7fjvpj8RUL3WxsBy8rcDcCi', 0.0000275)] op_return_val = h2b('e9cee71ab932fde863338d08be4de9dfe39ea049bdafb342ce659ec5450b69ae') tx = tx_utils.create_trx(op_return_val, 3, 'mgAqW5ZCnEp7fjvpj8RUL3WxsBy8rcDcCi', tx_outs, [tx_input]) hextx = b2h(tx.serialize()) tx_utils.verify_transaction(hextx, b2h(op_return_val))
def __init__(self, delay_time, spend_secret_hash, payee_sec, payer_sec, revoke_secret_hash): self.delay_time = delay_time self.spend_secret_hash = spend_secret_hash self.payee_sec = payee_sec self.payer_sec = payer_sec self.revoke_secret_hash = revoke_secret_hash self.script = compile_commit_script( b2h(payer_sec), b2h(payee_sec), spend_secret_hash, revoke_secret_hash, delay_time )
def solve_change(self, **kwargs): hash160_lookup = kwargs["hash160_lookup"] spend_secret = kwargs["spend_secret"] private_key = hash160_lookup.get(encoding.hash160(self.payer_sec)) secret_exponent, public_pair, compressed = private_key sig = self._create_sig(secret_exponent, **kwargs) spend_secret_hash = get_deposit_spend_secret_hash(b2h(self.script)) provided_spend_secret_hash = b2h(encoding.hash160(h2b(spend_secret))) assert (spend_secret_hash == provided_spend_secret_hash) script_asm = CHANGE_SCRIPTSIG.format(sig=b2h(sig), secret=spend_secret) return tools.compile(script_asm)
def __repr__(self): r = self.public_copy() if getattr(r, "_default_ui_context", None): 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 __init__(self, delay_time, spend_secret_hash, payee_sec, payer_sec, revoke_secret_hash): self.delay_time = delay_time self.spend_secret_hash = spend_secret_hash self.payee_sec = payee_sec self.payer_sec = payer_sec self.revoke_secret_hash = revoke_secret_hash self.script = h2b( compile_commit_script(b2h(payer_sec), b2h(payee_sec), spend_secret_hash, revoke_secret_hash, delay_time))
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 main(): parser = argparse.ArgumentParser(description="Bitcoin utilities. WARNING: obsolete. Use ku instead.") parser.add_argument('-a', "--address", help='show as Bitcoin address', action='store_true') parser.add_argument('-1', "--hash160", help='show as hash 160', action='store_true') parser.add_argument('-v', "--verbose", help='dump all information available', action='store_true') parser.add_argument('-w', "--wif", help='show as Bitcoin WIF', action='store_true') parser.add_argument('-n', "--uncompressed", help='show in uncompressed form', action='store_true') parser.add_argument('item', help='a WIF, secret exponent, X/Y public pair, SEC (as hex), hash160 (as hex), Bitcoin address', nargs="+") args = parser.parse_args() for c in args.item: # figure out what it is: # - secret exponent # - WIF # - X/Y public key (base 10 or hex) # - sec # - hash160 # - Bitcoin address secret_exponent = parse_as_private_key(c) if secret_exponent: public_pair = ecdsa.public_pair_for_secret_exponent(secp256k1.generator_secp256k1, secret_exponent) print("secret exponent: %d" % secret_exponent) print(" hex: %x" % secret_exponent) print("WIF: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=True)) print(" uncompressed: %s" % encoding.secret_exponent_to_wif(secret_exponent, compressed=False)) else: public_pair = parse_as_public_pair(c) if public_pair: bitcoin_address_uncompressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=False) bitcoin_address_compressed = encoding.public_pair_to_bitcoin_address(public_pair, compressed=True) print("public pair x: %d" % public_pair[0]) print("public pair y: %d" % public_pair[1]) print(" x as hex: %x" % public_pair[0]) print(" y as hex: %x" % public_pair[1]) print("y parity: %s" % "odd" if (public_pair[1] & 1) else "even") print("key pair as sec: %s" % b2h(encoding.public_pair_to_sec(public_pair, compressed=True))) s = b2h(encoding.public_pair_to_sec(public_pair, compressed=False)) print(" uncompressed: %s\\\n %s" % (s[:66], s[66:])) hash160 = encoding.public_pair_to_hash160_sec(public_pair, compressed=True) hash160_unc = encoding.public_pair_to_hash160_sec(public_pair, compressed=False) else: hash160 = parse_as_address(c) hash160_unc = None if not hash160: sys.stderr.write("can't decode input %s\n" % c) sys.exit(1) print("hash160: %s" % b2h(hash160)) if hash160_unc: print(" uncompressed: %s" % b2h(hash160_unc)) print("Bitcoin address: %s" % encoding.hash160_sec_to_bitcoin_address(hash160)) if hash160_unc: print(" uncompressed: %s" % encoding.hash160_sec_to_bitcoin_address(hash160_unc))
def solve_create_commit(self, **kwargs): hash160_lookup = kwargs["hash160_lookup"] private_key = hash160_lookup.get(encoding.hash160(self.payer_sec)) secret_exponent, public_pair, compressed = private_key sig = self._create_script_signature( secret_exponent, kwargs["sign_value"], kwargs["signature_type"] ) signature_placeholder = kwargs.get("signature_placeholder", DEFAULT_PLACEHOLDER_SIGNATURE) script_text = "OP_0 {payer_sig} {payee_sig} OP_1".format( payer_sig=b2h(sig), payee_sig=b2h(signature_placeholder) ) return tools.compile(script_text)
def from_script(cls, script): r = cls.match(script) if r: delay_time = get_commit_delay_time(b2h(cls.TEMPLATE)) spend_secret_hash = b2h(r["PUBKEYHASH_LIST"][0]) payee_sec = r["PUBKEY_LIST"][0] revoke_secret_hash = b2h(r["PUBKEYHASH_LIST"][1]) payer_sec = r["PUBKEY_LIST"][1] obj = cls(delay_time, spend_secret_hash, payee_sec, payer_sec, revoke_secret_hash) assert (obj.script == script) return obj raise ValueError("bad script") # pragma: no cover
def from_script(cls, script): r = cls.match(script) if r: payer_sec = r["PUBKEY_LIST"][0] payee_sec = r["PUBKEY_LIST"][1] assert (payer_sec == r["PUBKEY_LIST"][2]) assert (payer_sec == r["PUBKEY_LIST"][3]) spend_secret_hash = b2h(r["PUBKEYHASH_LIST"][0]) expire_time = get_deposit_expire_time(b2h(cls.TEMPLATE)) obj = cls(payer_sec, payee_sec, spend_secret_hash, expire_time) assert (obj.script == script) return obj raise ValueError("bad script") # pragma: no cover
def from_script(cls, script): r = cls.match(script) if r: delay_time = get_commit_delay_time(cls.TEMPLATE) spend_secret_hash = b2h(r["PUBKEYHASH_LIST"][0]) payee_sec = r["PUBKEY_LIST"][0] revoke_secret_hash = b2h(r["PUBKEYHASH_LIST"][1]) payer_sec = r["PUBKEY_LIST"][1] obj = cls(delay_time, spend_secret_hash, payee_sec, payer_sec, revoke_secret_hash) assert(obj.script == script) return obj raise ValueError("bad script")
def _validate(reference_script_hex, untrusted_script_hex): ref_script_bin = h2b(reference_script_hex) untrusted_script_bin = h2b(untrusted_script_hex) r_pc = 0 u_pc = 0 while r_pc < len(ref_script_bin) and u_pc < len(untrusted_script_bin): r_opcode, r_data, r_pc = tools.get_opcode(ref_script_bin, r_pc) u_opcode, u_data, u_pc = tools.get_opcode(untrusted_script_bin, u_pc) if r_data is not None and b2h(r_data) == "deadbeef": continue # placeholder for expected variable if r_opcode != u_opcode or r_data != u_data: raise InvalidScript(b2h(untrusted_script_bin)) if r_pc != len(ref_script_bin) or u_pc != len(untrusted_script_bin): raise InvalidScript(b2h(untrusted_script_bin))
def test_batch_handler_web_prepare(self): web_request = json.dumps([{'allyourbasearebelongtous': True}]) web_handler, certificates_to_issue = self._get_certificate_batch_web_handler() web_handler.set_certificates_in_batch(web_request) single_item_batch = web_handler.prepare_batch() self.assertEqual( b2h(single_item_batch), '38451f557bc2b5ad74012d3389798281b993fc7375c024615ed73fb147670ba7') web_handler, certificates_to_issue = self._get_certificate_batch_web_handler() web_handler.set_certificates_in_batch( [{'allyourbasearebelongtous': True}, {'allyourbasearebelongtous': False}]) multi_batch = web_handler.prepare_batch() self.assertNotEqual(b2h(single_item_batch), b2h(multi_batch))
def solve_change(self, **kwargs): hash160_lookup = kwargs["hash160_lookup"] spend_secret = kwargs["spend_secret"] private_key = hash160_lookup.get(encoding.hash160(self.payer_sec)) secret_exponent, public_pair, compressed = private_key sig = self._create_script_signature( secret_exponent, kwargs["sign_value"], kwargs["signature_type"] ) spend_secret_hash = get_deposit_spend_secret_hash(self.script) provided_spend_secret_hash = b2h(hash160(h2b(spend_secret))) assert(spend_secret_hash == provided_spend_secret_hash) script_text = "{sig} {secret} OP_1 OP_0".format( sig=b2h(sig), secret=spend_secret ) return tools.compile(script_text)
def make_transaction(src_priv_key, dst_address, value, data): src_address = b2h(utils.privtoaddr(src_priv_key)) nonce = get_num_transactions(src_address) gas_price = get_gas_price_in_wei() data_as_string = b2h(data) # print len(data_as_string) # if len(data) > 0: # data_as_string = "0x" + data_as_string start_gas = eval_startgas(src_address, dst_address, value, data_as_string, gas_price) nonce = int(nonce, 16) gas_price = int(gas_price, 16) #int(gas_price, 16)/20 start_gas = int(start_gas, 16) + 100000 start_gas = 4612288 # // 10 #start_gas = 38336 #start_gas = 30048 # start_gas = 5000000 for i in range(1): tx = transactions.Transaction(nonce, gas_price, start_gas, dst_address, value, data).sign(src_priv_key) tx_hex = b2h(rlp.encode(tx)) tx_hash = b2h(tx.hash) #print(tx_hex) # print str(tx_hash) if use_ether_scan: params = [{"hex" : "0x" + tx_hex }] else: params = ["0x" + tx_hex] return_value = json_call("eth_sendRawTransaction", params) if return_value == "0x0000000000000000000000000000000000000000000000000000000000000000": print "Transaction failed" return return_value nonce += 1 #print str(nonce) wait_for_confirmation(tx_hash) return return_value
def create_transaction(self, op_return_bytes): if self.prepared_inputs: inputs = self.prepared_inputs else: spendables = self.connector.get_unspent_outputs(self.issuing_address) if not spendables: error_message = 'No money to spend at address {}'.format(self.issuing_address) logging.error(error_message) raise InsufficientFundsError(error_message) cost = self.transaction_creator.estimate_cost_for_certificate_batch(self.tx_cost_constants) current_total = 0 inputs = [] random.shuffle(spendables) for s in spendables: inputs.append(s) current_total += s.coin_value if current_total > cost: break tx = self.transaction_creator.create_transaction(self.tx_cost_constants, self.issuing_address, inputs, op_return_bytes) hex_tx = b2h(tx.serialize()) logging.info('Unsigned hextx=%s', hex_tx) prepared_tx = tx_utils.prepare_tx_for_signing(hex_tx, inputs) return prepared_tx
def issue_transaction(self, blockchain_bytes): eth_data_field = b2h(blockchain_bytes) prepared_tx = self.create_transaction(blockchain_bytes) signed_tx = self.sign_transaction(prepared_tx) self.verify_transaction(signed_tx, eth_data_field) txid = self.broadcast_transaction(signed_tx) return txid
def verify_script(script_signature, script_public_key, signature_for_hash_type_f, expected_hash_type=None): stack = [] is_p2h = (len(script_public_key) == 23 and script_public_key[0] == opcodes.OP_HASH160 and script_public_key[-1] == opcodes.OP_EQUAL) if not eval_script(script_signature, signature_for_hash_type_f, expected_hash_type, stack): logging.debug("script_signature did not evaluate") return False if is_p2h: signatures, alt_script_public_key = stack[:-1], stack[-1] from pycoin.tx.script import tools from pycoin import serialize def sub(x): if x == '00': return '0' return x s1 = [sub(serialize.b2h(s)) for s in signatures] alt_script_signature = tools.compile(" ".join(s1)) if not eval_script(script_public_key, signature_for_hash_type_f, expected_hash_type, stack): logging.debug("script_public_key did not evaluate") return False if is_p2h and stack[-1] == VCH_TRUE: return verify_script(alt_script_signature, alt_script_public_key, signature_for_hash_type_f, expected_hash_type=expected_hash_type) return stack[-1] == VCH_TRUE
def reformat(spendable): return { "txid": b2h_rev(spendable.tx_hash), "index": spendable.tx_out_index, "value": spendable.coin_value, "script": b2h(spendable.script), }
def create_key(asset, netcode="BTC"): secure_random_data = os.urandom(32) key = BIP32Node.from_master_secret(secure_random_data, netcode=netcode) return { "asset": asset, "pubkey": b2h(key.sec()), "wif": key.wif(), "address": key.address(), }
def save_spendable(self, spendable): tx_hash = b2h_rev(spendable.tx_hash) script = b2h(spendable.script) c = 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 hash160data_txout(hexdata, value=548): data = binary(hexdata) if len(data) != 20: # 160 bit raise exceptions.InvalidHash160DataSize(len(data)) script_text = "OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG" % b2h(data) script_bin = tools.compile(script_text) return TxOut(value, script_bin)
def nulldata_txout(hexdata): data = binary(hexdata) if len(data) > 40: raise exceptions.MaxNulldataExceeded(len(data)) script_text = "OP_RETURN %s" % b2h(data) script_bin = tools.compile(script_text) return TxOut(0, script_bin)
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 hash160data_txout(hexdata, dust_limit=common.DUST_LIMIT): data = binary(hexdata) if len(data) != 20: # 160 bit raise exceptions.InvalidHash160DataSize(len(data)) script_text = "OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG" % b2h(data) script_bin = tools.compile(script_text) return TxOut(dust_limit, script_bin)
def solve_timeout(self, **kwargs): hash160_lookup = kwargs["hash160_lookup"] private_key = hash160_lookup.get(encoding.hash160(self.payer_sec)) secret_exponent, public_pair, compressed = private_key sig = self._create_script_signature( secret_exponent, kwargs["sign_value"], kwargs["signature_type"] ) return tools.compile("{sig} OP_0 OP_0".format(sig=b2h(sig)))
def main(): parser = argparse.ArgumentParser(description="Create a Bitcoin transaction.", epilog=EPILOG) parser.add_argument('-g', "--generate-unsigned", help='generate unsigned transaction', action='store_true') parser.add_argument('-f', "--private-key-file", help='file containing WIF or BIP0032 private keys', metavar="path-to-file-with-private-keys", type=argparse.FileType('r')) parser.add_argument('-p', "--private-key", help='WIF or BIP0032 private key', metavar="private-key", type=str, nargs="+") parser.add_argument('-c', "--coinbase", help='Create a (bogus) coinbase transaction. For testing purposes. You must include exactly one WIF in this case.', action='store_true') parser.add_argument("txinfo", help='either a hex dump of the unsigned transaction, or a list of bitcoin addresses with optional "/value" if they are destination addresses', nargs="+") args = parser.parse_args() if args.coinbase: new_tx = create_coinbase_tx(parser) tx_hash_hex = b2h(new_tx.hash()) tx_output_index = 0 tx_out_val = str(satoshi_to_btc(new_tx.txs_out[tx_output_index].coin_value)) tx_out_script_hex = b2h(new_tx.txs_out[tx_output_index].script) # product output in the form: # tx_hash_hex/tx_output_index_decimal/tx_out_val/tx_out_script_hex # which can be used as a fake input to a later transaction print("/".join([tx_hash_hex, str(tx_output_index), tx_out_val, tx_out_script_hex])) return unsigned_tx = get_unsigned_tx(parser) actual_tx_fee = check_fees(unsigned_tx) if actual_tx_fee < 0: sys.exit(1) print("transaction fee: %s BTC" % satoshi_to_btc(actual_tx_fee)) if args.generate_unsigned: s = io.BytesIO() unsigned_tx.stream(s) tx_bytes = s.getvalue() tx_hex = b2h(tx_bytes) print(tx_hex) sys.exit(0) secret_exponents = secret_exponents_iterator(args.private_key_file, args.private_key) solver = SecretExponentSolver(secret_exponents) new_tx = unsigned_tx.sign(solver) s = io.BytesIO() new_tx.stream(s) tx_bytes = s.getvalue() tx_hex = b2h(tx_bytes) print("copy the following hex to http://blockchain.info/pushtx to put the transaction on the network:\n") print(tx_hex)
def issue_transaction(self, op_return_bytes): op_return_value = b2h(op_return_bytes) prepared_tx = self.create_transaction(op_return_bytes) signed_tx = self.sign_transaction(prepared_tx) self.verify_transaction(signed_tx, op_return_value) txid = self.broadcast_transaction(signed_tx) logging.info('Broadcast transaction with txid %s', txid) return txid
def sec_as_hex(self, use_uncompressed=None): """ Return the SEC representation of this key as hex text. If use_uncompressed is not set, the preferred representation is returned. """ sec = self.sec(use_uncompressed=use_uncompressed) if sec is None: return None return b2h(sec)
def issue_transaction(self, blockchain_bytes): op_return_value = b2h(blockchain_bytes) prepared_tx = self.create_transaction(blockchain_bytes) signed_tx = self.sign_transaction(prepared_tx) self.verify_transaction(signed_tx, op_return_value) txid = self.broadcast_transaction(signed_tx) # this logging is already done in issuer # logging.info('Broadcast transaction with txid %s', txid) return txid
def txout(testnet, targetaddress, value): testnet = flag(testnet) targetaddress = address(testnet, targetaddress) value = positive_integer(value) prefix = b'\x6f' if testnet else b"\0" hash160 = b2h(bitcoin_address_to_hash160_sec(targetaddress, prefix)) script_text = "OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG" % hash160 script_bin = tools.compile(script_text) return TxOut(value, script_bin)
def trace_script(pc, opcode, data, stack, altstack, if_condition_stack, is_signature): from pycoin.serialize import b2h print("stack: [%s]" % ' '.join(b2h(s) for s in stack)) if len(altstack) > 0: print("altstack: %s" % altstack) print("condition stack: %s" % if_condition_stack) print("%3d : %02x %s" % (pc, opcode, disassemble_for_opcode_data(opcode, data))) if use_pdb: import pdb pdb.set_trace()
def __init__(self, secret_exponents): super(OfflineAwareSolver, self).__init__(secret_exponents) STANDARD_SCRIPT_OUT = "OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG" self.script_hash160 = [] for se in secret_exponents: pp = public_pair_for_secret_exponent(generator_secp256k1, se) h160sec = public_pair_to_hash160_sec(pp, False) script_text = STANDARD_SCRIPT_OUT % b2h(h160sec) print script_text self.script_hash160.append(compile(script_text))