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