How does a P2SH script get executed? I'm trying to visualize how a typical P2SH script gets executed, as I realize that it's a special form of script that gets executed slightly differently to a standard script.

Before P2SH:

Before P2SH added new validation rules, nodes would execute the script like this:



In other words, an old node would just be happy to check the the HASH160 of the redeem script matches the HASH160 in the scriptPubKey. No MULTISIG validation would need to take place, because OP_1 (TRUE) would be left on top of the stack.

After P2SH:

With the new validation rules, I'm guessing the script executes something like this:



Question:

Does P2SH validation create a second stack using a copy of the redeem script, and then validate that stack before moving on to deserializing the redeem script (and then validating that script as normal)?

I'm hoping that my visualization of P2SH execution isn't misleading.
Does P2SH validation create a second stack using a copy of the redeem script, and then validate that stack before moving on to deserializing the redeem script (and then validating that script as normal)?


Kind of. It really isn't a second stack but rather a copy of the original stack. Once the scriptPubKey execution is completed, the original stack before scriptPubKey execution is restored and then the redeemScript is executed.

The flow is something like this:


Execute scriptSig which creates stack
Copy stack to stackCopy
Execute scriptPubKey using stack
If P2SH, replace stack with stackCopy
If P2SH, Pop top item off of stack and execute as redeemScript using stack