Rajat Rao
Rajat Rao

Reputation: 9

Hashlock Transaction in bitcoin

I wanted to create a hashlocked transaction in bitcoin as a learning exercise. I am unable to verify whether the transaction has been spent successfully. I tried changing the preimage in the spending transaction but the result I got was the same ass when i was giving the correct preimage. What is the best way to figure out if the transaction was spent successfully?

This is the code I came up with:-

`


import util
import hashlib
from test_framework.address import script_to_p2sh
from test_framework.script import *



secret_preimage = b'my_secret_value'


hash_value = hashlib.sha256(secret_preimage).digest()


redeem_script = [OP_SHA256,hash_value,OP_EQUALVERIFY]


p2sh_address = script_to_p2sh(CScript(redeem_script))

print("P2SH address: ", p2sh_address)


test = util.TestWrapper()
test.setup()
node = test.nodes[0]


tx = node.generate_and_send_coins(p2sh_address)
tx_information = node.decoderawtransaction(tx.serialize().hex())

print(f"Transaction Id: {tx_information['txid']}")
print(f"Transaction sent to: {p2sh_address}")

spending_tx = test.create_spending_transaction(tx.hash)


scriptSig = [secret_preimage]
spending_tx.vin[0].scriptSig = CScript(scriptSig)

test_status = node.test_transaction(spending_tx)

tx_information = node.decoderawtransaction(spending_tx.serialize().hex())
print("\n\n #######  Spending Transaction  #######   \n\n")
print(f"Spending Transaction Id: {tx_information['txid']}")
print(f"Spending Transaction sent to: {p2sh_address}")
print("The spending transaction information:")
print(tx_information)

test.shutdown()

However, the test for mempool acceptance yields: {'txid': '30541ffc7eaf8942984207976904925f7898d53bd57f7872606d73351a5163bc', 'allowed': False, 'reject-reason': 'mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element)'} What am I doing wrong, and how can I fix it? Thanks in advance

Upvotes: 0

Views: 69

Answers (0)

Related Questions