Bugfix: avoid sub-cent change (lost in fees) whenever possible
[bitcoin.git] / script.cpp
bloba85c3710a3dfede9c4e9e2afd3cac1a52989e5a4
1 // Copyright (c) 2009-2010 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.
5 #include "headers.h"
7 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
11 typedef vector<unsigned char> valtype;
12 static const valtype vchFalse(0);
13 static const valtype vchZero(0);
14 static const valtype vchTrue(1, 1);
15 static const CBigNum bnZero(0);
16 static const CBigNum bnOne(1);
17 static const CBigNum bnFalse(0);
18 static const CBigNum bnTrue(1);
19 static const size_t nMaxNumSize = 4;
22 CBigNum CastToBigNum(const valtype& vch)
24 if (vch.size() > nMaxNumSize)
25 throw runtime_error("CastToBigNum() : overflow");
26 // Get rid of extra leading zeros
27 return CBigNum(CBigNum(vch).getvch());
30 bool CastToBool(const valtype& vch)
32 for (int i = 0; i < vch.size(); i++)
34 if (vch[i] != 0)
36 // Can be negative zero
37 if (i == vch.size()-1 && vch[i] == 0x80)
38 return false;
39 return true;
42 return false;
45 void MakeSameSize(valtype& vch1, valtype& vch2)
47 // Lengthen the shorter one
48 if (vch1.size() < vch2.size())
49 vch1.resize(vch2.size(), 0);
50 if (vch2.size() < vch1.size())
51 vch2.resize(vch1.size(), 0);
57 // Script is a stack machine (like Forth) that evaluates a predicate
58 // returning a bool indicating valid or not. There are no loops.
60 #define stacktop(i) (stack.at(stack.size()+(i)))
61 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
62 static inline void popstack(vector<valtype>& stack)
64 if (stack.empty())
65 throw runtime_error("popstack() : stack empty");
66 stack.pop_back();
70 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
72 CAutoBN_CTX pctx;
73 CScript::const_iterator pc = script.begin();
74 CScript::const_iterator pend = script.end();
75 CScript::const_iterator pbegincodehash = script.begin();
76 opcodetype opcode;
77 valtype vchPushValue;
78 vector<bool> vfExec;
79 vector<valtype> altstack;
80 if (script.size() > 10000)
81 return false;
82 int nOpCount = 0;
85 try
87 while (pc < pend)
89 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
92 // Read instruction
94 if (!script.GetOp(pc, opcode, vchPushValue))
95 return false;
96 if (vchPushValue.size() > 520)
97 return false;
98 if (opcode > OP_16 && ++nOpCount > 201)
99 return false;
101 if (opcode == OP_CAT ||
102 opcode == OP_SUBSTR ||
103 opcode == OP_LEFT ||
104 opcode == OP_RIGHT ||
105 opcode == OP_INVERT ||
106 opcode == OP_AND ||
107 opcode == OP_OR ||
108 opcode == OP_XOR ||
109 opcode == OP_2MUL ||
110 opcode == OP_2DIV ||
111 opcode == OP_MUL ||
112 opcode == OP_DIV ||
113 opcode == OP_MOD ||
114 opcode == OP_LSHIFT ||
115 opcode == OP_RSHIFT)
116 return false;
118 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
119 stack.push_back(vchPushValue);
120 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
121 switch (opcode)
124 // Push value
126 case OP_1NEGATE:
127 case OP_1:
128 case OP_2:
129 case OP_3:
130 case OP_4:
131 case OP_5:
132 case OP_6:
133 case OP_7:
134 case OP_8:
135 case OP_9:
136 case OP_10:
137 case OP_11:
138 case OP_12:
139 case OP_13:
140 case OP_14:
141 case OP_15:
142 case OP_16:
144 // ( -- value)
145 CBigNum bn((int)opcode - (int)(OP_1 - 1));
146 stack.push_back(bn.getvch());
148 break;
152 // Control
154 case OP_NOP:
155 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
156 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
157 break;
159 case OP_IF:
160 case OP_NOTIF:
162 // <expression> if [statements] [else [statements]] endif
163 bool fValue = false;
164 if (fExec)
166 if (stack.size() < 1)
167 return false;
168 valtype& vch = stacktop(-1);
169 fValue = CastToBool(vch);
170 if (opcode == OP_NOTIF)
171 fValue = !fValue;
172 popstack(stack);
174 vfExec.push_back(fValue);
176 break;
178 case OP_ELSE:
180 if (vfExec.empty())
181 return false;
182 vfExec.back() = !vfExec.back();
184 break;
186 case OP_ENDIF:
188 if (vfExec.empty())
189 return false;
190 vfExec.pop_back();
192 break;
194 case OP_VERIFY:
196 // (true -- ) or
197 // (false -- false) and return
198 if (stack.size() < 1)
199 return false;
200 bool fValue = CastToBool(stacktop(-1));
201 if (fValue)
202 popstack(stack);
203 else
204 return false;
206 break;
208 case OP_RETURN:
210 return false;
212 break;
216 // Stack ops
218 case OP_TOALTSTACK:
220 if (stack.size() < 1)
221 return false;
222 altstack.push_back(stacktop(-1));
223 popstack(stack);
225 break;
227 case OP_FROMALTSTACK:
229 if (altstack.size() < 1)
230 return false;
231 stack.push_back(altstacktop(-1));
232 popstack(altstack);
234 break;
236 case OP_2DROP:
238 // (x1 x2 -- )
239 if (stack.size() < 2)
240 return false;
241 popstack(stack);
242 popstack(stack);
244 break;
246 case OP_2DUP:
248 // (x1 x2 -- x1 x2 x1 x2)
249 if (stack.size() < 2)
250 return false;
251 valtype vch1 = stacktop(-2);
252 valtype vch2 = stacktop(-1);
253 stack.push_back(vch1);
254 stack.push_back(vch2);
256 break;
258 case OP_3DUP:
260 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
261 if (stack.size() < 3)
262 return false;
263 valtype vch1 = stacktop(-3);
264 valtype vch2 = stacktop(-2);
265 valtype vch3 = stacktop(-1);
266 stack.push_back(vch1);
267 stack.push_back(vch2);
268 stack.push_back(vch3);
270 break;
272 case OP_2OVER:
274 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
275 if (stack.size() < 4)
276 return false;
277 valtype vch1 = stacktop(-4);
278 valtype vch2 = stacktop(-3);
279 stack.push_back(vch1);
280 stack.push_back(vch2);
282 break;
284 case OP_2ROT:
286 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
287 if (stack.size() < 6)
288 return false;
289 valtype vch1 = stacktop(-6);
290 valtype vch2 = stacktop(-5);
291 stack.erase(stack.end()-6, stack.end()-4);
292 stack.push_back(vch1);
293 stack.push_back(vch2);
295 break;
297 case OP_2SWAP:
299 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
300 if (stack.size() < 4)
301 return false;
302 swap(stacktop(-4), stacktop(-2));
303 swap(stacktop(-3), stacktop(-1));
305 break;
307 case OP_IFDUP:
309 // (x - 0 | x x)
310 if (stack.size() < 1)
311 return false;
312 valtype vch = stacktop(-1);
313 if (CastToBool(vch))
314 stack.push_back(vch);
316 break;
318 case OP_DEPTH:
320 // -- stacksize
321 CBigNum bn(stack.size());
322 stack.push_back(bn.getvch());
324 break;
326 case OP_DROP:
328 // (x -- )
329 if (stack.size() < 1)
330 return false;
331 popstack(stack);
333 break;
335 case OP_DUP:
337 // (x -- x x)
338 if (stack.size() < 1)
339 return false;
340 valtype vch = stacktop(-1);
341 stack.push_back(vch);
343 break;
345 case OP_NIP:
347 // (x1 x2 -- x2)
348 if (stack.size() < 2)
349 return false;
350 stack.erase(stack.end() - 2);
352 break;
354 case OP_OVER:
356 // (x1 x2 -- x1 x2 x1)
357 if (stack.size() < 2)
358 return false;
359 valtype vch = stacktop(-2);
360 stack.push_back(vch);
362 break;
364 case OP_PICK:
365 case OP_ROLL:
367 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
368 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
369 if (stack.size() < 2)
370 return false;
371 int n = CastToBigNum(stacktop(-1)).getint();
372 popstack(stack);
373 if (n < 0 || n >= stack.size())
374 return false;
375 valtype vch = stacktop(-n-1);
376 if (opcode == OP_ROLL)
377 stack.erase(stack.end()-n-1);
378 stack.push_back(vch);
380 break;
382 case OP_ROT:
384 // (x1 x2 x3 -- x2 x3 x1)
385 // x2 x1 x3 after first swap
386 // x2 x3 x1 after second swap
387 if (stack.size() < 3)
388 return false;
389 swap(stacktop(-3), stacktop(-2));
390 swap(stacktop(-2), stacktop(-1));
392 break;
394 case OP_SWAP:
396 // (x1 x2 -- x2 x1)
397 if (stack.size() < 2)
398 return false;
399 swap(stacktop(-2), stacktop(-1));
401 break;
403 case OP_TUCK:
405 // (x1 x2 -- x2 x1 x2)
406 if (stack.size() < 2)
407 return false;
408 valtype vch = stacktop(-1);
409 stack.insert(stack.end()-2, vch);
411 break;
415 // Splice ops
417 case OP_CAT:
419 // (x1 x2 -- out)
420 if (stack.size() < 2)
421 return false;
422 valtype& vch1 = stacktop(-2);
423 valtype& vch2 = stacktop(-1);
424 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
425 popstack(stack);
426 if (stacktop(-1).size() > 520)
427 return false;
429 break;
431 case OP_SUBSTR:
433 // (in begin size -- out)
434 if (stack.size() < 3)
435 return false;
436 valtype& vch = stacktop(-3);
437 int nBegin = CastToBigNum(stacktop(-2)).getint();
438 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
439 if (nBegin < 0 || nEnd < nBegin)
440 return false;
441 if (nBegin > vch.size())
442 nBegin = vch.size();
443 if (nEnd > vch.size())
444 nEnd = vch.size();
445 vch.erase(vch.begin() + nEnd, vch.end());
446 vch.erase(vch.begin(), vch.begin() + nBegin);
447 popstack(stack);
448 popstack(stack);
450 break;
452 case OP_LEFT:
453 case OP_RIGHT:
455 // (in size -- out)
456 if (stack.size() < 2)
457 return false;
458 valtype& vch = stacktop(-2);
459 int nSize = CastToBigNum(stacktop(-1)).getint();
460 if (nSize < 0)
461 return false;
462 if (nSize > vch.size())
463 nSize = vch.size();
464 if (opcode == OP_LEFT)
465 vch.erase(vch.begin() + nSize, vch.end());
466 else
467 vch.erase(vch.begin(), vch.end() - nSize);
468 popstack(stack);
470 break;
472 case OP_SIZE:
474 // (in -- in size)
475 if (stack.size() < 1)
476 return false;
477 CBigNum bn(stacktop(-1).size());
478 stack.push_back(bn.getvch());
480 break;
484 // Bitwise logic
486 case OP_INVERT:
488 // (in - out)
489 if (stack.size() < 1)
490 return false;
491 valtype& vch = stacktop(-1);
492 for (int i = 0; i < vch.size(); i++)
493 vch[i] = ~vch[i];
495 break;
497 case OP_AND:
498 case OP_OR:
499 case OP_XOR:
501 // (x1 x2 - out)
502 if (stack.size() < 2)
503 return false;
504 valtype& vch1 = stacktop(-2);
505 valtype& vch2 = stacktop(-1);
506 MakeSameSize(vch1, vch2);
507 if (opcode == OP_AND)
509 for (int i = 0; i < vch1.size(); i++)
510 vch1[i] &= vch2[i];
512 else if (opcode == OP_OR)
514 for (int i = 0; i < vch1.size(); i++)
515 vch1[i] |= vch2[i];
517 else if (opcode == OP_XOR)
519 for (int i = 0; i < vch1.size(); i++)
520 vch1[i] ^= vch2[i];
522 popstack(stack);
524 break;
526 case OP_EQUAL:
527 case OP_EQUALVERIFY:
528 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
530 // (x1 x2 - bool)
531 if (stack.size() < 2)
532 return false;
533 valtype& vch1 = stacktop(-2);
534 valtype& vch2 = stacktop(-1);
535 bool fEqual = (vch1 == vch2);
536 // OP_NOTEQUAL is disabled because it would be too easy to say
537 // something like n != 1 and have some wiseguy pass in 1 with extra
538 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
539 //if (opcode == OP_NOTEQUAL)
540 // fEqual = !fEqual;
541 popstack(stack);
542 popstack(stack);
543 stack.push_back(fEqual ? vchTrue : vchFalse);
544 if (opcode == OP_EQUALVERIFY)
546 if (fEqual)
547 popstack(stack);
548 else
549 return false;
552 break;
556 // Numeric
558 case OP_1ADD:
559 case OP_1SUB:
560 case OP_2MUL:
561 case OP_2DIV:
562 case OP_NEGATE:
563 case OP_ABS:
564 case OP_NOT:
565 case OP_0NOTEQUAL:
567 // (in -- out)
568 if (stack.size() < 1)
569 return false;
570 CBigNum bn = CastToBigNum(stacktop(-1));
571 switch (opcode)
573 case OP_1ADD: bn += bnOne; break;
574 case OP_1SUB: bn -= bnOne; break;
575 case OP_2MUL: bn <<= 1; break;
576 case OP_2DIV: bn >>= 1; break;
577 case OP_NEGATE: bn = -bn; break;
578 case OP_ABS: if (bn < bnZero) bn = -bn; break;
579 case OP_NOT: bn = (bn == bnZero); break;
580 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
582 popstack(stack);
583 stack.push_back(bn.getvch());
585 break;
587 case OP_ADD:
588 case OP_SUB:
589 case OP_MUL:
590 case OP_DIV:
591 case OP_MOD:
592 case OP_LSHIFT:
593 case OP_RSHIFT:
594 case OP_BOOLAND:
595 case OP_BOOLOR:
596 case OP_NUMEQUAL:
597 case OP_NUMEQUALVERIFY:
598 case OP_NUMNOTEQUAL:
599 case OP_LESSTHAN:
600 case OP_GREATERTHAN:
601 case OP_LESSTHANOREQUAL:
602 case OP_GREATERTHANOREQUAL:
603 case OP_MIN:
604 case OP_MAX:
606 // (x1 x2 -- out)
607 if (stack.size() < 2)
608 return false;
609 CBigNum bn1 = CastToBigNum(stacktop(-2));
610 CBigNum bn2 = CastToBigNum(stacktop(-1));
611 CBigNum bn;
612 switch (opcode)
614 case OP_ADD:
615 bn = bn1 + bn2;
616 break;
618 case OP_SUB:
619 bn = bn1 - bn2;
620 break;
622 case OP_MUL:
623 if (!BN_mul(&bn, &bn1, &bn2, pctx))
624 return false;
625 break;
627 case OP_DIV:
628 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
629 return false;
630 break;
632 case OP_MOD:
633 if (!BN_mod(&bn, &bn1, &bn2, pctx))
634 return false;
635 break;
637 case OP_LSHIFT:
638 if (bn2 < bnZero || bn2 > CBigNum(2048))
639 return false;
640 bn = bn1 << bn2.getulong();
641 break;
643 case OP_RSHIFT:
644 if (bn2 < bnZero || bn2 > CBigNum(2048))
645 return false;
646 bn = bn1 >> bn2.getulong();
647 break;
649 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
650 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
651 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
652 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
653 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
654 case OP_LESSTHAN: bn = (bn1 < bn2); break;
655 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
656 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
657 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
658 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
659 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
661 popstack(stack);
662 popstack(stack);
663 stack.push_back(bn.getvch());
665 if (opcode == OP_NUMEQUALVERIFY)
667 if (CastToBool(stacktop(-1)))
668 popstack(stack);
669 else
670 return false;
673 break;
675 case OP_WITHIN:
677 // (x min max -- out)
678 if (stack.size() < 3)
679 return false;
680 CBigNum bn1 = CastToBigNum(stacktop(-3));
681 CBigNum bn2 = CastToBigNum(stacktop(-2));
682 CBigNum bn3 = CastToBigNum(stacktop(-1));
683 bool fValue = (bn2 <= bn1 && bn1 < bn3);
684 popstack(stack);
685 popstack(stack);
686 popstack(stack);
687 stack.push_back(fValue ? vchTrue : vchFalse);
689 break;
693 // Crypto
695 case OP_RIPEMD160:
696 case OP_SHA1:
697 case OP_SHA256:
698 case OP_HASH160:
699 case OP_HASH256:
701 // (in -- hash)
702 if (stack.size() < 1)
703 return false;
704 valtype& vch = stacktop(-1);
705 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
706 if (opcode == OP_RIPEMD160)
707 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
708 else if (opcode == OP_SHA1)
709 SHA1(&vch[0], vch.size(), &vchHash[0]);
710 else if (opcode == OP_SHA256)
711 SHA256(&vch[0], vch.size(), &vchHash[0]);
712 else if (opcode == OP_HASH160)
714 uint160 hash160 = Hash160(vch);
715 memcpy(&vchHash[0], &hash160, sizeof(hash160));
717 else if (opcode == OP_HASH256)
719 uint256 hash = Hash(vch.begin(), vch.end());
720 memcpy(&vchHash[0], &hash, sizeof(hash));
722 popstack(stack);
723 stack.push_back(vchHash);
725 break;
727 case OP_CODESEPARATOR:
729 // Hash starts after the code separator
730 pbegincodehash = pc;
732 break;
734 case OP_CHECKSIG:
735 case OP_CHECKSIGVERIFY:
737 // (sig pubkey -- bool)
738 if (stack.size() < 2)
739 return false;
741 valtype& vchSig = stacktop(-2);
742 valtype& vchPubKey = stacktop(-1);
744 ////// debug print
745 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
746 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
748 // Subset of script starting at the most recent codeseparator
749 CScript scriptCode(pbegincodehash, pend);
751 // Drop the signature, since there's no way for a signature to sign itself
752 scriptCode.FindAndDelete(CScript(vchSig));
754 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
756 popstack(stack);
757 popstack(stack);
758 stack.push_back(fSuccess ? vchTrue : vchFalse);
759 if (opcode == OP_CHECKSIGVERIFY)
761 if (fSuccess)
762 popstack(stack);
763 else
764 return false;
767 break;
769 case OP_CHECKMULTISIG:
770 case OP_CHECKMULTISIGVERIFY:
772 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
774 int i = 1;
775 if (stack.size() < i)
776 return false;
778 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
779 if (nKeysCount < 0 || nKeysCount > 20)
780 return false;
781 nOpCount += nKeysCount;
782 if (nOpCount > 201)
783 return false;
784 int ikey = ++i;
785 i += nKeysCount;
786 if (stack.size() < i)
787 return false;
789 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
790 if (nSigsCount < 0 || nSigsCount > nKeysCount)
791 return false;
792 int isig = ++i;
793 i += nSigsCount;
794 if (stack.size() < i)
795 return false;
797 // Subset of script starting at the most recent codeseparator
798 CScript scriptCode(pbegincodehash, pend);
800 // Drop the signatures, since there's no way for a signature to sign itself
801 for (int k = 0; k < nSigsCount; k++)
803 valtype& vchSig = stacktop(-isig-k);
804 scriptCode.FindAndDelete(CScript(vchSig));
807 bool fSuccess = true;
808 while (fSuccess && nSigsCount > 0)
810 valtype& vchSig = stacktop(-isig);
811 valtype& vchPubKey = stacktop(-ikey);
813 // Check signature
814 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
816 isig++;
817 nSigsCount--;
819 ikey++;
820 nKeysCount--;
822 // If there are more signatures left than keys left,
823 // then too many signatures have failed
824 if (nSigsCount > nKeysCount)
825 fSuccess = false;
828 while (i-- > 0)
829 popstack(stack);
830 stack.push_back(fSuccess ? vchTrue : vchFalse);
832 if (opcode == OP_CHECKMULTISIGVERIFY)
834 if (fSuccess)
835 popstack(stack);
836 else
837 return false;
840 break;
842 default:
843 return false;
846 // Size limits
847 if (stack.size() + altstack.size() > 1000)
848 return false;
851 catch (...)
853 return false;
857 if (!vfExec.empty())
858 return false;
860 return true;
871 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
873 if (nIn >= txTo.vin.size())
875 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
876 return 1;
878 CTransaction txTmp(txTo);
880 // In case concatenating two scripts ends up with two codeseparators,
881 // or an extra one at the end, this prevents all those possible incompatibilities.
882 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
884 // Blank out other inputs' signatures
885 for (int i = 0; i < txTmp.vin.size(); i++)
886 txTmp.vin[i].scriptSig = CScript();
887 txTmp.vin[nIn].scriptSig = scriptCode;
889 // Blank out some of the outputs
890 if ((nHashType & 0x1f) == SIGHASH_NONE)
892 // Wildcard payee
893 txTmp.vout.clear();
895 // Let the others update at will
896 for (int i = 0; i < txTmp.vin.size(); i++)
897 if (i != nIn)
898 txTmp.vin[i].nSequence = 0;
900 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
902 // Only lockin the txout payee at same index as txin
903 unsigned int nOut = nIn;
904 if (nOut >= txTmp.vout.size())
906 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
907 return 1;
909 txTmp.vout.resize(nOut+1);
910 for (int i = 0; i < nOut; i++)
911 txTmp.vout[i].SetNull();
913 // Let the others update at will
914 for (int i = 0; i < txTmp.vin.size(); i++)
915 if (i != nIn)
916 txTmp.vin[i].nSequence = 0;
919 // Blank out other inputs completely, not recommended for open transactions
920 if (nHashType & SIGHASH_ANYONECANPAY)
922 txTmp.vin[0] = txTmp.vin[nIn];
923 txTmp.vin.resize(1);
926 // Serialize and hash
927 CDataStream ss(SER_GETHASH);
928 ss.reserve(10000);
929 ss << txTmp << nHashType;
930 return Hash(ss.begin(), ss.end());
934 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
935 const CTransaction& txTo, unsigned int nIn, int nHashType)
937 CKey key;
938 if (!key.SetPubKey(vchPubKey))
939 return false;
941 // Hash type is one byte tacked on to the end of the signature
942 if (vchSig.empty())
943 return false;
944 if (nHashType == 0)
945 nHashType = vchSig.back();
946 else if (nHashType != vchSig.back())
947 return false;
948 vchSig.pop_back();
950 return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
962 bool Solver(const CScript& scriptPubKey, vector<pair<opcodetype, valtype> >& vSolutionRet)
964 // Templates
965 static vector<CScript> vTemplates;
966 if (vTemplates.empty())
968 // Standard tx, sender provides pubkey, receiver adds signature
969 vTemplates.push_back(CScript() << OP_PUBKEY << OP_CHECKSIG);
971 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
972 vTemplates.push_back(CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG);
975 // Scan templates
976 const CScript& script1 = scriptPubKey;
977 foreach(const CScript& script2, vTemplates)
979 vSolutionRet.clear();
980 opcodetype opcode1, opcode2;
981 vector<unsigned char> vch1, vch2;
983 // Compare
984 CScript::const_iterator pc1 = script1.begin();
985 CScript::const_iterator pc2 = script2.begin();
986 loop
988 if (pc1 == script1.end() && pc2 == script2.end())
990 // Found a match
991 reverse(vSolutionRet.begin(), vSolutionRet.end());
992 return true;
994 if (!script1.GetOp(pc1, opcode1, vch1))
995 break;
996 if (!script2.GetOp(pc2, opcode2, vch2))
997 break;
998 if (opcode2 == OP_PUBKEY)
1000 if (vch1.size() < 33 || vch1.size() > 120)
1001 break;
1002 vSolutionRet.push_back(make_pair(opcode2, vch1));
1004 else if (opcode2 == OP_PUBKEYHASH)
1006 if (vch1.size() != sizeof(uint160))
1007 break;
1008 vSolutionRet.push_back(make_pair(opcode2, vch1));
1010 else if (opcode1 != opcode2 || vch1 != vch2)
1012 break;
1017 vSolutionRet.clear();
1018 return false;
1022 bool Solver(const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1024 scriptSigRet.clear();
1026 vector<pair<opcodetype, valtype> > vSolution;
1027 if (!Solver(scriptPubKey, vSolution))
1028 return false;
1030 // Compile solution
1031 CRITICAL_BLOCK(cs_mapKeys)
1033 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1035 if (item.first == OP_PUBKEY)
1037 // Sign
1038 const valtype& vchPubKey = item.second;
1039 if (!mapKeys.count(vchPubKey))
1040 return false;
1041 if (hash != 0)
1043 vector<unsigned char> vchSig;
1044 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1045 return false;
1046 vchSig.push_back((unsigned char)nHashType);
1047 scriptSigRet << vchSig;
1050 else if (item.first == OP_PUBKEYHASH)
1052 // Sign and give pubkey
1053 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1054 if (mi == mapPubKeys.end())
1055 return false;
1056 const vector<unsigned char>& vchPubKey = (*mi).second;
1057 if (!mapKeys.count(vchPubKey))
1058 return false;
1059 if (hash != 0)
1061 vector<unsigned char> vchSig;
1062 if (!CKey::Sign(mapKeys[vchPubKey], hash, vchSig))
1063 return false;
1064 vchSig.push_back((unsigned char)nHashType);
1065 scriptSigRet << vchSig << vchPubKey;
1068 else
1070 return false;
1075 return true;
1079 bool IsStandard(const CScript& scriptPubKey)
1081 vector<pair<opcodetype, valtype> > vSolution;
1082 return Solver(scriptPubKey, vSolution);
1086 bool IsMine(const CScript& scriptPubKey)
1088 CScript scriptSig;
1089 return Solver(scriptPubKey, 0, 0, scriptSig);
1093 bool ExtractPubKey(const CScript& scriptPubKey, bool fMineOnly, vector<unsigned char>& vchPubKeyRet)
1095 vchPubKeyRet.clear();
1097 vector<pair<opcodetype, valtype> > vSolution;
1098 if (!Solver(scriptPubKey, vSolution))
1099 return false;
1101 CRITICAL_BLOCK(cs_mapKeys)
1103 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1105 valtype vchPubKey;
1106 if (item.first == OP_PUBKEY)
1108 vchPubKey = item.second;
1110 else if (item.first == OP_PUBKEYHASH)
1112 map<uint160, valtype>::iterator mi = mapPubKeys.find(uint160(item.second));
1113 if (mi == mapPubKeys.end())
1114 continue;
1115 vchPubKey = (*mi).second;
1117 if (!fMineOnly || mapKeys.count(vchPubKey))
1119 vchPubKeyRet = vchPubKey;
1120 return true;
1124 return false;
1128 bool ExtractHash160(const CScript& scriptPubKey, uint160& hash160Ret)
1130 hash160Ret = 0;
1132 vector<pair<opcodetype, valtype> > vSolution;
1133 if (!Solver(scriptPubKey, vSolution))
1134 return false;
1136 foreach(PAIRTYPE(opcodetype, valtype)& item, vSolution)
1138 if (item.first == OP_PUBKEYHASH)
1140 hash160Ret = uint160(item.second);
1141 return true;
1144 return false;
1148 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int nHashType)
1150 vector<vector<unsigned char> > stack;
1151 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1152 return false;
1153 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1154 return false;
1155 if (stack.empty())
1156 return false;
1157 return CastToBool(stack.back());
1161 bool SignSignature(const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1163 assert(nIn < txTo.vin.size());
1164 CTxIn& txin = txTo.vin[nIn];
1165 assert(txin.prevout.n < txFrom.vout.size());
1166 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1168 // Leave out the signature from the hash, since a signature can't sign itself.
1169 // The checksig op will also drop the signatures from its hash.
1170 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1172 if (!Solver(txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1173 return false;
1175 txin.scriptSig = scriptPrereq + txin.scriptSig;
1177 // Test solution
1178 if (scriptPrereq.empty())
1179 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, 0))
1180 return false;
1182 return true;
1186 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int nHashType)
1188 assert(nIn < txTo.vin.size());
1189 const CTxIn& txin = txTo.vin[nIn];
1190 if (txin.prevout.n >= txFrom.vout.size())
1191 return false;
1192 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1194 if (txin.prevout.hash != txFrom.GetHash())
1195 return false;
1197 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nHashType))
1198 return false;
1200 // Anytime a signature is successfully verified, it's proof the outpoint is spent,
1201 // so lets update the wallet spent flag if it doesn't know due to wallet.dat being
1202 // restored from backup or the user making copies of wallet.dat.
1203 WalletUpdateSpent(txin.prevout);
1205 return true;