Dealing with Bitcoin script. Spend bitcoin transaction P2SH output.
This article describes how to spend bitcoins from P2SH address using correct scriptSig value. P2SH address was created in previous article.
So now is time to send some coins to our custom script and then spend them by passing correct scriptSig value. Therefore let’s make a money. We need some coins to perform our operations. We can get them somewhere on faucet projects. Auxiliary address for sending coins from and sending coins to is mhkAm39upJjQk8CxBCAGbzX9DVppzBvQAU. This address is used to get testnet coins. Let’s send coins to our auxliary address.
We have 0.0887091 testnet coins. 0.008 coins we will send to our P2SH address, and 0.0007091 as a transaction fee.
After sending coins to P2SH address comes most interesting part — spending coins from P2SH address. And we should use our scriptSig which is simply enough. Just put there number 14 and hash of scriptPubKey. Sounds easy but we work with raw data and we will create transaction “by hands” using just text editor. Value of scriptSig described below.
First in spend scriptSig should be value which is needed in last part of equation 5+9=14. It’s 14 number. Then there should be a full scriptPubKey. It is used to reach 2 important goals — check if it’s correct transaction output and provide exact script itself because of funding transaction doesn’t contain this script but only hash of it. So network can check if hash of script in funding transaction corresponds to script provided in spending transaction. And if all are correct, then script can be executed. After concatenating of all parts scriptSig has next representation:
Keep in mind that Bitcoin script is stack based so first value on the stack will be 5e (OP_14) then script 55599387 (OP_5 OP_9 OP_ADD OP_EQUAL). Execution process pictured below. Size values are omitted.
And as a result stack contains numer 1 or true (OP_1). Transaction successfuly passed network rules and included into block.