Getting started with blockchain | Read P2SH and P2WSH in one article

P2SH and P2WSH are advanced scripts for bitcoin transactions that enable the construction of smart contract transactions with complex conditions.

First, we will look at the multi-signature script. Next, we introduce the most common trading script P2SH, Pay-to-Script-Hash paid to the script hash, which opens the entire world of a complex script. Finally, we introduce P2WSH, that is, Pay-to-Witness-Script-Hash pays for witness script hashing. The structural adjustment of P2WSH has a multi-faceted impact on bitcoin transactions.

1, multiple signature

The multi-signature script sets a condition in which N public keys are recorded in the script and at least M must provide a signature to unlock the funds. This is also known as the MN scheme, where N is the total number of keys and M is the number of signatures required for verification. For example, a 2/3 multi-signature is that three public keys are listed as potential signers and at least 2 valid signatures can be spent. At this point, standard multi-signature scripts are limited to a maximum of 15 listed public keys, which means you can do anything from multiple signatures between 1 and 15 or any combination within that range. Prior to the publication of this book, the restriction of 15 listed keys may be removed, so check the isStandard() function to see what the current network accepts.

The general form of the locking script that sets the MN multi-signature condition is:

M <Public Key 1> <Public Key 2> … <Public Key N> N CHECKMULTISIG

M is the number of signatures required to spend the output, and N is the total number of public keys listed. The locking script that sets the 2 to 3 multi-signature condition is as follows:

2 <Public Key A> <Public Key B> <Public Key C> 3 CHECKMULTISIG

The above lock script can be unlocked by a script containing a signature and a public key: or it can be unlocked by any two of the three archived public keys that are consistent with each other. The combination of the two scripts will form a validation script:

<Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 CHECKMULTISIG

When executed, the combined script displays the result as True only if the unlocked version of the script matches the unlocking script setting conditions.

The corresponding setting condition in the above example is: whether the unlocked script contains a valid signature of any two corresponding private keys of the three public keys.

l CHECKMULTISIG execution bug

There is a bug in the execution of CHECKMULTISIG that requires some minor workarounds. When the CHECCMULTISIG is executed, it should consume M + N + 2 items on the stack as arguments. However, due to this error, CHECKMULTISIG will pop out an extra value or a value that exceeds expectations.

Let's take a look at this more detailed / use previous / verification example:

<Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 CHECKMULTISIG

First, CHECKMULTISIG pops up the top item, which is N (in this case, N is "3"). Then it pops up N items, which are public keys that can be signed. In this example, the public keys A, B, and C. Then, it pops up an item, M, arbitration (how many signatures are needed). Here M = 2. At this point, CHECKMULTISIG should pop up the final M items, these are signatures and see if they are valid.

However, unfortunately, the implementation error caused CHECCKULTISIG to pop up another project (M+1 total). When checking the signature, no additional items are considered, so it has no direct impact on the CHECKMULTISIG itself. However, there must be extra values, because if it does not exist, when CHECKMULTISIG attempts to pop an empty stack, it causes a stack error and the script fails (mark the transaction as invalid). Because extra items are ignored, it can be anything, but usually uses 0. Because this bug becomes part of the consensus rule, it must now be copied forever. Therefore, the correct script verification will look like this:

0 <Signature B> <Signature C> 2 <Public Key A> <Public Key B> <Public Key C> 3 CHECKMULTISIG

This unlocks the script instead of the following:

<Signature B> <Signature C>

Instead:

0 <Signature B> <Signature C>

From now on, if you see a multisig unlock script, you should expect to see an extra 0 start, the sole purpose of which is to fix a bug that unexpectedly becomes a consensus rule solution.

That is to say, there are 3 private key signatures in the example corresponding to 3 public keys for checking multiple signatures, so as to ensure that the script does not generate bugs.

2, P2SH (Pay-to-Script-Hash)

P2SH was introduced in 2012 as a new, powerful type of transaction that greatly simplifies complex trading scripts. To further explain the need for P2SH, let us first look at a practical example.

Mohammed, an importer of electronic products in Dubai. Mohammed's company uses bitcoin multi-signature as its corporate accounting bookkeeping requirement. Multi-signature scripting is one of the most common uses of Bitcoin advanced scripting and is a script with considerable influence. For all customer payments (ie, accounts receivable), Mohammed's company requires multi-signature transactions. Based on the multi-signature mechanism, any payment by the customer requires at least two signatures to unlock, one from Mohammed and the other from its partner or agent with a backup key. Such a multi-signature mechanism can provide control and control for corporate governance, while also preventing theft, misappropriation and loss. The final script is very long:

