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* GetTxnTypeName(txntype 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";
235 // Returns true if script is valid.
237 bool EvalScriptInner(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType,
238 CScript::const_iterator pbegincodehash, CScript::const_iterator pendcodehash, int& nOpCount, int& nSigOpCount, 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)
1017 // This code should be removed when OP_EVAL has
1018 // a majority of hashing power on the network.
1019 // OP_EVAL behaves just like OP_NOP until
1021 if (!fTestNet || fDebug)
1023 // 1328054400 is Feb 1, 2012
1024 int64 nEvalSwitchTime = GetArg("opevaltime", 1328054400);
1025 if (GetTime() < nEvalSwitchTime)
1029 // Evaluate the top item on the stack as a Script
1030 // [serialized script ] -- [result(s) of executing script]
1031 if (stack.size() < 1)
1033 valtype& vchScript = stacktop(-1);
1034 CScript subscript(vchScript.begin(), vchScript.end());
1037 // Codeseparators not allowed
1038 if (subscript.Find(OP_CODESEPARATOR))
1041 if (!EvalScriptInner(stack, subscript, txTo, nIn, nHashType,
1042 pbegincodehash, pendcodehash, nOpCount, nSigOpCount, nRecurseDepth++))
1052 if (stack.size() + altstack.size() > 1000)
1062 if (!vfExec.empty())
1068 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script,
1069 const CTransaction& txTo, unsigned int nIn, int nHashType, int& nSigOpCountRet)
1071 CScript::const_iterator pbegincodehash = script.begin();
1072 CScript::const_iterator pendcodehash = script.end();
1075 return EvalScriptInner(stack, script, txTo, nIn, nHashType, pbegincodehash, pendcodehash,
1076 nOpCount, nSigOpCountRet, 0);
1087 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1089 if (nIn >= txTo.vin.size())
1091 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1094 CTransaction txTmp(txTo);
1096 // In case concatenating two scripts ends up with two codeseparators,
1097 // or an extra one at the end, this prevents all those possible incompatibilities.
1098 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1100 // Blank out other inputs' signatures
1101 for (int i = 0; i < txTmp.vin.size(); i++)
1102 txTmp.vin[i].scriptSig = CScript();
1103 txTmp.vin[nIn].scriptSig = scriptCode;
1105 // Blank out some of the outputs
1106 if ((nHashType & 0x1f) == SIGHASH_NONE)
1111 // Let the others update at will
1112 for (int i = 0; i < txTmp.vin.size(); i++)
1114 txTmp.vin[i].nSequence = 0;
1116 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1118 // Only lockin the txout payee at same index as txin
1119 unsigned int nOut = nIn;
1120 if (nOut >= txTmp.vout.size())
1122 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1125 txTmp.vout.resize(nOut+1);
1126 for (int i = 0; i < nOut; i++)
1127 txTmp.vout[i].SetNull();
1129 // Let the others update at will
1130 for (int i = 0; i < txTmp.vin.size(); i++)
1132 txTmp.vin[i].nSequence = 0;
1135 // Blank out other inputs completely, not recommended for open transactions
1136 if (nHashType & SIGHASH_ANYONECANPAY)
1138 txTmp.vin[0] = txTmp.vin[nIn];
1139 txTmp.vin.resize(1);
1142 // Serialize and hash
1143 CDataStream ss(SER_GETHASH);
1145 ss << txTmp << nHashType;
1146 return Hash(ss.begin(), ss.end());
1150 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1151 const CTransaction& txTo, unsigned int nIn, int nHashType)
1154 if (!key.SetPubKey(vchPubKey))
1157 // Hash type is one byte tacked on to the end of the signature
1161 nHashType = vchSig.back();
1162 else if (nHashType != vchSig.back())
1166 return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
1178 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1180 bool Solver(const CScript& scriptPubKey, txntype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1183 static map<txntype, CScript> mTemplates;
1184 if (mTemplates.empty())
1186 // Standard tx, sender provides pubkey, receiver adds signature
1187 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1189 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1190 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1192 // Sender provides N pubkeys, receivers provides M signatures
1193 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1195 // Sender provides script hash, receiver provides script and
1196 // as many signatures as required to satisfy script
1197 mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_DUP << OP_HASH160 << OP_SCRIPTHASH << OP_EQUALVERIFY << OP_EVAL));
1201 const CScript& script1 = scriptPubKey;
1202 BOOST_FOREACH(const PAIRTYPE(txntype, CScript)& tplate, mTemplates)
1204 const CScript& script2 = tplate.second;
1205 vSolutionsRet.clear();
1207 opcodetype opcode1, opcode2;
1208 vector<unsigned char> vch1, vch2;
1211 CScript::const_iterator pc1 = script1.begin();
1212 CScript::const_iterator pc2 = script2.begin();
1215 if (pc1 == script1.end() && pc2 == script2.end())
1218 typeRet = tplate.first;
1219 if (typeRet == TX_MULTISIG)
1221 // Additional checks for TX_MULTISIG:
1222 unsigned char m = vSolutionsRet.front()[0];
1223 unsigned char n = vSolutionsRet.back()[0];
1224 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1229 if (!script1.GetOp(pc1, opcode1, vch1))
1231 if (!script2.GetOp(pc2, opcode2, vch2))
1234 // Template matching opcodes:
1235 if (opcode2 == OP_PUBKEYS)
1237 while (vch1.size() >= 33 && vch1.size() <= 120)
1239 vSolutionsRet.push_back(vch1);
1240 if (!script1.GetOp(pc1, opcode1, vch1))
1243 if (!script2.GetOp(pc2, opcode2, vch2))
1245 // Normal situation is to fall through
1246 // to other if/else statments
1249 if (opcode2 == OP_PUBKEY)
1251 if (vch1.size() < 33 || vch1.size() > 120)
1253 vSolutionsRet.push_back(vch1);
1255 else if (opcode2 == OP_PUBKEYHASH)
1257 if (vch1.size() != sizeof(uint160))
1259 vSolutionsRet.push_back(vch1);
1261 else if (opcode2 == OP_SCRIPTHASH)
1263 if (vch1.size() != sizeof(uint160))
1265 vSolutionsRet.push_back(vch1);
1267 else if (opcode2 == OP_SMALLINTEGER)
1268 { // Single-byte small integer pushed onto vSolutions
1269 if (opcode1 == OP_0 ||
1270 (opcode1 >= OP_1 && opcode1 <= OP_16))
1272 char n = (char)CScript::DecodeOP_N(opcode1);
1273 vSolutionsRet.push_back(valtype(1, n));
1278 else if (opcode1 != opcode2 || vch1 != vch2)
1280 // Others must match exactly
1286 vSolutionsRet.clear();
1287 typeRet = TX_NONSTANDARD;
1292 bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1295 if (!keystore.GetKey(address, key))
1298 vector<unsigned char> vchSig;
1299 if (!key.Sign(hash, vchSig))
1301 vchSig.push_back((unsigned char)nHashType);
1302 scriptSigRet << vchSig;
1307 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1310 int nRequired = multisigdata.front()[0];
1311 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1313 const valtype& pubkey = *it;
1314 CBitcoinAddress address;
1315 address.SetPubKey(pubkey);
1316 if (Sign1(address, keystore, hash, nHashType, scriptSigRet))
1319 if (nSigned == nRequired) break;
1322 return nSigned==nRequired;
1326 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1327 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed).
1328 // Returns true if scriptPubKey could be completely satisified.
1330 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1332 scriptSigRet.clear();
1335 vector<valtype> vSolutions;
1336 if (!Solver(scriptPubKey, whichType, vSolutions))
1339 CBitcoinAddress address;
1343 case TX_NONSTANDARD:
1346 address.SetPubKey(vSolutions[0]);
1347 return Sign1(address, keystore, hash, nHashType, scriptSigRet);
1349 address.SetHash160(uint160(vSolutions[0]));
1350 if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
1355 keystore.GetPubKey(address, vch);
1356 scriptSigRet << vch;
1360 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1362 if (!Solver(keystore, CScript(subscript.begin(), subscript.end()), hash, nHashType, scriptSigRet))
1365 scriptSigRet << subscript; // signatures AND serialized script
1368 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1369 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1375 bool IsStandard(const CScript& scriptPubKey)
1377 vector<valtype> vSolutions;
1379 if (!Solver(scriptPubKey, whichType, vSolutions))
1382 if (whichType == TX_MULTISIG)
1384 unsigned char m = vSolutions.front()[0];
1385 unsigned char n = vSolutions.back()[0];
1386 // Support up to x-of-3 multisig txns as standard
1393 return whichType != TX_NONSTANDARD;
1397 int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1400 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1402 CBitcoinAddress address;
1403 address.SetPubKey(pubkey);
1404 if (keystore.HaveKey(address))
1410 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1412 vector<valtype> vSolutions;
1414 if (!Solver(scriptPubKey, whichType, vSolutions))
1417 CBitcoinAddress address;
1420 case TX_NONSTANDARD:
1423 address.SetPubKey(vSolutions[0]);
1424 return keystore.HaveKey(address);
1426 address.SetHash160(uint160(vSolutions[0]));
1427 return keystore.HaveKey(address);
1431 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1433 return IsMine(keystore, CScript(subscript.begin(), subscript.end()));
1437 // Only consider transactions "mine" if we own ALL the
1438 // keys involved. multi-signature transactions that are
1439 // partially owned (somebody else has a key that can spend
1440 // them) enable spend-out-from-under-you attacks, especially
1441 // in shared-wallet situations.
1442 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1443 return HaveKeys(vSolutions, keystore);
1449 bool ExtractAddress(const CScript& scriptPubKey, const CKeyStore* keystore, CBitcoinAddress& addressRet)
1451 vector<valtype> vSolutions;
1453 if (!Solver(scriptPubKey, whichType, vSolutions))
1456 if (whichType == TX_PUBKEY)
1458 addressRet.SetPubKey(vSolutions[0]);
1461 else if (whichType == TX_PUBKEYHASH)
1463 addressRet.SetHash160(uint160(vSolutions[0]));
1466 else if (whichType == TX_SCRIPTHASH)
1468 addressRet.SetScriptHash160(uint160(vSolutions[0]));
1471 // Multisig txns have more than one address...
1475 bool ExtractAddresses(const CScript& scriptPubKey, const CKeyStore* keystore, txntype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
1478 typeRet = TX_NONSTANDARD;
1479 vector<valtype> vSolutions;
1480 if (!Solver(scriptPubKey, typeRet, vSolutions))
1483 if (typeRet == TX_MULTISIG)
1485 nRequiredRet = vSolutions.front()[0];
1486 int n = vSolutions.back()[0];
1487 for (vector<valtype>::const_iterator it = vSolutions.begin()+1; it != vSolutions.begin()+vSolutions.size()-1; it++)
1489 CBitcoinAddress address;
1490 address.SetPubKey(*it);
1491 addressRet.push_back(address);
1497 CBitcoinAddress address;
1498 if (typeRet == TX_PUBKEYHASH)
1499 address.SetHash160(uint160(vSolutions.front()));
1500 else if (typeRet == TX_SCRIPTHASH)
1501 address.SetScriptHash160(uint160(vSolutions.front()));
1502 else if (typeRet == TX_PUBKEY)
1503 address.SetPubKey(vSolutions.front());
1504 addressRet.push_back(address);
1510 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
1512 vector<vector<unsigned char> > stack;
1513 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType, nSigOpCountRet))
1515 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType, nSigOpCountRet))
1519 bool fResult = CastToBool(stack.back());
1521 // This code should be removed when a compatibility-breaking block chain split has passed.
1522 // Special check for OP_EVAL backwards-compatibility: if scriptPubKey or scriptSig contains
1523 // OP_EVAL, then result must be identical if OP_EVAL is treated as a no-op:
1524 if (scriptSig.Find(OP_EVAL)+scriptPubKey.Find(OP_EVAL) > 0)
1528 CScript sigCopy = scriptSig;
1529 sigCopy.FindAndDelete(CScript(OP_EVAL));
1530 CScript pubKeyCopy = scriptPubKey;
1531 pubKeyCopy.FindAndDelete(CScript(OP_EVAL));
1533 if (!EvalScript(stack, sigCopy, txTo, nIn, nHashType, nUnused))
1535 if (!EvalScript(stack, pubKeyCopy, txTo, nIn, nHashType, nUnused))
1539 if (fResult != CastToBool(stack.back()))
1547 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1549 assert(nIn < txTo.vin.size());
1550 CTxIn& txin = txTo.vin[nIn];
1551 assert(txin.prevout.n < txFrom.vout.size());
1552 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1554 // Leave out the signature from the hash, since a signature can't sign itself.
1555 // The checksig op will also drop the signatures from its hash.
1556 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1558 if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1561 txin.scriptSig = scriptPrereq + txin.scriptSig;
1565 if (scriptPrereq.empty())
1566 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nUnused, 0))
1573 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
1575 assert(nIn < txTo.vin.size());
1576 const CTxIn& txin = txTo.vin[nIn];
1577 if (txin.prevout.n >= txFrom.vout.size())
1579 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1581 if (txin.prevout.hash != txFrom.GetHash())
1584 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType))
1590 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
1593 if (address.IsScript())
1594 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_EVAL;
1596 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
1599 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1603 *this << EncodeOP_N(nRequired);
1604 BOOST_FOREACH(const CKey& key, keys)
1605 *this << key.GetPubKey();
1606 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1609 void CScript::SetEval(const CScript& subscript)
1611 assert(!subscript.empty());
1612 uint160 subscriptHash = Hash160(subscript);
1614 *this << OP_DUP << OP_HASH160 << subscriptHash << OP_EQUALVERIFY << OP_EVAL;