OP CHECKSIG
OP_CHECKSIG is an opcode that verifies an ECDSA signature. It takes two inputs from the stack, a public key (on top of the stack) and an ECDSA signature in its DER_CANONISED format concatenated with sighash flags. It outputs true or false on the stack based on whether the signature check passes or fails.
Parameters
In addition to the stack parameters, OP_CHECKSIG needs to have
- the current transaction ,
- the index of the transaction input in which the signature is checked ,
- the scriptPubKey in which this OP_CHECKSIG belongs , and
- the value in satoshi that the input represents .
Note that is from previous transaction, in which the output is spent in current transaction.
How it works
In short, OP_CHECKSIG calls a function called "sighash" which produces a hash value of the serialised transaction. The hash value is the message on which the signature is verified. The signature and the public key involved in the verification are obtained from the stack.
In detail,
- Check the stack size is not less than 2.
- the public key and the signature are popped as the top 2 items of the stack.
- Check the signature encoding is of the correct format [<DER signature><hashtype>]. An example to be given here.
- Check the public key encoding is of the correct format. Both compressed public key and uncompressed public key can be acceptable. Two examples to be given here.
- A new subScript is created from the . The subScript starts from the most recent OP_CODESEPARATOR (the one just before the OP_CHECKSIG that is executed here) to the end of the . If there is no OP_CODESEPARATOR, the entire becomes the subScript.
- Any remaining OP_CODESEPARATORS are removed from the subScript.
- A serialisation algorithm is called to produce an input to double SHA256:
- nVersion in (4-byte little endian)
- double SHA256 of the serialisation of all input outpoints (32-byte hash)
- double SHA256 of the serialisation of nSequence of all inputs (32-byte hash)
- the outpoint being spent (32-byte + 4-byte little endian)
A function called SIGHASH Now depending on the hashtype various things can happen to txCopy, these will be discussed individually. See SIGHASH flags for more detail.
SIGHASH_ALL
This SIGHASH flag indicates that the signature will sign all the inputs and all the outputs.
Final signature check
An array of bytes is constructed from the serialized txCopy appended by four bytes for the hash type. This array is sha256 hashed twice, then the public key is used to check the supplied signature against the hash. The secp256k1 elliptic curve is used for the verification with the given public key.
Return values
OP_CHECKSIG will push true to the stack if the check passed, false otherwise. OP_CHECKSIGVERIFY leaves nothing on the stack but will cause the script eval to fail immediately if the check does not pass.
References
https://github.com/bitcoin-sv/bitcoin-sv/blob/master/src/script/interpreter.cpp