Bitcoin Core  26.99.0
P2P Digital Currency
interpreter.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2022 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_SCRIPT_INTERPRETER_H
7 #define BITCOIN_SCRIPT_INTERPRETER_H
8 
9 #include <consensus/amount.h>
10 #include <hash.h>
11 #include <primitives/transaction.h>
12 #include <script/script_error.h> // IWYU pragma: export
13 #include <span.h>
14 #include <uint256.h>
15 
16 #include <cstddef>
17 #include <cstdint>
18 #include <optional>
19 #include <vector>
20 
21 class CPubKey;
22 class CScript;
23 class CScriptNum;
24 class XOnlyPubKey;
25 struct CScriptWitness;
26 
28 enum
29 {
34 
38 };
39 
45 enum : uint32_t {
47 
48  // Evaluate P2SH subscripts (BIP16).
49  SCRIPT_VERIFY_P2SH = (1U << 0),
50 
51  // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
52  // Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure.
53  // (not used or intended as a consensus rule).
55 
56  // Passing a non-strict-DER signature to a checksig operation causes script failure (BIP62 rule 1)
57  SCRIPT_VERIFY_DERSIG = (1U << 2),
58 
59  // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
60  // (BIP62 rule 5).
61  SCRIPT_VERIFY_LOW_S = (1U << 3),
62 
63  // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (BIP62 rule 7).
65 
66  // Using a non-push operator in the scriptSig causes script failure (BIP62 rule 2).
68 
69  // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
70  // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
71  // any other push causes the script to fail (BIP62 rule 3).
72  // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
74 
75  // Discourage use of NOPs reserved for upgrades (NOP1-10)
76  //
77  // Provided so that nodes can avoid accepting or mining transactions
78  // containing executed NOP's whose meaning may change after a soft-fork,
79  // thus rendering the script invalid; with this flag set executing
80  // discouraged NOPs fails the script. This verification flag will never be
81  // a mandatory flag applied to scripts in a block. NOPs that are not
82  // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
83  // NOPs that have associated forks to give them new meaning (CLTV, CSV)
84  // are not subject to this rule.
86 
87  // Require that only a single stack element remains after evaluation. This changes the success criterion from
88  // "At least one stack element must remain, and when interpreted as a boolean, it must be true" to
89  // "Exactly one stack element must remain, and when interpreted as a boolean, it must be true".
90  // (BIP62 rule 6)
91  // Note: CLEANSTACK should never be used without P2SH or WITNESS.
92  // Note: WITNESS_V0 and TAPSCRIPT script execution have behavior similar to CLEANSTACK as part of their
93  // consensus rules. It is automatic there and does not need this flag.
95 
96  // Verify CHECKLOCKTIMEVERIFY
97  //
98  // See BIP65 for details.
100 
101  // support CHECKSEQUENCEVERIFY opcode
102  //
103  // See BIP112 for details
105 
106  // Support segregated witness
107  //
108  SCRIPT_VERIFY_WITNESS = (1U << 11),
109 
110  // Making v1-v16 witness program non-standard
111  //
113 
114  // Segwit script only: Require the argument of OP_IF/NOTIF to be exactly 0x01 or empty vector
115  //
116  // Note: TAPSCRIPT script execution has behavior similar to MINIMALIF as part of its consensus
117  // rules. It is automatic there and does not depend on this flag.
119 
120  // Signature(s) must be empty vector if a CHECK(MULTI)SIG operation failed
121  //
123 
124  // Public keys in segregated witness scripts must be compressed
125  //
127 
128  // Making OP_CODESEPARATOR and FindAndDelete fail any non-segwit scripts
129  //
131 
132  // Taproot/Tapscript validation (BIPs 341 & 342)
133  //
134  SCRIPT_VERIFY_TAPROOT = (1U << 17),
135 
136  // Making unknown Taproot leaf versions non-standard
137  //
139 
140  // Making unknown OP_SUCCESS non-standard
142 
143  // Making unknown public key versions (in BIP 342 scripts) non-standard
145 
146  // Constants to point to the highest flag in use. Add new flags above this line.
147  //
149 };
150 
151 bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror);
152 
154 {
155  // BIP341 precomputed data.
156  // These are single-SHA256, see https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki#cite_note-16.
164 
165  // BIP143 precomputed data (double-SHA256).
168  bool m_bip143_segwit_ready = false;
169 
170  std::vector<CTxOut> m_spent_outputs;
172  bool m_spent_outputs_ready = false;
173 
175 
183  template <class T>
184  void Init(const T& tx, std::vector<CTxOut>&& spent_outputs, bool force = false);
185 
186  template <class T>
187  explicit PrecomputedTransactionData(const T& tx);
188 };
189 
190 enum class SigVersion
191 {
192  BASE = 0,
193  WITNESS_V0 = 1,
194  TAPROOT = 2,
195  TAPSCRIPT = 3,
196 };
197 
199 {
201  bool m_tapleaf_hash_init = false;
204 
209 
211  bool m_annex_init = false;
216 
221 
223  std::optional<uint256> m_output_hash;
224 };
225 
227 static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE = 32;
228 static constexpr size_t WITNESS_V0_KEYHASH_SIZE = 20;
229 static constexpr size_t WITNESS_V1_TAPROOT_SIZE = 32;
230 
231 static constexpr uint8_t TAPROOT_LEAF_MASK = 0xfe;
232 static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT = 0xc0;
233 static constexpr size_t TAPROOT_CONTROL_BASE_SIZE = 33;
234 static constexpr size_t TAPROOT_CONTROL_NODE_SIZE = 32;
235 static constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT = 128;
237 
238 extern const HashWriter HASHER_TAPSIGHASH;
239 extern const HashWriter HASHER_TAPLEAF;
240 extern const HashWriter HASHER_TAPBRANCH;
241 
242 template <class T>
243 uint256 SignatureHash(const CScript& scriptCode, const T& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache = nullptr);
244 
246 {
247 public:
248  virtual bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
249  {
250  return false;
251  }
252 
253  virtual bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror = nullptr) const
254  {
255  return false;
256  }
257 
258  virtual bool CheckLockTime(const CScriptNum& nLockTime) const
259  {
260  return false;
261  }
262 
263  virtual bool CheckSequence(const CScriptNum& nSequence) const
264  {
265  return false;
266  }
267 
269 };
270 
275 {
276  ASSERT_FAIL,
277  FAIL,
278 };
279 
280 template<typename T>
281 bool SignatureHashSchnorr(uint256& hash_out, ScriptExecutionData& execdata, const T& tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData& cache, MissingDataBehavior mdb);
282 
283 template <class T>
285 {
286 private:
287  const T* txTo;
289  unsigned int nIn;
292 
293 protected:
294  virtual bool VerifyECDSASignature(const std::vector<unsigned char>& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const;
295  virtual bool VerifySchnorrSignature(Span<const unsigned char> sig, const XOnlyPubKey& pubkey, const uint256& sighash) const;
296 
297 public:
298  GenericTransactionSignatureChecker(const T* txToIn, unsigned int nInIn, const CAmount& amountIn, MissingDataBehavior mdb) : txTo(txToIn), m_mdb(mdb), nIn(nInIn), amount(amountIn), txdata(nullptr) {}
299  GenericTransactionSignatureChecker(const T* txToIn, unsigned int nInIn, const CAmount& amountIn, const PrecomputedTransactionData& txdataIn, MissingDataBehavior mdb) : txTo(txToIn), m_mdb(mdb), nIn(nInIn), amount(amountIn), txdata(&txdataIn) {}
300  bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override;
301  bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror = nullptr) const override;
302  bool CheckLockTime(const CScriptNum& nLockTime) const override;
303  bool CheckSequence(const CScriptNum& nSequence) const override;
304 };
305 
308 
310 {
311 protected:
313 
314 public:
316 
317  bool CheckECDSASignature(const std::vector<unsigned char>& scriptSig, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const override
318  {
319  return m_checker.CheckECDSASignature(scriptSig, vchPubKey, scriptCode, sigversion);
320  }
321 
322  bool CheckSchnorrSignature(Span<const unsigned char> sig, Span<const unsigned char> pubkey, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* serror = nullptr) const override
323  {
324  return m_checker.CheckSchnorrSignature(sig, pubkey, sigversion, execdata, serror);
325  }
326 
327  bool CheckLockTime(const CScriptNum& nLockTime) const override
328  {
329  return m_checker.CheckLockTime(nLockTime);
330  }
331  bool CheckSequence(const CScriptNum& nSequence) const override
332  {
333  return m_checker.CheckSequence(nSequence);
334  }
335 };
336 
338 uint256 ComputeTapleafHash(uint8_t leaf_version, Span<const unsigned char> script);
345 
346 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptExecutionData& execdata, ScriptError* error = nullptr);
347 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* error = nullptr);
348 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror = nullptr);
349 
350 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags);
351 
352 int FindAndDelete(CScript& script, const CScript& b);
353 
354 #endif // BITCOIN_SCRIPT_INTERPRETER_H
int64_t CAmount
Amount in satoshis (Can be negative)
Definition: amount.h:12
int flags
Definition: bitcoin-tx.cpp:530
virtual bool CheckLockTime(const CScriptNum &nLockTime) const
Definition: interpreter.h:258
virtual bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const
Definition: interpreter.h:253
virtual bool CheckSequence(const CScriptNum &nSequence) const
Definition: interpreter.h:263
virtual bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const
Definition: interpreter.h:248
virtual ~BaseSignatureChecker()
Definition: interpreter.h:268
An encapsulated public key.
Definition: pubkey.h:34
Serialized script, used inside transaction inputs and outputs.
Definition: script.h:414
const BaseSignatureChecker & m_checker
Definition: interpreter.h:312
DeferringSignatureChecker(const BaseSignatureChecker &checker)
Definition: interpreter.h:315
bool CheckSequence(const CScriptNum &nSequence) const override
Definition: interpreter.h:331
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
Definition: interpreter.h:317
bool CheckLockTime(const CScriptNum &nLockTime) const override
Definition: interpreter.h:327
bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const override
Definition: interpreter.h:322
bool CheckSchnorrSignature(Span< const unsigned char > sig, Span< const unsigned char > pubkey, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *serror=nullptr) const override
const PrecomputedTransactionData * txdata
Definition: interpreter.h:291
virtual bool VerifySchnorrSignature(Span< const unsigned char > sig, const XOnlyPubKey &pubkey, const uint256 &sighash) const
GenericTransactionSignatureChecker(const T *txToIn, unsigned int nInIn, const CAmount &amountIn, MissingDataBehavior mdb)
Definition: interpreter.h:298
const MissingDataBehavior m_mdb
Definition: interpreter.h:288
bool CheckECDSASignature(const std::vector< unsigned char > &scriptSig, const std::vector< unsigned char > &vchPubKey, const CScript &scriptCode, SigVersion sigversion) const override
bool CheckLockTime(const CScriptNum &nLockTime) const override
virtual bool VerifyECDSASignature(const std::vector< unsigned char > &vchSig, const CPubKey &vchPubKey, const uint256 &sighash) const
GenericTransactionSignatureChecker(const T *txToIn, unsigned int nInIn, const CAmount &amountIn, const PrecomputedTransactionData &txdataIn, MissingDataBehavior mdb)
Definition: interpreter.h:299
bool CheckSequence(const CScriptNum &nSequence) const override
A writer stream (for serialization) that computes a 256-bit hash.
Definition: hash.h:101
256-bit opaque blob.
Definition: uint256.h:106
static constexpr size_t WITNESS_V0_KEYHASH_SIZE
Definition: interpreter.h:228
bool SignatureHashSchnorr(uint256 &hash_out, ScriptExecutionData &execdata, const T &tx_to, uint32_t in_pos, uint8_t hash_type, SigVersion sigversion, const PrecomputedTransactionData &cache, MissingDataBehavior mdb)
bool VerifyScript(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags, const BaseSignatureChecker &checker, ScriptError *serror=nullptr)
SigVersion
Definition: interpreter.h:191
@ TAPROOT
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, key path spending; see BIP 341.
@ BASE
Bare scripts and BIP16 P2SH-wrapped redeemscripts.
@ TAPSCRIPT
Witness v1 with 32-byte program, not BIP16 P2SH-wrapped, script path spending, leaf version 0xc0; see...
@ WITNESS_V0
Witness v0 (P2WPKH and P2WSH); see BIP 141.
@ SCRIPT_VERIFY_NULLDUMMY
Definition: interpreter.h:64
@ SCRIPT_VERIFY_P2SH
Definition: interpreter.h:49
@ SCRIPT_VERIFY_SIGPUSHONLY
Definition: interpreter.h:67
@ SCRIPT_VERIFY_DISCOURAGE_OP_SUCCESS
Definition: interpreter.h:141
@ SCRIPT_VERIFY_WITNESS
Definition: interpreter.h:108
@ SCRIPT_VERIFY_CONST_SCRIPTCODE
Definition: interpreter.h:130
@ SCRIPT_VERIFY_MINIMALIF
Definition: interpreter.h:118
@ SCRIPT_VERIFY_LOW_S
Definition: interpreter.h:61
@ SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY
Definition: interpreter.h:99
@ SCRIPT_VERIFY_WITNESS_PUBKEYTYPE
Definition: interpreter.h:126
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_TAPROOT_VERSION
Definition: interpreter.h:138
@ SCRIPT_VERIFY_TAPROOT
Definition: interpreter.h:134
@ SCRIPT_VERIFY_STRICTENC
Definition: interpreter.h:54
@ SCRIPT_VERIFY_NULLFAIL
Definition: interpreter.h:122
@ SCRIPT_VERIFY_DERSIG
Definition: interpreter.h:57
@ SCRIPT_VERIFY_END_MARKER
Definition: interpreter.h:148
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_PUBKEYTYPE
Definition: interpreter.h:144
@ SCRIPT_VERIFY_CLEANSTACK
Definition: interpreter.h:94
@ SCRIPT_VERIFY_NONE
Definition: interpreter.h:46
@ SCRIPT_VERIFY_MINIMALDATA
Definition: interpreter.h:73
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS
Definition: interpreter.h:85
@ SCRIPT_VERIFY_CHECKSEQUENCEVERIFY
Definition: interpreter.h:104
@ SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM
Definition: interpreter.h:112
int FindAndDelete(CScript &script, const CScript &b)
const HashWriter HASHER_TAPBRANCH
Hasher with tag "TapBranch" pre-fed to it.
bool CheckSignatureEncoding(const std::vector< unsigned char > &vchSig, unsigned int flags, ScriptError *serror)
size_t CountWitnessSigOps(const CScript &scriptSig, const CScript &scriptPubKey, const CScriptWitness *witness, unsigned int flags)
static constexpr uint8_t TAPROOT_LEAF_MASK
Definition: interpreter.h:231
uint256 ComputeTaprootMerkleRoot(Span< const unsigned char > control, const uint256 &tapleaf_hash)
Compute the BIP341 taproot script tree Merkle root from control block and leaf hash.
static constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
Definition: interpreter.h:232
bool EvalScript(std::vector< std::vector< unsigned char > > &stack, const CScript &script, unsigned int flags, const BaseSignatureChecker &checker, SigVersion sigversion, ScriptExecutionData &execdata, ScriptError *error=nullptr)
static constexpr size_t WITNESS_V0_SCRIPTHASH_SIZE
Signature hash sizes.
Definition: interpreter.h:227
const HashWriter HASHER_TAPLEAF
Hasher with tag "TapLeaf" pre-fed to it.
uint256 ComputeTapleafHash(uint8_t leaf_version, Span< const unsigned char > script)
Compute the BIP341 tapleaf hash from leaf version & script.
static constexpr size_t TAPROOT_CONTROL_NODE_SIZE
Definition: interpreter.h:234
static constexpr size_t WITNESS_V1_TAPROOT_SIZE
Definition: interpreter.h:229
@ SIGHASH_INPUT_MASK
Definition: interpreter.h:37
@ SIGHASH_ANYONECANPAY
Definition: interpreter.h:33
@ SIGHASH_DEFAULT
Taproot only; implied when sighash byte is missing, and equivalent to SIGHASH_ALL.
Definition: interpreter.h:35
@ SIGHASH_ALL
Definition: interpreter.h:30
@ SIGHASH_NONE
Definition: interpreter.h:31
@ SIGHASH_OUTPUT_MASK
Definition: interpreter.h:36
@ SIGHASH_SINGLE
Definition: interpreter.h:32
static constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
Definition: interpreter.h:235
MissingDataBehavior
Enum to specify what *TransactionSignatureChecker's behavior should be when dealing with missing tran...
Definition: interpreter.h:275
@ ASSERT_FAIL
Abort execution through assertion failure (for consensus code)
@ FAIL
Just act as if the signature was invalid.
static constexpr size_t TAPROOT_CONTROL_MAX_SIZE
Definition: interpreter.h:236
uint256 SignatureHash(const CScript &scriptCode, const T &txTo, unsigned int nIn, int nHashType, const CAmount &amount, SigVersion sigversion, const PrecomputedTransactionData *cache=nullptr)
uint256 ComputeTapbranchHash(Span< const unsigned char > a, Span< const unsigned char > b)
Compute the BIP341 tapbranch hash from two branches.
static constexpr size_t TAPROOT_CONTROL_BASE_SIZE
Definition: interpreter.h:233
const HashWriter HASHER_TAPSIGHASH
Hasher with tag "TapSighash" pre-fed to it.
bool error(const char *fmt, const Args &... args)
Definition: logging.h:267
enum ScriptError_t ScriptError
void Init(const T &tx, std::vector< CTxOut > &&spent_outputs, bool force=false)
Initialize this PrecomputedTransactionData with transaction data.
bool m_bip341_taproot_ready
Whether the 5 fields above are initialized.
Definition: interpreter.h:163
PrecomputedTransactionData()=default
bool m_bip143_segwit_ready
Whether the 3 fields above are initialized.
Definition: interpreter.h:168
bool m_spent_outputs_ready
Whether m_spent_outputs is initialized.
Definition: interpreter.h:172
std::vector< CTxOut > m_spent_outputs
Definition: interpreter.h:170
std::optional< uint256 > m_output_hash
The hash of the corresponding output.
Definition: interpreter.h:223
uint256 m_tapleaf_hash
The tapleaf hash.
Definition: interpreter.h:203
uint256 m_annex_hash
Hash of the annex data.
Definition: interpreter.h:215
int64_t m_validation_weight_left
How much validation weight is left (decremented for every successful non-empty signature check).
Definition: interpreter.h:220
bool m_annex_present
Whether an annex is present.
Definition: interpreter.h:213
bool m_annex_init
Whether m_annex_present and (when needed) m_annex_hash are initialized.
Definition: interpreter.h:211
bool m_codeseparator_pos_init
Whether m_codeseparator_pos is initialized.
Definition: interpreter.h:206
bool m_tapleaf_hash_init
Whether m_tapleaf_hash is initialized.
Definition: interpreter.h:201
bool m_validation_weight_left_init
Whether m_validation_weight_left is initialized.
Definition: interpreter.h:218
uint32_t m_codeseparator_pos
Opcode position of the last executed OP_CODESEPARATOR (or 0xFFFFFFFF if none executed).
Definition: interpreter.h:208