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 // Evaluate the top item on the stack as a Script
1018 // [serialized script ] -- [result(s) of executing script]
1019 if (stack.size() < 1)
1021 valtype& vchScript = stacktop(-1);
1022 CScript subscript(vchScript.begin(), vchScript.end());
1025 // Codeseparators not allowed
1026 if (subscript.Find(OP_CODESEPARATOR))
1029 if (!EvalScriptInner(stack, subscript, txTo, nIn, nHashType,
1030 pbegincodehash, pendcodehash, nOpCount, nSigOpCount, nRecurseDepth++))
1040 if (stack.size() + altstack.size() > 1000)
1050 if (!vfExec.empty())
1056 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script,
1057 const CTransaction& txTo, unsigned int nIn, int nHashType, int& nSigOpCountRet)
1059 CScript::const_iterator pbegincodehash = script.begin();
1060 CScript::const_iterator pendcodehash = script.end();
1063 return EvalScriptInner(stack, script, txTo, nIn, nHashType, pbegincodehash, pendcodehash,
1064 nOpCount, nSigOpCountRet, 0);
1075 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1077 if (nIn >= txTo.vin.size())
1079 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1082 CTransaction txTmp(txTo);
1084 // In case concatenating two scripts ends up with two codeseparators,
1085 // or an extra one at the end, this prevents all those possible incompatibilities.
1086 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1088 // Blank out other inputs' signatures
1089 for (int i = 0; i < txTmp.vin.size(); i++)
1090 txTmp.vin[i].scriptSig = CScript();
1091 txTmp.vin[nIn].scriptSig = scriptCode;
1093 // Blank out some of the outputs
1094 if ((nHashType & 0x1f) == SIGHASH_NONE)
1099 // Let the others update at will
1100 for (int i = 0; i < txTmp.vin.size(); i++)
1102 txTmp.vin[i].nSequence = 0;
1104 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1106 // Only lockin the txout payee at same index as txin
1107 unsigned int nOut = nIn;
1108 if (nOut >= txTmp.vout.size())
1110 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1113 txTmp.vout.resize(nOut+1);
1114 for (int i = 0; i < nOut; i++)
1115 txTmp.vout[i].SetNull();
1117 // Let the others update at will
1118 for (int i = 0; i < txTmp.vin.size(); i++)
1120 txTmp.vin[i].nSequence = 0;
1123 // Blank out other inputs completely, not recommended for open transactions
1124 if (nHashType & SIGHASH_ANYONECANPAY)
1126 txTmp.vin[0] = txTmp.vin[nIn];
1127 txTmp.vin.resize(1);
1130 // Serialize and hash
1131 CDataStream ss(SER_GETHASH);
1133 ss << txTmp << nHashType;
1134 return Hash(ss.begin(), ss.end());
1138 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1139 const CTransaction& txTo, unsigned int nIn, int nHashType)
1142 if (!key.SetPubKey(vchPubKey))
1145 // Hash type is one byte tacked on to the end of the signature
1149 nHashType = vchSig.back();
1150 else if (nHashType != vchSig.back())
1154 return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
1166 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1168 bool Solver(const CScript& scriptPubKey, txntype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1171 static map<txntype, CScript> mTemplates;
1172 if (mTemplates.empty())
1174 // Standard tx, sender provides pubkey, receiver adds signature
1175 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1177 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1178 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1180 // Sender provides N pubkeys, receivers provides M signatures
1181 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1183 // Sender provides script hash, receiver provides script and
1184 // as many signatures as required to satisfy script
1185 mTemplates.insert(make_pair(TX_SCRIPTHASH, CScript() << OP_DUP << OP_HASH160 << OP_SCRIPTHASH << OP_EQUALVERIFY << OP_EVAL));
1189 const CScript& script1 = scriptPubKey;
1190 BOOST_FOREACH(const PAIRTYPE(txntype, CScript)& tplate, mTemplates)
1192 const CScript& script2 = tplate.second;
1193 vSolutionsRet.clear();
1195 opcodetype opcode1, opcode2;
1196 vector<unsigned char> vch1, vch2;
1199 CScript::const_iterator pc1 = script1.begin();
1200 CScript::const_iterator pc2 = script2.begin();
1203 if (pc1 == script1.end() && pc2 == script2.end())
1206 typeRet = tplate.first;
1207 if (typeRet == TX_MULTISIG)
1209 // Additional checks for TX_MULTISIG:
1210 unsigned char m = vSolutionsRet.front()[0];
1211 unsigned char n = vSolutionsRet.back()[0];
1212 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1217 if (!script1.GetOp(pc1, opcode1, vch1))
1219 if (!script2.GetOp(pc2, opcode2, vch2))
1222 // Template matching opcodes:
1223 if (opcode2 == OP_PUBKEYS)
1225 while (vch1.size() >= 33 && vch1.size() <= 120)
1227 vSolutionsRet.push_back(vch1);
1228 if (!script1.GetOp(pc1, opcode1, vch1))
1231 if (!script2.GetOp(pc2, opcode2, vch2))
1233 // Normal situation is to fall through
1234 // to other if/else statments
1237 if (opcode2 == OP_PUBKEY)
1239 if (vch1.size() < 33 || vch1.size() > 120)
1241 vSolutionsRet.push_back(vch1);
1243 else if (opcode2 == OP_PUBKEYHASH)
1245 if (vch1.size() != sizeof(uint160))
1247 vSolutionsRet.push_back(vch1);
1249 else if (opcode2 == OP_SCRIPTHASH)
1251 if (vch1.size() != sizeof(uint160))
1253 vSolutionsRet.push_back(vch1);
1255 else if (opcode2 == OP_SMALLINTEGER)
1256 { // Single-byte small integer pushed onto vSolutions
1257 if (opcode1 == OP_0 ||
1258 (opcode1 >= OP_1 && opcode1 <= OP_16))
1260 char n = (char)CScript::DecodeOP_N(opcode1);
1261 vSolutionsRet.push_back(valtype(1, n));
1266 else if (opcode1 != opcode2 || vch1 != vch2)
1268 // Others must match exactly
1274 vSolutionsRet.clear();
1275 typeRet = TX_NONSTANDARD;
1280 bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1283 if (!keystore.GetKey(address, key))
1286 vector<unsigned char> vchSig;
1287 if (!key.Sign(hash, vchSig))
1289 vchSig.push_back((unsigned char)nHashType);
1290 scriptSigRet << vchSig;
1295 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1298 int nRequired = multisigdata.front()[0];
1299 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1301 const valtype& pubkey = *it;
1302 CBitcoinAddress address;
1303 address.SetPubKey(pubkey);
1304 if (Sign1(address, keystore, hash, nHashType, scriptSigRet))
1307 if (nSigned == nRequired) break;
1310 return nSigned==nRequired;
1314 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1315 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed).
1316 // Returns true if scriptPubKey could be completely satisified.
1318 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, CScript& scriptSigRet)
1320 scriptSigRet.clear();
1323 vector<valtype> vSolutions;
1324 if (!Solver(scriptPubKey, whichType, vSolutions))
1327 CBitcoinAddress address;
1331 case TX_NONSTANDARD:
1334 address.SetPubKey(vSolutions[0]);
1335 return Sign1(address, keystore, hash, nHashType, scriptSigRet);
1337 address.SetHash160(uint160(vSolutions[0]));
1338 if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
1343 keystore.GetPubKey(address, vch);
1344 scriptSigRet << vch;
1348 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1350 if (!Solver(keystore, CScript(subscript.begin(), subscript.end()), hash, nHashType, scriptSigRet))
1353 scriptSigRet << subscript; // signatures AND serialized script
1356 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1357 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1363 bool IsStandard(const CScript& scriptPubKey)
1365 vector<valtype> vSolutions;
1367 if (!Solver(scriptPubKey, whichType, vSolutions))
1370 if (whichType == TX_MULTISIG)
1372 unsigned char m = vSolutions.front()[0];
1373 unsigned char n = vSolutions.back()[0];
1374 // Support up to x-of-3 multisig txns as standard
1381 return whichType != TX_NONSTANDARD;
1385 int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1388 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1390 CBitcoinAddress address;
1391 address.SetPubKey(pubkey);
1392 if (keystore.HaveKey(address))
1398 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1400 vector<valtype> vSolutions;
1402 if (!Solver(scriptPubKey, whichType, vSolutions))
1405 CBitcoinAddress address;
1408 case TX_NONSTANDARD:
1411 address.SetPubKey(vSolutions[0]);
1412 return keystore.HaveKey(address);
1414 address.SetHash160(uint160(vSolutions[0]));
1415 return keystore.HaveKey(address);
1419 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1421 return IsMine(keystore, CScript(subscript.begin(), subscript.end()));
1425 // Only consider transactions "mine" if we own ALL the
1426 // keys involved. multi-signature transactions that are
1427 // partially owned (somebody else has a key that can spend
1428 // them) enable spend-out-from-under-you attacks, especially
1429 // in shared-wallet situations.
1430 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1431 return HaveKeys(vSolutions, keystore);
1437 bool ExtractAddress(const CScript& scriptPubKey, const CKeyStore* keystore, CBitcoinAddress& addressRet)
1439 vector<valtype> vSolutions;
1441 if (!Solver(scriptPubKey, whichType, vSolutions))
1444 if (whichType == TX_PUBKEY)
1446 addressRet.SetPubKey(vSolutions[0]);
1449 else if (whichType == TX_PUBKEYHASH)
1451 addressRet.SetHash160(uint160(vSolutions[0]));
1454 else if (whichType == TX_SCRIPTHASH)
1456 addressRet.SetScriptHash160(uint160(vSolutions[0]));
1459 // Multisig txns have more than one address...
1463 bool ExtractAddresses(const CScript& scriptPubKey, const CKeyStore* keystore, txntype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
1466 typeRet = TX_NONSTANDARD;
1467 vector<valtype> vSolutions;
1468 if (!Solver(scriptPubKey, typeRet, vSolutions))
1471 if (typeRet == TX_MULTISIG)
1473 nRequiredRet = vSolutions.front()[0];
1474 int n = vSolutions.back()[0];
1475 for (vector<valtype>::const_iterator it = vSolutions.begin()+1; it != vSolutions.begin()+vSolutions.size()-1; it++)
1477 CBitcoinAddress address;
1478 address.SetPubKey(*it);
1479 addressRet.push_back(address);
1485 CBitcoinAddress address;
1486 if (typeRet == TX_PUBKEYHASH)
1487 address.SetHash160(uint160(vSolutions.front()));
1488 else if (typeRet == TX_SCRIPTHASH)
1489 address.SetScriptHash160(uint160(vSolutions.front()));
1490 else if (typeRet == TX_PUBKEY)
1491 address.SetPubKey(vSolutions.front());
1492 addressRet.push_back(address);
1498 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
1500 vector<vector<unsigned char> > stack;
1501 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType, nSigOpCountRet))
1503 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType, nSigOpCountRet))
1507 bool fResult = CastToBool(stack.back());
1509 // This code should be removed when a compatibility-breaking block chain split has passed.
1510 // Special check for OP_EVAL backwards-compatibility: if scriptPubKey or scriptSig contains
1511 // OP_EVAL, then result must be identical if OP_EVAL is treated as a no-op:
1512 if (scriptSig.Find(OP_EVAL)+scriptPubKey.Find(OP_EVAL) > 0)
1516 CScript sigCopy = scriptSig;
1517 sigCopy.FindAndDelete(CScript(OP_EVAL));
1518 CScript pubKeyCopy = scriptPubKey;
1519 pubKeyCopy.FindAndDelete(CScript(OP_EVAL));
1521 if (!EvalScript(stack, sigCopy, txTo, nIn, nHashType, nUnused))
1523 if (!EvalScript(stack, pubKeyCopy, txTo, nIn, nHashType, nUnused))
1527 if (fResult != CastToBool(stack.back()))
1535 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType, CScript scriptPrereq)
1537 assert(nIn < txTo.vin.size());
1538 CTxIn& txin = txTo.vin[nIn];
1539 assert(txin.prevout.n < txFrom.vout.size());
1540 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1542 // Leave out the signature from the hash, since a signature can't sign itself.
1543 // The checksig op will also drop the signatures from its hash.
1544 uint256 hash = SignatureHash(scriptPrereq + txout.scriptPubKey, txTo, nIn, nHashType);
1546 if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig))
1549 txin.scriptSig = scriptPrereq + txin.scriptSig;
1553 if (scriptPrereq.empty())
1554 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nUnused, 0))
1561 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, int& nSigOpCountRet, int nHashType)
1563 assert(nIn < txTo.vin.size());
1564 const CTxIn& txin = txTo.vin[nIn];
1565 if (txin.prevout.n >= txFrom.vout.size())
1567 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1569 if (txin.prevout.hash != txFrom.GetHash())
1572 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, nSigOpCountRet, nHashType))
1578 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
1581 if (address.IsScript())
1582 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_EVAL;
1584 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
1587 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1591 *this << EncodeOP_N(nRequired);
1592 BOOST_FOREACH(const CKey& key, keys)
1593 *this << key.GetPubKey();
1594 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1597 void CScript::SetEval(const CScript& subscript)
1599 assert(!subscript.empty());
1600 uint160 subscriptHash = Hash160(subscript);
1602 *this << OP_DUP << OP_HASH160 << subscriptHash << OP_EQUALVERIFY << OP_EVAL;