0

I'm trying to teach myself bitcoin script, and so far I'm failing with a seemingly trivial example. I'm using the Bitcoin Test Framework, and this is what I'm doing (simplified):

 # p2sh address for OP_TRUE, according to  https://bitcoin-script-debugger.visvirial.com/
address = '2ND8PB9RrfCaAcjfjP1Y6nAgFd9zWHYX4DN'
scriptPubKey = hex_str_to_bytes(self.nodes[0].validateaddress(address)['scriptPubKey'])

blocks = self.nodes[0].generatetoaddress(101, address)
tx0 = self.nodes[0].getblock(blockhash=blocks[0], verbosity=2)['tx'][0]

send_value = tx0['vout'][0]['value'] - Decimal("0.0001")

tx = CTransaction()
tx.vin = [CTxIn(COutPoint(int(tx0['txid'], 16),0),
                CScript([OP_TRUE]))]
tx.vout = [CTxOut(int(send_value * COIN), scriptPubKey)]
tx.calc_sha256()
tx_hex = tx.serialize().hex()

txid = self.nodes[0].sendrawtransaction(tx_hex)

This fails with the following error message:

test_framework.authproxy.JSONRPCException: mandatory-script-verify-flag-failed (Script evaluated without error but finished with a false/empty top stack element) (-26)

My understanding is that by providing OP_TRUE as a scriptSig, it should match the hash160 encoded in the address/input, and then the script itself should be executed and put 1 on the stack, which should successfuly unlock the input. What is wrong in my reasoning?

Murch
  • 71,155
  • 33
  • 180
  • 600
Horace
  • 1

1 Answers1

1

You are setting the scriptSig directly to the script that is being hashed, but that is incorrect. The way that P2SH works is that the script in the scriptPubKey will copy the top stack item and check it's hash. Since the script is OP_TRUE, you need to push the bytes for OP_TRUE to the stack, not execute OP_TRUE as your code currently does.

Instead of doing

CScript([OP_TRUE])

you should do

CScript([CScript([OP_TRUE])])

This does what I described. First you make a script which corresponds to the address you made. This script is encoded as bytes, and included as just a byte array in another script that will be the scriptSig.

Andrew Chow
  • 67,209
  • 5
  • 76
  • 149