Segregated witness outputs (only implement this after miners have accepted segwit, or you may lose money)
There are two ways of signaling that a scriptPubKey should be interpreted as a segregated witness program:
Native witness program
<version byte> <2 to 40 bytes of witness data>
The version byte must be equal to or less than 16.
P2SH wrapped witness program
OP_HASH160 <20 bytes of script hash> OP_EQUAL
The scriptSig must have exactly one item. That item is interpreted as a witness program, as above.
Once you extract the witness program, you must match it to one of the witness program types:
P2WPKH
0 <20 bytes of public key hash>
This is hashed identically to P2PKH.
P2WSH
0 <32 bytes of witness script hash>
This is pretty similar to P2SH, except that the script hash is SHA256, not HASH160.
Other version 0 scripts, not 20 or 32 bytes in length, are nobody-can-spend, so ignore them.
Note that any witness program format can be combined with any witness program. For example, you can have P2SH wrapping P2WSH, like this:
scriptPubKey:
OP_HASH160 <20 byte hash of scriptSig element> OP_EQUAL
scriptSig:
<34 byte serialized witness program>
unserialized witness program:
0 <32 byte hash of first witness item>
Then, the first witness item is unpacked and interpreted as the actual program.
m-of-n bare multisig