Let's finish by learning about conditional clauses and flow control, and taking a look at some examples of complex scripts.
Pay-to-Witness-Script-Hash inside Pay-to-Script-Hash
Similarly, a P2WSH witness program for a multisig script or other complicated script can be embedded inside a P2SH script and address, making it possible for any wallet to make payments that are segwit compatible.
As we saw in Pay-to-Witness-Script-Hash (P2WSH), Mohammed's company is using Segregated Witness payments with multisignature scripts. To make it possible for any client to pay his company, regardless of whether their wallets are upgraded for segwit, Mohammed's wallet can embed the P2WSH witness program inside a P2SH script.
First, Mohammed's wallet hashes the redeem script with SHA256 (just once). Let's use bx to do that on the command-line:
Mohammed's wallet creates a P2WSH witness program:
echo \ 2 \ [04C16B8698A9ABF84250A7C3EA7EEDEF9897D1C8C6ADF47F06CF73370D74DCCA01CDCA79DCC5C395D7EEC6984D83F1F50C900A24DD47F569FD4193AF5DE762C587] \ [04A2192968D8655D6A935BEAF2CA23E3FB87A3495E7AF308EDF08DAC3C1FCBFC2C75B4B0F4D0B1B70CD2423657738C0C2B1D5CE65C97D78D0E34224858008E8B49] \ [047E63248B75DB7379BE9CDA8CE5751D16485F431E46117B9D0C1837C9D5737812F393DA7D4420D7E1A9162F0279CFC10F1E8E8F3020DECDBC3C0DD389D9977965] \ [0421D65CBD7149B255382ED7F78E946580657EE6FDA162A187543A9D85BAAA93A4AB3A8F044DADA618D087227440645ABE8A35DA8C5B73997AD343BE5C2AFD94A5] \ [043752580AFA1ECED3C68D446BCAB69AC0BA7DF50D56231BE0AABF1FDEEC78A6A45E394BA29A1EDF518C022DD618DA774D207D137AAB59E0B000EB7ED238F4D800] \ 5 CHECKMULTISIG \ | bx script-encode | bx sha256 9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73
Next, the hashed redeem script is turned into a P2WSH witness program:
0 9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73
Then, the witness program itself is hashed with SHA256 and RIPEMD160, producing a new 20-byte hash, as used in traditional P2SH. Let's use bx on the command-line to do that:
The HASH160 of the P2WSH witness program:
echo \ '0 [9592d601848d04b172905e0ddb0adde59f1590f1e553ffc81ddc4b0ed927dd73]'\ | bx script-encode | bx sha256 | bx ripemd160 86762607e8fe87c0c37740cddee880988b9455b2
Next, the wallet constructs a P2SH bitcoin address from this hash. Again, we use bx to calculate on the command-line:
P2SH bitcoin address
echo \ '86762607e8fe87c0c37740cddee880988b9455b2'\ | bx address-encode -v 5 3Dwz1MXhM6EfFoJChHCxh1jWHb8GQqRenG
Now, Mohammed's clients can make payments to this address without any need to support segwit. To send a payment to Mohammed, a wallet would lock the output with the following P2SH script:
P2SH script used to lock payments to Mohammed's multisig
HASH160 86762607e8fe87c0c37740cddee880988b9455b2 EQUAL
Mohammed's company can then construct segwit transactions to spend these payments, taking advantage of segwit features including lower transaction fees.