2<Mohammed's Public Key> <Partner1 Public Key> <Partner2 Public Key>

<Partner3 Public Key> <Attorney Public Key> 5 OP_C HECKMULTISIG Although multi-signature is very powerful, it is inconvenient to use. Based on the previous script, Mohammed must send the script to each customer before the customer pays, and each customer must also use a special bitcoin wallet software that generates customer transaction scripts. Every customer has to learn how to use it. The script to complete the transaction.

In addition, since the script may contain a particularly long public key, the final transaction script may be as much as five times the length of the original transaction script. Extra length scripts will incur a cost to the customer. Finally, a long transaction script will always be recorded in the UTXO set of all nodes' random access memory until the funds are used. The use of such complex output scripts makes it difficult to make actual transactions.

P2SH was introduced to solve this practical problem, and it is designed to make the use of complex scripts as simple as paying directly to Bitcoin addresses. In P2SH payments, complex locking scripts are replaced by electronic fingerprints, which are hashes in cryptography.

When a transaction attempts to pay for UTXO, to unlock the payment script, it must contain a script that matches the hash. The meaning of P2SH is that the script is paid to the hash matching, and the script will be rendered later when the output is paid.

In a P2SH transaction, the lock script is replaced by a hashed 20-byte hash value, called a redemption script. Because it appears in the system at redemption instead of in lock script mode.

