What is the procedure to restore redeem script of P2SH address from a transaction sent from that address? The script is stored on the blockchain in the tx data, the question is how to extract it?
1 Answer
If the P2SH output is already redeemed, then the transaction that spent it must have provided the redeemscript with the scriptSig in the outpoint to that P2SH output.
The last push of data in the scriptSig contains the whole redeemscript (https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki#Specification).
E.g. for a multi-signature the scriptSig that spends the output will be of the form:
scriptSig: 0 [signature1] ... [signatureM] {M [pubkey1] ... [pubkeyN] N OP_CHECKMULTISIG}
Where everything inside {...}
is a push of that redeemscript which you just have to extract.