What is the signature digest for Segwit outputs (Assume there's no OP_CODESEPERATOR)



For standard P2PKH, the signature digest is generated this way:

NewTransaction


settle the TxOuts well
set all TxIn scripts to empty
insert the Previous Locking Script into the TxIn you are signing
append hash type code to the end of the transaction
SHA256 twice this transaction
Be a digest.




For standard P2SH, the signature digest is generated this way:

NewTransaction


settle the TxOuts well
set all TxIn scripts to empty
insert the Previous Unlocking Script's Redeem Script into the TxIn you are signing
append hash type code to the end of the transaction
SHA256 twice this transaction
Be a digest.




I learned those above from here. As for those above, I have written programs and successfully signed and submitted Bitcoin transactions to the blockchain.

But when it comes to Segwit, I don't know what the digest should be. For P2WPKH output, I tried to use the same method to get the digest as P2PKH, but it failed. Blockchain told me my signature was wrong.
For signatures in P2WPKH and P2WSH spends, the sighash algorithm is described in BIP143.

It is very different from the one used in legacy spends.