def output_index_for_address(self, address_or_hash160): """ Returns the index of the output in this transaction that pays to the provided address. Args: address_or_hash160 (str or bytes): If a string, a Base58Check encoded address. If bytes, the hash160 of the public key. Returns: int: The index of the corresponding output or None. """ if isinstance(address_or_hash160, str): ver, h160 = address_to_key_hash(address_or_hash160) elif isinstance(address_or_hash160, bytes): h160 = address_or_hash160 else: raise TypeError("address_or_hash160 can only be bytes or str") rv = None for i, o in enumerate(self.outputs): scr = o.script if scr.is_p2pkh() or scr.is_p2sh(): if scr.get_hash160() == h160: rv = i break return rv
def test_op_checklocktimeverify(): prev_txn_hash = Hash('6eae1e03964799c4e29039db459ea4fad4df57c2b06f730b60032a48fb075620') txn_input = TransactionInput(prev_txn_hash, 0, Script(""), 1) addr = "1HJiL6AYYmtkbJzC9bxAorznWijwNK5Z8E" out_script_pub_key = Script.build_p2pkh( utils.address_to_key_hash(addr)[1]) txn_output = TransactionOutput(9000, out_script_pub_key) # Create the txn txn = Transaction(Transaction.DEFAULT_TRANSACTION_VERSION, [txn_input], [txn_output], 367987) # This is one more (367988) so it should fail s = Script("0x749d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid # This is negative, so it should fail s = Script("0xfff74d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid # This is one less (367986) so it should pass s = Script("0x729d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.stop # Now reformulate the txn so that the input is finalized txn_input.sequence_num = 0xffffffff si.run_script(s) assert not si.valid # The last check is if there are mismatching notions of locktime txn_input.sequence_num = 1 txn.lock_time = 500000001 si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid
def build_signed_transaction(self, addresses_and_amounts, use_unconfirmed=False, insert_into_cache=False, fees=None, expiration=0): address = list(addresses_and_amounts.keys())[0] amount = addresses_and_amounts[address] inputs = [ bitcoin.TransactionInput(self.MOCK_UTXO, self.MOCK_UTXO_INDEX, bitcoin.Script(), 0xffffffff) ] outputs = [ bitcoin.TransactionOutput( amount, bitcoin.Script.build_p2sh( utils.address_to_key_hash(address)[1])) ] tx = bitcoin.Transaction( bitcoin.Transaction.DEFAULT_TRANSACTION_VERSION, inputs, outputs, 0x0) tx.sign_input(0, bitcoin.Transaction.SIG_HASH_ALL, self.PRIVATE_KEY, self.MOCK_UTXO_SCRIPT_PUBKEY) return [tx]
def test_op_checklocktimeverify(): prev_txn_hash = Hash( '6eae1e03964799c4e29039db459ea4fad4df57c2b06f730b60032a48fb075620') txn_input = TransactionInput(prev_txn_hash, 0, Script(""), 1) addr = "1HJiL6AYYmtkbJzC9bxAorznWijwNK5Z8E" out_script_pub_key = Script.build_p2pkh(utils.address_to_key_hash(addr)[1]) txn_output = TransactionOutput(9000, out_script_pub_key) # Create the txn txn = Transaction(Transaction.DEFAULT_TRANSACTION_VERSION, [txn_input], [txn_output], 367987) # This is one more (367988) so it should fail s = Script("0x749d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid # This is negative, so it should fail s = Script("0xfff74d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid # This is one less (367986) so it should pass s = Script("0x729d05 OP_CHECKLOCKTIMEVERIFY") si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.stop # Now reformulate the txn so that the input is finalized txn_input.sequence_num = 0xffffffff si.run_script(s) assert not si.valid # The last check is if there are mismatching notions of locktime txn_input.sequence_num = 1 txn.lock_time = 500000001 si = ScriptInterpreter(txn=txn, input_index=0, sub_script=out_script_pub_key) si.run_script(s) assert not si.valid
def write_ew_message(msg): """Write a message to the blockchain.""" print("write_ew_message({})" % msg) # Create a bitcoin script object with our message if len(msg) > 72: raise Exception('Message is too long and may not be accepted.') msg = "EW " + msg message_script = Script('OP_RETURN 0x{}'.format(utils.bytes_to_str(msg.encode()))) # Define the fee we're willing to pay for the tx tx_fee = 11000 # Get the first UTXO from our set that can cover the fee utxo = None for utxo_addr, utxos in wallet.get_utxos().items(): for u in utxos: if u.value > tx_fee: utxo = u break if utxo: break if not utxo: raise Exception('No UTXOs available to pay for the transaction.') # Build the transaction inputs (there is only one, but Transaction expects a list) inputs = [TransactionInput(outpoint=utxo.transaction_hash, outpoint_index=utxo.outpoint_index, script=utxo.script, sequence_num=0xffffffff)] outputs = [] # Build one output with our custom message script outputs.append(TransactionOutput(value=0, script=message_script)) # Build another output to pay the UTXO money back to one of our addresses _, change_key_hash = utils.address_to_key_hash(wallet._accounts[0].get_next_address(True)) outputs.append(TransactionOutput(value=utxo.value - tx_fee, script=Script.build_p2pkh(change_key_hash))) # Build an unsigned transaction object txn = Transaction(version=Transaction.DEFAULT_TRANSACTION_VERSION, inputs=inputs, outputs=outputs, lock_time=0 ) # Sign the transaction with the correct private key private_key = wallet.get_private_key(utxo_addr) txn.sign_input(input_index=0, hash_type=Transaction.SIG_HASH_ALL, private_key=private_key, sub_script=utxo.script ) # Broadcast the transaction tx = wallet.broadcast_transaction(txn.to_hex()) return tx
def set_txn_side_effect_for_hd_discovery(self): # For each used account, there are at least 2 calls required: # 1 for the first DISCOVERY_INCREMENT payout addresses and 1 # for the first DISCOVERY_INCREMENT change # addresses. Depending on the number of used addresses for the # account, this will change. effects = [] n = self._num_used_accounts if n == 0: n = 1 for acct_num in range(n): for change in [0, 1]: num_used = self._num_used_addresses[acct_num][change] r = math.ceil((num_used + HDAccount.GAP_LIMIT) / self.address_increment) k = 'change_addresses' if change else 'payout_addresses' addr_list = self._acct_keys[acct_num][k] if change: metadata = dict(block=234790 + r, block_hash=Hash("000000000000000007d57f03ebe36dbe4f87ab2f340e93b45999ab249b6dc0df"), confirmations=23890 - r) else: metadata = dict(block=None, block_hash=None, confirmations=0) if r == 0: r = 1 for i in range(r): start = i * self.address_increment end = (i + 1) * self.address_increment addr_range = range(start, end) out = TransactionOutput(value=100000, script=Script.build_p2pkh( address_to_key_hash( addr_list[i])[1])) dummy_txn = Transaction(1, [], [out], 0) m = MockTxnDict(num_used=num_used, addr_range=addr_range, addr_list=addr_list, used_value=[dict(metadata=metadata, transaction=dummy_txn)], unused_value=[]) effects.append(m) self.get_transactions.side_effect = effects return len(effects)
def build_signed_transaction( self, addresses_and_amounts, use_unconfirmed=False, insert_into_cache=False, fees=None, expiration=0): address = list(addresses_and_amounts.keys())[0] amount = addresses_and_amounts[address] inputs = [bitcoin.TransactionInput(self.MOCK_UTXO, self.MOCK_UTXO_INDEX, bitcoin.Script(), 0xffffffff)] outputs = [bitcoin.TransactionOutput(amount, bitcoin.Script.build_p2sh(utils.address_to_key_hash(address)[1]))] tx = bitcoin.Transaction(bitcoin.Transaction.DEFAULT_TRANSACTION_VERSION, inputs, outputs, 0x0) tx.sign_input(0, bitcoin.Transaction.SIG_HASH_ALL, self.PRIVATE_KEY, self.MOCK_UTXO_SCRIPT_PUBKEY) return [tx]
def test_op_checksig(): # This is from the same example as in test_signing.py txn = Transaction.from_hex( "0100000001205607fb482a03600b736fb0c257dfd4faa49e45db3990e2c4994796031eae6e000000001976a914e9f061ff2c9885c7b137de35e416cbd5d3e1087c88acffffffff0128230000000000001976a914f1fd1dc65af03c30fe743ac63cef3a120ffab57d88ac00000000" ) # nopep8 pub_key_hex = "0x04e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbef" # nopep8 sig_hex = "0x3045022100ed84be709227397fb1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd826201" # nopep8 s = Script("%s %s OP_CHECKSIG" % (sig_hex, pub_key_hex)) prev_script_pub_key = Script.build_p2pkh( utils.address_to_key_hash("1NKxQnbtKDdL6BY1UaKdrzCxQHfn3TQnqZ")[1]) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 1 assert si.stack[0] is True s = Script("%s %s OP_CHECKSIGVERIFY" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 0 assert not si.stop # Try it once more with an incorrect sig pub_key_hex = "0x04e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbef" # nopep8 sig_hex = "0x3045022100ed84be709227397fc1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd826201" # nopep8 s = Script("%s %s OP_CHECKSIG" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 1 assert si.stack[0] is False s = Script("%s %s OP_CHECKSIGVERIFY" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 0 assert si.stop
def test_sign_txn(): # Let's create a txn trying to spend one of Satoshi's coins: block 1 # We make the (false) assertion that we own the private key (private_key1) # and for a raw txn, we put the scriptPubKey associated with that private key address1 = keys[0][1].address(compressed=False) address2 = keys[1][1].address(compressed=False) # Real txn in block 369023 to keys[0] prev_txn_hash = hash.Hash( '6eae1e03964799c4e29039db459ea4fad4df57c2b06f730b60032a48fb075620') prev_script_pub_key = script.Script.build_p2pkh( utils.address_to_key_hash(address1)[1]) txn_input = txn.TransactionInput(prev_txn_hash, 0, script.Script(""), 0xffffffff) # Build the output so that it pays out to address2 out_script_pub_key = script.Script.build_p2pkh( utils.address_to_key_hash(address2)[1]) txn_output = txn.TransactionOutput(9000, out_script_pub_key) # 1000 satoshi fee # Create the txn transaction = txn.Transaction(txn.Transaction.DEFAULT_TRANSACTION_VERSION, [txn_input], [txn_output], 0) # Now sign input 0 (there is only 1) transaction.sign_input(0, txn.Transaction.SIG_HASH_ALL, keys[0][0], prev_script_pub_key) # Dump it out as hex signed_txn_hex = transaction.to_hex() # The above txn was submitted via bitcoin-cli. # See: https://www.blocktrail.com/BTC/tx/695f0b8605cc8a117c3fe5b959e6ee2fabfa49dcc615ac496b5dd114105cd360 assert signed_txn_hex == "0100000001205607fb482a03600b736fb0c257dfd4faa49e45db3990e2c4994796031eae6e000000008b483045022100ed84be709227397fb1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd8262014104e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbefffffffff0128230000000000001976a914f1fd1dc65af03c30fe743ac63cef3a120ffab57d88ac00000000" # nopep8 assert transaction.verify_input_signature(0, prev_script_pub_key) assert not transaction.verify_input_signature(0, out_script_pub_key)
def test_op_checksig(): # This is from the same example as in test_signing.py txn = Transaction.from_hex("0100000001205607fb482a03600b736fb0c257dfd4faa49e45db3990e2c4994796031eae6e000000001976a914e9f061ff2c9885c7b137de35e416cbd5d3e1087c88acffffffff0128230000000000001976a914f1fd1dc65af03c30fe743ac63cef3a120ffab57d88ac00000000") # nopep8 pub_key_hex = "0x04e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbef" # nopep8 sig_hex = "0x3045022100ed84be709227397fb1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd826201" # nopep8 s = Script("%s %s OP_CHECKSIG" % (sig_hex, pub_key_hex)) prev_script_pub_key = Script.build_p2pkh(utils.address_to_key_hash( "1NKxQnbtKDdL6BY1UaKdrzCxQHfn3TQnqZ")[1]) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 1 assert si.stack[0] is True s = Script("%s %s OP_CHECKSIGVERIFY" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 0 assert not si.stop # Try it once more with an incorrect sig pub_key_hex = "0x04e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbef" # nopep8 sig_hex = "0x3045022100ed84be709227397fc1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd826201" # nopep8 s = Script("%s %s OP_CHECKSIG" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 1 assert si.stack[0] is False s = Script("%s %s OP_CHECKSIGVERIFY" % (sig_hex, pub_key_hex)) si = ScriptInterpreter(txn=txn, input_index=0, sub_script=prev_script_pub_key) si.run_script(s) assert len(si.stack) == 0 assert si.stop
def test_sign_txn(): # Let's create a txn trying to spend one of Satoshi's coins: block 1 # We make the (false) assertion that we own the private key (private_key1) # and for a raw txn, we put the scriptPubKey associated with that private key address1 = keys[0][1].address(compressed=False) address2 = keys[1][1].address(compressed=False) # Real txn in block 369023 to keys[0] prev_txn_hash = hash.Hash('6eae1e03964799c4e29039db459ea4fad4df57c2b06f730b60032a48fb075620') prev_script_pub_key = script.Script.build_p2pkh(utils.address_to_key_hash(address1)[1]) txn_input = txn.TransactionInput(prev_txn_hash, 0, script.Script(""), 0xffffffff) # Build the output so that it pays out to address2 out_script_pub_key = script.Script.build_p2pkh(utils.address_to_key_hash(address2)[1]) txn_output = txn.TransactionOutput(9000, out_script_pub_key) # 1000 satoshi fee # Create the txn transaction = txn.Transaction(txn.Transaction.DEFAULT_TRANSACTION_VERSION, [txn_input], [txn_output], 0) # Now sign input 0 (there is only 1) transaction.sign_input(0, txn.Transaction.SIG_HASH_ALL, keys[0][0], prev_script_pub_key) # Dump it out as hex signed_txn_hex = transaction.to_hex() # The above txn was submitted via bitcoin-cli. # See: https://www.blocktrail.com/BTC/tx/695f0b8605cc8a117c3fe5b959e6ee2fabfa49dcc615ac496b5dd114105cd360 assert signed_txn_hex == "0100000001205607fb482a03600b736fb0c257dfd4faa49e45db3990e2c4994796031eae6e000000008b483045022100ed84be709227397fb1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd8262014104e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbefffffffff0128230000000000001976a914f1fd1dc65af03c30fe743ac63cef3a120ffab57d88ac00000000" # nopep8 assert transaction.verify_input_signature(0, prev_script_pub_key) assert not transaction.verify_input_signature(0, out_script_pub_key)