upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/script.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/script.cpp')
-rw-r--r--src/script.cpp1178
1 files changed, 1178 insertions, 0 deletions
diff --git a/src/script.cpp b/src/script.cpp
new file mode 100644
index 0000000..1e6e1ca
--- /dev/null
+++ b/src/script.cpp
@@ -0,0 +1,1178 @@
1// Copyright (c) 2009 Satoshi Nakamoto
2// Distributed under the MIT/X11 software license, see the accompanying
3// file license.txt or http://www.opensource.org/licenses/mit-license.php.
4
5#include "headers.h"
6
7bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
8
9
10
11typedef vector<unsigned char> valtype;
12static const valtype vchFalse(0);
13static const valtype vchZero(0);
14static const valtype vchTrue(1, 1);
15static const CBigNum bnZero(0);
16static const CBigNum bnOne(1);
17static const CBigNum bnFalse(0);
18static const CBigNum bnTrue(1);
19
20
21bool CastToBool(const valtype& vch)
22{
23 return (CBigNum(vch) != bnZero);
24}
25
26void MakeSameSize(valtype& vch1, valtype& vch2)
27{
28 // Lengthen the shorter one
29 if (vch1.size() < vch2.size())
30 vch1.resize(vch2.size(), 0);
31 if (vch2.size() < vch1.size())
32 vch2.resize(vch1.size(), 0);
33}
34
35
36
37//
38// Script is a stack machine (like Forth) that evaluates a predicate
39// returning a bool indicating valid or not. There are no loops.
40//
41#define stacktop(i) (stack.at(stack.size()+(i)))
42#define altstacktop(i) (altstack.at(altstack.size()+(i)))
43
44bool EvalScript(const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
45 vector<vector<unsigned char> >* pvStackRet)
46{
47 CAutoBN_CTX pctx;
48 CScript::const_iterator pc = script.begin();
49 CScript::const_iterator pend = script.end();
50 CScript::const_iterator pbegincodehash = script.begin();
51 vector<bool> vfExec;
52 vector<valtype> stack;
53 vector<valtype> altstack;
54 unsigned int nOpCount = 0;
55 if (pvStackRet)
56 pvStackRet->clear();
57
58
59 while (pc < pend)
60 {
61 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
62
63 //
64 // Read instruction
65 //
66 opcodetype opcode;
67 valtype vchPushValue;
68 if (!script.GetOp(pc, opcode, vchPushValue))
69 return false;
70
71 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
72 return false;
73
74 // Disabled opcodes. Checked before the fExec test, so they invalidate
75 // the script even inside a branch that is never taken.
76 //
77 // These are unbounded: OP_CAT grows a stack element without limit
78 // (<x> OP_DUP OP_CAT repeated doubles it each time, so a tiny script
79 // exhausts memory), and OP_LSHIFT shifts by an attacker-supplied
80 // amount with no ceiling. Both let any transaction take down every
81 // node that validates it. Bitcoin removed the whole group for this.
82 if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT ||
83 opcode == OP_RIGHT || opcode == OP_INVERT || opcode == OP_AND ||
84 opcode == OP_OR || opcode == OP_XOR || opcode == OP_2MUL ||
85 opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV ||
86 opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT)
87 return false;
88
89 // Counted outside fExec for the same reason: the cost of a script must
90 // not depend on which branch a signature happens to take. Pushes are
91 // exempt because their cost is already bounded by the script's own
92 // length and by MAX_SCRIPT_ELEMENT_SIZE.
93 if (opcode > OP_16 && ++nOpCount > MAX_OPS_PER_SCRIPT)
94 return false;
95
96 if (fExec && opcode <= OP_PUSHDATA4)
97 stack.push_back(vchPushValue);
98 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
99 switch (opcode)
100 {
101 //
102 // Push value
103 //
104 case OP_1NEGATE:
105 case OP_1:
106 case OP_2:
107 case OP_3:
108 case OP_4:
109 case OP_5:
110 case OP_6:
111 case OP_7:
112 case OP_8:
113 case OP_9:
114 case OP_10:
115 case OP_11:
116 case OP_12:
117 case OP_13:
118 case OP_14:
119 case OP_15:
120 case OP_16:
121 {
122 // ( -- value)
123 CBigNum bn((int)opcode - (int)(OP_1 - 1));
124 stack.push_back(bn.getvch());
125 }
126 break;
127
128
129 //
130 // Control
131 //
132 case OP_NOP:
133 break;
134
135 case OP_VER:
136 {
137 CBigNum bn(VERSION);
138 stack.push_back(bn.getvch());
139 }
140 break;
141
142 case OP_IF:
143 case OP_NOTIF:
144 case OP_VERIF:
145 case OP_VERNOTIF:
146 {
147 // <expression> if [statements] [else [statements]] endif
148 bool fValue = false;
149 if (fExec)
150 {
151 if (stack.size() < 1)
152 return false;
153 valtype& vch = stacktop(-1);
154 if (opcode == OP_VERIF || opcode == OP_VERNOTIF)
155 fValue = (CBigNum(VERSION) >= CBigNum(vch));
156 else
157 fValue = CastToBool(vch);
158 if (opcode == OP_NOTIF || opcode == OP_VERNOTIF)
159 fValue = !fValue;
160 stack.pop_back();
161 }
162 vfExec.push_back(fValue);
163 }
164 break;
165
166 case OP_ELSE:
167 {
168 if (vfExec.empty())
169 return false;
170 vfExec.back() = !vfExec.back();
171 }
172 break;
173
174 case OP_ENDIF:
175 {
176 if (vfExec.empty())
177 return false;
178 vfExec.pop_back();
179 }
180 break;
181
182 case OP_VERIFY:
183 {
184 // (true -- ) or
185 // (false -- false) and return
186 if (stack.size() < 1)
187 return false;
188 bool fValue = CastToBool(stacktop(-1));
189 if (fValue)
190 stack.pop_back();
191 else
192 pc = pend;
193 }
194 break;
195
196 case OP_RETURN:
197 {
198 // Must fail the script outright, never just stop executing it.
199 //
200 // scriptSig and scriptPubKey are evaluated as one concatenated
201 // script (see VerifySignature). The 0.1.0 behaviour here was
202 // "pc = pend", which jumps past everything that follows — so a
203 // scriptSig of <OP_TRUE OP_RETURN> skipped the entire
204 // scriptPubKey, including OP_CHECKSIG, and the final
205 // CastToBool(stack.back()) saw the attacker's own OP_TRUE.
206 // That let anyone spend anyone else's outputs without a
207 // signature. Bitcoin closed this in 0.3.5.
208 return false;
209 }
210
211
212 //
213 // Stack ops
214 //
215 case OP_TOALTSTACK:
216 {
217 if (stack.size() < 1)
218 return false;
219 altstack.push_back(stacktop(-1));
220 stack.pop_back();
221 }
222 break;
223
224 case OP_FROMALTSTACK:
225 {
226 if (altstack.size() < 1)
227 return false;
228 stack.push_back(altstacktop(-1));
229 altstack.pop_back();
230 }
231 break;
232
233 case OP_2DROP:
234 {
235 // (x1 x2 -- )
236 stack.pop_back();
237 stack.pop_back();
238 }
239 break;
240
241 case OP_2DUP:
242 {
243 // (x1 x2 -- x1 x2 x1 x2)
244 if (stack.size() < 2)
245 return false;
246 valtype vch1 = stacktop(-2);
247 valtype vch2 = stacktop(-1);
248 stack.push_back(vch1);
249 stack.push_back(vch2);
250 }
251 break;
252
253 case OP_3DUP:
254 {
255 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
256 if (stack.size() < 3)
257 return false;
258 valtype vch1 = stacktop(-3);
259 valtype vch2 = stacktop(-2);
260 valtype vch3 = stacktop(-1);
261 stack.push_back(vch1);
262 stack.push_back(vch2);
263 stack.push_back(vch3);
264 }
265 break;
266
267 case OP_2OVER:
268 {
269 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
270 if (stack.size() < 4)
271 return false;
272 valtype vch1 = stacktop(-4);
273 valtype vch2 = stacktop(-3);
274 stack.push_back(vch1);
275 stack.push_back(vch2);
276 }
277 break;
278
279 case OP_2ROT:
280 {
281 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
282 if (stack.size() < 6)
283 return false;
284 valtype vch1 = stacktop(-6);
285 valtype vch2 = stacktop(-5);
286 stack.erase(stack.end()-6, stack.end()-4);
287 stack.push_back(vch1);
288 stack.push_back(vch2);
289 }
290 break;
291
292 case OP_2SWAP:
293 {
294 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
295 if (stack.size() < 4)
296 return false;
297 swap(stacktop(-4), stacktop(-2));
298 swap(stacktop(-3), stacktop(-1));
299 }
300 break;
301
302 case OP_IFDUP:
303 {
304 // (x - 0 | x x)
305 if (stack.size() < 1)
306 return false;
307 valtype vch = stacktop(-1);
308 if (CastToBool(vch))
309 stack.push_back(vch);
310 }
311 break;
312
313 case OP_DEPTH:
314 {
315 // -- stacksize
316 CBigNum bn(stack.size());
317 stack.push_back(bn.getvch());
318 }
319 break;
320
321 case OP_DROP:
322 {
323 // (x -- )
324 if (stack.size() < 1)
325 return false;
326 stack.pop_back();
327 }
328 break;
329
330 case OP_DUP:
331 {
332 // (x -- x x)
333 if (stack.size() < 1)
334 return false;
335 valtype vch = stacktop(-1);
336 stack.push_back(vch);
337 }
338 break;
339
340 case OP_NIP:
341 {
342 // (x1 x2 -- x2)
343 if (stack.size() < 2)
344 return false;
345 stack.erase(stack.end() - 2);
346 }
347 break;
348
349 case OP_OVER:
350 {
351 // (x1 x2 -- x1 x2 x1)
352 if (stack.size() < 2)
353 return false;
354 valtype vch = stacktop(-2);
355 stack.push_back(vch);
356 }
357 break;
358
359 case OP_PICK:
360 case OP_ROLL:
361 {
362 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
363 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
364 if (stack.size() < 2)
365 return false;
366 int n = CBigNum(stacktop(-1)).getint();
367 stack.pop_back();
368 if (n < 0 || n >= stack.size())
369 return false;
370 valtype vch = stacktop(-n-1);
371 if (opcode == OP_ROLL)
372 stack.erase(stack.end()-n-1);
373 stack.push_back(vch);
374 }
375 break;
376
377 case OP_ROT:
378 {
379 // (x1 x2 x3 -- x2 x3 x1)
380 // x2 x1 x3 after first swap
381 // x2 x3 x1 after second swap
382 if (stack.size() < 3)
383 return false;
384 swap(stacktop(-3), stacktop(-2));
385 swap(stacktop(-2), stacktop(-1));
386 }
387 break;
388
389 case OP_SWAP:
390 {
391 // (x1 x2 -- x2 x1)
392 if (stack.size() < 2)
393 return false;
394 swap(stacktop(-2), stacktop(-1));
395 }
396 break;
397
398 case OP_TUCK:
399 {
400 // (x1 x2 -- x2 x1 x2)
401 if (stack.size() < 2)
402 return false;
403 valtype vch = stacktop(-1);
404 stack.insert(stack.end()-2, vch);
405 }
406 break;
407
408
409 //
410 // Splice ops
411 //
412 case OP_CAT:
413 {
414 // (x1 x2 -- out)
415 if (stack.size() < 2)
416 return false;
417 valtype& vch1 = stacktop(-2);
418 valtype& vch2 = stacktop(-1);
419 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
420 stack.pop_back();
421 }
422 break;
423
424 case OP_SUBSTR:
425 {
426 // (in begin size -- out)
427 if (stack.size() < 3)
428 return false;
429 valtype& vch = stacktop(-3);
430 int nBegin = CBigNum(stacktop(-2)).getint();
431 int nEnd = nBegin + CBigNum(stacktop(-1)).getint();
432 if (nBegin < 0 || nEnd < nBegin)
433 return false;
434 if (nBegin > vch.size())
435 nBegin = vch.size();
436 if (nEnd > vch.size())
437 nEnd = vch.size();
438 vch.erase(vch.begin() + nEnd, vch.end());
439 vch.erase(vch.begin(), vch.begin() + nBegin);
440 stack.pop_back();
441 stack.pop_back();
442 }
443 break;
444
445 case OP_LEFT:
446 case OP_RIGHT:
447 {
448 // (in size -- out)
449 if (stack.size() < 2)
450 return false;
451 valtype& vch = stacktop(-2);
452 int nSize = CBigNum(stacktop(-1)).getint();
453 if (nSize < 0)
454 return false;
455 if (nSize > vch.size())
456 nSize = vch.size();
457 if (opcode == OP_LEFT)
458 vch.erase(vch.begin() + nSize, vch.end());
459 else
460 vch.erase(vch.begin(), vch.end() - nSize);
461 stack.pop_back();
462 }
463 break;
464
465 case OP_SIZE:
466 {
467 // (in -- in size)
468 if (stack.size() < 1)
469 return false;
470 CBigNum bn(stacktop(-1).size());
471 stack.push_back(bn.getvch());
472 }
473 break;
474
475
476 //
477 // Bitwise logic
478 //
479 case OP_INVERT:
480 {
481 // (in - out)
482 if (stack.size() < 1)
483 return false;
484 valtype& vch = stacktop(-1);
485 for (int i = 0; i < vch.size(); i++)
486 vch[i] = ~vch[i];
487 }
488 break;
489
490 case OP_AND:
491 case OP_OR:
492 case OP_XOR:
493 {
494 // (x1 x2 - out)
495 if (stack.size() < 2)
496 return false;
497 valtype& vch1 = stacktop(-2);
498 valtype& vch2 = stacktop(-1);
499 MakeSameSize(vch1, vch2);
500 if (opcode == OP_AND)
501 {
502 for (int i = 0; i < vch1.size(); i++)
503 vch1[i] &= vch2[i];
504 }
505 else if (opcode == OP_OR)
506 {
507 for (int i = 0; i < vch1.size(); i++)
508 vch1[i] |= vch2[i];
509 }
510 else if (opcode == OP_XOR)
511 {
512 for (int i = 0; i < vch1.size(); i++)
513 vch1[i] ^= vch2[i];
514 }
515 stack.pop_back();
516 }
517 break;
518
519 case OP_EQUAL:
520 case OP_EQUALVERIFY:
521 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
522 {
523 // (x1 x2 - bool)
524 if (stack.size() < 2)
525 return false;
526 valtype& vch1 = stacktop(-2);
527 valtype& vch2 = stacktop(-1);
528 bool fEqual = (vch1 == vch2);
529 // OP_NOTEQUAL is disabled because it would be too easy to say
530 // something like n != 1 and have some wiseguy pass in 1 with extra
531 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
532 //if (opcode == OP_NOTEQUAL)
533 // fEqual = !fEqual;
534 stack.pop_back();
535 stack.pop_back();
536 stack.push_back(fEqual ? vchTrue : vchFalse);
537 if (opcode == OP_EQUALVERIFY)
538 {
539 if (fEqual)
540 stack.pop_back();
541 else
542 pc = pend;
543 }
544 }
545 break;
546
547
548 //
549 // Numeric
550 //
551 case OP_1ADD:
552 case OP_1SUB:
553 case OP_2MUL:
554 case OP_2DIV:
555 case OP_NEGATE:
556 case OP_ABS:
557 case OP_NOT:
558 case OP_0NOTEQUAL:
559 {
560 // (in -- out)
561 if (stack.size() < 1)
562 return false;
563 CBigNum bn(stacktop(-1));
564 switch (opcode)
565 {
566 case OP_1ADD: bn += bnOne; break;
567 case OP_1SUB: bn -= bnOne; break;
568 case OP_2MUL: bn <<= 1; break;
569 case OP_2DIV: bn >>= 1; break;
570 case OP_NEGATE: bn = -bn; break;
571 case OP_ABS: if (bn < bnZero) bn = -bn; break;
572 case OP_NOT: bn = (bn == bnZero); break;
573 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
574 }
575 stack.pop_back();
576 stack.push_back(bn.getvch());
577 }
578 break;
579
580 case OP_ADD:
581 case OP_SUB:
582 case OP_MUL:
583 case OP_DIV:
584 case OP_MOD:
585 case OP_LSHIFT:
586 case OP_RSHIFT:
587 case OP_BOOLAND:
588 case OP_BOOLOR:
589 case OP_NUMEQUAL:
590 case OP_NUMEQUALVERIFY:
591 case OP_NUMNOTEQUAL:
592 case OP_LESSTHAN:
593 case OP_GREATERTHAN:
594 case OP_LESSTHANOREQUAL:
595 case OP_GREATERTHANOREQUAL:
596 case OP_MIN:
597 case OP_MAX:
598 {
599 // (x1 x2 -- out)
600 if (stack.size() < 2)
601 return false;
602 CBigNum bn1(stacktop(-2));
603 CBigNum bn2(stacktop(-1));
604 CBigNum bn;
605 switch (opcode)
606 {
607 case OP_ADD:
608 bn = bn1 + bn2;
609 break;
610
611 case OP_SUB:
612 bn = bn1 - bn2;
613 break;
614
615 case OP_MUL:
616 if (!BN_mul(bn.get(), bn1.get(), bn2.get(), pctx))
617 return false;
618 break;
619
620 case OP_DIV:
621 if (!BN_div(bn.get(), NULL, bn1.get(), bn2.get(), pctx))
622 return false;
623 break;
624
625 case OP_MOD:
626 if (!BN_mod(bn.get(), bn1.get(), bn2.get(), pctx))
627 return false;
628 break;
629
630 case OP_LSHIFT:
631 if (bn2 < bnZero)
632 return false;
633 bn = bn1 << bn2.getulong();
634 break;
635
636 case OP_RSHIFT:
637 if (bn2 < bnZero)
638 return false;
639 bn = bn1 >> bn2.getulong();
640 break;
641
642 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
643 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
644 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
645 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
646 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
647 case OP_LESSTHAN: bn = (bn1 < bn2); break;
648 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
649 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
650 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
651 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
652 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
653 }
654 stack.pop_back();
655 stack.pop_back();
656 stack.push_back(bn.getvch());
657
658 if (opcode == OP_NUMEQUALVERIFY)
659 {
660 if (CastToBool(stacktop(-1)))
661 stack.pop_back();
662 else
663 pc = pend;
664 }
665 }
666 break;
667
668 case OP_WITHIN:
669 {
670 // (x min max -- out)
671 if (stack.size() < 3)
672 return false;
673 CBigNum bn1(stacktop(-3));
674 CBigNum bn2(stacktop(-2));
675 CBigNum bn3(stacktop(-1));
676 bool fValue = (bn2 <= bn1 && bn1 < bn3);
677 stack.pop_back();
678 stack.pop_back();
679 stack.pop_back();
680 stack.push_back(fValue ? vchTrue : vchFalse);
681 }
682 break;
683
684
685 //
686 // Crypto
687 //
688 case OP_RIPEMD160:
689 case OP_SHA1:
690 case OP_SHA256:
691 case OP_HASH160:
692 case OP_HASH256:
693 {
694 // (in -- hash)
695 if (stack.size() < 1)
696 return false;
697 valtype& vch = stacktop(-1);
698 valtype vchHash(opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160 ? 20 : 32);
699 if (opcode == OP_RIPEMD160)
700 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
701 else if (opcode == OP_SHA1)
702 SHA1(&vch[0], vch.size(), &vchHash[0]);
703 else if (opcode == OP_SHA256)
704 SHA256(&vch[0], vch.size(), &vchHash[0]);
705 else if (opcode == OP_HASH160)
706 {
707 uint160 hash160 = Hash160(vch);
708 memcpy(&vchHash[0], &hash160, sizeof(hash160));
709 }
710 else if (opcode == OP_HASH256)
711 {
712 uint256 hash = Hash(vch.begin(), vch.end());
713 memcpy(&vchHash[0], &hash, sizeof(hash));
714 }
715 stack.pop_back();
716 stack.push_back(vchHash);
717 }
718 break;
719
720 case OP_CODESEPARATOR:
721 {
722 // Hash starts after the code separator
723 pbegincodehash = pc;
724 }
725 break;
726
727 case OP_CHECKSIG:
728 case OP_CHECKSIGVERIFY:
729 {
730 // (sig pubkey -- bool)
731 if (stack.size() < 2)
732 return false;
733
734 valtype& vchSig = stacktop(-2);
735 valtype& vchPubKey = stacktop(-1);
736
737 ////// debug print
738 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
739 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
740
741 // Subset of script starting at the most recent codeseparator
742 CScript scriptCode(pbegincodehash, pend);
743
744 // Drop the signature, since there's no way for a signature to sign itself
745 scriptCode.FindAndDelete(CScript(vchSig));
746
747 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
748
749 stack.pop_back();
750 stack.pop_back();
751 stack.push_back(fSuccess ? vchTrue : vchFalse);
752 if (opcode == OP_CHECKSIGVERIFY)
753 {
754 if (fSuccess)
755 stack.pop_back();
756 else
757 pc = pend;
758 }
759 }
760 break;
761
762 case OP_CHECKMULTISIG:
763 case OP_CHECKMULTISIGVERIFY:
764 {
765 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
766
767 int i = 1;
768 if (stack.size() < i)
769 return false;
770
771 int nKeysCount = CBigNum(stacktop(-i)).getint();
772 if (nKeysCount < 0)
773 return false;
774 int ikey = ++i;
775 i += nKeysCount;
776 if (stack.size() < i)
777 return false;
778
779 int nSigsCount = CBigNum(stacktop(-i)).getint();
780 if (nSigsCount < 0 || nSigsCount > nKeysCount)
781 return false;
782 int isig = ++i;
783 i += nSigsCount;
784 if (stack.size() < i)
785 return false;
786
787 // Subset of script starting at the most recent codeseparator
788 CScript scriptCode(pbegincodehash, pend);
789
790 // Drop the signatures, since there's no way for a signature to sign itself
791 for (int i = 0; i < nSigsCount; i++)
792 {
793 valtype& vchSig = stacktop(-isig-i);
794 scriptCode.FindAndDelete(CScript(vchSig));
795 }
796
797 bool fSuccess = true;
798 while (fSuccess && nSigsCount > 0)
799 {
800 valtype& vchSig = stacktop(-isig);
801 valtype& vchPubKey = stacktop(-ikey);
802
803 // Check signature
804 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
805 {
806 isig++;
807 nSigsCount--;
808 }
809 ikey++;
810 nKeysCount--;
811
812 // If there are more signatures left than keys left,
813 // then too many signatures have failed
814 if (nSigsCount > nKeysCount)
815 fSuccess = false;
816 }
817
818 while (i-- > 0)
819 stack.pop_back();
820 stack.push_back(fSuccess ? vchTrue : vchFalse);
821
822 if (opcode == OP_CHECKMULTISIGVERIFY)
823 {
824 if (fSuccess)
825 stack.pop_back();
826 else
827 pc = pend;
828 }
829 }
830 break;
831
832 default:
833 return false;
834 }
835
836 // Both stacks together, because OP_TOALTSTACK would otherwise move the
837 // problem rather than solve it.
838 if (stack.size() + altstack.size() > MAX_STACK_SIZE)
839 return false;
840 }
841
842
843 if (pvStackRet)
844 *pvStackRet = stack;
845 return (stack.empty() ? false : CastToBool(stack.back()));
846}
847
848#undef top
849
850
851
852
853
854
855
856
857
858uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
859{
860 if (nIn >= txTo.vin.size())
861 {
862 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
863 return 1;
864 }
865 CTransaction txTmp(txTo);
866
867 // In case concatenating two scripts ends up with two codeseparators,
868 // or an extra one at the end, this prevents all those possible incompatibilities.
869 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
870
871 // Blank out other inputs' signatures
872 for (int i = 0; i < txTmp.vin.size(); i++)
873 txTmp.vin[i].scriptSig = CScript();
874 txTmp.vin[nIn].scriptSig = scriptCode;
875
876 // Blank out some of the outputs
877 if ((nHashType & 0x1f) == SIGHASH_NONE)
878 {
879 // Wildcard payee
880 txTmp.vout.clear();
881
882 // Let the others update at will
883 for (int i = 0; i < txTmp.vin.size(); i++)
884 if (i != nIn)
885 txTmp.vin[i].nSequence = 0;
886 }
887 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
888 {
889 // Only lockin the txout payee at same index as txin
890 unsigned int nOut = nIn;
891 if (nOut >= txTmp.vout.size())
892 {
893 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
894 return 1;
895 }
896 txTmp.vout.resize(nOut+1);
897 for (int i = 0; i < nOut; i++)
898 txTmp.vout[i].SetNull();
899
900 // Let the others update at will
901 for (int i = 0; i < txTmp.vin.size(); i++)
902 if (i != nIn)
903 txTmp.vin[i].nSequence = 0;
904 }
905
906 // Blank out other inputs completely, not recommended for open transactions
907 if (nHashType & SIGHASH_ANYONECANPAY)
908 {
909 txTmp.vin[0] = txTmp.vin[nIn];
910 txTmp.vin.resize(1);
911 }
912
913 // Serialize and hash
914 CDataStream ss(SER_GETHASH);
915 ss.reserve(10000);
916 ss << txTmp << nHashType;
917 return Hash(ss.begin(), ss.end());
918}
919
920
921bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
922 const CTransaction& txTo, unsigned int nIn, int nHashType)
923{
924 CKey key;
925 if (!key.SetPubKey(vchPubKey))
926 return false;
927
928 // Hash type is one byte tacked on to the end of the signature
929 if (vchSig.empty())
930 return false;
931 if (nHashType == 0)
932 nHashType = vchSig.back();
933 else if (nHashType != vchSig.back())
934 return false;
935 vchSig.pop_back();
936
937 if (key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig))
938 return true;
939
940 return false;
941}
942
943
944
945
946
947
948
949
950
951
952
953bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)
954{
955 // Templates
956 static vector<CScript> vTemplates;
957 if (vTemplates.empty())
958 {
959 // Standard tx, sender provides pubkey, receiver adds signature
960 vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);
961
962 // Short account number tx, sender provides hash of pubkey, receiver provides signature and pubkey
963 vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);
964 }
965
966 // Scan templates
967 const CScript& script1 = scriptPubKey;
968 foreach(const CScript& script2, vTemplates)
969 {
970 vSolutionRet.clear();
971 opcodetype opcode1, opcode2;
972 vector<unsigned char> vch1, vch2;
973
974 // Compare
975 CScript::const_iterator pc1 = script1.begin();
976 CScript::const_iterator pc2 = script2.begin();
977 loop
978 {
979 bool f1 = script1.GetOp(pc1, opcode1, vch1);
980 bool f2 = script2.GetOp(pc2, opcode2, vch2);
981 if (!f1 && !f2)
982 {
983 // Success
984 reverse(vSolutionRet.begin(), vSolutionRet.end());
985 return true;
986 }
987 else if (f1 != f2)
988 {
989 break;
990 }
991 else if (opcode2 == OP_PUBKEY)
992 {
993 if (vch1.size() <= sizeof(uint256))
994 break;
995 vSolutionRet.push_back(make_pair(opcode2, vch1));
996 }
997 else if (opcode2 == OP_PUBKEYHASH)
998 {
999 if (vch1.size() != sizeof(uint160))
1000 break;
1001 vSolutionRet.push_back(make_pair(opcode2, vch1));
1002 }
1003 else if (opcode1 != opcode2)
1004 {
1005 break;
1006 }
1007 }
1008 }
1009
1010 vSolutionRet.clear();
1011 return false;
1012}
1013
1014
1015bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1016{
1017 scriptSigRet.clear();
1018
1019 vector<pair<opcodetype, valtype> > vSolution;
1020 if (!Solver(scriptPubKey, vSolution))
1021 return false;
1022
1023 // Compile solution. Public keys stay available for encrypted wallets so the
1024 // wallet can recognize its own outputs while locked; private keys are
1025 // fetched only for an actual signature.
1026 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1027 {
1028 if (item.first == OP_PUBKEY)
1029 {
1030 const valtype& vchPubKey = item.second;
1031 if (!WalletCanSpendKey(vchPubKey))
1032 return false;
1033 if (hash != 0)
1034 {
1035 CPrivKey vchPrivKey;
1036 string strError;
1037 if (!GetWalletPrivKey(vchPubKey, vchPrivKey, strError))
1038 return false;
1039 vector<unsigned char> vchSig;
1040 if (!CKey::Sign(vchPrivKey, hash, vchSig))
1041 return false;
1042 vchSig.push_back((unsigned char)nHashType);
1043 scriptSigRet << vchSig;
1044 }
1045 }
1046 else if (item.first == OP_PUBKEYHASH)
1047 {
1048 vector<unsigned char> vchPubKey;
1049 {
1050 CRITICAL_BLOCK(cs_mapKeys)
1051 {
1052 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1053 if (mi == mapPubKeys.end())
1054 return false;
1055 vchPubKey = (*mi).second;
1056 }
1057 }
1058 if (!WalletCanSpendKey(vchPubKey))
1059 return false;
1060 if (hash != 0)
1061 {
1062 CPrivKey vchPrivKey;
1063 string strError;
1064 if (!GetWalletPrivKey(vchPubKey, vchPrivKey, strError))
1065 return false;
1066 vector<unsigned char> vchSig;
1067 if (!CKey::Sign(vchPrivKey, hash, vchSig))
1068 return false;
1069 vchSig.push_back((unsigned char)nHashType);
1070 scriptSigRet << vchSig << vchPubKey;
1071 }
1072 }
1073 }
1074
1075 return true;
1076}
1077
1078
1079bool IsMine(const CScript& scriptPubKey)
1080{
1081 CScript scriptSig;
1082 return Solver(scriptPubKey, 0, 0, scriptSig);
1083}
1084
1085
1086bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
1087{
1088 vchPubKeyRet.clear();
1089
1090 vector<pair<opcodetype, valtype> > vSolution;
1091 if (!Solver(scriptPubKey, vSolution))
1092 return false;
1093
1094 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1095 {
1096 valtype vchPubKey;
1097 if (item.first == OP_PUBKEY)
1098 {
1099 vchPubKey = item.second;
1100 }
1101 else if (item.first == OP_PUBKEYHASH)
1102 {
1103 CRITICAL_BLOCK(cs_mapKeys)
1104 {
1105 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1106 if (mi == mapPubKeys.end())
1107 continue;
1108 vchPubKey = (*mi).second;
1109 }
1110 }
1111 if (!fMineOnly || WalletCanSpendKey(vchPubKey))
1112 {
1113 vchPubKeyRet = vchPubKey;
1114 return true;
1115 }
1116 }
1117 return false;
1118}
1119
1120
1121bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
1122{
1123 hash160Ret = 0;
1124
1125 vector<pair<opcodetype, valtype> > vSolution;
1126 if (!Solver(scriptPubKey, vSolution))
1127 return false;
1128
1129 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1130 {
1131 if (item.first == OP_PUBKEYHASH)
1132 {
1133 hash160Ret = uint160(item.second);
1134 return true;
1135 }
1136 }
1137 return false;
1138}
1139
1140
1141bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1142{
1143 assert(nIn < txTo.vin.size());
1144 CTxIn& txin = txTo.vin[nIn];
1145 assert(txin.prevout.n < txFrom.vout.size());
1146 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1147
1148 // Leave out the signature from the hash, since a signature can't sign itself.
1149 // The checksig op will also drop the signatures from its hash.
1150 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1151
1152 if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1153 return false;
1154
1155 txin.scriptSig = scriptPrereq + txin.scriptSig;
1156
1157 // Test solution
1158 if (scriptPrereq.empty())
1159 if (!EvalScript(txin.scriptSig + CScript(OP_CODESEPARATOR) + txout.scriptPubKey, txTo, nIn))
1160 return false;
1161
1162 return true;
1163}
1164
1165
1166bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType)
1167{
1168 assert(nIn < txTo.vin.size());
1169 const CTxIn& txin = txTo.vin[nIn];
1170 if (txin.prevout.n >= txFrom.vout.size())
1171 return false;
1172 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1173
1174 if (txin.prevout.hash != txFrom.GetHash())
1175 return false;
1176
1177 return EvalScript(txin.scriptSig + CScript(OP_CODESEPARATOR) + txout.scriptPubKey, txTo, nIn, nHashType);
1178}