1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2015 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 #include "interpreter.h"
7 
8 #include "primitives/transaction.h"
9 #include "crypto/ripemd160.h"
10 #include "crypto/sha1.h"
11 #include "crypto/sha256.h"
12 #include "pubkey.h"
13 #include "script/script.h"
14 #include "uint256.h"
15 
16 using namespace std;
17 
18 typedef vector<unsigned char> valtype;
19 
20 namespace {
21 
set_success(ScriptError * ret)22 inline bool set_success(ScriptError* ret)
23 {
24     if (ret)
25         *ret = SCRIPT_ERR_OK;
26     return true;
27 }
28 
set_error(ScriptError * ret,const ScriptError serror)29 inline bool set_error(ScriptError* ret, const ScriptError serror)
30 {
31     if (ret)
32         *ret = serror;
33     return false;
34 }
35 
36 } // anon namespace
37 
CastToBool(const valtype & vch)38 bool CastToBool(const valtype& vch)
39 {
40     for (unsigned int i = 0; i < vch.size(); i++)
41     {
42         if (vch[i] != 0)
43         {
44             // Can be negative zero
45             if (i == vch.size()-1 && vch[i] == 0x80)
46                 return false;
47             return true;
48         }
49     }
50     return false;
51 }
52 
53 /**
54  * Script is a stack machine (like Forth) that evaluates a predicate
55  * returning a bool indicating valid or not.  There are no loops.
56  */
57 #define stacktop(i)  (stack.at(stack.size()+(i)))
58 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
popstack(vector<valtype> & stack)59 static inline void popstack(vector<valtype>& stack)
60 {
61     if (stack.empty())
62         throw runtime_error("popstack(): stack empty");
63     stack.pop_back();
64 }
65 
IsCompressedOrUncompressedPubKey(const valtype & vchPubKey)66 bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
67     if (vchPubKey.size() < 33) {
68         //  Non-canonical public key: too short
69         return false;
70     }
71     if (vchPubKey[0] == 0x04) {
72         if (vchPubKey.size() != 65) {
73             //  Non-canonical public key: invalid length for uncompressed key
74             return false;
75         }
76     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
77         if (vchPubKey.size() != 33) {
78             //  Non-canonical public key: invalid length for compressed key
79             return false;
80         }
81     } else {
82         //  Non-canonical public key: neither compressed nor uncompressed
83         return false;
84     }
85     return true;
86 }
87 
IsCompressedPubKey(const valtype & vchPubKey)88 bool static IsCompressedPubKey(const valtype &vchPubKey) {
89     if (vchPubKey.size() != 33) {
90         //  Non-canonical public key: invalid length for compressed key
91         return false;
92     }
93     if (vchPubKey[0] != 0x02 && vchPubKey[0] != 0x03) {
94         //  Non-canonical public key: invalid prefix for compressed key
95         return false;
96     }
97     return true;
98 }
99 
100 /**
101  * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
102  * Where R and S are not negative (their first byte has its highest bit not set), and not
103  * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
104  * in which case a single 0 byte is necessary and even required).
105  *
106  * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
107  *
108  * This function is consensus-critical since BIP66.
109  */
IsValidSignatureEncoding(const std::vector<unsigned char> & sig)110 bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
111     // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
112     // * total-length: 1-byte length descriptor of everything that follows,
113     //   excluding the sighash byte.
114     // * R-length: 1-byte length descriptor of the R value that follows.
115     // * R: arbitrary-length big-endian encoded R value. It must use the shortest
116     //   possible encoding for a positive integers (which means no null bytes at
117     //   the start, except a single one when the next byte has its highest bit set).
118     // * S-length: 1-byte length descriptor of the S value that follows.
119     // * S: arbitrary-length big-endian encoded S value. The same rules apply.
120     // * sighash: 1-byte value indicating what data is hashed (not part of the DER
121     //   signature)
122 
123     // Minimum and maximum size constraints.
124     if (sig.size() < 9) return false;
125     if (sig.size() > 73) return false;
126 
127     // A signature is of type 0x30 (compound).
128     if (sig[0] != 0x30) return false;
129 
130     // Make sure the length covers the entire signature.
131     if (sig[1] != sig.size() - 3) return false;
132 
133     // Extract the length of the R element.
134     unsigned int lenR = sig[3];
135 
136     // Make sure the length of the S element is still inside the signature.
137     if (5 + lenR >= sig.size()) return false;
138 
139     // Extract the length of the S element.
140     unsigned int lenS = sig[5 + lenR];
141 
142     // Verify that the length of the signature matches the sum of the length
143     // of the elements.
144     if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
145 
146     // Check whether the R element is an integer.
147     if (sig[2] != 0x02) return false;
148 
149     // Zero-length integers are not allowed for R.
150     if (lenR == 0) return false;
151 
152     // Negative numbers are not allowed for R.
153     if (sig[4] & 0x80) return false;
154 
155     // Null bytes at the start of R are not allowed, unless R would
156     // otherwise be interpreted as a negative number.
157     if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
158 
159     // Check whether the S element is an integer.
160     if (sig[lenR + 4] != 0x02) return false;
161 
162     // Zero-length integers are not allowed for S.
163     if (lenS == 0) return false;
164 
165     // Negative numbers are not allowed for S.
166     if (sig[lenR + 6] & 0x80) return false;
167 
168     // Null bytes at the start of S are not allowed, unless S would otherwise be
169     // interpreted as a negative number.
170     if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
171 
172     return true;
173 }
174 
IsLowDERSignature(const valtype & vchSig,ScriptError * serror)175 bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
176     if (!IsValidSignatureEncoding(vchSig)) {
177         return set_error(serror, SCRIPT_ERR_SIG_DER);
178     }
179     std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
180     if (!CPubKey::CheckLowS(vchSigCopy)) {
181         return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
182     }
183     return true;
184 }
185 
IsDefinedHashtypeSignature(const valtype & vchSig)186 bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
187     if (vchSig.size() == 0) {
188         return false;
189     }
190     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
191     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
192         return false;
193 
194     return true;
195 }
196 
CheckSignatureEncoding(const vector<unsigned char> & vchSig,unsigned int flags,ScriptError * serror)197 bool CheckSignatureEncoding(const vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
198     // Empty signature. Not strictly DER encoded, but allowed to provide a
199     // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
200     if (vchSig.size() == 0) {
201         return true;
202     }
203     if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
204         return set_error(serror, SCRIPT_ERR_SIG_DER);
205     } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
206         // serror is set
207         return false;
208     } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
209         return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
210     }
211     return true;
212 }
213 
CheckPubKeyEncoding(const valtype & vchPubKey,unsigned int flags,const SigVersion & sigversion,ScriptError * serror)214 bool static CheckPubKeyEncoding(const valtype &vchPubKey, unsigned int flags, const SigVersion &sigversion, ScriptError* serror) {
215     if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchPubKey)) {
216         return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
217     }
218     // Only compressed keys are accepted in segwit
219     if ((flags & SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && sigversion == SIGVERSION_WITNESS_V0 && !IsCompressedPubKey(vchPubKey)) {
220         return set_error(serror, SCRIPT_ERR_WITNESS_PUBKEYTYPE);
221     }
222     return true;
223 }
224 
CheckMinimalPush(const valtype & data,opcodetype opcode)225 bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
226     if (data.size() == 0) {
227         // Could have used OP_0.
228         return opcode == OP_0;
229     } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
230         // Could have used OP_1 .. OP_16.
231         return opcode == OP_1 + (data[0] - 1);
232     } else if (data.size() == 1 && data[0] == 0x81) {
233         // Could have used OP_1NEGATE.
234         return opcode == OP_1NEGATE;
235     } else if (data.size() <= 75) {
236         // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
237         return opcode == data.size();
238     } else if (data.size() <= 255) {
239         // Could have used OP_PUSHDATA.
240         return opcode == OP_PUSHDATA1;
241     } else if (data.size() <= 65535) {
242         // Could have used OP_PUSHDATA2.
243         return opcode == OP_PUSHDATA2;
244     }
245     return true;
246 }
247 
EvalScript(vector<vector<unsigned char>> & stack,const CScript & script,unsigned int flags,const BaseSignatureChecker & checker,SigVersion sigversion,ScriptError * serror)248 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
249 {
250     static const CScriptNum bnZero(0);
251     static const CScriptNum bnOne(1);
252     static const CScriptNum bnFalse(0);
253     static const CScriptNum bnTrue(1);
254     static const valtype vchFalse(0);
255     static const valtype vchZero(0);
256     static const valtype vchTrue(1, 1);
257 
258     CScript::const_iterator pc = script.begin();
259     CScript::const_iterator pend = script.end();
260     CScript::const_iterator pbegincodehash = script.begin();
261     opcodetype opcode;
262     valtype vchPushValue;
263     vector<bool> vfExec;
264     vector<valtype> altstack;
265     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
266     if (script.size() > MAX_SCRIPT_SIZE)
267         return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
268     int nOpCount = 0;
269     bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
270 
271     try
272     {
273         while (pc < pend)
274         {
275             bool fExec = !count(vfExec.begin(), vfExec.end(), false);
276 
277             //
278             // Read instruction
279             //
280             if (!script.GetOp(pc, opcode, vchPushValue))
281                 return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
282             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
283                 return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
284 
285             // Note how OP_RESERVED does not count towards the opcode limit.
286             if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
287                 return set_error(serror, SCRIPT_ERR_OP_COUNT);
288 
289             if (opcode == OP_CAT ||
290                 opcode == OP_SUBSTR ||
291                 opcode == OP_LEFT ||
292                 opcode == OP_RIGHT ||
293                 opcode == OP_INVERT ||
294                 opcode == OP_AND ||
295                 opcode == OP_OR ||
296                 opcode == OP_XOR ||
297                 opcode == OP_2MUL ||
298                 opcode == OP_2DIV ||
299                 opcode == OP_MUL ||
300                 opcode == OP_DIV ||
301                 opcode == OP_MOD ||
302                 opcode == OP_LSHIFT ||
303                 opcode == OP_RSHIFT)
304                 return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
305 
306             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
307                 if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
308                     return set_error(serror, SCRIPT_ERR_MINIMALDATA);
309                 }
310                 stack.push_back(vchPushValue);
311             } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
312             switch (opcode)
313             {
314                 //
315                 // Push value
316                 //
317                 case OP_1NEGATE:
318                 case OP_1:
319                 case OP_2:
320                 case OP_3:
321                 case OP_4:
322                 case OP_5:
323                 case OP_6:
324                 case OP_7:
325                 case OP_8:
326                 case OP_9:
327                 case OP_10:
328                 case OP_11:
329                 case OP_12:
330                 case OP_13:
331                 case OP_14:
332                 case OP_15:
333                 case OP_16:
334                 {
335                     // ( -- value)
336                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
337                     stack.push_back(bn.getvch());
338                     // The result of these opcodes should always be the minimal way to push the data
339                     // they push, so no need for a CheckMinimalPush here.
340                 }
341                 break;
342 
343 
344                 //
345                 // Control
346                 //
347                 case OP_NOP:
348                     break;
349 
350                 case OP_CHECKLOCKTIMEVERIFY:
351                 {
352                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
353                         // not enabled; treat as a NOP2
354                         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
355                             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
356                         }
357                         break;
358                     }
359 
360                     if (stack.size() < 1)
361                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
362 
363                     // Note that elsewhere numeric opcodes are limited to
364                     // operands in the range -2**31+1 to 2**31-1, however it is
365                     // legal for opcodes to produce results exceeding that
366                     // range. This limitation is implemented by CScriptNum's
367                     // default 4-byte limit.
368                     //
369                     // If we kept to that limit we'd have a year 2038 problem,
370                     // even though the nLockTime field in transactions
371                     // themselves is uint32 which only becomes meaningless
372                     // after the year 2106.
373                     //
374                     // Thus as a special case we tell CScriptNum to accept up
375                     // to 5-byte bignums, which are good until 2**39-1, well
376                     // beyond the 2**32-1 limit of the nLockTime field itself.
377                     const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
378 
379                     // In the rare event that the argument may be < 0 due to
380                     // some arithmetic being done first, you can always use
381                     // 0 MAX CHECKLOCKTIMEVERIFY.
382                     if (nLockTime < 0)
383                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
384 
385                     // Actually compare the specified lock time with the transaction.
386                     if (!checker.CheckLockTime(nLockTime))
387                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
388 
389                     break;
390                 }
391 
392                 case OP_CHECKSEQUENCEVERIFY:
393                 {
394                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
395                         // not enabled; treat as a NOP3
396                         if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
397                             return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
398                         }
399                         break;
400                     }
401 
402                     if (stack.size() < 1)
403                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
404 
405                     // nSequence, like nLockTime, is a 32-bit unsigned integer
406                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
407                     // 5-byte numeric operands.
408                     const CScriptNum nSequence(stacktop(-1), fRequireMinimal, 5);
409 
410                     // In the rare event that the argument may be < 0 due to
411                     // some arithmetic being done first, you can always use
412                     // 0 MAX CHECKSEQUENCEVERIFY.
413                     if (nSequence < 0)
414                         return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
415 
416                     // To provide for future soft-fork extensibility, if the
417                     // operand has the disabled lock-time flag set,
418                     // CHECKSEQUENCEVERIFY behaves as a NOP.
419                     if ((nSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
420                         break;
421 
422                     // Compare the specified sequence number with the input.
423                     if (!checker.CheckSequence(nSequence))
424                         return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
425 
426                     break;
427                 }
428 
429                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
430                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
431                 {
432                     if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
433                         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
434                 }
435                 break;
436 
437                 case OP_IF:
438                 case OP_NOTIF:
439                 {
440                     // <expression> if [statements] [else [statements]] endif
441                     bool fValue = false;
442                     if (fExec)
443                     {
444                         if (stack.size() < 1)
445                             return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
446                         valtype& vch = stacktop(-1);
447                         if (sigversion == SIGVERSION_WITNESS_V0 && (flags & SCRIPT_VERIFY_MINIMALIF)) {
448                             if (vch.size() > 1)
449                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
450                             if (vch.size() == 1 && vch[0] != 1)
451                                 return set_error(serror, SCRIPT_ERR_MINIMALIF);
452                         }
453                         fValue = CastToBool(vch);
454                         if (opcode == OP_NOTIF)
455                             fValue = !fValue;
456                         popstack(stack);
457                     }
458                     vfExec.push_back(fValue);
459                 }
460                 break;
461 
462                 case OP_ELSE:
463                 {
464                     if (vfExec.empty())
465                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
466                     vfExec.back() = !vfExec.back();
467                 }
468                 break;
469 
470                 case OP_ENDIF:
471                 {
472                     if (vfExec.empty())
473                         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
474                     vfExec.pop_back();
475                 }
476                 break;
477 
478                 case OP_VERIFY:
479                 {
480                     // (true -- ) or
481                     // (false -- false) and return
482                     if (stack.size() < 1)
483                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
484                     bool fValue = CastToBool(stacktop(-1));
485                     if (fValue)
486                         popstack(stack);
487                     else
488                         return set_error(serror, SCRIPT_ERR_VERIFY);
489                 }
490                 break;
491 
492                 case OP_RETURN:
493                 {
494                     return set_error(serror, SCRIPT_ERR_OP_RETURN);
495                 }
496                 break;
497 
498 
499                 //
500                 // Stack ops
501                 //
502                 case OP_TOALTSTACK:
503                 {
504                     if (stack.size() < 1)
505                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
506                     altstack.push_back(stacktop(-1));
507                     popstack(stack);
508                 }
509                 break;
510 
511                 case OP_FROMALTSTACK:
512                 {
513                     if (altstack.size() < 1)
514                         return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
515                     stack.push_back(altstacktop(-1));
516                     popstack(altstack);
517                 }
518                 break;
519 
520                 case OP_2DROP:
521                 {
522                     // (x1 x2 -- )
523                     if (stack.size() < 2)
524                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
525                     popstack(stack);
526                     popstack(stack);
527                 }
528                 break;
529 
530                 case OP_2DUP:
531                 {
532                     // (x1 x2 -- x1 x2 x1 x2)
533                     if (stack.size() < 2)
534                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
535                     valtype vch1 = stacktop(-2);
536                     valtype vch2 = stacktop(-1);
537                     stack.push_back(vch1);
538                     stack.push_back(vch2);
539                 }
540                 break;
541 
542                 case OP_3DUP:
543                 {
544                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
545                     if (stack.size() < 3)
546                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
547                     valtype vch1 = stacktop(-3);
548                     valtype vch2 = stacktop(-2);
549                     valtype vch3 = stacktop(-1);
550                     stack.push_back(vch1);
551                     stack.push_back(vch2);
552                     stack.push_back(vch3);
553                 }
554                 break;
555 
556                 case OP_2OVER:
557                 {
558                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
559                     if (stack.size() < 4)
560                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
561                     valtype vch1 = stacktop(-4);
562                     valtype vch2 = stacktop(-3);
563                     stack.push_back(vch1);
564                     stack.push_back(vch2);
565                 }
566                 break;
567 
568                 case OP_2ROT:
569                 {
570                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
571                     if (stack.size() < 6)
572                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
573                     valtype vch1 = stacktop(-6);
574                     valtype vch2 = stacktop(-5);
575                     stack.erase(stack.end()-6, stack.end()-4);
576                     stack.push_back(vch1);
577                     stack.push_back(vch2);
578                 }
579                 break;
580 
581                 case OP_2SWAP:
582                 {
583                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
584                     if (stack.size() < 4)
585                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
586                     swap(stacktop(-4), stacktop(-2));
587                     swap(stacktop(-3), stacktop(-1));
588                 }
589                 break;
590 
591                 case OP_IFDUP:
592                 {
593                     // (x - 0 | x x)
594                     if (stack.size() < 1)
595                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
596                     valtype vch = stacktop(-1);
597                     if (CastToBool(vch))
598                         stack.push_back(vch);
599                 }
600                 break;
601 
602                 case OP_DEPTH:
603                 {
604                     // -- stacksize
605                     CScriptNum bn(stack.size());
606                     stack.push_back(bn.getvch());
607                 }
608                 break;
609 
610                 case OP_DROP:
611                 {
612                     // (x -- )
613                     if (stack.size() < 1)
614                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
615                     popstack(stack);
616                 }
617                 break;
618 
619                 case OP_DUP:
620                 {
621                     // (x -- x x)
622                     if (stack.size() < 1)
623                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
624                     valtype vch = stacktop(-1);
625                     stack.push_back(vch);
626                 }
627                 break;
628 
629                 case OP_NIP:
630                 {
631                     // (x1 x2 -- x2)
632                     if (stack.size() < 2)
633                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
634                     stack.erase(stack.end() - 2);
635                 }
636                 break;
637 
638                 case OP_OVER:
639                 {
640                     // (x1 x2 -- x1 x2 x1)
641                     if (stack.size() < 2)
642                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
643                     valtype vch = stacktop(-2);
644                     stack.push_back(vch);
645                 }
646                 break;
647 
648                 case OP_PICK:
649                 case OP_ROLL:
650                 {
651                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
652                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
653                     if (stack.size() < 2)
654                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
655                     int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
656                     popstack(stack);
657                     if (n < 0 || n >= (int)stack.size())
658                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
659                     valtype vch = stacktop(-n-1);
660                     if (opcode == OP_ROLL)
661                         stack.erase(stack.end()-n-1);
662                     stack.push_back(vch);
663                 }
664                 break;
665 
666                 case OP_ROT:
667                 {
668                     // (x1 x2 x3 -- x2 x3 x1)
669                     //  x2 x1 x3  after first swap
670                     //  x2 x3 x1  after second swap
671                     if (stack.size() < 3)
672                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
673                     swap(stacktop(-3), stacktop(-2));
674                     swap(stacktop(-2), stacktop(-1));
675                 }
676                 break;
677 
678                 case OP_SWAP:
679                 {
680                     // (x1 x2 -- x2 x1)
681                     if (stack.size() < 2)
682                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
683                     swap(stacktop(-2), stacktop(-1));
684                 }
685                 break;
686 
687                 case OP_TUCK:
688                 {
689                     // (x1 x2 -- x2 x1 x2)
690                     if (stack.size() < 2)
691                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
692                     valtype vch = stacktop(-1);
693                     stack.insert(stack.end()-2, vch);
694                 }
695                 break;
696 
697 
698                 case OP_SIZE:
699                 {
700                     // (in -- in size)
701                     if (stack.size() < 1)
702                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
703                     CScriptNum bn(stacktop(-1).size());
704                     stack.push_back(bn.getvch());
705                 }
706                 break;
707 
708 
709                 //
710                 // Bitwise logic
711                 //
712                 case OP_EQUAL:
713                 case OP_EQUALVERIFY:
714                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
715                 {
716                     // (x1 x2 - bool)
717                     if (stack.size() < 2)
718                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
719                     valtype& vch1 = stacktop(-2);
720                     valtype& vch2 = stacktop(-1);
721                     bool fEqual = (vch1 == vch2);
722                     // OP_NOTEQUAL is disabled because it would be too easy to say
723                     // something like n != 1 and have some wiseguy pass in 1 with extra
724                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
725                     //if (opcode == OP_NOTEQUAL)
726                     //    fEqual = !fEqual;
727                     popstack(stack);
728                     popstack(stack);
729                     stack.push_back(fEqual ? vchTrue : vchFalse);
730                     if (opcode == OP_EQUALVERIFY)
731                     {
732                         if (fEqual)
733                             popstack(stack);
734                         else
735                             return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
736                     }
737                 }
738                 break;
739 
740 
741                 //
742                 // Numeric
743                 //
744                 case OP_1ADD:
745                 case OP_1SUB:
746                 case OP_NEGATE:
747                 case OP_ABS:
748                 case OP_NOT:
749                 case OP_0NOTEQUAL:
750                 {
751                     // (in -- out)
752                     if (stack.size() < 1)
753                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
754                     CScriptNum bn(stacktop(-1), fRequireMinimal);
755                     switch (opcode)
756                     {
757                     case OP_1ADD:       bn += bnOne; break;
758                     case OP_1SUB:       bn -= bnOne; break;
759                     case OP_NEGATE:     bn = -bn; break;
760                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
761                     case OP_NOT:        bn = (bn == bnZero); break;
762                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
763                     default:            assert(!"invalid opcode"); break;
764                     }
765                     popstack(stack);
766                     stack.push_back(bn.getvch());
767                 }
768                 break;
769 
770                 case OP_ADD:
771                 case OP_SUB:
772                 case OP_BOOLAND:
773                 case OP_BOOLOR:
774                 case OP_NUMEQUAL:
775                 case OP_NUMEQUALVERIFY:
776                 case OP_NUMNOTEQUAL:
777                 case OP_LESSTHAN:
778                 case OP_GREATERTHAN:
779                 case OP_LESSTHANOREQUAL:
780                 case OP_GREATERTHANOREQUAL:
781                 case OP_MIN:
782                 case OP_MAX:
783                 {
784                     // (x1 x2 -- out)
785                     if (stack.size() < 2)
786                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
787                     CScriptNum bn1(stacktop(-2), fRequireMinimal);
788                     CScriptNum bn2(stacktop(-1), fRequireMinimal);
789                     CScriptNum bn(0);
790                     switch (opcode)
791                     {
792                     case OP_ADD:
793                         bn = bn1 + bn2;
794                         break;
795 
796                     case OP_SUB:
797                         bn = bn1 - bn2;
798                         break;
799 
800                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
801                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
802                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
803                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
804                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
805                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
806                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
807                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
808                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
809                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
810                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
811                     default:                     assert(!"invalid opcode"); break;
812                     }
813                     popstack(stack);
814                     popstack(stack);
815                     stack.push_back(bn.getvch());
816 
817                     if (opcode == OP_NUMEQUALVERIFY)
818                     {
819                         if (CastToBool(stacktop(-1)))
820                             popstack(stack);
821                         else
822                             return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
823                     }
824                 }
825                 break;
826 
827                 case OP_WITHIN:
828                 {
829                     // (x min max -- out)
830                     if (stack.size() < 3)
831                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
832                     CScriptNum bn1(stacktop(-3), fRequireMinimal);
833                     CScriptNum bn2(stacktop(-2), fRequireMinimal);
834                     CScriptNum bn3(stacktop(-1), fRequireMinimal);
835                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
836                     popstack(stack);
837                     popstack(stack);
838                     popstack(stack);
839                     stack.push_back(fValue ? vchTrue : vchFalse);
840                 }
841                 break;
842 
843 
844                 //
845                 // Crypto
846                 //
847                 case OP_RIPEMD160:
848                 case OP_SHA1:
849                 case OP_SHA256:
850                 case OP_HASH160:
851                 case OP_HASH256:
852                 {
853                     // (in -- hash)
854                     if (stack.size() < 1)
855                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
856                     valtype& vch = stacktop(-1);
857                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
858                     if (opcode == OP_RIPEMD160)
859                         CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
860                     else if (opcode == OP_SHA1)
861                         CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
862                     else if (opcode == OP_SHA256)
863                         CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
864                     else if (opcode == OP_HASH160)
865                         CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
866                     else if (opcode == OP_HASH256)
867                         CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash));
868                     popstack(stack);
869                     stack.push_back(vchHash);
870                 }
871                 break;
872 
873                 case OP_CODESEPARATOR:
874                 {
875                     // Hash starts after the code separator
876                     pbegincodehash = pc;
877                 }
878                 break;
879 
880                 case OP_CHECKSIG:
881                 case OP_CHECKSIGVERIFY:
882                 {
883                     // (sig pubkey -- bool)
884                     if (stack.size() < 2)
885                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
886 
887                     valtype& vchSig    = stacktop(-2);
888                     valtype& vchPubKey = stacktop(-1);
889 
890                     // Subset of script starting at the most recent codeseparator
891                     CScript scriptCode(pbegincodehash, pend);
892 
893                     // Drop the signature in pre-segwit scripts but not segwit scripts
894                     if (sigversion == SIGVERSION_BASE) {
895                         scriptCode.FindAndDelete(CScript(vchSig));
896                     }
897 
898                     if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
899                         //serror is set
900                         return false;
901                     }
902                     bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
903 
904                     if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && vchSig.size())
905                         return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
906 
907                     popstack(stack);
908                     popstack(stack);
909                     stack.push_back(fSuccess ? vchTrue : vchFalse);
910                     if (opcode == OP_CHECKSIGVERIFY)
911                     {
912                         if (fSuccess)
913                             popstack(stack);
914                         else
915                             return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
916                     }
917                 }
918                 break;
919 
920                 case OP_CHECKMULTISIG:
921                 case OP_CHECKMULTISIGVERIFY:
922                 {
923                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
924 
925                     int i = 1;
926                     if ((int)stack.size() < i)
927                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
928 
929                     int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
930                     if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
931                         return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
932                     nOpCount += nKeysCount;
933                     if (nOpCount > MAX_OPS_PER_SCRIPT)
934                         return set_error(serror, SCRIPT_ERR_OP_COUNT);
935                     int ikey = ++i;
936                     // ikey2 is the position of last non-signature item in the stack. Top stack item = 1.
937                     // With SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if operation fails.
938                     int ikey2 = nKeysCount + 2;
939                     i += nKeysCount;
940                     if ((int)stack.size() < i)
941                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
942 
943                     int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
944                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
945                         return set_error(serror, SCRIPT_ERR_SIG_COUNT);
946                     int isig = ++i;
947                     i += nSigsCount;
948                     if ((int)stack.size() < i)
949                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
950 
951                     // Subset of script starting at the most recent codeseparator
952                     CScript scriptCode(pbegincodehash, pend);
953 
954                     // Drop the signature in pre-segwit scripts but not segwit scripts
955                     for (int k = 0; k < nSigsCount; k++)
956                     {
957                         valtype& vchSig = stacktop(-isig-k);
958                         if (sigversion == SIGVERSION_BASE) {
959                             scriptCode.FindAndDelete(CScript(vchSig));
960                         }
961                     }
962 
963                     bool fSuccess = true;
964                     while (fSuccess && nSigsCount > 0)
965                     {
966                         valtype& vchSig    = stacktop(-isig);
967                         valtype& vchPubKey = stacktop(-ikey);
968 
969                         // Note how this makes the exact order of pubkey/signature evaluation
970                         // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
971                         // See the script_(in)valid tests for details.
972                         if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, sigversion, serror)) {
973                             // serror is set
974                             return false;
975                         }
976 
977                         // Check signature
978                         bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
979 
980                         if (fOk) {
981                             isig++;
982                             nSigsCount--;
983                         }
984                         ikey++;
985                         nKeysCount--;
986 
987                         // If there are more signatures left than keys left,
988                         // then too many signatures have failed. Exit early,
989                         // without checking any further signatures.
990                         if (nSigsCount > nKeysCount)
991                             fSuccess = false;
992                     }
993 
994                     // Clean up stack of actual arguments
995                     while (i-- > 1) {
996                         // If the operation failed, we require that all signatures must be empty vector
997                         if (!fSuccess && (flags & SCRIPT_VERIFY_NULLFAIL) && !ikey2 && stacktop(-1).size())
998                             return set_error(serror, SCRIPT_ERR_SIG_NULLFAIL);
999                         if (ikey2 > 0)
1000                             ikey2--;
1001                         popstack(stack);
1002                     }
1003 
1004                     // A bug causes CHECKMULTISIG to consume one extra argument
1005                     // whose contents were not checked in any way.
1006                     //
1007                     // Unfortunately this is a potential source of mutability,
1008                     // so optionally verify it is exactly equal to zero prior
1009                     // to removing it from the stack.
1010                     if (stack.size() < 1)
1011                         return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1012                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1013                         return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
1014                     popstack(stack);
1015 
1016                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1017 
1018                     if (opcode == OP_CHECKMULTISIGVERIFY)
1019                     {
1020                         if (fSuccess)
1021                             popstack(stack);
1022                         else
1023                             return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
1024                     }
1025                 }
1026                 break;
1027 
1028                 default:
1029                     return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
1030             }
1031 
1032             // Size limits
1033             if (stack.size() + altstack.size() > 1000)
1034                 return set_error(serror, SCRIPT_ERR_STACK_SIZE);
1035         }
1036     }
1037     catch (...)
1038     {
1039         return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1040     }
1041 
1042     if (!vfExec.empty())
1043         return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1044 
1045     return set_success(serror);
1046 }
1047 
1048 namespace {
1049 
1050 /**
1051  * Wrapper that serializes like CTransaction, but with the modifications
1052  *  required for the signature hash done in-place
1053  */
1054 class CTransactionSignatureSerializer {
1055 private:
1056     const CTransaction& txTo;  //!< reference to the spending transaction (the one being serialized)
1057     const CScript& scriptCode; //!< output script being consumed
1058     const unsigned int nIn;    //!< input index of txTo being signed
1059     const bool fAnyoneCanPay;  //!< whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1060     const bool fHashSingle;    //!< whether the hashtype is SIGHASH_SINGLE
1061     const bool fHashNone;      //!< whether the hashtype is SIGHASH_NONE
1062 
1063 public:
CTransactionSignatureSerializer(const CTransaction & txToIn,const CScript & scriptCodeIn,unsigned int nInIn,int nHashTypeIn)1064     CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1065         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1066         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1067         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1068         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1069 
1070     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1071     template<typename S>
SerializeScriptCode(S & s,int nType,int nVersion) const1072     void SerializeScriptCode(S &s, int nType, int nVersion) const {
1073         CScript::const_iterator it = scriptCode.begin();
1074         CScript::const_iterator itBegin = it;
1075         opcodetype opcode;
1076         unsigned int nCodeSeparators = 0;
1077         while (scriptCode.GetOp(it, opcode)) {
1078             if (opcode == OP_CODESEPARATOR)
1079                 nCodeSeparators++;
1080         }
1081         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1082         it = itBegin;
1083         while (scriptCode.GetOp(it, opcode)) {
1084             if (opcode == OP_CODESEPARATOR) {
1085                 s.write((char*)&itBegin[0], it-itBegin-1);
1086                 itBegin = it;
1087             }
1088         }
1089         if (itBegin != scriptCode.end())
1090             s.write((char*)&itBegin[0], it-itBegin);
1091     }
1092 
1093     /** Serialize an input of txTo */
1094     template<typename S>
SerializeInput(S & s,unsigned int nInput,int nType,int nVersion) const1095     void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
1096         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1097         if (fAnyoneCanPay)
1098             nInput = nIn;
1099         // Serialize the prevout
1100         ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
1101         // Serialize the script
1102         if (nInput != nIn)
1103             // Blank out other inputs' signatures
1104             ::Serialize(s, CScriptBase(), nType, nVersion);
1105         else
1106             SerializeScriptCode(s, nType, nVersion);
1107         // Serialize the nSequence
1108         if (nInput != nIn && (fHashSingle || fHashNone))
1109             // let the others update at will
1110             ::Serialize(s, (int)0, nType, nVersion);
1111         else
1112             ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
1113     }
1114 
1115     /** Serialize an output of txTo */
1116     template<typename S>
SerializeOutput(S & s,unsigned int nOutput,int nType,int nVersion) const1117     void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
1118         if (fHashSingle && nOutput != nIn)
1119             // Do not lock-in the txout payee at other indices as txin
1120             ::Serialize(s, CTxOut(), nType, nVersion);
1121         else
1122             ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
1123     }
1124 
1125     /** Serialize txTo */
1126     template<typename S>
Serialize(S & s,int nType,int nVersion) const1127     void Serialize(S &s, int nType, int nVersion) const {
1128         // Serialize nVersion
1129         ::Serialize(s, txTo.nVersion, nType, nVersion);
1130         // Serialize vin
1131         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1132         ::WriteCompactSize(s, nInputs);
1133         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1134              SerializeInput(s, nInput, nType, nVersion);
1135         // Serialize vout
1136         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1137         ::WriteCompactSize(s, nOutputs);
1138         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1139              SerializeOutput(s, nOutput, nType, nVersion);
1140         // Serialize nLockTime
1141         ::Serialize(s, txTo.nLockTime, nType, nVersion);
1142     }
1143 };
1144 
GetPrevoutHash(const CTransaction & txTo)1145 uint256 GetPrevoutHash(const CTransaction& txTo) {
1146     CHashWriter ss(SER_GETHASH, 0);
1147     for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1148         ss << txTo.vin[n].prevout;
1149     }
1150     return ss.GetHash();
1151 }
1152 
GetSequenceHash(const CTransaction & txTo)1153 uint256 GetSequenceHash(const CTransaction& txTo) {
1154     CHashWriter ss(SER_GETHASH, 0);
1155     for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1156         ss << txTo.vin[n].nSequence;
1157     }
1158     return ss.GetHash();
1159 }
1160 
GetOutputsHash(const CTransaction & txTo)1161 uint256 GetOutputsHash(const CTransaction& txTo) {
1162     CHashWriter ss(SER_GETHASH, 0);
1163     for (unsigned int n = 0; n < txTo.vout.size(); n++) {
1164         ss << txTo.vout[n];
1165     }
1166     return ss.GetHash();
1167 }
1168 
1169 } // anon namespace
1170 
PrecomputedTransactionData(const CTransaction & txTo)1171 PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
1172 {
1173     hashPrevouts = GetPrevoutHash(txTo);
1174     hashSequence = GetSequenceHash(txTo);
1175     hashOutputs = GetOutputsHash(txTo);
1176 }
1177 
SignatureHash(const CScript & scriptCode,const CTransaction & txTo,unsigned int nIn,int nHashType,const CAmount & amount,SigVersion sigversion,const PrecomputedTransactionData * cache)1178 uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1179 {
1180     if (sigversion == SIGVERSION_WITNESS_V0) {
1181         uint256 hashPrevouts;
1182         uint256 hashSequence;
1183         uint256 hashOutputs;
1184 
1185         if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1186             hashPrevouts = cache ? cache->hashPrevouts : GetPrevoutHash(txTo);
1187         }
1188 
1189         if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1190             hashSequence = cache ? cache->hashSequence : GetSequenceHash(txTo);
1191         }
1192 
1193 
1194         if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1195             hashOutputs = cache ? cache->hashOutputs : GetOutputsHash(txTo);
1196         } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1197             CHashWriter ss(SER_GETHASH, 0);
1198             ss << txTo.vout[nIn];
1199             hashOutputs = ss.GetHash();
1200         }
1201 
1202         CHashWriter ss(SER_GETHASH, 0);
1203         // Version
1204         ss << txTo.nVersion;
1205         // Input prevouts/nSequence (none/all, depending on flags)
1206         ss << hashPrevouts;
1207         ss << hashSequence;
1208         // The input being signed (replacing the scriptSig with scriptCode + amount)
1209         // The prevout may already be contained in hashPrevout, and the nSequence
1210         // may already be contain in hashSequence.
1211         ss << txTo.vin[nIn].prevout;
1212         ss << static_cast<const CScriptBase&>(scriptCode);
1213         ss << amount;
1214         ss << txTo.vin[nIn].nSequence;
1215         // Outputs (none/one/all, depending on flags)
1216         ss << hashOutputs;
1217         // Locktime
1218         ss << txTo.nLockTime;
1219         // Sighash type
1220         ss << nHashType;
1221 
1222         return ss.GetHash();
1223     }
1224 
1225     static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001"));
1226     if (nIn >= txTo.vin.size()) {
1227         //  nIn out of range
1228         return one;
1229     }
1230 
1231     // Check for invalid use of SIGHASH_SINGLE
1232     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1233         if (nIn >= txTo.vout.size()) {
1234             //  nOut out of range
1235             return one;
1236         }
1237     }
1238 
1239     // Wrapper to serialize only the necessary parts of the transaction being signed
1240     CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1241 
1242     // Serialize and hash
1243     CHashWriter ss(SER_GETHASH, 0);
1244     ss << txTmp << nHashType;
1245     return ss.GetHash();
1246 }
1247 
VerifySignature(const std::vector<unsigned char> & vchSig,const CPubKey & pubkey,const uint256 & sighash) const1248 bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1249 {
1250     return pubkey.Verify(sighash, vchSig);
1251 }
1252 
CheckSig(const vector<unsigned char> & vchSigIn,const vector<unsigned char> & vchPubKey,const CScript & scriptCode,SigVersion sigversion) const1253 bool TransactionSignatureChecker::CheckSig(const vector<unsigned char>& vchSigIn, const vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1254 {
1255     CPubKey pubkey(vchPubKey);
1256     if (!pubkey.IsValid())
1257         return false;
1258 
1259     // Hash type is one byte tacked on to the end of the signature
1260     vector<unsigned char> vchSig(vchSigIn);
1261     if (vchSig.empty())
1262         return false;
1263     int nHashType = vchSig.back();
1264     vchSig.pop_back();
1265 
1266     uint256 sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->txdata);
1267 
1268     if (!VerifySignature(vchSig, pubkey, sighash))
1269         return false;
1270 
1271     return true;
1272 }
1273 
CheckLockTime(const CScriptNum & nLockTime) const1274 bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1275 {
1276     // There are two kinds of nLockTime: lock-by-blockheight
1277     // and lock-by-blocktime, distinguished by whether
1278     // nLockTime < LOCKTIME_THRESHOLD.
1279     //
1280     // We want to compare apples to apples, so fail the script
1281     // unless the type of nLockTime being tested is the same as
1282     // the nLockTime in the transaction.
1283     if (!(
1284         (txTo->nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
1285         (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1286     ))
1287         return false;
1288 
1289     // Now that we know we're comparing apples-to-apples, the
1290     // comparison is a simple numeric one.
1291     if (nLockTime > (int64_t)txTo->nLockTime)
1292         return false;
1293 
1294     // Finally the nLockTime feature can be disabled and thus
1295     // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1296     // finalized by setting nSequence to maxint. The
1297     // transaction would be allowed into the blockchain, making
1298     // the opcode ineffective.
1299     //
1300     // Testing if this vin is not final is sufficient to
1301     // prevent this condition. Alternatively we could test all
1302     // inputs, but testing just this input minimizes the data
1303     // required to prove correct CHECKLOCKTIMEVERIFY execution.
1304     if (CTxIn::SEQUENCE_FINAL == txTo->vin[nIn].nSequence)
1305         return false;
1306 
1307     return true;
1308 }
1309 
CheckSequence(const CScriptNum & nSequence) const1310 bool TransactionSignatureChecker::CheckSequence(const CScriptNum& nSequence) const
1311 {
1312     // Relative lock times are supported by comparing the passed
1313     // in operand to the sequence number of the input.
1314     const int64_t txToSequence = (int64_t)txTo->vin[nIn].nSequence;
1315 
1316     // Fail if the transaction's version number is not set high
1317     // enough to trigger BIP 68 rules.
1318     if (static_cast<uint32_t>(txTo->nVersion) < 2)
1319         return false;
1320 
1321     // Sequence numbers with their most significant bit set are not
1322     // consensus constrained. Testing that the transaction's sequence
1323     // number do not have this bit set prevents using this property
1324     // to get around a CHECKSEQUENCEVERIFY check.
1325     if (txToSequence & CTxIn::SEQUENCE_LOCKTIME_DISABLE_FLAG)
1326         return false;
1327 
1328     // Mask off any bits that do not have consensus-enforced meaning
1329     // before doing the integer comparisons
1330     const uint32_t nLockTimeMask = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | CTxIn::SEQUENCE_LOCKTIME_MASK;
1331     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
1332     const CScriptNum nSequenceMasked = nSequence & nLockTimeMask;
1333 
1334     // There are two kinds of nSequence: lock-by-blockheight
1335     // and lock-by-blocktime, distinguished by whether
1336     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
1337     //
1338     // We want to compare apples to apples, so fail the script
1339     // unless the type of nSequenceMasked being tested is the same as
1340     // the nSequenceMasked in the transaction.
1341     if (!(
1342         (txToSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) ||
1343         (txToSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG)
1344     )) {
1345         return false;
1346     }
1347 
1348     // Now that we know we're comparing apples-to-apples, the
1349     // comparison is a simple numeric one.
1350     if (nSequenceMasked > txToSequenceMasked)
1351         return false;
1352 
1353     return true;
1354 }
1355 
VerifyWitnessProgram(const CScriptWitness & witness,int witversion,const std::vector<unsigned char> & program,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror)1356 static bool VerifyWitnessProgram(const CScriptWitness& witness, int witversion, const std::vector<unsigned char>& program, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1357 {
1358     vector<vector<unsigned char> > stack;
1359     CScript scriptPubKey;
1360 
1361     if (witversion == 0) {
1362         if (program.size() == 32) {
1363             // Version 0 segregated witness program: SHA256(CScript) inside the program, CScript + inputs in witness
1364             if (witness.stack.size() == 0) {
1365                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY);
1366             }
1367             scriptPubKey = CScript(witness.stack.back().begin(), witness.stack.back().end());
1368             stack = std::vector<std::vector<unsigned char> >(witness.stack.begin(), witness.stack.end() - 1);
1369             uint256 hashScriptPubKey;
1370             CSHA256().Write(&scriptPubKey[0], scriptPubKey.size()).Finalize(hashScriptPubKey.begin());
1371             if (memcmp(hashScriptPubKey.begin(), &program[0], 32)) {
1372                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH);
1373             }
1374         } else if (program.size() == 20) {
1375             // Special case for pay-to-pubkeyhash; signature + pubkey in witness
1376             if (witness.stack.size() != 2) {
1377                 return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH); // 2 items in witness
1378             }
1379             scriptPubKey << OP_DUP << OP_HASH160 << program << OP_EQUALVERIFY << OP_CHECKSIG;
1380             stack = witness.stack;
1381         } else {
1382             return set_error(serror, SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH);
1383         }
1384     } else if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM) {
1385         return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM);
1386     } else {
1387         // Higher version witness scripts return true for future softfork compatibility
1388         return set_success(serror);
1389     }
1390 
1391     // Disallow stack item size > MAX_SCRIPT_ELEMENT_SIZE in witness stack
1392     for (unsigned int i = 0; i < stack.size(); i++) {
1393         if (stack.at(i).size() > MAX_SCRIPT_ELEMENT_SIZE)
1394             return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
1395     }
1396 
1397     if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_WITNESS_V0, serror)) {
1398         return false;
1399     }
1400 
1401     // Scripts inside witness implicitly require cleanstack behaviour
1402     if (stack.size() != 1)
1403         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1404     if (!CastToBool(stack.back()))
1405         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1406     return true;
1407 }
1408 
VerifyScript(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags,const BaseSignatureChecker & checker,ScriptError * serror)1409 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror)
1410 {
1411     static const CScriptWitness emptyWitness;
1412     if (witness == NULL) {
1413         witness = &emptyWitness;
1414     }
1415     bool hadWitness = false;
1416 
1417     set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1418 
1419     if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1420         return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1421     }
1422 
1423     vector<vector<unsigned char> > stack, stackCopy;
1424     if (!EvalScript(stack, scriptSig, flags, checker, SIGVERSION_BASE, serror))
1425         // serror is set
1426         return false;
1427     if (flags & SCRIPT_VERIFY_P2SH)
1428         stackCopy = stack;
1429     if (!EvalScript(stack, scriptPubKey, flags, checker, SIGVERSION_BASE, serror))
1430         // serror is set
1431         return false;
1432     if (stack.empty())
1433         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1434     if (CastToBool(stack.back()) == false)
1435         return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1436 
1437     // Bare witness programs
1438     int witnessversion;
1439     std::vector<unsigned char> witnessprogram;
1440     if (flags & SCRIPT_VERIFY_WITNESS) {
1441         if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1442             hadWitness = true;
1443             if (scriptSig.size() != 0) {
1444                 // The scriptSig must be _exactly_ CScript(), otherwise we reintroduce malleability.
1445                 return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED);
1446             }
1447             if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1448                 return false;
1449             }
1450             // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1451             // for witness programs.
1452             stack.resize(1);
1453         }
1454     }
1455 
1456     // Additional validation for spend-to-script-hash transactions:
1457     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1458     {
1459         // scriptSig must be literals-only or validation fails
1460         if (!scriptSig.IsPushOnly())
1461             return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1462 
1463         // Restore stack.
1464         swap(stack, stackCopy);
1465 
1466         // stack cannot be empty here, because if it was the
1467         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1468         // an empty stack and the EvalScript above would return false.
1469         assert(!stack.empty());
1470 
1471         const valtype& pubKeySerialized = stack.back();
1472         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1473         popstack(stack);
1474 
1475         if (!EvalScript(stack, pubKey2, flags, checker, SIGVERSION_BASE, serror))
1476             // serror is set
1477             return false;
1478         if (stack.empty())
1479             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1480         if (!CastToBool(stack.back()))
1481             return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1482 
1483         // P2SH witness program
1484         if (flags & SCRIPT_VERIFY_WITNESS) {
1485             if (pubKey2.IsWitnessProgram(witnessversion, witnessprogram)) {
1486                 hadWitness = true;
1487                 if (scriptSig != CScript() << std::vector<unsigned char>(pubKey2.begin(), pubKey2.end())) {
1488                     // The scriptSig must be _exactly_ a single push of the redeemScript. Otherwise we
1489                     // reintroduce malleability.
1490                     return set_error(serror, SCRIPT_ERR_WITNESS_MALLEATED_P2SH);
1491                 }
1492                 if (!VerifyWitnessProgram(*witness, witnessversion, witnessprogram, flags, checker, serror)) {
1493                     return false;
1494                 }
1495                 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
1496                 // for witness programs.
1497                 stack.resize(1);
1498             }
1499         }
1500     }
1501 
1502     // The CLEANSTACK check is only performed after potential P2SH evaluation,
1503     // as the non-P2SH evaluation of a P2SH script will obviously not result in
1504     // a clean stack (the P2SH inputs remain). The same holds for witness evaluation.
1505     if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1506         // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1507         // would be possible, which is not a softfork (and P2SH should be one).
1508         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1509         assert((flags & SCRIPT_VERIFY_WITNESS) != 0);
1510         if (stack.size() != 1) {
1511             return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1512         }
1513     }
1514 
1515     if (flags & SCRIPT_VERIFY_WITNESS) {
1516         // We can't check for correct unexpected witness data if P2SH was off, so require
1517         // that WITNESS implies P2SH. Otherwise, going from WITNESS->P2SH+WITNESS would be
1518         // possible, which is not a softfork.
1519         assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1520         if (!hadWitness && !witness->IsNull()) {
1521             return set_error(serror, SCRIPT_ERR_WITNESS_UNEXPECTED);
1522         }
1523     }
1524 
1525     return set_success(serror);
1526 }
1527 
WitnessSigOps(int witversion,const std::vector<unsigned char> & witprogram,const CScriptWitness & witness,int flags)1528 size_t static WitnessSigOps(int witversion, const std::vector<unsigned char>& witprogram, const CScriptWitness& witness, int flags)
1529 {
1530     if (witversion == 0) {
1531         if (witprogram.size() == 20)
1532             return 1;
1533 
1534         if (witprogram.size() == 32 && witness.stack.size() > 0) {
1535             CScript subscript(witness.stack.back().begin(), witness.stack.back().end());
1536             return subscript.GetSigOpCount(true);
1537         }
1538     }
1539 
1540     // Future flags may be implemented here.
1541     return 0;
1542 }
1543 
CountWitnessSigOps(const CScript & scriptSig,const CScript & scriptPubKey,const CScriptWitness * witness,unsigned int flags)1544 size_t CountWitnessSigOps(const CScript& scriptSig, const CScript& scriptPubKey, const CScriptWitness* witness, unsigned int flags)
1545 {
1546     static const CScriptWitness witnessEmpty;
1547 
1548     if ((flags & SCRIPT_VERIFY_WITNESS) == 0) {
1549         return 0;
1550     }
1551     assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1552 
1553     int witnessversion;
1554     std::vector<unsigned char> witnessprogram;
1555     if (scriptPubKey.IsWitnessProgram(witnessversion, witnessprogram)) {
1556         return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1557     }
1558 
1559     if (scriptPubKey.IsPayToScriptHash() && scriptSig.IsPushOnly()) {
1560         CScript::const_iterator pc = scriptSig.begin();
1561         vector<unsigned char> data;
1562         while (pc < scriptSig.end()) {
1563             opcodetype opcode;
1564             scriptSig.GetOp(pc, opcode, data);
1565         }
1566         CScript subscript(data.begin(), data.end());
1567         if (subscript.IsWitnessProgram(witnessversion, witnessprogram)) {
1568             return WitnessSigOps(witnessversion, witnessprogram, witness ? *witness : witnessEmpty, flags);
1569         }
1570     }
1571 
1572     return 0;
1573 }
1574