1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
10 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
14 typedef vector<unsigned char> valtype;
15 static const valtype vchFalse(0);
16 static const valtype vchZero(0);
17 static const valtype vchTrue(1, 1);
18 static const CBigNum bnZero(0);
19 static const CBigNum bnOne(1);
20 static const CBigNum bnFalse(0);
21 static const CBigNum bnTrue(1);
22 static const size_t nMaxNumSize = 4;
25 CBigNum CastToBigNum(const valtype& vch)
27 if (vch.size() > nMaxNumSize)
28 throw runtime_error("CastToBigNum() : overflow");
29 // Get rid of extra leading zeros
30 return CBigNum(CBigNum(vch).getvch());
33 bool CastToBool(const valtype& vch)
35 for (int i = 0; i < vch.size(); i++)
39 // Can be negative zero
40 if (i == vch.size()-1 && vch[i] == 0x80)
48 void MakeSameSize(valtype& vch1, valtype& vch2)
50 // Lengthen the shorter one
51 if (vch1.size() < vch2.size())
52 vch1.resize(vch2.size(), 0);
53 if (vch2.size() < vch1.size())
54 vch2.resize(vch1.size(), 0);
60 // Script is a stack machine (like Forth) that evaluates a predicate
61 // returning a bool indicating valid or not. There are no loops.
63 #define stacktop(i) (stack.at(stack.size()+(i)))
64 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
65 static inline void popstack(vector<valtype>& stack)
68 throw runtime_error("popstack() : stack empty");
73 const char* GetTxnOutputType(txnouttype t)
77 case TX_NONSTANDARD: return "nonstandard";
78 case TX_PUBKEY: return "pubkey";
79 case TX_PUBKEYHASH: return "pubkeyhash";
80 case TX_SCRIPTHASH: return "scripthash";
81 case TX_MULTISIG: return "multisig";
87 const char* GetOpName(opcodetype opcode)
92 case OP_0 : return "0";
93 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
94 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
95 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
96 case OP_1NEGATE : return "-1";
97 case OP_RESERVED : return "OP_RESERVED";
98 case OP_1 : return "1";
99 case OP_2 : return "2";
100 case OP_3 : return "3";
101 case OP_4 : return "4";
102 case OP_5 : return "5";
103 case OP_6 : return "6";
104 case OP_7 : return "7";
105 case OP_8 : return "8";
106 case OP_9 : return "9";
107 case OP_10 : return "10";
108 case OP_11 : return "11";
109 case OP_12 : return "12";
110 case OP_13 : return "13";
111 case OP_14 : return "14";
112 case OP_15 : return "15";
113 case OP_16 : return "16";
116 case OP_NOP : return "OP_NOP";
117 case OP_VER : return "OP_VER";
118 case OP_IF : return "OP_IF";
119 case OP_NOTIF : return "OP_NOTIF";
120 case OP_VERIF : return "OP_VERIF";
121 case OP_VERNOTIF : return "OP_VERNOTIF";
122 case OP_ELSE : return "OP_ELSE";
123 case OP_ENDIF : return "OP_ENDIF";
124 case OP_VERIFY : return "OP_VERIFY";
125 case OP_RETURN : return "OP_RETURN";
128 case OP_TOALTSTACK : return "OP_TOALTSTACK";
129 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
130 case OP_2DROP : return "OP_2DROP";
131 case OP_2DUP : return "OP_2DUP";
132 case OP_3DUP : return "OP_3DUP";
133 case OP_2OVER : return "OP_2OVER";
134 case OP_2ROT : return "OP_2ROT";
135 case OP_2SWAP : return "OP_2SWAP";
136 case OP_IFDUP : return "OP_IFDUP";
137 case OP_DEPTH : return "OP_DEPTH";
138 case OP_DROP : return "OP_DROP";
139 case OP_DUP : return "OP_DUP";
140 case OP_NIP : return "OP_NIP";
141 case OP_OVER : return "OP_OVER";
142 case OP_PICK : return "OP_PICK";
143 case OP_ROLL : return "OP_ROLL";
144 case OP_ROT : return "OP_ROT";
145 case OP_SWAP : return "OP_SWAP";
146 case OP_TUCK : return "OP_TUCK";
149 case OP_CAT : return "OP_CAT";
150 case OP_SUBSTR : return "OP_SUBSTR";
151 case OP_LEFT : return "OP_LEFT";
152 case OP_RIGHT : return "OP_RIGHT";
153 case OP_SIZE : return "OP_SIZE";
156 case OP_INVERT : return "OP_INVERT";
157 case OP_AND : return "OP_AND";
158 case OP_OR : return "OP_OR";
159 case OP_XOR : return "OP_XOR";
160 case OP_EQUAL : return "OP_EQUAL";
161 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
162 case OP_RESERVED1 : return "OP_RESERVED1";
163 case OP_RESERVED2 : return "OP_RESERVED2";
166 case OP_1ADD : return "OP_1ADD";
167 case OP_1SUB : return "OP_1SUB";
168 case OP_2MUL : return "OP_2MUL";
169 case OP_2DIV : return "OP_2DIV";
170 case OP_NEGATE : return "OP_NEGATE";
171 case OP_ABS : return "OP_ABS";
172 case OP_NOT : return "OP_NOT";
173 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
174 case OP_ADD : return "OP_ADD";
175 case OP_SUB : return "OP_SUB";
176 case OP_MUL : return "OP_MUL";
177 case OP_DIV : return "OP_DIV";
178 case OP_MOD : return "OP_MOD";
179 case OP_LSHIFT : return "OP_LSHIFT";
180 case OP_RSHIFT : return "OP_RSHIFT";
181 case OP_BOOLAND : return "OP_BOOLAND";
182 case OP_BOOLOR : return "OP_BOOLOR";
183 case OP_NUMEQUAL : return "OP_NUMEQUAL";
184 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
185 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
186 case OP_LESSTHAN : return "OP_LESSTHAN";
187 case OP_GREATERTHAN : return "OP_GREATERTHAN";
188 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
189 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
190 case OP_MIN : return "OP_MIN";
191 case OP_MAX : return "OP_MAX";
192 case OP_WITHIN : return "OP_WITHIN";
195 case OP_RIPEMD160 : return "OP_RIPEMD160";
196 case OP_SHA1 : return "OP_SHA1";
197 case OP_SHA256 : return "OP_SHA256";
198 case OP_HASH160 : return "OP_HASH160";
199 case OP_HASH256 : return "OP_HASH256";
200 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
201 case OP_CHECKSIG : return "OP_CHECKSIG";
202 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
203 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
204 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
207 case OP_EVAL : return "OP_EVAL";
210 case OP_NOP2 : return "OP_NOP2";
211 case OP_NOP3 : return "OP_NOP3";
212 case OP_NOP4 : return "OP_NOP4";
213 case OP_NOP5 : return "OP_NOP5";
214 case OP_NOP6 : return "OP_NOP6";
215 case OP_NOP7 : return "OP_NOP7";
216 case OP_NOP8 : return "OP_NOP8";
217 case OP_NOP9 : return "OP_NOP9";
218 case OP_NOP10 : return "OP_NOP10";
222 // template matching params
223 case OP_SCRIPTHASH : return "OP_SCRIPTHASH";
224 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
225 case OP_PUBKEY : return "OP_PUBKEY";
227 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
234 // Returns true if script is valid.
236 bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
237 CScript::const_iterator pbegincodehash, CScript::const_iterator pendcodehash, int& nOpCount, int& nSigOpCount,
238 bool fStrictOpEval, int nRecurseDepth)
241 CScript::const_iterator pc = script.begin();
242 CScript::const_iterator pend = script.end();
244 valtype vchPushValue;
246 vector<valtype> altstack;
247 if (script.size() > 10000)
250 // Limit OP_EVAL recursion
251 if (nRecurseDepth > 2)
258 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
263 if (!script.GetOp(pc, opcode, vchPushValue))
265 if (vchPushValue.size() > 520)
267 if (opcode > OP_16 && ++nOpCount > 201)
270 if (opcode == OP_CAT ||
271 opcode == OP_SUBSTR ||
273 opcode == OP_RIGHT ||
274 opcode == OP_INVERT ||
283 opcode == OP_LSHIFT ||
287 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
288 stack.push_back(vchPushValue);
289 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
314 CBigNum bn((int)opcode - (int)(OP_1 - 1));
315 stack.push_back(bn.getvch());
324 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:
331 // <expression> if [statements] [else [statements]] endif
335 if (stack.size() < 1)
337 valtype& vch = stacktop(-1);
338 fValue = CastToBool(vch);
339 if (opcode == OP_NOTIF)
343 vfExec.push_back(fValue);
351 vfExec.back() = !vfExec.back();
366 // (false -- false) and return
367 if (stack.size() < 1)
369 bool fValue = CastToBool(stacktop(-1));
389 if (stack.size() < 1)
391 altstack.push_back(stacktop(-1));
396 case OP_FROMALTSTACK:
398 if (altstack.size() < 1)
400 stack.push_back(altstacktop(-1));
408 if (stack.size() < 2)
417 // (x1 x2 -- x1 x2 x1 x2)
418 if (stack.size() < 2)
420 valtype vch1 = stacktop(-2);
421 valtype vch2 = stacktop(-1);
422 stack.push_back(vch1);
423 stack.push_back(vch2);
429 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
430 if (stack.size() < 3)
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);
443 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
444 if (stack.size() < 4)
446 valtype vch1 = stacktop(-4);
447 valtype vch2 = stacktop(-3);
448 stack.push_back(vch1);
449 stack.push_back(vch2);
455 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
456 if (stack.size() < 6)
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);
468 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
469 if (stack.size() < 4)
471 swap(stacktop(-4), stacktop(-2));
472 swap(stacktop(-3), stacktop(-1));
479 if (stack.size() < 1)
481 valtype vch = stacktop(-1);
483 stack.push_back(vch);
490 CBigNum bn(stack.size());
491 stack.push_back(bn.getvch());
498 if (stack.size() < 1)
507 if (stack.size() < 1)
509 valtype vch = stacktop(-1);
510 stack.push_back(vch);
517 if (stack.size() < 2)
519 stack.erase(stack.end() - 2);
525 // (x1 x2 -- x1 x2 x1)
526 if (stack.size() < 2)
528 valtype vch = stacktop(-2);
529 stack.push_back(vch);
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)
540 int n = CastToBigNum(stacktop(-1)).getint();
542 if (n < 0 || n >= stack.size())
544 valtype vch = stacktop(-n-1);
545 if (opcode == OP_ROLL)
546 stack.erase(stack.end()-n-1);
547 stack.push_back(vch);
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)
558 swap(stacktop(-3), stacktop(-2));
559 swap(stacktop(-2), stacktop(-1));
566 if (stack.size() < 2)
568 swap(stacktop(-2), stacktop(-1));
574 // (x1 x2 -- x2 x1 x2)
575 if (stack.size() < 2)
577 valtype vch = stacktop(-1);
578 stack.insert(stack.end()-2, vch);
589 if (stack.size() < 2)
591 valtype& vch1 = stacktop(-2);
592 valtype& vch2 = stacktop(-1);
593 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
595 if (stacktop(-1).size() > 520)
602 // (in begin size -- out)
603 if (stack.size() < 3)
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)
610 if (nBegin > vch.size())
612 if (nEnd > vch.size())
614 vch.erase(vch.begin() + nEnd, vch.end());
615 vch.erase(vch.begin(), vch.begin() + nBegin);
625 if (stack.size() < 2)
627 valtype& vch = stacktop(-2);
628 int nSize = CastToBigNum(stacktop(-1)).getint();
631 if (nSize > vch.size())
633 if (opcode == OP_LEFT)
634 vch.erase(vch.begin() + nSize, vch.end());
636 vch.erase(vch.begin(), vch.end() - nSize);
644 if (stack.size() < 1)
646 CBigNum bn(stacktop(-1).size());
647 stack.push_back(bn.getvch());
658 if (stack.size() < 1)
660 valtype& vch = stacktop(-1);
661 for (int i = 0; i < vch.size(); i++)
671 if (stack.size() < 2)
673 valtype& vch1 = stacktop(-2);
674 valtype& vch2 = stacktop(-1);
675 MakeSameSize(vch1, vch2);
676 if (opcode == OP_AND)
678 for (int i = 0; i < vch1.size(); i++)
681 else if (opcode == OP_OR)
683 for (int i = 0; i < vch1.size(); i++)
686 else if (opcode == OP_XOR)
688 for (int i = 0; i < vch1.size(); i++)
697 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
700 if (stack.size() < 2)
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)
712 stack.push_back(fEqual ? vchTrue : vchFalse);
713 if (opcode == OP_EQUALVERIFY)
737 if (stack.size() < 1)
739 CBigNum bn = CastToBigNum(stacktop(-1));
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;
753 stack.push_back(bn.getvch());
767 case OP_NUMEQUALVERIFY:
771 case OP_LESSTHANOREQUAL:
772 case OP_GREATERTHANOREQUAL:
777 if (stack.size() < 2)
779 CBigNum bn1 = CastToBigNum(stacktop(-2));
780 CBigNum bn2 = CastToBigNum(stacktop(-1));
793 if (!BN_mul(&bn, &bn1, &bn2, pctx))
798 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
803 if (!BN_mod(&bn, &bn1, &bn2, pctx))
808 if (bn2 < bnZero || bn2 > CBigNum(2048))
810 bn = bn1 << bn2.getulong();
814 if (bn2 < bnZero || bn2 > CBigNum(2048))
816 bn = bn1 >> bn2.getulong();
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;
834 stack.push_back(bn.getvch());
836 if (opcode == OP_NUMEQUALVERIFY)
838 if (CastToBool(stacktop(-1)))
848 // (x min max -- out)
849 if (stack.size() < 3)
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);
858 stack.push_back(fValue ? vchTrue : vchFalse);
873 if (stack.size() < 1)
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));
894 stack.push_back(vchHash);
898 case OP_CODESEPARATOR:
900 // Hash starts after the code separator
906 case OP_CHECKSIGVERIFY:
908 // (sig pubkey -- bool)
909 if (stack.size() < 2)
912 valtype& vchSig = stacktop(-2);
913 valtype& vchPubKey = stacktop(-1);
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, pendcodehash);
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);
930 stack.push_back(fSuccess ? vchTrue : vchFalse);
931 if (opcode == OP_CHECKSIGVERIFY)
941 case OP_CHECKMULTISIG:
942 case OP_CHECKMULTISIGVERIFY:
944 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
947 if (stack.size() < i)
950 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
951 if (nKeysCount < 0 || nKeysCount > 20)
953 nOpCount += nKeysCount;
958 if (stack.size() < i)
961 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
962 if (nSigsCount < 0 || nSigsCount > nKeysCount)
966 if (stack.size() < i)
969 // Subset of script starting at the most recent codeseparator
970 CScript scriptCode(pbegincodehash, pendcodehash);
972 // Drop the signatures, since there's no way for a signature to sign itself
973 for (int k = 0; k < nSigsCount; k++)
975 valtype& vchSig = stacktop(-isig-k);
976 scriptCode.FindAndDelete(CScript(vchSig));
979 bool fSuccess = true;
980 while (fSuccess && nSigsCount > 0)
982 valtype& vchSig = stacktop(-isig);
983 valtype& vchPubKey = stacktop(-ikey);
986 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
995 // If there are more signatures left than keys left,
996 // then too many signatures have failed
997 if (nSigsCount > nKeysCount)
1003 stack.push_back(fSuccess ? vchTrue : vchFalse);
1005 if (opcode == OP_CHECKMULTISIGVERIFY)
1018 break; // Act as a NO_OP
1021 // Evaluate the top item on the stack as a Script
1022 // [serialized script ] -- [result(s) of executing script]
1023 if (stack.size() < 1)
1025 valtype& vchScript = stacktop(-1);
1026 CScript subscript(vchScript.begin(), vchScript.end());
1029 // Codeseparators not allowed; they don't make sense 'inside' an OP_EVAL, because
1030 // their purpose is to change which parts of the scriptPubKey script is copied
1031 // and signed by OP_CHECKSIG, but OP_EVAl'ed code is in the scriptSig, not the scriptPubKey.
1032 if (subscript.Find(OP_CODESEPARATOR))
1035 if (!EvalScriptInner(stack, subscript, txTo, nIn, nHashType,
1036 pbegincodehash, pendcodehash, nOpCount, nSigOpCount, fStrictOpEval, nRecurseDepth++))
1046 if (stack.size() + altstack.size() > 1000)
1056 if (!vfExec.empty())
1062 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script,
1063 const CTransaction& txTo, unsigned int nIn, int nHashType,
1064 bool fStrictOpEval, int& nSigOpCountRet)
1066 CScript::const_iterator pbegincodehash = script.begin();
1067 CScript::const_iterator pendcodehash = script.end();
1070 return EvalScriptInner(stack, script, txTo, nIn, nHashType, pbegincodehash, pendcodehash,
1071 nOpCount, nSigOpCountRet, fStrictOpEval, 0);
1082 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1084 if (nIn >= txTo.vin.size())
1086 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1089 CTransaction txTmp(txTo);
1091 // In case concatenating two scripts ends up with two codeseparators,
1092 // or an extra one at the end, this prevents all those possible incompatibilities.
1093 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1095 // Blank out other inputs' signatures
1096 for (int i = 0; i < txTmp.vin.size(); i++)
1097 txTmp.vin[i].scriptSig = CScript();
1098 txTmp.vin[nIn].scriptSig = scriptCode;
1100 // Blank out some of the outputs
1101 if ((nHashType & 0x1f) == SIGHASH_NONE)
1106 // Let the others update at will
1107 for (int i = 0; i < txTmp.vin.size(); i++)
1109 txTmp.vin[i].nSequence = 0;
1111 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1113 // Only lockin the txout payee at same index as txin
1114 unsigned int nOut = nIn;
1115 if (nOut >= txTmp.vout.size())
1117 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1120 txTmp.vout.resize(nOut+1);
1121 for (int i = 0; i < nOut; i++)
1122 txTmp.vout[i].SetNull();
1124 // Let the others update at will
1125 for (int i = 0; i < txTmp.vin.size(); i++)
1127 txTmp.vin[i].nSequence = 0;
1130 // Blank out other inputs completely, not recommended for open transactions
1131 if (nHashType & SIGHASH_ANYONECANPAY)
1133 txTmp.vin[0] = txTmp.vin[nIn];
1134 txTmp.vin.resize(1);
1137 // Serialize and hash
1138 CDataStream ss(SER_GETHASH);
1140 ss << txTmp << nHashType;
1141 return Hash(ss.begin(), ss.end());
1145 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1146 const CTransaction& txTo, unsigned int nIn, int nHashType)
1149 if (!key.SetPubKey(vchPubKey))
1152 // Hash type is one byte tacked on to the end of the signature
1156 nHashType = vchSig.back();
1157 else if (nHashType != vchSig.back())
1161 return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
1173 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1175 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1178 static map<txnouttype, CScript> mTemplates;
1179 if (mTemplates.empty())
1181 // Standard tx, sender provides pubkey, receiver adds signature
1182 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1184 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1185 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1187 // Sender provides N pubkeys, receivers provides M signatures
1188 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1190 // Sender provides script hash, receiver provides script and
1191 // as many signatures as required to satisfy script
1192 mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_DUP << OP_HASH160 << OP_SCRIPTHASH << OP_EQUALVERIFY << OP_EVAL));
1196 const CScript& script1 = scriptPubKey;
1197 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1199 const CScript& script2 = tplate.second;
1200 vSolutionsRet.clear();
1202 opcodetype opcode1, opcode2;
1203 vector<unsigned char> vch1, vch2;
1206 CScript::const_iterator pc1 = script1.begin();
1207 CScript::const_iterator pc2 = script2.begin();
1210 if (pc1 == script1.end() && pc2 == script2.end())
1213 typeRet = tplate.first;
1214 if (typeRet == TX_MULTISIG)
1216 // Additional checks for TX_MULTISIG:
1217 unsigned char m = vSolutionsRet.front()[0];
1218 unsigned char n = vSolutionsRet.back()[0];
1219 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1224 if (!script1.GetOp(pc1, opcode1, vch1))
1226 if (!script2.GetOp(pc2, opcode2, vch2))
1229 // Template matching opcodes:
1230 if (opcode2 == OP_PUBKEYS)
1232 while (vch1.size() >= 33 && vch1.size() <= 120)
1234 vSolutionsRet.push_back(vch1);
1235 if (!script1.GetOp(pc1, opcode1, vch1))
1238 if (!script2.GetOp(pc2, opcode2, vch2))
1240 // Normal situation is to fall through
1241 // to other if/else statments
1244 if (opcode2 == OP_PUBKEY)
1246 if (vch1.size() < 33 || vch1.size() > 120)
1248 vSolutionsRet.push_back(vch1);
1250 else if (opcode2 == OP_PUBKEYHASH)
1252 if (vch1.size() != sizeof(uint160))
1254 vSolutionsRet.push_back(vch1);
1256 else if (opcode2 == OP_SCRIPTHASH)
1258 if (vch1.size() != sizeof(uint160))
1260 vSolutionsRet.push_back(vch1);
1262 else if (opcode2 == OP_SMALLINTEGER)
1263 { // Single-byte small integer pushed onto vSolutions
1264 if (opcode1 == OP_0 ||
1265 (opcode1 >= OP_1 && opcode1 <= OP_16))
1267 char n = (char)CScript::DecodeOP_N(opcode1);
1268 vSolutionsRet.push_back(valtype(1, n));
1273 else if (opcode1 != opcode2 || vch1 != vch2)
1275 // Others must match exactly
1281 vSolutionsRet.clear();
1282 typeRet = TX_NONSTANDARD;
1287 bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1290 if (!keystore.GetKey(address, key))
1293 vector<unsigned char> vchSig;
1294 if (!key.Sign(hash, vchSig))
1296 vchSig.push_back((unsigned char)nHashType);
1297 scriptSigRet << vchSig;
1302 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1305 int nRequired = multisigdata.front()[0];
1306 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1308 const valtype& pubkey = *it;
1309 CBitcoinAddress address;
1310 address.SetPubKey(pubkey);
1311 if (Sign1(address, keystore, hash, nHashType, scriptSigRet))
1314 if (nSigned == nRequired) break;
1317 return nSigned==nRequired;
1321 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1322 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed).
1323 // Returns true if scriptPubKey could be completely satisified.
1325 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1327 scriptSigRet.clear();
1329 txnouttype whichType;
1330 vector<valtype> vSolutions;
1331 if (!Solver(scriptPubKey, whichType, vSolutions))
1334 CBitcoinAddress address;
1338 case TX_NONSTANDARD:
1341 address.SetPubKey(vSolutions[0]);
1342 return Sign1(address, keystore, hash, nHashType, scriptSigRet);
1344 address.SetHash160(uint160(vSolutions[0]));
1345 if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
1350 keystore.GetPubKey(address, vch);
1351 scriptSigRet << vch;
1355 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1357 if (!Solver(keystore, subscript, hash, nHashType, scriptSigRet))
1360 // static_cast to get vector.operator<< instead of CScript.operator<<
1361 scriptSigRet << static_cast<valtype>(subscript); // signatures AND serialized script
1364 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1365 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1371 bool IsStandard(const CScript& scriptPubKey)
1373 vector<valtype> vSolutions;
1374 txnouttype whichType;
1375 if (!Solver(scriptPubKey, whichType, vSolutions))
1378 if (whichType == TX_MULTISIG)
1380 unsigned char m = vSolutions.front()[0];
1381 unsigned char n = vSolutions.back()[0];
1382 // Support up to x-of-3 multisig txns as standard
1389 return whichType != TX_NONSTANDARD;
1393 int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1396 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1398 CBitcoinAddress address;
1399 address.SetPubKey(pubkey);
1400 if (keystore.HaveKey(address))
1406 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1408 vector<valtype> vSolutions;
1409 txnouttype whichType;
1410 if (!Solver(scriptPubKey, whichType, vSolutions))
1413 CBitcoinAddress address;
1416 case TX_NONSTANDARD:
1419 address.SetPubKey(vSolutions[0]);
1420 return keystore.HaveKey(address);
1422 address.SetHash160(uint160(vSolutions[0]));
1423 return keystore.HaveKey(address);
1427 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1429 return IsMine(keystore, subscript);
1433 // Only consider transactions "mine" if we own ALL the
1434 // keys involved. multi-signature transactions that are
1435 // partially owned (somebody else has a key that can spend
1436 // them) enable spend-out-from-under-you attacks, especially
1437 // in shared-wallet situations.
1438 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1439 return HaveKeys(vSolutions, keystore);
1445 bool ExtractAddress(const CScript& scriptPubKey, const CKeyStore* keystore, CBitcoinAddress& addressRet)
1447 vector<valtype> vSolutions;
1448 txnouttype whichType;
1449 if (!Solver(scriptPubKey, whichType, vSolutions))
1452 if (whichType == TX_PUBKEY)
1454 addressRet.SetPubKey(vSolutions[0]);
1457 else if (whichType == TX_PUBKEYHASH)
1459 addressRet.SetHash160(uint160(vSolutions[0]));
1462 else if (whichType == TX_SCRIPTHASH)
1464 addressRet.SetScriptHash160(uint160(vSolutions[0]));
1467 // Multisig txns have more than one address...
1471 bool ExtractAddresses(const CScript& scriptPubKey, const CKeyStore* keystore, txnouttype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
1474 typeRet = TX_NONSTANDARD;
1475 vector<valtype> vSolutions;
1476 if (!Solver(scriptPubKey, typeRet, vSolutions))
1479 if (typeRet == TX_MULTISIG)
1481 nRequiredRet = vSolutions.front()[0];
1482 int n = vSolutions.back()[0];
1483 for (int i = 1; i < vSolutions.size()-1; i++)
1485 CBitcoinAddress address;
1486 address.SetPubKey(vSolutions[i]);
1487 addressRet.push_back(address);
1493 CBitcoinAddress address;
1494 if (typeRet == TX_PUBKEYHASH)
1495 address.SetHash160(uint160(vSolutions.front()));
1496 else if (typeRet == TX_SCRIPTHASH)
1497 address.SetScriptHash160(uint160(vSolutions.front()));
1498 else if (typeRet == TX_PUBKEY)
1499 address.SetPubKey(vSolutions.front());
1500 addressRet.push_back(address);
1506 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet,
1507 int nHashType, bool fStrictOpEval)
1509 vector<vector<unsigned char> > stack;
1510 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType, fStrictOpEval, nSigOpCountRet))
1512 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType, fStrictOpEval, nSigOpCountRet))
1516 bool fResult = CastToBool(stack.back());
1518 // This code should be removed when a compatibility-breaking block chain split has passed.
1519 // Special check for OP_EVAL backwards-compatibility: if scriptPubKey or scriptSig contains
1520 // OP_EVAL, then result must be identical if OP_EVAL is treated as a no-op:
1521 if (fResult && fStrictOpEval && (scriptPubKey.Find(OP_EVAL) || scriptSig.Find(OP_EVAL)))
1522 return VerifyScript(scriptSig, scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType, false);
1528 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1530 assert(nIn < txTo.vin.size());
1531 CTxIn& txin = txTo.vin[nIn];
1532 assert(txin.prevout.n < txFrom.vout.size());
1533 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1535 // Leave out the signature from the hash, since a signature can't sign itself.
1536 // The checksig op will also drop the signatures from its hash.
1537 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1539 if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1542 txin.scriptSig = scriptPrereq + txin.scriptSig;
1546 if (scriptPrereq.empty())
1547 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nUnused, 0, true))
1554 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType, bool fStrictOpEval)
1556 assert(nIn < txTo.vin.size());
1557 const CTxIn& txin = txTo.vin[nIn];
1558 if (txin.prevout.n >= txFrom.vout.size())
1560 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1562 if (txin.prevout.hash != txFrom.GetHash())
1565 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType, fStrictOpEval))
1571 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
1574 if (address.IsScript())
1575 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_EVAL;
1577 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
1580 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1584 *this << EncodeOP_N(nRequired);
1585 BOOST_FOREACH(const CKey& key, keys)
1586 *this << key.GetPubKey();
1587 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1590 void CScript::SetEval(const CScript& subscript)
1592 assert(!subscript.empty());
1593 uint160 subscriptHash = Hash160(subscript);
1595 *this << OP_DUP << OP_HASH160 << subscriptHash << OP_EQUALVERIFY << OP_EVAL;