Let's finish by learning about conditional clauses and flow control, and taking a look at some examples of complex scripts.
Pay-to-Witness-Public-Key-Hash inside Pay-to-Script-Hash
The first form of witness script we will examine is P2SH(P2WPKH). This is a Pay-to-Witness-Public-Key-Hash witness program, embedded inside a Pay-to-Script-Hash script, so that it can be used by a wallet that is not aware of segwit.
Bob's wallet constructs a P2WPKH witness program with Bob's public key. This witness program is then hashed and the resulting hash is encoded as a P2SH script. The P2SH script is converted to a bitcoin address, one that starts with a "3," as we saw in the Pay-to-Script-Hash (P2SH) section.
Bob's wallet starts with the P2WPKH witness program we saw earlier:
Bob's P2WPKH witness program:
The P2WPKH witness program consists of the witness version and Bob's 20-byte public key hash.
Bob's wallet then hashes the preceding witness program, first with SHA256, then with RIPEMD160, producing another 20-byte hash.
Let's use bx on the command line to replicate that:
HASH160 of the P2WPKH witness program
echo \ '0 [ab68025513c3dbd2f7b92a94e0581f5d50f654e7]'\ | bx script-encode | bx sha256 | bx ripemd160 3e0547268b3b19288b3adef9719ec8659f4b2b0b
Next, the redeem script hash is converted to a bitcoin address. Let's use bx on the command-line again:
echo \ '3e0547268b3b19288b3adef9719ec8659f4b2b0b' \ | bx address-encode -v 5 37Lx99uaGn5avKBxiW26HjedQE3LrDCZru
Now, Bob can display this address for customers to pay for their coffee. Alice's wallet can make a payment to 37Lx99uaGn5avKBxiW26HjedQE3LrDCZru, just as it would to any other bitcoin address.
To pay Bob, Alice's wallet would lock the output with a P2SH script:
HASH160 3e0547268b3b19288b3adef9719ec8659f4b2b0b EQUAL
Even though Alice's wallet has no support for segwit, the payment it creates can be spent by Bob with a segwit transaction.