The following table lists the P2SH scripts. ![P2SH script](https://upload-images.jianshu.io/upload_images/17002326-953b3abf43331dde.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

As can be seen from the table, for P2SH, a complex script detailing the conditions of the output (redemption script) will not be displayed in the lock script.

Instead, only its hash value is rendered in the lock script, and the redemption script itself is rendered later as part of the output of the unlock script when it is spent. This allows the transaction costs for the miners to be transferred from the sender to the payee, and complex calculations are transferred from the sender to the payee.

A P2SH transaction uses a lock script to associate the output with a hash, rather than being associated with a particularly long script. The lock script used is:

HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e EQUAL

As you can see, this script is much shorter than the previous long script. Instead of "paying to the five multi-signature scripts", this P2SH is equivalent to "paying to the script containing the hash." When customers pay Mohammed, they only need to include this very short lock script in their payment instructions. When Mohammed wants to spend this UTXO, attach the original redemption script (hash with UTXO lock) and the necessary unlock signature, such as:

<Sig1> <Sig2> <2 PK1 PK2 PK3 PK4 PK5 5 CHECKMULTISIG>

The two scripts are combined in two steps. First, compare the redemption script to the lock script to confirm that it matches the hash:

<2 PK1 PK2 PK3 PK4 PK5 5 CHECKMULTISIG> HASH160 <redeem scriptHash> EQUAL

If the redemption script matches the hash, the unlock script will be executed to release the redemption script:

<Sig1> <Sig2> 2 PK1 PK2 PK3 PK4 PK5 5 CHECKMULTISIG

###3, P2WSH (Pay-to-Witness-Script-Hash)

P2WSH is P2SH that supports isolated witness types. Let us introduce the concept of isolated witness.

Segregated Witness is a structural adjustment of Bitcoin designed to move the Witness data portion out of a transaction's scriptSig field to a separate witness data structure accompanying the transaction. When the client requests transaction data, it can choose whether or not the witness data accompanying the part is required.

Segregated Witnesses are defined by the following BIPs:

BIP-141 Main definition of segregation testimony

BIP-143 version 0 witness signature verification

BIP-144 Peer-to-Peer Service – New Network Messaging and Serialization Format

BIP-145 Isolation Witness (for miners) getblocktemplate upgrade

l Why do you need to isolate the testimony?

Segregation Witness is a structural adjustment that will have an impact in many ways – scalability, security, economic incentives, and overall performance of Bitcoin:

l Transactional scalability

After the witness is removed from the transaction, the transaction hash used as the identifier does not contain witness data. Because the witness data is the only part of the transaction that can be modified by a third party (see the section on transaction identifiers), removing it also removes the opportunity for a trade-forward attack. By segregating the witness, the transaction becomes immutable to anyone (except the creator himself), which greatly enhances many other protocols that rely on the advanced bitcoin transaction architecture.

Executable. Such as payment channels, cross-connect transactions and lightning networks.

l Script version management

After the introduction of the quarantine witness script, similar to the transaction and block have their version number, and each lock script also has a script version number. The condition of the script version number allows the scripting language to be upgraded in a backwards compatible manner (that is, a soft fork upgrade) to introduce new script operands, syntax, or semantics. The ability to non-destructively upgrade scripting languages ​​will greatly accelerate the pace of innovation in Bitcoin.

l Network and storage expansion

Witness data is often an important contributor to the total volume of the transaction. More complex scripts are usually very large, such as those used for multi-signature or payment channels. Sometimes these scripts take up most of the transaction (over 75%). Segregated Witness improves the scalability of Bitcoin by moving witness data out of the transaction. The node can remove the witness data after verifying the signature, or ignore it entirely for simple payment verification. Witness data does not need to be sent to all nodes, nor does it need to be stored on the hard disk by all nodes.

l Signature verification optimization

The quarantine witness upgrade signature function (CHECKSIG, CHECKMULTISIG, etc.) reduces the computational complexity of the algorithm. Before the introduction of the quarantine witness, the algorithm used to generate the signature requires a large number of hash operations that are proportional to the size of the transaction. In terms of the number of signature operations in O(n2), the data hash calculation is increased, introducing a large amount of computational burden on all node verification signatures. After introducing the isolation testimony, algorithmic changes reduce the complexity of O(n2).

l Offline signature improvement

The quarantine witness signature contains the value (quantity) referenced by each input in the signed hash hash. Prior to this, an offline signature device, such as a hardware wallet, had to verify the number of each input before signing the transaction. This is usually done through a large number of data streams that are referenced as inputs to previous transactions. Since this number is now part of the signed promise hash hash, the offline device does not require a previous transaction. If the quantity does not match (by a compromised online system false positive), the signature is invalid.

In the P2PSH example, Muhammad's company used P2SH to express a multi-signature script. The payment to Muhammad's company is coded into a lock script like this:

P2SH output script example:

HASH160 54c557e07dde5bb6cb791c7a540e0a4796f5e97e EQUAL

This P2SH script references a hash of a redeem script that defines a "2 of 3" multi-signature requirement to use funds. In order to use this output, Muhammad's company will provide this redemption script (whose hash value matches the script hash value in the P2SH output) and the signature required to satisfy the redemption script, all in the transaction output:

Display a decoded transaction in which the P2SH output is used:

[…] "Vin" : ["txid": "abcdef12345…","vout": 0, "scriptSig": "<SigA> <SigB> <2 PubA PubB PubC PubD PubE 5 CHECKMULTISIG>", ]

Now let's see how the entire example is upgraded to a segregated witness. If Muhammad's client is using a quarantine witness-compatible wallet, they will pay and create a "Pay to Script Hash" (P2WSH) output that looks like this:

P2WSH output script example:

0 9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73

Again, as in the P2WPKH example, you can see that it is much simpler to isolate the witness equivalent script, omitting the various script operators you see in the P2SH script. Instead, the quarantine witness contains only two values ​​pushed to the stack: a witness version (0) and a 32-byte redemption script hash value.

Tip When P2SH uses a 20-byte RIPEMD160 (SHA256(script)) hash, the P2WSH witness uses a 32-byte SHA256 (script) hash. When choosing a hash algorithm, this difference is intentional and is used to distinguish between two types of witnesses (P2WPKH and P2WSH) by hash length and provide more for P2WSH (128 bits instead of 80 bits P2SH). Strong security.

Muhammad's company can satisfy and spend P2WSH output by providing the correct redemption script and enough signatures. As part of the witness data, redemption scripts and signatures are isolated from this expense transaction. Inside the transaction input, Muhammad's wallet will place an empty scriptSig:

Shows a P2WSH output that is decoded using the quarantine witness data:

[…] "Vin" : ["txid": "abcdef12345…","vout": 0, "scriptSig":"",][…]"witness": "<SigA> <SigB > <2 PubA PubB PubC PubD PubE 5 CHECKMULTISIG>"[…]

We can see that the witness data is placed in Witness and the scriptSig is empty.

The node can remove the witness data after verifying the signature, or ignore it entirely for simple payment verification. Witness data does not need to be sent to all nodes, nor does it need to be stored on the hard disk by all nodes.

4, summary

**Multi-signature** is very powerful, but the complexity of the lock script is very large, but it is still inconvenient to use.

**P2SH** was introduced to solve this practical problem, and it is designed to make the use of complex scripts as simple as paying directly to Bitcoin addresses. In P2SH payments, complex locking scripts are replaced by hash values.

**P2SH**'s unlock script is usually a major contributor to the total volume of the transaction. More complex scripts are usually very large, such as those used for multiple signatures or payment channels.

**P2WSH** improves the scalability of Bitcoin by moving the unlock script (witness data) out of the transaction, while increasing block capacity and reducing transaction fees.

5, the reference "Proficient in Bitcoin (Second Edition)"

— Author: BitTribeLab Sun Haitao