Line data Source code
1 : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : // Copyright (c) 2009-2014 The Bitcoin developers
3 : // Copyright (c) 2017-2021 The PIVX Core developers
4 : // Distributed under the MIT software license, see the accompanying
5 : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 :
7 : #include "interpreter.h"
8 :
9 : #include "consensus/upgrades.h"
10 : #include "crypto/ripemd160.h"
11 : #include "crypto/sha1.h"
12 : #include "crypto/sha256.h"
13 : #include "pubkey.h"
14 : #include "script/script.h"
15 :
16 :
17 : typedef std::vector<unsigned char> valtype;
18 :
19 : namespace {
20 :
21 26262186 : inline bool set_success(ScriptError* ret)
22 : {
23 26262186 : if (ret)
24 5284307 : *ret = SCRIPT_ERR_OK;
25 : return true;
26 : }
27 :
28 26264549 : inline bool set_error(ScriptError* ret, const ScriptError serror)
29 : {
30 26264549 : if (ret)
31 5286025 : *ret = serror;
32 26263468 : return false;
33 : }
34 :
35 : } // anon namespace
36 :
37 8667737 : bool CastToBool(const valtype& vch)
38 : {
39 8668212 : for (unsigned int i = 0; i < vch.size(); i++)
40 : {
41 8667460 : if (vch[i] != 0)
42 : {
43 : // Can be negative zero
44 8666985 : if (i == vch.size()-1 && vch[i] == 0x80)
45 : return false;
46 8666984 : return true;
47 : }
48 : }
49 : return false;
50 : }
51 :
52 : /**
53 : * Script is a stack machine (like Forth) that evaluates a predicate
54 : * returning a bool indicating valid or not. There are no loops.
55 : */
56 : #define stacktop(i) (stack.at(stack.size()+(i)))
57 : #define altstacktop(i) (altstack.at(altstack.size()+(i)))
58 50964868 : static inline void popstack(std::vector<valtype>& stack)
59 : {
60 50964868 : if (stack.empty())
61 0 : throw std::runtime_error("popstack() : stack empty");
62 50964868 : stack.pop_back();
63 50964868 : }
64 :
65 7370752 : bool static IsCompressedOrUncompressedPubKey(const valtype &vchPubKey) {
66 7370752 : if (vchPubKey.size() < CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
67 : // Non-canonical public key: too short
68 : return false;
69 : }
70 7370751 : if (vchPubKey[0] == 0x04) {
71 4518 : if (vchPubKey.size() != CPubKey::PUBLIC_KEY_SIZE) {
72 : // Non-canonical public key: invalid length for uncompressed key
73 0 : return false;
74 : }
75 7366233 : } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
76 7366225 : if (vchPubKey.size() != CPubKey::COMPRESSED_PUBLIC_KEY_SIZE) {
77 : // Non-canonical public key: invalid length for compressed key
78 0 : return false;
79 : }
80 : } else {
81 : // Non-canonical public key: neither compressed nor uncompressed
82 : return false;
83 : }
84 : return true;
85 : }
86 :
87 : /**
88 : * A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
89 : * Where R and S are not negative (their first byte has its highest bit not set), and not
90 : * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
91 : * in which case a single 0 byte is necessary and even required).
92 : *
93 : * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
94 : *
95 : * This function is consensus-critical since BIP66.
96 : */
97 15538341 : bool static IsValidSignatureEncoding(const std::vector<unsigned char> &sig) {
98 : // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] [sighash]
99 : // * total-length: 1-byte length descriptor of everything that follows,
100 : // excluding the sighash byte.
101 : // * R-length: 1-byte length descriptor of the R value that follows.
102 : // * R: arbitrary-length big-endian encoded R value. It must use the shortest
103 : // possible encoding for a positive integers (which means no null bytes at
104 : // the start, except a single one when the next byte has its highest bit set).
105 : // * S-length: 1-byte length descriptor of the S value that follows.
106 : // * S: arbitrary-length big-endian encoded S value. The same rules apply.
107 : // * sighash: 1-byte value indicating what data is hashed (not part of the DER
108 : // signature)
109 :
110 : // Minimum and maximum size constraints.
111 15538341 : if (sig.size() < 9) return false;
112 15538335 : if (sig.size() > 73) return false;
113 :
114 : // A signature is of type 0x30 (compound).
115 15538334 : if (sig[0] != 0x30) return false;
116 :
117 : // Make sure the length covers the entire signature.
118 15537751 : if (sig[1] != sig.size() - 3) return false;
119 :
120 : // Extract the length of the R element.
121 15537748 : unsigned int lenR = sig[3];
122 :
123 : // Make sure the length of the S element is still inside the signature.
124 15537748 : if (5 + lenR >= sig.size()) return false;
125 :
126 : // Extract the length of the S element.
127 15537747 : unsigned int lenS = sig[5 + lenR];
128 :
129 : // Verify that the length of the signature matches the sum of the length
130 : // of the elements.
131 15537747 : if ((size_t)(lenR + lenS + 7) != sig.size()) return false;
132 :
133 : // Check whether the R element is an integer.
134 15537746 : if (sig[2] != 0x02) return false;
135 :
136 : // Zero-length integers are not allowed for R.
137 15537745 : if (lenR == 0) return false;
138 :
139 : // Negative numbers are not allowed for R.
140 15537744 : if (sig[4] & 0x80) return false;
141 :
142 : // Null bytes at the start of R are not allowed, unless R would
143 : // otherwise be interpreted as a negative number.
144 15537730 : if (lenR > 1 && (sig[4] == 0x00) && !(sig[5] & 0x80)) return false;
145 :
146 : // Check whether the S element is an integer.
147 15537724 : if (sig[lenR + 4] != 0x02) return false;
148 :
149 : // Zero-length integers are not allowed for S.
150 15537723 : if (lenS == 0) return false;
151 :
152 : // Negative numbers are not allowed for S.
153 15537722 : if (sig[lenR + 6] & 0x80) return false;
154 :
155 : // Null bytes at the start of S are not allowed, unless S would otherwise be
156 : // interpreted as a negative number.
157 15537721 : if (lenS > 1 && (sig[lenR + 6] == 0x00) && !(sig[lenR + 7] & 0x80)) return false;
158 :
159 : return true;
160 : }
161 :
162 7370648 : bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) {
163 7370648 : if (!IsValidSignatureEncoding(vchSig)) {
164 0 : return set_error(serror, SCRIPT_ERR_SIG_DER);
165 : }
166 : // https://bitcoin.stackexchange.com/a/12556:
167 : // Also note that inside transaction signatures, an extra hashtype byte
168 : // follows the actual signature data.
169 14741336 : std::vector<unsigned char> vchSigCopy(vchSig.begin(), vchSig.begin() + vchSig.size() - 1);
170 : // If the S value is above the order of the curve divided by two, its
171 : // complement modulo the order could have been used instead, which is
172 : // one byte shorter when encoded correctly.
173 7370648 : if (!CPubKey::CheckLowS(vchSigCopy))
174 7370650 : return set_error(serror, SCRIPT_ERR_SIG_HIGH_S);
175 :
176 : return true;
177 : }
178 :
179 7371295 : bool static IsDefinedHashtypeSignature(const valtype &vchSig) {
180 7371295 : if (vchSig.size() == 0) {
181 : return false;
182 : }
183 7371295 : unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
184 7371295 : if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
185 6 : return false;
186 :
187 : return true;
188 : }
189 :
190 8481928 : bool CheckSignatureEncoding(const std::vector<unsigned char> &vchSig, unsigned int flags, ScriptError* serror) {
191 : // Empty signature. Not strictly DER encoded, but allowed to provide a
192 : // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
193 8481928 : if (vchSig.size() == 0) {
194 : return true;
195 : }
196 8481896 : if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsValidSignatureEncoding(vchSig)) {
197 589 : return set_error(serror, SCRIPT_ERR_SIG_DER);
198 8481304 : } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) {
199 : // serror is set
200 : return false;
201 8481302 : } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) {
202 6 : return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE);
203 : }
204 : return true;
205 : }
206 :
207 8480779 : bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) {
208 8480779 : if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) {
209 9 : return set_error(serror, SCRIPT_ERR_PUBKEYTYPE);
210 : }
211 : return true;
212 : }
213 :
214 22201809 : bool static CheckMinimalPush(const valtype& data, opcodetype opcode) {
215 22201809 : if (data.size() == 0) {
216 : // Could have used OP_0.
217 610 : return opcode == OP_0;
218 22201234 : } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) {
219 : // Could have used OP_1 .. OP_16.
220 16 : return opcode == OP_1 + (data[0] - 1);
221 22201218 : } else if (data.size() == 1 && data[0] == 0x81) {
222 : // Could have used OP_1NEGATE.
223 1 : return opcode == OP_1NEGATE;
224 22201217 : } else if (data.size() <= 75) {
225 : // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
226 22200269 : return opcode == data.size();
227 951 : } else if (data.size() <= 255) {
228 : // Could have used OP_PUSHDATA.
229 685 : return opcode == OP_PUSHDATA1;
230 266 : } else if (data.size() <= 65535) {
231 : // Could have used OP_PUSHDATA2.
232 266 : return opcode == OP_PUSHDATA2;
233 : }
234 : return true;
235 : }
236 :
237 17677655 : bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
238 : {
239 17677655 : static const CScriptNum bnZero(0);
240 17677655 : static const CScriptNum bnOne(1);
241 17677655 : static const valtype vchFalse(0);
242 17677655 : static const valtype vchTrue(1, 1);
243 :
244 17677655 : CScript::const_iterator pc = script.begin();
245 17677655 : CScript::const_iterator pend = script.end();
246 17677655 : CScript::const_iterator pbegincodehash = script.begin();
247 17677655 : opcodetype opcode;
248 35355210 : valtype vchPushValue;
249 35355210 : std::vector<bool> vfExec;
250 17677655 : std::vector<valtype> altstack;
251 17677655 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
252 26326362 : if (script.size() > MAX_SCRIPT_SIZE)
253 1 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
254 17677654 : int nOpCount = 0;
255 17677654 : bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0;
256 :
257 77751276 : try
258 : {
259 77751276 : while (pc < pend)
260 : {
261 60074179 : bool fExec = !count(vfExec.begin(), vfExec.end(), false);
262 :
263 : //
264 : // Read instruction
265 : //
266 60074179 : if (!script.GetOp(pc, opcode, vchPushValue))
267 3 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
268 60074176 : if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
269 2 : return set_error(serror, SCRIPT_ERR_PUSH_SIZE);
270 :
271 : // Note how OP_RESERVED does not count towards the opcode limit.
272 60074174 : if (opcode > OP_16 && ++nOpCount > 201)
273 3 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
274 :
275 60074171 : if (opcode == OP_CAT ||
276 : opcode == OP_SUBSTR ||
277 60074171 : opcode == OP_LEFT ||
278 60074165 : opcode == OP_RIGHT ||
279 60074164 : opcode == OP_INVERT ||
280 60074163 : opcode == OP_AND ||
281 60074162 : opcode == OP_OR ||
282 60074161 : opcode == OP_XOR ||
283 60074159 : opcode == OP_2MUL ||
284 60074157 : opcode == OP_2DIV ||
285 60074155 : opcode == OP_MUL ||
286 60074153 : opcode == OP_DIV ||
287 60074151 : opcode == OP_MOD ||
288 60074149 : opcode == OP_LSHIFT ||
289 : opcode == OP_RSHIFT)
290 24 : return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes.
291 :
292 60074147 : if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) {
293 25876545 : if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) {
294 21 : return set_error(serror, SCRIPT_ERR_MINIMALDATA);
295 : }
296 25876524 : stack.push_back(vchPushValue);
297 34197602 : } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
298 34196121 : switch (opcode)
299 : {
300 : //
301 : // Push value
302 : //
303 260086 : case OP_1NEGATE:
304 260086 : case OP_1:
305 260086 : case OP_2:
306 260086 : case OP_3:
307 260086 : case OP_4:
308 260086 : case OP_5:
309 260086 : case OP_6:
310 260086 : case OP_7:
311 260086 : case OP_8:
312 260086 : case OP_9:
313 260086 : case OP_10:
314 260086 : case OP_11:
315 260086 : case OP_12:
316 260086 : case OP_13:
317 260086 : case OP_14:
318 260086 : case OP_15:
319 260086 : case OP_16:
320 260086 : {
321 : // ( -- value)
322 260086 : CScriptNum bn((int)opcode - (int)(OP_1 - 1));
323 260086 : stack.push_back(bn.getvch());
324 : // The result of these opcodes should always be the minimal way to push the data
325 : // they push, so no need for a CheckMinimalPush here.
326 : }
327 260086 : break;
328 :
329 :
330 : //
331 : // Control
332 : //
333 : case OP_NOP:
334 : break;
335 :
336 19 : case OP_EXCHANGEADDR:
337 : // Not enabled, treat as OP_UNKNOWN
338 19 : if (!(flags & SCRIPT_VERIFY_EXCHANGEADDR)) {
339 0 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
340 : }
341 19 : if (!script.IsPayToExchangeAddress())
342 0 : return set_error(serror, SCRIPT_ERR_EXCHANGEADDRVERIFY);
343 : break;
344 :
345 18 : case OP_CHECKLOCKTIMEVERIFY:
346 18 : {
347 18 : if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
348 : // not enabled; treat as a NOP2
349 6 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
350 1 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
351 : }
352 17 : break;
353 : }
354 :
355 12 : if (stack.size() < 1)
356 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
357 :
358 : // CLTV will only be verified if it is a supermajority.
359 : // Otherwise it will be ignored and transaction will be treated as normal.
360 :
361 : // Note that elsewhere numeric opcodes are limited to
362 : // operands in the range -2**31+1 to 2**31-1, however it is
363 : // legal for opcodes to produce results exceeding that
364 : // range. This limitation is implemented by CScriptNum's
365 : // default 4-byte limit.
366 : //
367 : // If we kept to that limit we'd have a year 2038 problem,
368 : // even though the nLockTime field in transactions
369 : // themselves is uint32 which only becomes meaningless
370 : // after the year 2106.
371 : //
372 : // Thus as a special case we tell CScriptNum to accept up
373 : // to 5-byte bignums, which are good until 2**39-1, well
374 : // beyond the 2**32-1 limit of the nLockTime field itself.
375 12 : const CScriptNum nLockTime(stacktop(-1), fRequireMinimal, 5);
376 :
377 : // In the rare event that the argument may be < 0 due to
378 : // some arithmetic being done first, you can always use
379 : // 0 MAX CHECKLOCKTIMEVERIFY.
380 12 : if (nLockTime < 0)
381 0 : return set_error(serror, SCRIPT_ERR_NEGATIVE_LOCKTIME);
382 :
383 : // Actually compare the specified lock time with the transaction.
384 12 : if (!checker.CheckLockTime(nLockTime))
385 1 : return set_error(serror, SCRIPT_ERR_UNSATISFIED_LOCKTIME);
386 :
387 : break;
388 : }
389 :
390 65 : case OP_NOP1: case OP_NOP3: case OP_NOP4: case OP_NOP5:
391 65 : case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
392 65 : {
393 65 : if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)
394 11 : return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS);
395 : }
396 : break;
397 :
398 858 : case OP_IF:
399 858 : case OP_NOTIF:
400 858 : {
401 : // <expression> if [statements] [else [statements]] endif
402 858 : bool fValue = false;
403 858 : if (fExec)
404 : {
405 844 : if (stack.size() < 1)
406 4 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
407 840 : valtype& vch = stacktop(-1);
408 840 : fValue = CastToBool(vch);
409 840 : if (opcode == OP_NOTIF)
410 18 : fValue = !fValue;
411 840 : popstack(stack);
412 : }
413 854 : vfExec.push_back(fValue);
414 : }
415 : break;
416 :
417 720 : case OP_ELSE:
418 720 : {
419 720 : if (vfExec.empty())
420 4 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
421 716 : vfExec.back() = !vfExec.back();
422 : }
423 716 : break;
424 :
425 672 : case OP_ENDIF:
426 672 : {
427 672 : if (vfExec.empty())
428 8 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
429 664 : vfExec.pop_back();
430 : }
431 : break;
432 :
433 31 : case OP_VERIFY:
434 31 : {
435 : // (true -- ) or
436 : // (false -- false) and return
437 31 : if (stack.size() < 1)
438 1 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
439 30 : bool fValue = CastToBool(stacktop(-1));
440 30 : if (fValue)
441 28 : popstack(stack);
442 : else
443 2 : return set_error(serror, SCRIPT_ERR_VERIFY);
444 : }
445 : break;
446 :
447 5 : case OP_RETURN:
448 5 : {
449 5 : return set_error(serror, SCRIPT_ERR_OP_RETURN);
450 : }
451 10 : break;
452 :
453 :
454 : //
455 : // Stack ops
456 : //
457 10 : case OP_TOALTSTACK:
458 10 : {
459 10 : if (stack.size() < 1)
460 1 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
461 9 : altstack.push_back(stacktop(-1));
462 9 : popstack(stack);
463 : }
464 : break;
465 :
466 5 : case OP_FROMALTSTACK:
467 5 : {
468 5 : if (altstack.size() < 1)
469 2 : return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION);
470 3 : stack.push_back(altstacktop(-1));
471 3 : popstack(altstack);
472 : }
473 : break;
474 :
475 11 : case OP_2DROP:
476 11 : {
477 : // (x1 x2 -- )
478 11 : if (stack.size() < 2)
479 1 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
480 10 : popstack(stack);
481 10 : popstack(stack);
482 : }
483 : break;
484 :
485 66666 : case OP_2DUP:
486 66666 : {
487 : // (x1 x2 -- x1 x2 x1 x2)
488 66666 : if (stack.size() < 2)
489 6 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
490 66663 : valtype vch1 = stacktop(-2);
491 133326 : valtype vch2 = stacktop(-1);
492 66663 : stack.push_back(vch1);
493 66663 : stack.push_back(vch2);
494 : }
495 66663 : break;
496 :
497 1646 : case OP_3DUP:
498 1646 : {
499 : // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
500 1646 : if (stack.size() < 3)
501 8 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
502 1642 : valtype vch1 = stacktop(-3);
503 3284 : valtype vch2 = stacktop(-2);
504 3284 : valtype vch3 = stacktop(-1);
505 1642 : stack.push_back(vch1);
506 1642 : stack.push_back(vch2);
507 1642 : stack.push_back(vch3);
508 : }
509 1642 : break;
510 :
511 5 : case OP_2OVER:
512 5 : {
513 : // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
514 5 : if (stack.size() < 4)
515 6 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
516 2 : valtype vch1 = stacktop(-4);
517 4 : valtype vch2 = stacktop(-3);
518 2 : stack.push_back(vch1);
519 2 : stack.push_back(vch2);
520 : }
521 2 : break;
522 :
523 13 : case OP_2ROT:
524 13 : {
525 : // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
526 13 : if (stack.size() < 6)
527 2 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
528 12 : valtype vch1 = stacktop(-6);
529 24 : valtype vch2 = stacktop(-5);
530 12 : stack.erase(stack.end()-6, stack.end()-4);
531 12 : stack.push_back(vch1);
532 12 : stack.push_back(vch2);
533 : }
534 12 : break;
535 :
536 5 : case OP_2SWAP:
537 5 : {
538 : // (x1 x2 x3 x4 -- x3 x4 x1 x2)
539 5 : if (stack.size() < 4)
540 3 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
541 2 : swap(stacktop(-4), stacktop(-2));
542 2 : swap(stacktop(-3), stacktop(-1));
543 : }
544 : break;
545 :
546 6 : case OP_IFDUP:
547 6 : {
548 : // (x - 0 | x x)
549 6 : if (stack.size() < 1)
550 4 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
551 4 : valtype vch = stacktop(-1);
552 4 : if (CastToBool(vch))
553 3 : stack.push_back(vch);
554 : }
555 4 : break;
556 :
557 75 : case OP_DEPTH:
558 75 : {
559 : // -- stacksize
560 75 : CScriptNum bn(stack.size());
561 75 : stack.push_back(bn.getvch());
562 : }
563 75 : break;
564 :
565 69223 : case OP_DROP:
566 69223 : {
567 : // (x -- )
568 69223 : if (stack.size() < 1)
569 2 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
570 69221 : popstack(stack);
571 : }
572 : break;
573 :
574 8382557 : case OP_DUP:
575 8382557 : {
576 : // (x -- x x)
577 8382557 : if (stack.size() < 1)
578 6 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
579 8382555 : valtype vch = stacktop(-1);
580 8382555 : stack.push_back(vch);
581 : }
582 8382555 : break;
583 :
584 10 : case OP_NIP:
585 10 : {
586 : // (x1 x2 -- x2)
587 10 : if (stack.size() < 2)
588 3 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
589 7 : stack.erase(stack.end() - 2);
590 : }
591 7 : break;
592 :
593 6 : case OP_OVER:
594 6 : {
595 : // (x1 x2 -- x1 x2 x1)
596 6 : if (stack.size() < 2)
597 6 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
598 3 : valtype vch = stacktop(-2);
599 3 : stack.push_back(vch);
600 : }
601 3 : break;
602 :
603 36 : case OP_PICK:
604 36 : case OP_ROLL:
605 36 : {
606 : // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
607 : // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
608 36 : if (stack.size() < 2)
609 4 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
610 32 : int n = CScriptNum(stacktop(-1), fRequireMinimal).getint();
611 30 : popstack(stack);
612 30 : if (n < 0 || n >= (int)stack.size())
613 14 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
614 25 : valtype vch = stacktop(-n-1);
615 25 : if (opcode == OP_ROLL)
616 9 : stack.erase(stack.end()-n-1);
617 25 : stack.push_back(vch);
618 : }
619 25 : break;
620 :
621 598 : case OP_ROT:
622 598 : {
623 : // (x1 x2 x3 -- x2 x3 x1)
624 : // x2 x1 x3 after first swap
625 : // x2 x3 x1 after second swap
626 598 : if (stack.size() < 3)
627 4 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
628 594 : swap(stacktop(-3), stacktop(-2));
629 594 : swap(stacktop(-2), stacktop(-1));
630 : }
631 : break;
632 :
633 12 : case OP_SWAP:
634 12 : {
635 : // (x1 x2 -- x2 x1)
636 12 : if (stack.size() < 2)
637 3 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
638 9 : swap(stacktop(-2), stacktop(-1));
639 : }
640 : break;
641 :
642 6 : case OP_TUCK:
643 6 : {
644 : // (x1 x2 -- x2 x1 x2)
645 6 : if (stack.size() < 2)
646 6 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
647 3 : valtype vch = stacktop(-1);
648 3 : stack.insert(stack.end()-2, vch);
649 : }
650 3 : break;
651 :
652 :
653 35 : case OP_SIZE:
654 35 : {
655 : // (in -- in size)
656 35 : if (stack.size() < 1)
657 4 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
658 33 : CScriptNum bn(stacktop(-1).size());
659 33 : stack.push_back(bn.getvch());
660 : }
661 33 : break;
662 :
663 :
664 : //
665 : // Bitwise logic
666 : //
667 8464415 : case OP_EQUAL:
668 8464415 : case OP_EQUALVERIFY:
669 : //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
670 8464415 : {
671 : // (x1 x2 - bool)
672 8464415 : if (stack.size() < 2)
673 4 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
674 8464411 : valtype& vch1 = stacktop(-2);
675 8464411 : valtype& vch2 = stacktop(-1);
676 8464411 : bool fEqual = (vch1 == vch2);
677 : // OP_NOTEQUAL is disabled because it would be too easy to say
678 : // something like n != 1 and have some wiseguy pass in 1 with extra
679 : // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
680 : //if (opcode == OP_NOTEQUAL)
681 : // fEqual = !fEqual;
682 8464411 : popstack(stack);
683 8464411 : popstack(stack);
684 8464488 : stack.push_back(fEqual ? vchTrue : vchFalse);
685 8464411 : if (opcode == OP_EQUALVERIFY)
686 : {
687 8382487 : if (fEqual)
688 8382461 : popstack(stack);
689 : else
690 27 : return set_error(serror, SCRIPT_ERR_EQUALVERIFY);
691 : }
692 : }
693 : break;
694 :
695 :
696 : //
697 : // Numeric
698 : //
699 125 : case OP_1ADD:
700 125 : case OP_1SUB:
701 125 : case OP_NEGATE:
702 125 : case OP_ABS:
703 125 : case OP_NOT:
704 125 : case OP_0NOTEQUAL:
705 125 : {
706 : // (in -- out)
707 125 : if (stack.size() < 1)
708 12 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
709 119 : CScriptNum bn(stacktop(-1), fRequireMinimal);
710 95 : switch (opcode)
711 : {
712 8 : case OP_1ADD: bn += bnOne; break;
713 3 : case OP_1SUB: bn -= bnOne; break;
714 4 : case OP_NEGATE: bn = -bn; break;
715 5 : case OP_ABS: if (bn < bnZero) bn = -bn; break;
716 69 : case OP_NOT: bn = (bn == bnZero); break;
717 6 : case OP_0NOTEQUAL: bn = (bn != bnZero); break;
718 0 : default: assert(!"invalid opcode"); break;
719 : }
720 95 : popstack(stack);
721 95 : stack.push_back(bn.getvch());
722 : }
723 95 : break;
724 :
725 188 : case OP_ADD:
726 188 : case OP_SUB:
727 188 : case OP_BOOLAND:
728 188 : case OP_BOOLOR:
729 188 : case OP_NUMEQUAL:
730 188 : case OP_NUMEQUALVERIFY:
731 188 : case OP_NUMNOTEQUAL:
732 188 : case OP_LESSTHAN:
733 188 : case OP_GREATERTHAN:
734 188 : case OP_LESSTHANOREQUAL:
735 188 : case OP_GREATERTHANOREQUAL:
736 188 : case OP_MIN:
737 188 : case OP_MAX:
738 188 : {
739 : // (x1 x2 -- out)
740 188 : if (stack.size() < 2)
741 13 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
742 175 : CScriptNum bn1(stacktop(-2), fRequireMinimal);
743 157 : CScriptNum bn2(stacktop(-1), fRequireMinimal);
744 144 : CScriptNum bn(0);
745 144 : switch (opcode)
746 : {
747 36 : case OP_ADD:
748 36 : bn = bn1 + bn2;
749 36 : break;
750 :
751 6 : case OP_SUB:
752 6 : bn = bn1 - bn2;
753 6 : break;
754 :
755 12 : case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
756 9 : case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
757 28 : case OP_NUMEQUAL: bn = (bn1 == bn2); break;
758 4 : case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
759 5 : case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
760 8 : case OP_LESSTHAN: bn = (bn1 < bn2); break;
761 8 : case OP_GREATERTHAN: bn = (bn1 > bn2); break;
762 8 : case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
763 8 : case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
764 11 : case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
765 11 : case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
766 0 : default: assert(!"invalid opcode"); break;
767 : }
768 144 : popstack(stack);
769 144 : popstack(stack);
770 144 : stack.push_back(bn.getvch());
771 :
772 144 : if (opcode == OP_NUMEQUALVERIFY)
773 : {
774 4 : if (CastToBool(stacktop(-1)))
775 4 : popstack(stack);
776 : else
777 13 : return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY);
778 : }
779 : }
780 144 : break;
781 :
782 17 : case OP_WITHIN:
783 17 : {
784 : // (x min max -- out)
785 17 : if (stack.size() < 3)
786 2 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
787 16 : CScriptNum bn1(stacktop(-3), fRequireMinimal);
788 15 : CScriptNum bn2(stacktop(-2), fRequireMinimal);
789 14 : CScriptNum bn3(stacktop(-1), fRequireMinimal);
790 13 : bool fValue = (bn2 <= bn1 && bn1 < bn3);
791 13 : popstack(stack);
792 13 : popstack(stack);
793 13 : popstack(stack);
794 19 : stack.push_back(fValue ? vchTrue : vchFalse);
795 : }
796 13 : break;
797 :
798 :
799 : //
800 : // Crypto
801 : //
802 8464318 : case OP_RIPEMD160:
803 8464318 : case OP_SHA1:
804 8464318 : case OP_SHA256:
805 8464318 : case OP_HASH160:
806 8464318 : case OP_HASH256:
807 8464318 : {
808 : // (in -- hash)
809 8464318 : if (stack.size() < 1)
810 22 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
811 8464308 : valtype& vch = stacktop(-1);
812 8464387 : valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
813 8464308 : if (opcode == OP_RIPEMD160)
814 5 : CRIPEMD160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
815 8464303 : else if (opcode == OP_SHA1)
816 44 : CSHA1().Write(vch.data(), vch.size()).Finalize(vchHash.data());
817 8464259 : else if (opcode == OP_SHA256)
818 9 : CSHA256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
819 8464250 : else if (opcode == OP_HASH160)
820 8464245 : CHash160().Write(vch.data(), vch.size()).Finalize(vchHash.data());
821 5 : else if (opcode == OP_HASH256)
822 5 : CHash256().Write(vch.data(), vch.size()).Finalize(vchHash.data());
823 8464308 : popstack(stack);
824 8464308 : stack.push_back(vchHash);
825 : }
826 8464308 : break;
827 :
828 10 : case OP_CODESEPARATOR:
829 10 : {
830 : // Hash starts after the code separator
831 10 : pbegincodehash = pc;
832 : }
833 10 : break;
834 :
835 8479398 : case OP_CHECKSIG:
836 8479398 : case OP_CHECKSIGVERIFY:
837 8479398 : {
838 : // (sig pubkey -- bool)
839 8479398 : if (stack.size() < 2)
840 3 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
841 :
842 8479395 : valtype& vchSig = stacktop(-2);
843 8479395 : valtype& vchPubKey = stacktop(-1);
844 :
845 : // Subset of script starting at the most recent codeseparator
846 16958694 : CScript scriptCode(pbegincodehash, pend);
847 :
848 : // Drop the signature, since there's no way for a signature to sign itself
849 8479395 : scriptCode.FindAndDelete(CScript(vchSig));
850 :
851 8479395 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
852 : //serror is set
853 111 : return false;
854 : }
855 8479343 : bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
856 :
857 8479343 : popstack(stack);
858 8479343 : popstack(stack);
859 8479391 : stack.push_back(fSuccess ? vchTrue : vchFalse);
860 8479343 : if (opcode == OP_CHECKSIGVERIFY)
861 : {
862 66668 : if (fSuccess)
863 66664 : popstack(stack);
864 : else
865 60 : return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY);
866 : }
867 : }
868 : break;
869 :
870 2402 : case OP_CHECKMULTISIG:
871 2402 : case OP_CHECKMULTISIGVERIFY:
872 2402 : {
873 : // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
874 :
875 2402 : int i = 1;
876 2402 : if ((int)stack.size() < i)
877 1 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
878 :
879 2401 : int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
880 2399 : if (nKeysCount < 0 || nKeysCount > MAX_PUBKEYS_PER_MULTISIG)
881 2 : return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT);
882 2397 : nOpCount += nKeysCount;
883 2397 : if (nOpCount > 201)
884 2 : return set_error(serror, SCRIPT_ERR_OP_COUNT);
885 2395 : int ikey = ++i;
886 2395 : i += nKeysCount;
887 2395 : if ((int)stack.size() < i)
888 1 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
889 :
890 2394 : int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint();
891 2391 : if (nSigsCount < 0 || nSigsCount > nKeysCount)
892 2 : return set_error(serror, SCRIPT_ERR_SIG_COUNT);
893 2389 : int isig = ++i;
894 2389 : i += nSigsCount;
895 2389 : if ((int)stack.size() < i)
896 12 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
897 :
898 : // Subset of script starting at the most recent codeseparator
899 4733 : CScript scriptCode(pbegincodehash, pend);
900 :
901 : // Drop the signatures, since there's no way for a signature to sign itself
902 3763 : for (int k = 0; k < nSigsCount; k++)
903 : {
904 1386 : valtype& vchSig = stacktop(-isig-k);
905 2772 : scriptCode.FindAndDelete(CScript(vchSig));
906 : }
907 :
908 : bool fSuccess = true;
909 3761 : while (fSuccess && nSigsCount > 0)
910 : {
911 1398 : valtype& vchSig = stacktop(-isig);
912 1398 : valtype& vchPubKey = stacktop(-ikey);
913 :
914 : // Note how this makes the exact order of pubkey/signature evaluation
915 : // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set.
916 : // See the script_(in)valid tests for details.
917 1398 : if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
918 : // serror is set
919 55 : return false;
920 : }
921 :
922 : // Check signature
923 1384 : bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode, sigversion);
924 :
925 1384 : if (fOk) {
926 1273 : isig++;
927 1273 : nSigsCount--;
928 : }
929 1384 : ikey++;
930 1384 : nKeysCount--;
931 :
932 : // If there are more signatures left than keys left,
933 : // then too many signatures have failed. Exit early,
934 : // without checking any further signatures.
935 1384 : if (nSigsCount > nKeysCount)
936 53 : fSuccess = false;
937 : }
938 :
939 : // Clean up stack of actual arguments
940 11494 : while (i-- > 1)
941 9131 : popstack(stack);
942 :
943 : // A bug causes CHECKMULTISIG to consume one extra argument
944 : // whose contents were not checked in any way.
945 : //
946 : // Unfortunately this is a potential source of mutability,
947 : // so optionally verify it is exactly equal to zero prior
948 : // to removing it from the stack.
949 2363 : if (stack.size() < 1)
950 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
951 2363 : if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
952 7 : return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY);
953 2356 : popstack(stack);
954 :
955 2407 : stack.push_back(fSuccess ? vchTrue : vchFalse);
956 :
957 2356 : if (opcode == OP_CHECKMULTISIGVERIFY)
958 : {
959 246 : if (fSuccess)
960 246 : popstack(stack);
961 : else
962 21 : return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY);
963 : }
964 : }
965 : break;
966 :
967 7 : case OP_CHECKCOLDSTAKEVERIFY:
968 7 : {
969 7 : if (!checker.CheckColdStake(false, script, stack, flags, serror)) {
970 : // serror set
971 : return false;
972 : }
973 : }
974 : break;
975 :
976 109 : case OP_CHECKCOLDSTAKEVERIFY_LOF:
977 109 : {
978 : // Allow last output script "free"
979 109 : if (!checker.CheckColdStake(true, script, stack, flags, serror)) {
980 : // serror set
981 : return false;
982 : }
983 : }
984 : break;
985 :
986 85 : default:
987 85 : return set_error(serror, SCRIPT_ERR_BAD_OPCODE);
988 : }
989 :
990 : // Size limits
991 60073624 : if (stack.size() + altstack.size() > 1000)
992 2 : return set_error(serror, SCRIPT_ERR_STACK_SIZE);
993 : }
994 : }
995 65 : catch (...)
996 : {
997 130 : return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
998 : }
999 :
1000 17677097 : if (!vfExec.empty())
1001 6 : return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL);
1002 :
1003 21227783 : return set_success(serror);
1004 : }
1005 :
1006 : namespace {
1007 :
1008 : /**
1009 : * Wrapper that serializes like CTransaction, but with the modifications
1010 : * required for the signature hash done in-place
1011 : */
1012 : class CTransactionSignatureSerializer {
1013 : private:
1014 : const CTransaction &txTo; //! reference to the spending transaction (the one being serialized)
1015 : const CScript &scriptCode; //! output script being consumed
1016 : const unsigned int nIn; //! input index of txTo being signed
1017 : const bool fAnyoneCanPay; //! whether the hashtype has the SIGHASH_ANYONECANPAY flag set
1018 : const bool fHashSingle; //! whether the hashtype is SIGHASH_SINGLE
1019 : const bool fHashNone; //! whether the hashtype is SIGHASH_NONE
1020 :
1021 : public:
1022 2164343 : CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
1023 : txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
1024 2164343 : fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
1025 2164343 : fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
1026 2164343 : fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
1027 :
1028 : /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1029 : template<typename S>
1030 2164343 : void SerializeScriptCode(S &s) const {
1031 2164343 : CScript::const_iterator it = scriptCode.begin();
1032 2164343 : CScript::const_iterator itBegin = it;
1033 : opcodetype opcode;
1034 2164343 : unsigned int nCodeSeparators = 0;
1035 13473831 : while (scriptCode.GetOp(it, opcode)) {
1036 11309508 : if (opcode == OP_CODESEPARATOR)
1037 67887 : nCodeSeparators++;
1038 : }
1039 2245556 : ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1040 2164343 : it = itBegin;
1041 13473831 : while (scriptCode.GetOp(it, opcode)) {
1042 11309508 : if (opcode == OP_CODESEPARATOR) {
1043 67887 : s.write((char*)&itBegin[0], it-itBegin-1);
1044 67887 : itBegin = it;
1045 : }
1046 : }
1047 4328676 : if (itBegin != scriptCode.end())
1048 2136763 : s.write((char*)&itBegin[0], it-itBegin);
1049 2164343 : }
1050 :
1051 : /** Serialize an input of txTo */
1052 : template<typename S>
1053 4509810 : void SerializeInput(S &s, unsigned int nInput) const {
1054 : // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1055 4509810 : if (fAnyoneCanPay)
1056 21702 : nInput = nIn;
1057 : // Serialize the prevout
1058 4509810 : ::Serialize(s, txTo.vin[nInput].prevout);
1059 4509810 : assert(nInput != NOT_AN_INPUT);
1060 : // Serialize the script
1061 4509810 : if (nInput != nIn)
1062 : // Blank out other inputs' signatures
1063 4690944 : ::Serialize(s, CScript());
1064 : else
1065 2164343 : SerializeScriptCode(s);
1066 : // Serialize the nSequence
1067 4509810 : if (nInput != nIn && (fHashSingle || fHashNone))
1068 : // let the others update at will
1069 4509810 : ::Serialize(s, (int)0);
1070 : else
1071 4507789 : ::Serialize(s, txTo.vin[nInput].nSequence);
1072 4509810 : }
1073 :
1074 : /** Serialize an output of txTo */
1075 : template<typename S>
1076 6222359 : void SerializeOutput(S &s, unsigned int nOutput) const {
1077 6222359 : if (fHashSingle && nOutput != nIn)
1078 : // Do not lock-in the txout payee at other indices as txin
1079 1992 : ::Serialize(s, CTxOut());
1080 : else
1081 6221363 : ::Serialize(s, txTo.vout[nOutput]);
1082 6222359 : }
1083 :
1084 : /** Serialize txTo */
1085 : template<typename S>
1086 2164343 : void Serialize(S &s) const {
1087 : // Serialize nVersion
1088 2164343 : ::Serialize(s, txTo.nVersion);
1089 : // Serialize nType
1090 2164343 : ::Serialize(s, txTo.nType);
1091 : // Serialize vin
1092 2164343 : unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1093 2164343 : ::WriteCompactSize(s, nInputs);
1094 6674153 : for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1095 4509810 : SerializeInput(s, nInput);
1096 : // Serialize vout
1097 2164343 : unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1098 2164343 : ::WriteCompactSize(s, nOutputs);
1099 8386692 : for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1100 6222359 : SerializeOutput(s, nOutput);
1101 : // Serialize nLockTime
1102 2164343 : ::Serialize(s, txTo.nLockTime);
1103 2164343 : }
1104 : };
1105 :
1106 : const unsigned char PIVX_PREVOUTS_HASH_PERSONALIZATION[crypto_generichash_blake2b_PERSONALBYTES] =
1107 : {'P','I','V','X','P','r','e','v','o','u','t','H','a','s','h'};
1108 : const unsigned char PIVX_SEQUENCE_HASH_PERSONALIZATION[crypto_generichash_blake2b_PERSONALBYTES] =
1109 : {'P','I','V','X','S','e','q','u','e','n','c','H','a','s','h'};
1110 : const unsigned char PIVX_OUTPUTS_HASH_PERSONALIZATION[crypto_generichash_blake2b_PERSONALBYTES] =
1111 : {'P','I','V','X','O','u','t','p','u','t','s','H','a','s','h'};
1112 : const unsigned char PIVX_SHIELDED_SPENDS_HASH_PERSONALIZATION[crypto_generichash_blake2b_PERSONALBYTES] =
1113 : {'P','I','V','X','S','S','p','e','n','d','s','H','a','s','h'};
1114 : const unsigned char PIVX_SHIELDED_OUTPUTS_HASH_PERSONALIZATION[crypto_generichash_blake2b_PERSONALBYTES] =
1115 : {'P','I','V','X','S','O','u','t','p','u','t','H','a','s','h'};
1116 :
1117 :
1118 :
1119 3790336 : uint256 GetPrevoutHash(const CTransaction& txTo) {
1120 3790336 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_PREVOUTS_HASH_PERSONALIZATION);
1121 29628080 : for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1122 25837780 : ss << txTo.vin[n].prevout;
1123 : }
1124 3790336 : return ss.GetHash();
1125 : }
1126 :
1127 3787117 : uint256 GetSequenceHash(const CTransaction& txTo) {
1128 3787117 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_SEQUENCE_HASH_PERSONALIZATION);
1129 16124340 : for (unsigned int n = 0; n < txTo.vin.size(); n++) {
1130 12337230 : ss << txTo.vin[n].nSequence;
1131 : }
1132 3787117 : return ss.GetHash();
1133 : }
1134 :
1135 3791961 : uint256 GetOutputsHash(const CTransaction& txTo) {
1136 3791961 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_OUTPUTS_HASH_PERSONALIZATION);
1137 24884800 : for (unsigned int n = 0; n < txTo.vout.size(); n++) {
1138 21092800 : ss << txTo.vout[n];
1139 : }
1140 3791961 : return ss.GetHash();
1141 : }
1142 :
1143 3747065 : uint256 GetShieldedSpendsHash(const CTransaction& txTo) {
1144 3747065 : assert(txTo.sapData);
1145 3747065 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_SHIELDED_SPENDS_HASH_PERSONALIZATION);
1146 3747065 : auto sapData = txTo.sapData;
1147 3760428 : for (const auto& n : sapData->vShieldedSpend) {
1148 13365 : ss << n.cv;
1149 13365 : ss << n.anchor;
1150 13365 : ss << n.nullifier;
1151 13365 : ss << n.rk;
1152 13365 : ss << n.zkproof;
1153 : }
1154 11241175 : return ss.GetHash();
1155 : }
1156 :
1157 3754952 : uint256 GetShieldedOutputsHash(const CTransaction& txTo) {
1158 3754952 : assert(txTo.sapData);
1159 3754952 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_SHIELDED_OUTPUTS_HASH_PERSONALIZATION);
1160 3754952 : auto sapData = txTo.sapData;
1161 4282587 : for (const auto& n : sapData->vShieldedOutput) {
1162 527640 : ss << n;
1163 : }
1164 11264856 : return ss.GetHash();
1165 : }
1166 :
1167 : } // anon namespace
1168 :
1169 18671275 : PrecomputedTransactionData::PrecomputedTransactionData(const CTransaction& txTo)
1170 : {
1171 3734265 : hashPrevouts = GetPrevoutHash(txTo);
1172 3734265 : hashSequence = GetSequenceHash(txTo);
1173 3734265 : hashOutputs = GetOutputsHash(txTo);
1174 3734265 : if (txTo.sapData) {
1175 3734265 : hashShieldedSpends = GetShieldedSpendsHash(txTo);
1176 3734265 : hashShieldedOutputs = GetShieldedOutputsHash(txTo);
1177 : }
1178 3734265 : }
1179 :
1180 2240742 : uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, const CAmount& amount, SigVersion sigversion, const PrecomputedTransactionData* cache)
1181 : {
1182 2240742 : if (nIn >= txTo.vin.size() && nIn != NOT_AN_INPUT) {
1183 : // nIn out of range
1184 0 : return UINT256_ONE;
1185 : }
1186 :
1187 2240742 : if (txTo.isSaplingVersion() && sigversion != SIGVERSION_SAPLING) {
1188 0 : throw std::runtime_error("SignatureHash in Sapling tx with wrong sigversion " + std::to_string(sigversion));
1189 : }
1190 :
1191 2240742 : if (sigversion == SIGVERSION_SAPLING) {
1192 :
1193 76402 : uint256 hashPrevouts;
1194 76402 : uint256 hashSequence;
1195 76402 : uint256 hashOutputs;
1196 76402 : uint256 hashShieldedSpends;
1197 76402 : uint256 hashShieldedOutputs;
1198 76402 : bool hasSapData = false;
1199 :
1200 76402 : if (!(nHashType & SIGHASH_ANYONECANPAY)) {
1201 66101 : hashPrevouts = cache ? cache->hashPrevouts : GetPrevoutHash(txTo);
1202 : }
1203 :
1204 76402 : if (!(nHashType & SIGHASH_ANYONECANPAY) && (nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1205 61382 : hashSequence = cache ? cache->hashSequence : GetSequenceHash(txTo);
1206 : }
1207 :
1208 76402 : if ((nHashType & 0x1f) != SIGHASH_SINGLE && (nHashType & 0x1f) != SIGHASH_NONE) {
1209 66976 : hashOutputs = cache ? cache->hashOutputs : GetOutputsHash(txTo);
1210 9426 : } else if ((nHashType & 0x1f) == SIGHASH_SINGLE && nIn < txTo.vout.size()) {
1211 4711 : CBLAKE2bWriter ss(SER_GETHASH, 0, PIVX_OUTPUTS_HASH_PERSONALIZATION);
1212 4711 : ss << txTo.vout[nIn];
1213 9422 : hashOutputs = ss.GetHash();
1214 : }
1215 :
1216 76402 : if (txTo.sapData) {
1217 76400 : if (!txTo.sapData->vShieldedSpend.empty()) {
1218 12803 : hashShieldedSpends = cache ? cache->hashShieldedSpends : GetShieldedSpendsHash(txTo);
1219 : hasSapData = true;
1220 : }
1221 :
1222 76400 : if (!txTo.sapData->vShieldedOutput.empty()) {
1223 27075 : hashShieldedOutputs = cache ? cache->hashShieldedOutputs : GetShieldedOutputsHash(txTo);
1224 : hasSapData = true;
1225 : }
1226 : }
1227 :
1228 : // todo: complete branch id with the active network upgrade
1229 76402 : uint32_t leConsensusBranchId = htole32(0);
1230 76402 : unsigned char personalization[16] = {};
1231 76402 : memcpy(personalization, "PIVXSigHash", 12);
1232 76402 : memcpy(personalization+12, &leConsensusBranchId, 4);
1233 :
1234 76402 : CBLAKE2bWriter ss(SER_GETHASH, 0, personalization);
1235 : // Version
1236 76402 : ss << txTo.nVersion;
1237 : // Type
1238 76402 : ss << txTo.nType;
1239 : // Input prevouts/nSequence (none/all, depending on flags)
1240 76402 : ss << hashPrevouts;
1241 76402 : ss << hashSequence;
1242 : // Outputs (none/one/all, depending on flags)
1243 76402 : ss << hashOutputs;
1244 :
1245 76402 : if (hasSapData) {
1246 : // Spend descriptions
1247 39587 : ss << hashShieldedSpends;
1248 : // Output descriptions
1249 39587 : ss << hashShieldedOutputs;
1250 : // Sapling value balance
1251 39587 : ss << txTo.sapData->valueBalance;
1252 : }
1253 :
1254 76402 : if (nIn != NOT_AN_INPUT) {
1255 : // The input being signed (replacing the scriptSig with scriptCode + amount)
1256 : // The prevout may already be contained in hashPrevout, and the nSequence
1257 : // may already be contained in hashSequence.
1258 70837 : ss << txTo.vin[nIn].prevout;
1259 70837 : ss << scriptCode;
1260 70837 : ss << amount;
1261 70837 : ss << txTo.vin[nIn].nSequence;
1262 : }
1263 :
1264 : // Extra payload for special transactions
1265 76402 : if (txTo.IsSpecialTx()) {
1266 1699 : ss << *(txTo.extraPayload);
1267 : }
1268 :
1269 : // Locktime
1270 76402 : ss << txTo.nLockTime;
1271 : // Sighash type
1272 76402 : ss << nHashType;
1273 :
1274 152804 : return ss.GetHash();
1275 : }
1276 :
1277 : // Check for invalid use of SIGHASH_SINGLE
1278 2164347 : if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1279 1357 : if (nIn >= txTo.vout.size()) {
1280 : // nOut out of range
1281 4 : return UINT256_ONE;
1282 : }
1283 : }
1284 :
1285 : // Wrapper to serialize only the necessary parts of the transaction being signed
1286 2164343 : CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1287 :
1288 : // Serialize and hash
1289 2164343 : CHashWriter ss(SER_GETHASH, 0);
1290 2164343 : ss << txTmp << nHashType;
1291 4405085 : return ss.GetHash();
1292 : }
1293 :
1294 818834 : bool TransactionSignatureChecker::VerifySignature(const std::vector<unsigned char>& vchSig, const CPubKey& pubkey, const uint256& sighash) const
1295 : {
1296 818834 : return pubkey.Verify(sighash, vchSig);
1297 : }
1298 :
1299 1840704 : bool TransactionSignatureChecker::CheckSig(const std::vector<unsigned char>& vchSigIn, const std::vector<unsigned char>& vchPubKey, const CScript& scriptCode, SigVersion sigversion) const
1300 : {
1301 1840704 : CPubKey pubkey(vchPubKey);
1302 1840704 : if (!pubkey.IsValid())
1303 : return false;
1304 :
1305 : // Hash type is one byte tacked on to the end of the signature
1306 3681397 : std::vector<unsigned char> vchSig(vchSigIn);
1307 1840693 : if (vchSig.empty())
1308 : return false;
1309 1840661 : int nHashType = vchSig.back();
1310 1840661 : vchSig.pop_back();
1311 :
1312 1840661 : const uint256& sighash = SignatureHash(scriptCode, *txTo, nIn, nHashType, amount, sigversion, this->precomTxData);
1313 :
1314 1840661 : if (!VerifySignature(vchSig, pubkey, sighash))
1315 128 : return false;
1316 :
1317 : return true;
1318 : }
1319 :
1320 12 : bool TransactionSignatureChecker::CheckLockTime(const CScriptNum& nLockTime) const
1321 : {
1322 : // There are two times of nLockTime: lock-by-blockheight
1323 : // and lock-by-blocktime, distinguished by whether
1324 : // nLockTime < LOCKTIME_THRESHOLD.
1325 : //
1326 : // We want to compare apples to apples, so fail the script
1327 : // unless the type of nLockTime being tested is the same as
1328 : // the nLockTime in the transaction.
1329 5 : if (!(
1330 12 : (txTo->nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
1331 5 : (txTo->nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
1332 : ))
1333 : return false;
1334 :
1335 : // Now that we know we're comparing apples-to-apples, the
1336 : // comparison is a simple numeric one.
1337 12 : if (nLockTime > (int64_t)txTo->nLockTime)
1338 : return false;
1339 :
1340 : // Finally the nLockTime feature can be disabled and thus
1341 : // CHECKLOCKTIMEVERIFY bypassed if every txin has been
1342 : // finalized by setting nSequence to maxint. The
1343 : // transaction would be allowed into the blockchain, making
1344 : // the opcode ineffective.
1345 : //
1346 : // Testing if this vin is not final is sufficient to
1347 : // prevent this condition. Alternatively we could test all
1348 : // inputs, but testing just this input minimizes the data
1349 : // required to prove correct CHECKLOCKTIMEVERIFY execution.
1350 12 : if (txTo->vin[nIn].IsFinal())
1351 0 : return false;
1352 :
1353 : return true;
1354 : }
1355 :
1356 42 : bool TransactionSignatureChecker::CheckColdStake(bool fAllowLastOutputFree, const CScript& prevoutScript, std::vector<valtype>& stack, unsigned int flags, ScriptError* serror) const
1357 : {
1358 : // the stack can contain only <sig> <pk> <pkh> at this point
1359 42 : if ((int)stack.size() != 3) {
1360 0 : return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION);
1361 : }
1362 : // check pubkey/signature encoding
1363 42 : valtype& vchSig = stacktop(-3);
1364 42 : valtype& vchPubKey = stacktop(-2);
1365 84 : if (!CheckSignatureEncoding(vchSig, flags, serror) ||
1366 42 : !CheckPubKeyEncoding(vchPubKey, flags, serror)) {
1367 : // serror is set
1368 0 : return false;
1369 : }
1370 : // check hash size
1371 42 : valtype& vchPubKeyHash = stacktop(-1);
1372 42 : if ((int)vchPubKeyHash.size() != 20) {
1373 0 : return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE);
1374 : }
1375 :
1376 : // check it is used in a valid cold stake transaction.
1377 : // Transaction must be a coinstake tx
1378 42 : if (!txTo->IsCoinStake()) {
1379 4 : return set_error(serror, SCRIPT_ERR_CHECKCOLDSTAKEVERIFY);
1380 : }
1381 : // There must be one single input
1382 38 : if (txTo->vin.size() != 1) {
1383 0 : return set_error(serror, SCRIPT_ERR_CHECKCOLDSTAKEVERIFY);
1384 : }
1385 : // Since this is a coinstake, it has at least 2 outputs
1386 38 : const unsigned int outs = txTo->vout.size();
1387 38 : assert(outs >= 2);
1388 : // All outputs must have the same pubKeyScript, and it must match the script we are spending.
1389 : // If the coinstake has at least 3 outputs, the last one can be left free, to be used for
1390 : // budget/masternode payments (before v6.0 enforcement), and is checked in CheckColdstakeFreeOutput().
1391 : // Here we verify only that input amount goes to the non-free outputs.
1392 : CAmount outValue{0};
1393 77 : for (unsigned int i = 1; i < outs; i++) {
1394 49 : if (txTo->vout[i].scriptPubKey != prevoutScript) {
1395 : // Only the last one can be different (and only when outs >=3 and fAllowLastOutputFree=true)
1396 14 : if (!fAllowLastOutputFree || i != outs-1 || outs < 3) {
1397 10 : return set_error(serror, SCRIPT_ERR_CHECKCOLDSTAKEVERIFY);
1398 : }
1399 : } else {
1400 35 : outValue += txTo->vout[i].nValue;
1401 : }
1402 : }
1403 28 : if (outValue < amount) {
1404 3 : return set_error(serror, SCRIPT_ERR_CHECKCOLDSTAKEVERIFY);
1405 : }
1406 : return true;
1407 : }
1408 :
1409 :
1410 8585768 : bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, SigVersion sigversion, ScriptError* serror)
1411 : {
1412 8585768 : set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR);
1413 :
1414 8585768 : if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) {
1415 8585772 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1416 : }
1417 :
1418 17171508 : std::vector<std::vector<unsigned char> > stack, stackCopy;
1419 8585764 : if (!EvalScript(stack, scriptSig, flags, checker, sigversion, serror))
1420 : // serror is set
1421 : return false;
1422 8585709 : if (flags & SCRIPT_VERIFY_P2SH)
1423 8517857 : stackCopy = stack;
1424 8585709 : if (!EvalScript(stack, scriptPubKey, flags, checker, sigversion, serror))
1425 : // serror is set
1426 : return false;
1427 8585219 : if (stack.empty())
1428 10 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1429 8585209 : if (CastToBool(stack.back()) == false)
1430 125 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1431 :
1432 : // Additional validation for spend-to-script-hash transactions:
1433 8585086 : if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1434 : {
1435 : // scriptSig must be literals-only or validation fails
1436 81659 : if (!scriptSig.IsPushOnly())
1437 4 : return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY);
1438 :
1439 : // Restore stack.
1440 81655 : swap(stack, stackCopy);
1441 :
1442 : // stack cannot be empty here, because if it was the
1443 : // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1444 : // an empty stack and the EvalScript above would return false.
1445 81655 : assert(!stack.empty());
1446 :
1447 81655 : const valtype& pubKeySerialized = stack.back();
1448 163295 : CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1449 81655 : popstack(stack);
1450 :
1451 81655 : if (!EvalScript(stack, pubKey2, flags, checker, sigversion, serror))
1452 : // serror is set
1453 19 : return false;
1454 81644 : if (stack.empty())
1455 0 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1456 81644 : if (!CastToBool(stack.back()))
1457 19 : return set_error(serror, SCRIPT_ERR_EVAL_FALSE);
1458 : }
1459 :
1460 : // The CLEANSTACK check is only performed after potential P2SH evaluation,
1461 : // as the non-P2SH evaluation of a P2SH script will obviously not result in
1462 : // a clean stack (the P2SH inputs remain).
1463 8585069 : if ((flags & SCRIPT_VERIFY_CLEANSTACK) != 0) {
1464 : // Disallow CLEANSTACK without P2SH, as otherwise a switch CLEANSTACK->P2SH+CLEANSTACK
1465 : // would be possible, which is not a softfork (and P2SH should be one).
1466 7388717 : assert((flags & SCRIPT_VERIFY_P2SH) != 0);
1467 7388717 : if (stack.size() != 1) {
1468 4 : return set_error(serror, SCRIPT_ERR_CLEANSTACK);
1469 : }
1470 : }
1471 :
1472 10319953 : return set_success(serror);
1473 : }
|