Docs Tidy up
[bitcoinplatinum.git] / src / script.cpp
blobc29648c2bcd4042ab4083e69f8aea1ef2648377b
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <boost/foreach.hpp>
6 #include <boost/tuple/tuple.hpp>
8 using namespace std;
9 using namespace boost;
11 #include "script.h"
12 #include "keystore.h"
13 #include "bignum.h"
14 #include "key.h"
15 #include "main.h"
16 #include "sync.h"
17 #include "util.h"
19 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
23 typedef vector<unsigned char> valtype;
24 static const valtype vchFalse(0);
25 static const valtype vchZero(0);
26 static const valtype vchTrue(1, 1);
27 static const CBigNum bnZero(0);
28 static const CBigNum bnOne(1);
29 static const CBigNum bnFalse(0);
30 static const CBigNum bnTrue(1);
31 static const size_t nMaxNumSize = 4;
34 CBigNum CastToBigNum(const valtype& vch)
36 if (vch.size() > nMaxNumSize)
37 throw runtime_error("CastToBigNum() : overflow");
38 // Get rid of extra leading zeros
39 return CBigNum(CBigNum(vch).getvch());
42 bool CastToBool(const valtype& vch)
44 for (unsigned int i = 0; i < vch.size(); i++)
46 if (vch[i] != 0)
48 // Can be negative zero
49 if (i == vch.size()-1 && vch[i] == 0x80)
50 return false;
51 return true;
54 return false;
57 void MakeSameSize(valtype& vch1, valtype& vch2)
59 // Lengthen the shorter one
60 if (vch1.size() < vch2.size())
61 vch1.resize(vch2.size(), 0);
62 if (vch2.size() < vch1.size())
63 vch2.resize(vch1.size(), 0);
69 // Script is a stack machine (like Forth) that evaluates a predicate
70 // returning a bool indicating valid or not. There are no loops.
72 #define stacktop(i) (stack.at(stack.size()+(i)))
73 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
74 static inline void popstack(vector<valtype>& stack)
76 if (stack.empty())
77 throw runtime_error("popstack() : stack empty");
78 stack.pop_back();
82 const char* GetTxnOutputType(txnouttype t)
84 switch (t)
86 case TX_NONSTANDARD: return "nonstandard";
87 case TX_PUBKEY: return "pubkey";
88 case TX_PUBKEYHASH: return "pubkeyhash";
89 case TX_SCRIPTHASH: return "scripthash";
90 case TX_MULTISIG: return "multisig";
92 return NULL;
96 const char* GetOpName(opcodetype opcode)
98 switch (opcode)
100 // push value
101 case OP_0 : return "0";
102 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
103 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
104 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
105 case OP_1NEGATE : return "-1";
106 case OP_RESERVED : return "OP_RESERVED";
107 case OP_1 : return "1";
108 case OP_2 : return "2";
109 case OP_3 : return "3";
110 case OP_4 : return "4";
111 case OP_5 : return "5";
112 case OP_6 : return "6";
113 case OP_7 : return "7";
114 case OP_8 : return "8";
115 case OP_9 : return "9";
116 case OP_10 : return "10";
117 case OP_11 : return "11";
118 case OP_12 : return "12";
119 case OP_13 : return "13";
120 case OP_14 : return "14";
121 case OP_15 : return "15";
122 case OP_16 : return "16";
124 // control
125 case OP_NOP : return "OP_NOP";
126 case OP_VER : return "OP_VER";
127 case OP_IF : return "OP_IF";
128 case OP_NOTIF : return "OP_NOTIF";
129 case OP_VERIF : return "OP_VERIF";
130 case OP_VERNOTIF : return "OP_VERNOTIF";
131 case OP_ELSE : return "OP_ELSE";
132 case OP_ENDIF : return "OP_ENDIF";
133 case OP_VERIFY : return "OP_VERIFY";
134 case OP_RETURN : return "OP_RETURN";
136 // stack ops
137 case OP_TOALTSTACK : return "OP_TOALTSTACK";
138 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
139 case OP_2DROP : return "OP_2DROP";
140 case OP_2DUP : return "OP_2DUP";
141 case OP_3DUP : return "OP_3DUP";
142 case OP_2OVER : return "OP_2OVER";
143 case OP_2ROT : return "OP_2ROT";
144 case OP_2SWAP : return "OP_2SWAP";
145 case OP_IFDUP : return "OP_IFDUP";
146 case OP_DEPTH : return "OP_DEPTH";
147 case OP_DROP : return "OP_DROP";
148 case OP_DUP : return "OP_DUP";
149 case OP_NIP : return "OP_NIP";
150 case OP_OVER : return "OP_OVER";
151 case OP_PICK : return "OP_PICK";
152 case OP_ROLL : return "OP_ROLL";
153 case OP_ROT : return "OP_ROT";
154 case OP_SWAP : return "OP_SWAP";
155 case OP_TUCK : return "OP_TUCK";
157 // splice ops
158 case OP_CAT : return "OP_CAT";
159 case OP_SUBSTR : return "OP_SUBSTR";
160 case OP_LEFT : return "OP_LEFT";
161 case OP_RIGHT : return "OP_RIGHT";
162 case OP_SIZE : return "OP_SIZE";
164 // bit logic
165 case OP_INVERT : return "OP_INVERT";
166 case OP_AND : return "OP_AND";
167 case OP_OR : return "OP_OR";
168 case OP_XOR : return "OP_XOR";
169 case OP_EQUAL : return "OP_EQUAL";
170 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
171 case OP_RESERVED1 : return "OP_RESERVED1";
172 case OP_RESERVED2 : return "OP_RESERVED2";
174 // numeric
175 case OP_1ADD : return "OP_1ADD";
176 case OP_1SUB : return "OP_1SUB";
177 case OP_2MUL : return "OP_2MUL";
178 case OP_2DIV : return "OP_2DIV";
179 case OP_NEGATE : return "OP_NEGATE";
180 case OP_ABS : return "OP_ABS";
181 case OP_NOT : return "OP_NOT";
182 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
183 case OP_ADD : return "OP_ADD";
184 case OP_SUB : return "OP_SUB";
185 case OP_MUL : return "OP_MUL";
186 case OP_DIV : return "OP_DIV";
187 case OP_MOD : return "OP_MOD";
188 case OP_LSHIFT : return "OP_LSHIFT";
189 case OP_RSHIFT : return "OP_RSHIFT";
190 case OP_BOOLAND : return "OP_BOOLAND";
191 case OP_BOOLOR : return "OP_BOOLOR";
192 case OP_NUMEQUAL : return "OP_NUMEQUAL";
193 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
194 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
195 case OP_LESSTHAN : return "OP_LESSTHAN";
196 case OP_GREATERTHAN : return "OP_GREATERTHAN";
197 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
198 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
199 case OP_MIN : return "OP_MIN";
200 case OP_MAX : return "OP_MAX";
201 case OP_WITHIN : return "OP_WITHIN";
203 // crypto
204 case OP_RIPEMD160 : return "OP_RIPEMD160";
205 case OP_SHA1 : return "OP_SHA1";
206 case OP_SHA256 : return "OP_SHA256";
207 case OP_HASH160 : return "OP_HASH160";
208 case OP_HASH256 : return "OP_HASH256";
209 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
210 case OP_CHECKSIG : return "OP_CHECKSIG";
211 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
212 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
213 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
215 // expanson
216 case OP_NOP1 : return "OP_NOP1";
217 case OP_NOP2 : return "OP_NOP2";
218 case OP_NOP3 : return "OP_NOP3";
219 case OP_NOP4 : return "OP_NOP4";
220 case OP_NOP5 : return "OP_NOP5";
221 case OP_NOP6 : return "OP_NOP6";
222 case OP_NOP7 : return "OP_NOP7";
223 case OP_NOP8 : return "OP_NOP8";
224 case OP_NOP9 : return "OP_NOP9";
225 case OP_NOP10 : return "OP_NOP10";
229 // template matching params
230 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
231 case OP_PUBKEY : return "OP_PUBKEY";
233 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
234 default:
235 return "OP_UNKNOWN";
239 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
241 CAutoBN_CTX pctx;
242 CScript::const_iterator pc = script.begin();
243 CScript::const_iterator pend = script.end();
244 CScript::const_iterator pbegincodehash = script.begin();
245 opcodetype opcode;
246 valtype vchPushValue;
247 vector<bool> vfExec;
248 vector<valtype> altstack;
249 if (script.size() > 10000)
250 return false;
251 int nOpCount = 0;
256 while (pc < pend)
258 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
261 // Read instruction
263 if (!script.GetOp(pc, opcode, vchPushValue))
264 return false;
265 if (vchPushValue.size() > 520)
266 return false;
267 if (opcode > OP_16 && ++nOpCount > 201)
268 return false;
270 if (opcode == OP_CAT ||
271 opcode == OP_SUBSTR ||
272 opcode == OP_LEFT ||
273 opcode == OP_RIGHT ||
274 opcode == OP_INVERT ||
275 opcode == OP_AND ||
276 opcode == OP_OR ||
277 opcode == OP_XOR ||
278 opcode == OP_2MUL ||
279 opcode == OP_2DIV ||
280 opcode == OP_MUL ||
281 opcode == OP_DIV ||
282 opcode == OP_MOD ||
283 opcode == OP_LSHIFT ||
284 opcode == OP_RSHIFT)
285 return false;
287 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
288 stack.push_back(vchPushValue);
289 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
290 switch (opcode)
293 // Push value
295 case OP_1NEGATE:
296 case OP_1:
297 case OP_2:
298 case OP_3:
299 case OP_4:
300 case OP_5:
301 case OP_6:
302 case OP_7:
303 case OP_8:
304 case OP_9:
305 case OP_10:
306 case OP_11:
307 case OP_12:
308 case OP_13:
309 case OP_14:
310 case OP_15:
311 case OP_16:
313 // ( -- value)
314 CBigNum bn((int)opcode - (int)(OP_1 - 1));
315 stack.push_back(bn.getvch());
317 break;
321 // Control
323 case OP_NOP:
324 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
325 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
326 break;
328 case OP_IF:
329 case OP_NOTIF:
331 // <expression> if [statements] [else [statements]] endif
332 bool fValue = false;
333 if (fExec)
335 if (stack.size() < 1)
336 return false;
337 valtype& vch = stacktop(-1);
338 fValue = CastToBool(vch);
339 if (opcode == OP_NOTIF)
340 fValue = !fValue;
341 popstack(stack);
343 vfExec.push_back(fValue);
345 break;
347 case OP_ELSE:
349 if (vfExec.empty())
350 return false;
351 vfExec.back() = !vfExec.back();
353 break;
355 case OP_ENDIF:
357 if (vfExec.empty())
358 return false;
359 vfExec.pop_back();
361 break;
363 case OP_VERIFY:
365 // (true -- ) or
366 // (false -- false) and return
367 if (stack.size() < 1)
368 return false;
369 bool fValue = CastToBool(stacktop(-1));
370 if (fValue)
371 popstack(stack);
372 else
373 return false;
375 break;
377 case OP_RETURN:
379 return false;
381 break;
385 // Stack ops
387 case OP_TOALTSTACK:
389 if (stack.size() < 1)
390 return false;
391 altstack.push_back(stacktop(-1));
392 popstack(stack);
394 break;
396 case OP_FROMALTSTACK:
398 if (altstack.size() < 1)
399 return false;
400 stack.push_back(altstacktop(-1));
401 popstack(altstack);
403 break;
405 case OP_2DROP:
407 // (x1 x2 -- )
408 if (stack.size() < 2)
409 return false;
410 popstack(stack);
411 popstack(stack);
413 break;
415 case OP_2DUP:
417 // (x1 x2 -- x1 x2 x1 x2)
418 if (stack.size() < 2)
419 return false;
420 valtype vch1 = stacktop(-2);
421 valtype vch2 = stacktop(-1);
422 stack.push_back(vch1);
423 stack.push_back(vch2);
425 break;
427 case OP_3DUP:
429 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
430 if (stack.size() < 3)
431 return false;
432 valtype vch1 = stacktop(-3);
433 valtype vch2 = stacktop(-2);
434 valtype vch3 = stacktop(-1);
435 stack.push_back(vch1);
436 stack.push_back(vch2);
437 stack.push_back(vch3);
439 break;
441 case OP_2OVER:
443 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
444 if (stack.size() < 4)
445 return false;
446 valtype vch1 = stacktop(-4);
447 valtype vch2 = stacktop(-3);
448 stack.push_back(vch1);
449 stack.push_back(vch2);
451 break;
453 case OP_2ROT:
455 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
456 if (stack.size() < 6)
457 return false;
458 valtype vch1 = stacktop(-6);
459 valtype vch2 = stacktop(-5);
460 stack.erase(stack.end()-6, stack.end()-4);
461 stack.push_back(vch1);
462 stack.push_back(vch2);
464 break;
466 case OP_2SWAP:
468 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
469 if (stack.size() < 4)
470 return false;
471 swap(stacktop(-4), stacktop(-2));
472 swap(stacktop(-3), stacktop(-1));
474 break;
476 case OP_IFDUP:
478 // (x - 0 | x x)
479 if (stack.size() < 1)
480 return false;
481 valtype vch = stacktop(-1);
482 if (CastToBool(vch))
483 stack.push_back(vch);
485 break;
487 case OP_DEPTH:
489 // -- stacksize
490 CBigNum bn(stack.size());
491 stack.push_back(bn.getvch());
493 break;
495 case OP_DROP:
497 // (x -- )
498 if (stack.size() < 1)
499 return false;
500 popstack(stack);
502 break;
504 case OP_DUP:
506 // (x -- x x)
507 if (stack.size() < 1)
508 return false;
509 valtype vch = stacktop(-1);
510 stack.push_back(vch);
512 break;
514 case OP_NIP:
516 // (x1 x2 -- x2)
517 if (stack.size() < 2)
518 return false;
519 stack.erase(stack.end() - 2);
521 break;
523 case OP_OVER:
525 // (x1 x2 -- x1 x2 x1)
526 if (stack.size() < 2)
527 return false;
528 valtype vch = stacktop(-2);
529 stack.push_back(vch);
531 break;
533 case OP_PICK:
534 case OP_ROLL:
536 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
537 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
538 if (stack.size() < 2)
539 return false;
540 int n = CastToBigNum(stacktop(-1)).getint();
541 popstack(stack);
542 if (n < 0 || n >= (int)stack.size())
543 return false;
544 valtype vch = stacktop(-n-1);
545 if (opcode == OP_ROLL)
546 stack.erase(stack.end()-n-1);
547 stack.push_back(vch);
549 break;
551 case OP_ROT:
553 // (x1 x2 x3 -- x2 x3 x1)
554 // x2 x1 x3 after first swap
555 // x2 x3 x1 after second swap
556 if (stack.size() < 3)
557 return false;
558 swap(stacktop(-3), stacktop(-2));
559 swap(stacktop(-2), stacktop(-1));
561 break;
563 case OP_SWAP:
565 // (x1 x2 -- x2 x1)
566 if (stack.size() < 2)
567 return false;
568 swap(stacktop(-2), stacktop(-1));
570 break;
572 case OP_TUCK:
574 // (x1 x2 -- x2 x1 x2)
575 if (stack.size() < 2)
576 return false;
577 valtype vch = stacktop(-1);
578 stack.insert(stack.end()-2, vch);
580 break;
584 // Splice ops
586 case OP_CAT:
588 // (x1 x2 -- out)
589 if (stack.size() < 2)
590 return false;
591 valtype& vch1 = stacktop(-2);
592 valtype& vch2 = stacktop(-1);
593 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
594 popstack(stack);
595 if (stacktop(-1).size() > 520)
596 return false;
598 break;
600 case OP_SUBSTR:
602 // (in begin size -- out)
603 if (stack.size() < 3)
604 return false;
605 valtype& vch = stacktop(-3);
606 int nBegin = CastToBigNum(stacktop(-2)).getint();
607 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
608 if (nBegin < 0 || nEnd < nBegin)
609 return false;
610 if (nBegin > (int)vch.size())
611 nBegin = vch.size();
612 if (nEnd > (int)vch.size())
613 nEnd = vch.size();
614 vch.erase(vch.begin() + nEnd, vch.end());
615 vch.erase(vch.begin(), vch.begin() + nBegin);
616 popstack(stack);
617 popstack(stack);
619 break;
621 case OP_LEFT:
622 case OP_RIGHT:
624 // (in size -- out)
625 if (stack.size() < 2)
626 return false;
627 valtype& vch = stacktop(-2);
628 int nSize = CastToBigNum(stacktop(-1)).getint();
629 if (nSize < 0)
630 return false;
631 if (nSize > (int)vch.size())
632 nSize = vch.size();
633 if (opcode == OP_LEFT)
634 vch.erase(vch.begin() + nSize, vch.end());
635 else
636 vch.erase(vch.begin(), vch.end() - nSize);
637 popstack(stack);
639 break;
641 case OP_SIZE:
643 // (in -- in size)
644 if (stack.size() < 1)
645 return false;
646 CBigNum bn(stacktop(-1).size());
647 stack.push_back(bn.getvch());
649 break;
653 // Bitwise logic
655 case OP_INVERT:
657 // (in - out)
658 if (stack.size() < 1)
659 return false;
660 valtype& vch = stacktop(-1);
661 for (unsigned int i = 0; i < vch.size(); i++)
662 vch[i] = ~vch[i];
664 break;
666 case OP_AND:
667 case OP_OR:
668 case OP_XOR:
670 // (x1 x2 - out)
671 if (stack.size() < 2)
672 return false;
673 valtype& vch1 = stacktop(-2);
674 valtype& vch2 = stacktop(-1);
675 MakeSameSize(vch1, vch2);
676 if (opcode == OP_AND)
678 for (unsigned int i = 0; i < vch1.size(); i++)
679 vch1[i] &= vch2[i];
681 else if (opcode == OP_OR)
683 for (unsigned int i = 0; i < vch1.size(); i++)
684 vch1[i] |= vch2[i];
686 else if (opcode == OP_XOR)
688 for (unsigned int i = 0; i < vch1.size(); i++)
689 vch1[i] ^= vch2[i];
691 popstack(stack);
693 break;
695 case OP_EQUAL:
696 case OP_EQUALVERIFY:
697 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
699 // (x1 x2 - bool)
700 if (stack.size() < 2)
701 return false;
702 valtype& vch1 = stacktop(-2);
703 valtype& vch2 = stacktop(-1);
704 bool fEqual = (vch1 == vch2);
705 // OP_NOTEQUAL is disabled because it would be too easy to say
706 // something like n != 1 and have some wiseguy pass in 1 with extra
707 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
708 //if (opcode == OP_NOTEQUAL)
709 // fEqual = !fEqual;
710 popstack(stack);
711 popstack(stack);
712 stack.push_back(fEqual ? vchTrue : vchFalse);
713 if (opcode == OP_EQUALVERIFY)
715 if (fEqual)
716 popstack(stack);
717 else
718 return false;
721 break;
725 // Numeric
727 case OP_1ADD:
728 case OP_1SUB:
729 case OP_2MUL:
730 case OP_2DIV:
731 case OP_NEGATE:
732 case OP_ABS:
733 case OP_NOT:
734 case OP_0NOTEQUAL:
736 // (in -- out)
737 if (stack.size() < 1)
738 return false;
739 CBigNum bn = CastToBigNum(stacktop(-1));
740 switch (opcode)
742 case OP_1ADD: bn += bnOne; break;
743 case OP_1SUB: bn -= bnOne; break;
744 case OP_2MUL: bn <<= 1; break;
745 case OP_2DIV: bn >>= 1; break;
746 case OP_NEGATE: bn = -bn; break;
747 case OP_ABS: if (bn < bnZero) bn = -bn; break;
748 case OP_NOT: bn = (bn == bnZero); break;
749 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
750 default: assert(!"invalid opcode"); break;
752 popstack(stack);
753 stack.push_back(bn.getvch());
755 break;
757 case OP_ADD:
758 case OP_SUB:
759 case OP_MUL:
760 case OP_DIV:
761 case OP_MOD:
762 case OP_LSHIFT:
763 case OP_RSHIFT:
764 case OP_BOOLAND:
765 case OP_BOOLOR:
766 case OP_NUMEQUAL:
767 case OP_NUMEQUALVERIFY:
768 case OP_NUMNOTEQUAL:
769 case OP_LESSTHAN:
770 case OP_GREATERTHAN:
771 case OP_LESSTHANOREQUAL:
772 case OP_GREATERTHANOREQUAL:
773 case OP_MIN:
774 case OP_MAX:
776 // (x1 x2 -- out)
777 if (stack.size() < 2)
778 return false;
779 CBigNum bn1 = CastToBigNum(stacktop(-2));
780 CBigNum bn2 = CastToBigNum(stacktop(-1));
781 CBigNum bn;
782 switch (opcode)
784 case OP_ADD:
785 bn = bn1 + bn2;
786 break;
788 case OP_SUB:
789 bn = bn1 - bn2;
790 break;
792 case OP_MUL:
793 if (!BN_mul(&bn, &bn1, &bn2, pctx))
794 return false;
795 break;
797 case OP_DIV:
798 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
799 return false;
800 break;
802 case OP_MOD:
803 if (!BN_mod(&bn, &bn1, &bn2, pctx))
804 return false;
805 break;
807 case OP_LSHIFT:
808 if (bn2 < bnZero || bn2 > CBigNum(2048))
809 return false;
810 bn = bn1 << bn2.getulong();
811 break;
813 case OP_RSHIFT:
814 if (bn2 < bnZero || bn2 > CBigNum(2048))
815 return false;
816 bn = bn1 >> bn2.getulong();
817 break;
819 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
820 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
821 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
822 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
823 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
824 case OP_LESSTHAN: bn = (bn1 < bn2); break;
825 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
826 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
827 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
828 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
829 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
830 default: assert(!"invalid opcode"); break;
832 popstack(stack);
833 popstack(stack);
834 stack.push_back(bn.getvch());
836 if (opcode == OP_NUMEQUALVERIFY)
838 if (CastToBool(stacktop(-1)))
839 popstack(stack);
840 else
841 return false;
844 break;
846 case OP_WITHIN:
848 // (x min max -- out)
849 if (stack.size() < 3)
850 return false;
851 CBigNum bn1 = CastToBigNum(stacktop(-3));
852 CBigNum bn2 = CastToBigNum(stacktop(-2));
853 CBigNum bn3 = CastToBigNum(stacktop(-1));
854 bool fValue = (bn2 <= bn1 && bn1 < bn3);
855 popstack(stack);
856 popstack(stack);
857 popstack(stack);
858 stack.push_back(fValue ? vchTrue : vchFalse);
860 break;
864 // Crypto
866 case OP_RIPEMD160:
867 case OP_SHA1:
868 case OP_SHA256:
869 case OP_HASH160:
870 case OP_HASH256:
872 // (in -- hash)
873 if (stack.size() < 1)
874 return false;
875 valtype& vch = stacktop(-1);
876 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
877 if (opcode == OP_RIPEMD160)
878 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
879 else if (opcode == OP_SHA1)
880 SHA1(&vch[0], vch.size(), &vchHash[0]);
881 else if (opcode == OP_SHA256)
882 SHA256(&vch[0], vch.size(), &vchHash[0]);
883 else if (opcode == OP_HASH160)
885 uint160 hash160 = Hash160(vch);
886 memcpy(&vchHash[0], &hash160, sizeof(hash160));
888 else if (opcode == OP_HASH256)
890 uint256 hash = Hash(vch.begin(), vch.end());
891 memcpy(&vchHash[0], &hash, sizeof(hash));
893 popstack(stack);
894 stack.push_back(vchHash);
896 break;
898 case OP_CODESEPARATOR:
900 // Hash starts after the code separator
901 pbegincodehash = pc;
903 break;
905 case OP_CHECKSIG:
906 case OP_CHECKSIGVERIFY:
908 // (sig pubkey -- bool)
909 if (stack.size() < 2)
910 return false;
912 valtype& vchSig = stacktop(-2);
913 valtype& vchPubKey = stacktop(-1);
915 ////// debug print
916 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
917 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
919 // Subset of script starting at the most recent codeseparator
920 CScript scriptCode(pbegincodehash, pend);
922 // Drop the signature, since there's no way for a signature to sign itself
923 scriptCode.FindAndDelete(CScript(vchSig));
925 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
927 popstack(stack);
928 popstack(stack);
929 stack.push_back(fSuccess ? vchTrue : vchFalse);
930 if (opcode == OP_CHECKSIGVERIFY)
932 if (fSuccess)
933 popstack(stack);
934 else
935 return false;
938 break;
940 case OP_CHECKMULTISIG:
941 case OP_CHECKMULTISIGVERIFY:
943 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
945 int i = 1;
946 if ((int)stack.size() < i)
947 return false;
949 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
950 if (nKeysCount < 0 || nKeysCount > 20)
951 return false;
952 nOpCount += nKeysCount;
953 if (nOpCount > 201)
954 return false;
955 int ikey = ++i;
956 i += nKeysCount;
957 if ((int)stack.size() < i)
958 return false;
960 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
961 if (nSigsCount < 0 || nSigsCount > nKeysCount)
962 return false;
963 int isig = ++i;
964 i += nSigsCount;
965 if ((int)stack.size() < i)
966 return false;
968 // Subset of script starting at the most recent codeseparator
969 CScript scriptCode(pbegincodehash, pend);
971 // Drop the signatures, since there's no way for a signature to sign itself
972 for (int k = 0; k < nSigsCount; k++)
974 valtype& vchSig = stacktop(-isig-k);
975 scriptCode.FindAndDelete(CScript(vchSig));
978 bool fSuccess = true;
979 while (fSuccess && nSigsCount > 0)
981 valtype& vchSig = stacktop(-isig);
982 valtype& vchPubKey = stacktop(-ikey);
984 // Check signature
985 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
987 isig++;
988 nSigsCount--;
990 ikey++;
991 nKeysCount--;
993 // If there are more signatures left than keys left,
994 // then too many signatures have failed
995 if (nSigsCount > nKeysCount)
996 fSuccess = false;
999 while (i-- > 0)
1000 popstack(stack);
1001 stack.push_back(fSuccess ? vchTrue : vchFalse);
1003 if (opcode == OP_CHECKMULTISIGVERIFY)
1005 if (fSuccess)
1006 popstack(stack);
1007 else
1008 return false;
1011 break;
1013 default:
1014 return false;
1017 // Size limits
1018 if (stack.size() + altstack.size() > 1000)
1019 return false;
1022 catch (...)
1024 return false;
1028 if (!vfExec.empty())
1029 return false;
1031 return true;
1042 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1044 if (nIn >= txTo.vin.size())
1046 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1047 return 1;
1049 CTransaction txTmp(txTo);
1051 // In case concatenating two scripts ends up with two codeseparators,
1052 // or an extra one at the end, this prevents all those possible incompatibilities.
1053 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1055 // Blank out other inputs' signatures
1056 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1057 txTmp.vin[i].scriptSig = CScript();
1058 txTmp.vin[nIn].scriptSig = scriptCode;
1060 // Blank out some of the outputs
1061 if ((nHashType & 0x1f) == SIGHASH_NONE)
1063 // Wildcard payee
1064 txTmp.vout.clear();
1066 // Let the others update at will
1067 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1068 if (i != nIn)
1069 txTmp.vin[i].nSequence = 0;
1071 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1073 // Only lockin the txout payee at same index as txin
1074 unsigned int nOut = nIn;
1075 if (nOut >= txTmp.vout.size())
1077 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1078 return 1;
1080 txTmp.vout.resize(nOut+1);
1081 for (unsigned int i = 0; i < nOut; i++)
1082 txTmp.vout[i].SetNull();
1084 // Let the others update at will
1085 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1086 if (i != nIn)
1087 txTmp.vin[i].nSequence = 0;
1090 // Blank out other inputs completely, not recommended for open transactions
1091 if (nHashType & SIGHASH_ANYONECANPAY)
1093 txTmp.vin[0] = txTmp.vin[nIn];
1094 txTmp.vin.resize(1);
1097 // Serialize and hash
1098 CDataStream ss(SER_GETHASH, 0);
1099 ss.reserve(10000);
1100 ss << txTmp << nHashType;
1101 return Hash(ss.begin(), ss.end());
1105 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1106 // twice for every transaction (once when accepted into memory pool, and
1107 // again when accepted into the block chain)
1109 class CSignatureCache
1111 private:
1112 // sigdata_type is (signature hash, signature, public key):
1113 typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1114 std::set< sigdata_type> setValid;
1115 CCriticalSection cs_sigcache;
1117 public:
1118 bool
1119 Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1121 LOCK(cs_sigcache);
1123 sigdata_type k(hash, vchSig, pubKey);
1124 std::set<sigdata_type>::iterator mi = setValid.find(k);
1125 if (mi != setValid.end())
1126 return true;
1127 return false;
1130 void
1131 Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1133 // DoS prevention: limit cache size to less than 10MB
1134 // (~200 bytes per cache entry times 50,000 entries)
1135 // Since there are a maximum of 20,000 signature operations per block
1136 // 50,000 is a reasonable default.
1137 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1138 if (nMaxCacheSize <= 0) return;
1140 LOCK(cs_sigcache);
1142 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1144 // Evict a random entry. Random because that helps
1145 // foil would-be DoS attackers who might try to pre-generate
1146 // and re-use a set of valid signatures just-slightly-greater
1147 // than our cache size.
1148 uint256 randomHash = GetRandHash();
1149 std::vector<unsigned char> unused;
1150 std::set<sigdata_type>::iterator it =
1151 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1152 if (it == setValid.end())
1153 it = setValid.begin();
1154 setValid.erase(*it);
1157 sigdata_type k(hash, vchSig, pubKey);
1158 setValid.insert(k);
1162 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1163 const CTransaction& txTo, unsigned int nIn, int nHashType)
1165 static CSignatureCache signatureCache;
1167 // Hash type is one byte tacked on to the end of the signature
1168 if (vchSig.empty())
1169 return false;
1170 if (nHashType == 0)
1171 nHashType = vchSig.back();
1172 else if (nHashType != vchSig.back())
1173 return false;
1174 vchSig.pop_back();
1176 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1178 if (signatureCache.Get(sighash, vchSig, vchPubKey))
1179 return true;
1181 CKey key;
1182 if (!key.SetPubKey(vchPubKey))
1183 return false;
1185 if (!key.Verify(sighash, vchSig))
1186 return false;
1188 signatureCache.Set(sighash, vchSig, vchPubKey);
1189 return true;
1201 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1203 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1205 // Templates
1206 static map<txnouttype, CScript> mTemplates;
1207 if (mTemplates.empty())
1209 // Standard tx, sender provides pubkey, receiver adds signature
1210 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1212 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1213 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1215 // Sender provides N pubkeys, receivers provides M signatures
1216 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1219 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1220 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1221 if (scriptPubKey.IsPayToScriptHash())
1223 typeRet = TX_SCRIPTHASH;
1224 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1225 vSolutionsRet.push_back(hashBytes);
1226 return true;
1229 // Scan templates
1230 const CScript& script1 = scriptPubKey;
1231 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1233 const CScript& script2 = tplate.second;
1234 vSolutionsRet.clear();
1236 opcodetype opcode1, opcode2;
1237 vector<unsigned char> vch1, vch2;
1239 // Compare
1240 CScript::const_iterator pc1 = script1.begin();
1241 CScript::const_iterator pc2 = script2.begin();
1242 loop
1244 if (pc1 == script1.end() && pc2 == script2.end())
1246 // Found a match
1247 typeRet = tplate.first;
1248 if (typeRet == TX_MULTISIG)
1250 // Additional checks for TX_MULTISIG:
1251 unsigned char m = vSolutionsRet.front()[0];
1252 unsigned char n = vSolutionsRet.back()[0];
1253 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1254 return false;
1256 return true;
1258 if (!script1.GetOp(pc1, opcode1, vch1))
1259 break;
1260 if (!script2.GetOp(pc2, opcode2, vch2))
1261 break;
1263 // Template matching opcodes:
1264 if (opcode2 == OP_PUBKEYS)
1266 while (vch1.size() >= 33 && vch1.size() <= 120)
1268 vSolutionsRet.push_back(vch1);
1269 if (!script1.GetOp(pc1, opcode1, vch1))
1270 break;
1272 if (!script2.GetOp(pc2, opcode2, vch2))
1273 break;
1274 // Normal situation is to fall through
1275 // to other if/else statments
1278 if (opcode2 == OP_PUBKEY)
1280 if (vch1.size() < 33 || vch1.size() > 120)
1281 break;
1282 vSolutionsRet.push_back(vch1);
1284 else if (opcode2 == OP_PUBKEYHASH)
1286 if (vch1.size() != sizeof(uint160))
1287 break;
1288 vSolutionsRet.push_back(vch1);
1290 else if (opcode2 == OP_SMALLINTEGER)
1291 { // Single-byte small integer pushed onto vSolutions
1292 if (opcode1 == OP_0 ||
1293 (opcode1 >= OP_1 && opcode1 <= OP_16))
1295 char n = (char)CScript::DecodeOP_N(opcode1);
1296 vSolutionsRet.push_back(valtype(1, n));
1298 else
1299 break;
1301 else if (opcode1 != opcode2 || vch1 != vch2)
1303 // Others must match exactly
1304 break;
1309 vSolutionsRet.clear();
1310 typeRet = TX_NONSTANDARD;
1311 return false;
1315 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1317 CKey key;
1318 if (!keystore.GetKey(address, key))
1319 return false;
1321 vector<unsigned char> vchSig;
1322 if (!key.Sign(hash, vchSig))
1323 return false;
1324 vchSig.push_back((unsigned char)nHashType);
1325 scriptSigRet << vchSig;
1327 return true;
1330 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1332 int nSigned = 0;
1333 int nRequired = multisigdata.front()[0];
1334 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1336 const valtype& pubkey = multisigdata[i];
1337 CKeyID keyID = CPubKey(pubkey).GetID();
1338 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1339 ++nSigned;
1341 return nSigned==nRequired;
1345 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1346 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1347 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1348 // Returns false if scriptPubKey could not be completely satisified.
1350 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1351 CScript& scriptSigRet, txnouttype& whichTypeRet)
1353 scriptSigRet.clear();
1355 vector<valtype> vSolutions;
1356 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1357 return false;
1359 CKeyID keyID;
1360 switch (whichTypeRet)
1362 case TX_NONSTANDARD:
1363 return false;
1364 case TX_PUBKEY:
1365 keyID = CPubKey(vSolutions[0]).GetID();
1366 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1367 case TX_PUBKEYHASH:
1368 keyID = CKeyID(uint160(vSolutions[0]));
1369 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1370 return false;
1371 else
1373 CPubKey vch;
1374 keystore.GetPubKey(keyID, vch);
1375 scriptSigRet << vch;
1377 return true;
1378 case TX_SCRIPTHASH:
1379 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1381 case TX_MULTISIG:
1382 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1383 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1385 return false;
1388 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1390 switch (t)
1392 case TX_NONSTANDARD:
1393 return -1;
1394 case TX_PUBKEY:
1395 return 1;
1396 case TX_PUBKEYHASH:
1397 return 2;
1398 case TX_MULTISIG:
1399 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1400 return -1;
1401 return vSolutions[0][0] + 1;
1402 case TX_SCRIPTHASH:
1403 return 1; // doesn't include args needed by the script
1405 return -1;
1408 bool IsStandard(const CScript& scriptPubKey)
1410 vector<valtype> vSolutions;
1411 txnouttype whichType;
1412 if (!Solver(scriptPubKey, whichType, vSolutions))
1413 return false;
1415 if (whichType == TX_MULTISIG)
1417 unsigned char m = vSolutions.front()[0];
1418 unsigned char n = vSolutions.back()[0];
1419 // Support up to x-of-3 multisig txns as standard
1420 if (n < 1 || n > 3)
1421 return false;
1422 if (m < 1 || m > n)
1423 return false;
1426 return whichType != TX_NONSTANDARD;
1430 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1432 unsigned int nResult = 0;
1433 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1435 CKeyID keyID = CPubKey(pubkey).GetID();
1436 if (keystore.HaveKey(keyID))
1437 ++nResult;
1439 return nResult;
1443 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1445 private:
1446 const CKeyStore *keystore;
1447 public:
1448 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1449 bool operator()(const CNoDestination &dest) const { return false; }
1450 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1451 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1454 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1456 return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1459 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1461 vector<valtype> vSolutions;
1462 txnouttype whichType;
1463 if (!Solver(scriptPubKey, whichType, vSolutions))
1464 return false;
1466 CKeyID keyID;
1467 switch (whichType)
1469 case TX_NONSTANDARD:
1470 return false;
1471 case TX_PUBKEY:
1472 keyID = CPubKey(vSolutions[0]).GetID();
1473 return keystore.HaveKey(keyID);
1474 case TX_PUBKEYHASH:
1475 keyID = CKeyID(uint160(vSolutions[0]));
1476 return keystore.HaveKey(keyID);
1477 case TX_SCRIPTHASH:
1479 CScript subscript;
1480 if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1481 return false;
1482 return IsMine(keystore, subscript);
1484 case TX_MULTISIG:
1486 // Only consider transactions "mine" if we own ALL the
1487 // keys involved. multi-signature transactions that are
1488 // partially owned (somebody else has a key that can spend
1489 // them) enable spend-out-from-under-you attacks, especially
1490 // in shared-wallet situations.
1491 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1492 return HaveKeys(keys, keystore) == keys.size();
1495 return false;
1498 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1500 vector<valtype> vSolutions;
1501 txnouttype whichType;
1502 if (!Solver(scriptPubKey, whichType, vSolutions))
1503 return false;
1505 if (whichType == TX_PUBKEY)
1507 addressRet = CPubKey(vSolutions[0]).GetID();
1508 return true;
1510 else if (whichType == TX_PUBKEYHASH)
1512 addressRet = CKeyID(uint160(vSolutions[0]));
1513 return true;
1515 else if (whichType == TX_SCRIPTHASH)
1517 addressRet = CScriptID(uint160(vSolutions[0]));
1518 return true;
1520 // Multisig txns have more than one address...
1521 return false;
1524 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1526 addressRet.clear();
1527 typeRet = TX_NONSTANDARD;
1528 vector<valtype> vSolutions;
1529 if (!Solver(scriptPubKey, typeRet, vSolutions))
1530 return false;
1532 if (typeRet == TX_MULTISIG)
1534 nRequiredRet = vSolutions.front()[0];
1535 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1537 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1538 addressRet.push_back(address);
1541 else
1543 nRequiredRet = 1;
1544 CTxDestination address;
1545 if (!ExtractDestination(scriptPubKey, address))
1546 return false;
1547 addressRet.push_back(address);
1550 return true;
1553 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1554 bool fValidatePayToScriptHash, int nHashType)
1556 vector<vector<unsigned char> > stack, stackCopy;
1557 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1558 return false;
1559 if (fValidatePayToScriptHash)
1560 stackCopy = stack;
1561 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1562 return false;
1563 if (stack.empty())
1564 return false;
1566 if (CastToBool(stack.back()) == false)
1567 return false;
1569 // Additional validation for spend-to-script-hash transactions:
1570 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1572 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1573 return false; // or validation fails
1575 const valtype& pubKeySerialized = stackCopy.back();
1576 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1577 popstack(stackCopy);
1579 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
1580 return false;
1581 if (stackCopy.empty())
1582 return false;
1583 return CastToBool(stackCopy.back());
1586 return true;
1590 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1592 assert(nIn < txTo.vin.size());
1593 CTxIn& txin = txTo.vin[nIn];
1595 // Leave out the signature from the hash, since a signature can't sign itself.
1596 // The checksig op will also drop the signatures from its hash.
1597 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1599 txnouttype whichType;
1600 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1601 return false;
1603 if (whichType == TX_SCRIPTHASH)
1605 // Solver returns the subscript that need to be evaluated;
1606 // the final scriptSig is the signatures from that
1607 // and then the serialized subscript:
1608 CScript subscript = txin.scriptSig;
1610 // Recompute txn hash using subscript in place of scriptPubKey:
1611 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1613 txnouttype subType;
1614 bool fSolved =
1615 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1616 // Append serialized subscript whether or not it is completely signed:
1617 txin.scriptSig << static_cast<valtype>(subscript);
1618 if (!fSolved) return false;
1621 // Test solution
1622 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, 0);
1625 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1627 assert(nIn < txTo.vin.size());
1628 CTxIn& txin = txTo.vin[nIn];
1629 assert(txin.prevout.n < txFrom.vout.size());
1630 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1632 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1635 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
1637 assert(nIn < txTo.vin.size());
1638 const CTxIn& txin = txTo.vin[nIn];
1639 if (txin.prevout.n >= txFrom.vout.size())
1640 return false;
1641 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1643 if (txin.prevout.hash != txFrom.GetHash())
1644 return false;
1646 return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
1649 static CScript PushAll(const vector<valtype>& values)
1651 CScript result;
1652 BOOST_FOREACH(const valtype& v, values)
1653 result << v;
1654 return result;
1657 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1658 const vector<valtype>& vSolutions,
1659 vector<valtype>& sigs1, vector<valtype>& sigs2)
1661 // Combine all the signatures we've got:
1662 set<valtype> allsigs;
1663 BOOST_FOREACH(const valtype& v, sigs1)
1665 if (!v.empty())
1666 allsigs.insert(v);
1668 BOOST_FOREACH(const valtype& v, sigs2)
1670 if (!v.empty())
1671 allsigs.insert(v);
1674 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1675 assert(vSolutions.size() > 1);
1676 unsigned int nSigsRequired = vSolutions.front()[0];
1677 unsigned int nPubKeys = vSolutions.size()-2;
1678 map<valtype, valtype> sigs;
1679 BOOST_FOREACH(const valtype& sig, allsigs)
1681 for (unsigned int i = 0; i < nPubKeys; i++)
1683 const valtype& pubkey = vSolutions[i+1];
1684 if (sigs.count(pubkey))
1685 continue; // Already got a sig for this pubkey
1687 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0))
1689 sigs[pubkey] = sig;
1690 break;
1694 // Now build a merged CScript:
1695 unsigned int nSigsHave = 0;
1696 CScript result; result << OP_0; // pop-one-too-many workaround
1697 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1699 if (sigs.count(vSolutions[i+1]))
1701 result << sigs[vSolutions[i+1]];
1702 ++nSigsHave;
1705 // Fill any missing with OP_0:
1706 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1707 result << OP_0;
1709 return result;
1712 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1713 const txnouttype txType, const vector<valtype>& vSolutions,
1714 vector<valtype>& sigs1, vector<valtype>& sigs2)
1716 switch (txType)
1718 case TX_NONSTANDARD:
1719 // Don't know anything about this, assume bigger one is correct:
1720 if (sigs1.size() >= sigs2.size())
1721 return PushAll(sigs1);
1722 return PushAll(sigs2);
1723 case TX_PUBKEY:
1724 case TX_PUBKEYHASH:
1725 // Signatures are bigger than placeholders or empty scripts:
1726 if (sigs1.empty() || sigs1[0].empty())
1727 return PushAll(sigs2);
1728 return PushAll(sigs1);
1729 case TX_SCRIPTHASH:
1730 if (sigs1.empty() || sigs1.back().empty())
1731 return PushAll(sigs2);
1732 else if (sigs2.empty() || sigs2.back().empty())
1733 return PushAll(sigs1);
1734 else
1736 // Recurse to combine:
1737 valtype spk = sigs1.back();
1738 CScript pubKey2(spk.begin(), spk.end());
1740 txnouttype txType2;
1741 vector<vector<unsigned char> > vSolutions2;
1742 Solver(pubKey2, txType2, vSolutions2);
1743 sigs1.pop_back();
1744 sigs2.pop_back();
1745 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1746 result << spk;
1747 return result;
1749 case TX_MULTISIG:
1750 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1753 return CScript();
1756 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1757 const CScript& scriptSig1, const CScript& scriptSig2)
1759 txnouttype txType;
1760 vector<vector<unsigned char> > vSolutions;
1761 Solver(scriptPubKey, txType, vSolutions);
1763 vector<valtype> stack1;
1764 EvalScript(stack1, scriptSig1, CTransaction(), 0, 0);
1765 vector<valtype> stack2;
1766 EvalScript(stack2, scriptSig2, CTransaction(), 0, 0);
1768 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1771 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1773 unsigned int n = 0;
1774 const_iterator pc = begin();
1775 opcodetype lastOpcode = OP_INVALIDOPCODE;
1776 while (pc < end())
1778 opcodetype opcode;
1779 if (!GetOp(pc, opcode))
1780 break;
1781 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1782 n++;
1783 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1785 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1786 n += DecodeOP_N(lastOpcode);
1787 else
1788 n += 20;
1790 lastOpcode = opcode;
1792 return n;
1795 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1797 if (!IsPayToScriptHash())
1798 return GetSigOpCount(true);
1800 // This is a pay-to-script-hash scriptPubKey;
1801 // get the last item that the scriptSig
1802 // pushes onto the stack:
1803 const_iterator pc = scriptSig.begin();
1804 vector<unsigned char> data;
1805 while (pc < scriptSig.end())
1807 opcodetype opcode;
1808 if (!scriptSig.GetOp(pc, opcode, data))
1809 return 0;
1810 if (opcode > OP_16)
1811 return 0;
1814 /// ... and return it's opcount:
1815 CScript subscript(data.begin(), data.end());
1816 return subscript.GetSigOpCount(true);
1819 bool CScript::IsPayToScriptHash() const
1821 // Extra-fast test for pay-to-script-hash CScripts:
1822 return (this->size() == 23 &&
1823 this->at(0) == OP_HASH160 &&
1824 this->at(1) == 0x14 &&
1825 this->at(22) == OP_EQUAL);
1828 class CScriptVisitor : public boost::static_visitor<bool>
1830 private:
1831 CScript *script;
1832 public:
1833 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1835 bool operator()(const CNoDestination &dest) const {
1836 script->clear();
1837 return false;
1840 bool operator()(const CKeyID &keyID) const {
1841 script->clear();
1842 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1843 return true;
1846 bool operator()(const CScriptID &scriptID) const {
1847 script->clear();
1848 *script << OP_HASH160 << scriptID << OP_EQUAL;
1849 return true;
1853 void CScript::SetDestination(const CTxDestination& dest)
1855 boost::apply_visitor(CScriptVisitor(this), dest);
1858 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1860 this->clear();
1862 *this << EncodeOP_N(nRequired);
1863 BOOST_FOREACH(const CKey& key, keys)
1864 *this << key.GetPubKey();
1865 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;