How does P2SH works?

All bitcoins are secured by a script: a sequence of instructions describing how to spend the bitcoins it secures. When spending bitcoins, arguments resulting in a valid execution of the script must be provided. While the underlying language used for these scripts can handle many different operations (arithmetic, cryptography, string operations, …), only a few standard script templates are broadcasted by Bitcoin peers.

Among them is P2SH, pay-to-script-hash. P2SH Bitcoin addresses (those beginning with a ‘3’) encode the cryptographic hash of a script, instead of encoding a ECDSA public key like the first version of Bitcoin addresses (beginning with a ‘1’). The hashed script, along with the arguments needed for its valid execution, are only revealed when spending the bitcoins sent to a P2SH address.

The main use of P2SH is multisig, 99% of known P2SH scripts use it. The remaining 1% is what I explored.