1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <boost/foreach.hpp>
6 #include <boost/tuple/tuple.hpp>
19 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
23 typedef vector<unsigned char> valtype;
24 static const valtype vchFalse(0);
25 static const valtype vchZero(0);
26 static const valtype vchTrue(1, 1);
27 static const CBigNum bnZero(0);
28 static const CBigNum bnOne(1);
29 static const CBigNum bnFalse(0);
30 static const CBigNum bnTrue(1);
31 static const size_t nMaxNumSize = 4;
34 CBigNum CastToBigNum(const valtype& vch)
36 if (vch.size() > nMaxNumSize)
37 throw runtime_error("CastToBigNum() : overflow");
38 // Get rid of extra leading zeros
39 return CBigNum(CBigNum(vch).getvch());
42 bool CastToBool(const valtype& vch)
44 for (unsigned int i = 0; i < vch.size(); i++)
48 // Can be negative zero
49 if (i == vch.size()-1 && vch[i] == 0x80)
57 void MakeSameSize(valtype& vch1, valtype& vch2)
59 // Lengthen the shorter one
60 if (vch1.size() < vch2.size())
61 vch1.resize(vch2.size(), 0);
62 if (vch2.size() < vch1.size())
63 vch2.resize(vch1.size(), 0);
69 // Script is a stack machine (like Forth) that evaluates a predicate
70 // returning a bool indicating valid or not. There are no loops.
72 #define stacktop(i) (stack.at(stack.size()+(i)))
73 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
74 static inline void popstack(vector<valtype>& stack)
77 throw runtime_error("popstack() : stack empty");
82 const char* GetTxnOutputType(txnouttype t)
86 case TX_NONSTANDARD: return "nonstandard";
87 case TX_PUBKEY: return "pubkey";
88 case TX_PUBKEYHASH: return "pubkeyhash";
89 case TX_SCRIPTHASH: return "scripthash";
90 case TX_MULTISIG: return "multisig";
96 const char* GetOpName(opcodetype opcode)
101 case OP_0 : return "0";
102 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
103 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
104 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
105 case OP_1NEGATE : return "-1";
106 case OP_RESERVED : return "OP_RESERVED";
107 case OP_1 : return "1";
108 case OP_2 : return "2";
109 case OP_3 : return "3";
110 case OP_4 : return "4";
111 case OP_5 : return "5";
112 case OP_6 : return "6";
113 case OP_7 : return "7";
114 case OP_8 : return "8";
115 case OP_9 : return "9";
116 case OP_10 : return "10";
117 case OP_11 : return "11";
118 case OP_12 : return "12";
119 case OP_13 : return "13";
120 case OP_14 : return "14";
121 case OP_15 : return "15";
122 case OP_16 : return "16";
125 case OP_NOP : return "OP_NOP";
126 case OP_VER : return "OP_VER";
127 case OP_IF : return "OP_IF";
128 case OP_NOTIF : return "OP_NOTIF";
129 case OP_VERIF : return "OP_VERIF";
130 case OP_VERNOTIF : return "OP_VERNOTIF";
131 case OP_ELSE : return "OP_ELSE";
132 case OP_ENDIF : return "OP_ENDIF";
133 case OP_VERIFY : return "OP_VERIFY";
134 case OP_RETURN : return "OP_RETURN";
137 case OP_TOALTSTACK : return "OP_TOALTSTACK";
138 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
139 case OP_2DROP : return "OP_2DROP";
140 case OP_2DUP : return "OP_2DUP";
141 case OP_3DUP : return "OP_3DUP";
142 case OP_2OVER : return "OP_2OVER";
143 case OP_2ROT : return "OP_2ROT";
144 case OP_2SWAP : return "OP_2SWAP";
145 case OP_IFDUP : return "OP_IFDUP";
146 case OP_DEPTH : return "OP_DEPTH";
147 case OP_DROP : return "OP_DROP";
148 case OP_DUP : return "OP_DUP";
149 case OP_NIP : return "OP_NIP";
150 case OP_OVER : return "OP_OVER";
151 case OP_PICK : return "OP_PICK";
152 case OP_ROLL : return "OP_ROLL";
153 case OP_ROT : return "OP_ROT";
154 case OP_SWAP : return "OP_SWAP";
155 case OP_TUCK : return "OP_TUCK";
158 case OP_CAT : return "OP_CAT";
159 case OP_SUBSTR : return "OP_SUBSTR";
160 case OP_LEFT : return "OP_LEFT";
161 case OP_RIGHT : return "OP_RIGHT";
162 case OP_SIZE : return "OP_SIZE";
165 case OP_INVERT : return "OP_INVERT";
166 case OP_AND : return "OP_AND";
167 case OP_OR : return "OP_OR";
168 case OP_XOR : return "OP_XOR";
169 case OP_EQUAL : return "OP_EQUAL";
170 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
171 case OP_RESERVED1 : return "OP_RESERVED1";
172 case OP_RESERVED2 : return "OP_RESERVED2";
175 case OP_1ADD : return "OP_1ADD";
176 case OP_1SUB : return "OP_1SUB";
177 case OP_2MUL : return "OP_2MUL";
178 case OP_2DIV : return "OP_2DIV";
179 case OP_NEGATE : return "OP_NEGATE";
180 case OP_ABS : return "OP_ABS";
181 case OP_NOT : return "OP_NOT";
182 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
183 case OP_ADD : return "OP_ADD";
184 case OP_SUB : return "OP_SUB";
185 case OP_MUL : return "OP_MUL";
186 case OP_DIV : return "OP_DIV";
187 case OP_MOD : return "OP_MOD";
188 case OP_LSHIFT : return "OP_LSHIFT";
189 case OP_RSHIFT : return "OP_RSHIFT";
190 case OP_BOOLAND : return "OP_BOOLAND";
191 case OP_BOOLOR : return "OP_BOOLOR";
192 case OP_NUMEQUAL : return "OP_NUMEQUAL";
193 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
194 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
195 case OP_LESSTHAN : return "OP_LESSTHAN";
196 case OP_GREATERTHAN : return "OP_GREATERTHAN";
197 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
198 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
199 case OP_MIN : return "OP_MIN";
200 case OP_MAX : return "OP_MAX";
201 case OP_WITHIN : return "OP_WITHIN";
204 case OP_RIPEMD160 : return "OP_RIPEMD160";
205 case OP_SHA1 : return "OP_SHA1";
206 case OP_SHA256 : return "OP_SHA256";
207 case OP_HASH160 : return "OP_HASH160";
208 case OP_HASH256 : return "OP_HASH256";
209 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
210 case OP_CHECKSIG : return "OP_CHECKSIG";
211 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
212 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
213 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
216 case OP_NOP1 : return "OP_NOP1";
217 case OP_NOP2 : return "OP_NOP2";
218 case OP_NOP3 : return "OP_NOP3";
219 case OP_NOP4 : return "OP_NOP4";
220 case OP_NOP5 : return "OP_NOP5";
221 case OP_NOP6 : return "OP_NOP6";
222 case OP_NOP7 : return "OP_NOP7";
223 case OP_NOP8 : return "OP_NOP8";
224 case OP_NOP9 : return "OP_NOP9";
225 case OP_NOP10 : return "OP_NOP10";
229 // template matching params
230 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
231 case OP_PUBKEY : return "OP_PUBKEY";
233 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
239 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
242 CScript::const_iterator pc = script.begin();
243 CScript::const_iterator pend = script.end();
244 CScript::const_iterator pbegincodehash = script.begin();
246 valtype vchPushValue;
248 vector<valtype> altstack;
249 if (script.size() > 10000)
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_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
325 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
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 >= (int)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 > (int)vch.size())
612 if (nEnd > (int)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 > (int)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 (unsigned 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 (unsigned int i = 0; i < vch1.size(); i++)
681 else if (opcode == OP_OR)
683 for (unsigned int i = 0; i < vch1.size(); i++)
686 else if (opcode == OP_XOR)
688 for (unsigned 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, pend);
922 // Drop the signature, since there's no way for a signature to sign itself
923 scriptCode.FindAndDelete(CScript(vchSig));
925 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
929 stack.push_back(fSuccess ? vchTrue : vchFalse);
930 if (opcode == OP_CHECKSIGVERIFY)
940 case OP_CHECKMULTISIG:
941 case OP_CHECKMULTISIGVERIFY:
943 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
946 if ((int)stack.size() < i)
949 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
950 if (nKeysCount < 0 || nKeysCount > 20)
952 nOpCount += nKeysCount;
957 if ((int)stack.size() < i)
960 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
961 if (nSigsCount < 0 || nSigsCount > nKeysCount)
965 if ((int)stack.size() < i)
968 // Subset of script starting at the most recent codeseparator
969 CScript scriptCode(pbegincodehash, pend);
971 // Drop the signatures, since there's no way for a signature to sign itself
972 for (int k = 0; k < nSigsCount; k++)
974 valtype& vchSig = stacktop(-isig-k);
975 scriptCode.FindAndDelete(CScript(vchSig));
978 bool fSuccess = true;
979 while (fSuccess && nSigsCount > 0)
981 valtype& vchSig = stacktop(-isig);
982 valtype& vchPubKey = stacktop(-ikey);
985 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
993 // If there are more signatures left than keys left,
994 // then too many signatures have failed
995 if (nSigsCount > nKeysCount)
1001 stack.push_back(fSuccess ? vchTrue : vchFalse);
1003 if (opcode == OP_CHECKMULTISIGVERIFY)
1018 if (stack.size() + altstack.size() > 1000)
1028 if (!vfExec.empty())
1042 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1044 if (nIn >= txTo.vin.size())
1046 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1049 CTransaction txTmp(txTo);
1051 // In case concatenating two scripts ends up with two codeseparators,
1052 // or an extra one at the end, this prevents all those possible incompatibilities.
1053 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1055 // Blank out other inputs' signatures
1056 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1057 txTmp.vin[i].scriptSig = CScript();
1058 txTmp.vin[nIn].scriptSig = scriptCode;
1060 // Blank out some of the outputs
1061 if ((nHashType & 0x1f) == SIGHASH_NONE)
1066 // Let the others update at will
1067 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1069 txTmp.vin[i].nSequence = 0;
1071 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1073 // Only lockin the txout payee at same index as txin
1074 unsigned int nOut = nIn;
1075 if (nOut >= txTmp.vout.size())
1077 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1080 txTmp.vout.resize(nOut+1);
1081 for (unsigned int i = 0; i < nOut; i++)
1082 txTmp.vout[i].SetNull();
1084 // Let the others update at will
1085 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1087 txTmp.vin[i].nSequence = 0;
1090 // Blank out other inputs completely, not recommended for open transactions
1091 if (nHashType & SIGHASH_ANYONECANPAY)
1093 txTmp.vin[0] = txTmp.vin[nIn];
1094 txTmp.vin.resize(1);
1097 // Serialize and hash
1098 CDataStream ss(SER_GETHASH, 0);
1100 ss << txTmp << nHashType;
1101 return Hash(ss.begin(), ss.end());
1105 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1106 // twice for every transaction (once when accepted into memory pool, and
1107 // again when accepted into the block chain)
1109 class CSignatureCache
1112 // sigdata_type is (signature hash, signature, public key):
1113 typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1114 std::set< sigdata_type> setValid;
1115 CCriticalSection cs_sigcache;
1119 Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1123 sigdata_type k(hash, vchSig, pubKey);
1124 std::set<sigdata_type>::iterator mi = setValid.find(k);
1125 if (mi != setValid.end())
1131 Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1133 // DoS prevention: limit cache size to less than 10MB
1134 // (~200 bytes per cache entry times 50,000 entries)
1135 // Since there are a maximum of 20,000 signature operations per block
1136 // 50,000 is a reasonable default.
1137 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1138 if (nMaxCacheSize <= 0) return;
1142 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1144 // Evict a random entry. Random because that helps
1145 // foil would-be DoS attackers who might try to pre-generate
1146 // and re-use a set of valid signatures just-slightly-greater
1147 // than our cache size.
1148 uint256 randomHash = GetRandHash();
1149 std::vector<unsigned char> unused;
1150 std::set<sigdata_type>::iterator it =
1151 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1152 if (it == setValid.end())
1153 it = setValid.begin();
1154 setValid.erase(*it);
1157 sigdata_type k(hash, vchSig, pubKey);
1162 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1163 const CTransaction& txTo, unsigned int nIn, int nHashType)
1165 static CSignatureCache signatureCache;
1167 // Hash type is one byte tacked on to the end of the signature
1171 nHashType = vchSig.back();
1172 else if (nHashType != vchSig.back())
1176 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1178 if (signatureCache.Get(sighash, vchSig, vchPubKey))
1182 if (!key.SetPubKey(vchPubKey))
1185 if (!key.Verify(sighash, vchSig))
1188 signatureCache.Set(sighash, vchSig, vchPubKey);
1201 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1203 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1206 static map<txnouttype, CScript> mTemplates;
1207 if (mTemplates.empty())
1209 // Standard tx, sender provides pubkey, receiver adds signature
1210 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1212 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1213 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1215 // Sender provides N pubkeys, receivers provides M signatures
1216 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1219 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1220 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1221 if (scriptPubKey.IsPayToScriptHash())
1223 typeRet = TX_SCRIPTHASH;
1224 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1225 vSolutionsRet.push_back(hashBytes);
1230 const CScript& script1 = scriptPubKey;
1231 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1233 const CScript& script2 = tplate.second;
1234 vSolutionsRet.clear();
1236 opcodetype opcode1, opcode2;
1237 vector<unsigned char> vch1, vch2;
1240 CScript::const_iterator pc1 = script1.begin();
1241 CScript::const_iterator pc2 = script2.begin();
1244 if (pc1 == script1.end() && pc2 == script2.end())
1247 typeRet = tplate.first;
1248 if (typeRet == TX_MULTISIG)
1250 // Additional checks for TX_MULTISIG:
1251 unsigned char m = vSolutionsRet.front()[0];
1252 unsigned char n = vSolutionsRet.back()[0];
1253 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1258 if (!script1.GetOp(pc1, opcode1, vch1))
1260 if (!script2.GetOp(pc2, opcode2, vch2))
1263 // Template matching opcodes:
1264 if (opcode2 == OP_PUBKEYS)
1266 while (vch1.size() >= 33 && vch1.size() <= 120)
1268 vSolutionsRet.push_back(vch1);
1269 if (!script1.GetOp(pc1, opcode1, vch1))
1272 if (!script2.GetOp(pc2, opcode2, vch2))
1274 // Normal situation is to fall through
1275 // to other if/else statments
1278 if (opcode2 == OP_PUBKEY)
1280 if (vch1.size() < 33 || vch1.size() > 120)
1282 vSolutionsRet.push_back(vch1);
1284 else if (opcode2 == OP_PUBKEYHASH)
1286 if (vch1.size() != sizeof(uint160))
1288 vSolutionsRet.push_back(vch1);
1290 else if (opcode2 == OP_SMALLINTEGER)
1291 { // Single-byte small integer pushed onto vSolutions
1292 if (opcode1 == OP_0 ||
1293 (opcode1 >= OP_1 && opcode1 <= OP_16))
1295 char n = (char)CScript::DecodeOP_N(opcode1);
1296 vSolutionsRet.push_back(valtype(1, n));
1301 else if (opcode1 != opcode2 || vch1 != vch2)
1303 // Others must match exactly
1309 vSolutionsRet.clear();
1310 typeRet = TX_NONSTANDARD;
1315 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1318 if (!keystore.GetKey(address, key))
1321 vector<unsigned char> vchSig;
1322 if (!key.Sign(hash, vchSig))
1324 vchSig.push_back((unsigned char)nHashType);
1325 scriptSigRet << vchSig;
1330 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1333 int nRequired = multisigdata.front()[0];
1334 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1336 const valtype& pubkey = *it;
1337 CKeyID keyID = CPubKey(pubkey).GetID();
1338 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1341 if (nSigned == nRequired) break;
1344 return nSigned==nRequired;
1348 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1349 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1350 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1351 // Returns false if scriptPubKey could not be completely satisified.
1353 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1354 CScript& scriptSigRet, txnouttype& whichTypeRet)
1356 scriptSigRet.clear();
1358 vector<valtype> vSolutions;
1359 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1363 switch (whichTypeRet)
1365 case TX_NONSTANDARD:
1368 keyID = CPubKey(vSolutions[0]).GetID();
1369 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1371 keyID = CKeyID(uint160(vSolutions[0]));
1372 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1377 keystore.GetPubKey(keyID, vch);
1378 scriptSigRet << vch;
1382 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1385 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1386 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1391 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1395 case TX_NONSTANDARD:
1402 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1404 return vSolutions[0][0] + 1;
1406 return 1; // doesn't include args needed by the script
1411 bool IsStandard(const CScript& scriptPubKey)
1413 vector<valtype> vSolutions;
1414 txnouttype whichType;
1415 if (!Solver(scriptPubKey, whichType, vSolutions))
1418 if (whichType == TX_MULTISIG)
1420 unsigned char m = vSolutions.front()[0];
1421 unsigned char n = vSolutions.back()[0];
1422 // Support up to x-of-3 multisig txns as standard
1429 return whichType != TX_NONSTANDARD;
1433 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1435 unsigned int nResult = 0;
1436 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1438 CKeyID keyID = CPubKey(pubkey).GetID();
1439 if (keystore.HaveKey(keyID))
1446 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1449 const CKeyStore *keystore;
1451 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1452 bool operator()(const CNoDestination &dest) const { return false; }
1453 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1454 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1457 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1459 return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1462 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1464 vector<valtype> vSolutions;
1465 txnouttype whichType;
1466 if (!Solver(scriptPubKey, whichType, vSolutions))
1472 case TX_NONSTANDARD:
1475 keyID = CPubKey(vSolutions[0]).GetID();
1476 return keystore.HaveKey(keyID);
1478 keyID = CKeyID(uint160(vSolutions[0]));
1479 return keystore.HaveKey(keyID);
1483 if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1485 return IsMine(keystore, subscript);
1489 // Only consider transactions "mine" if we own ALL the
1490 // keys involved. multi-signature transactions that are
1491 // partially owned (somebody else has a key that can spend
1492 // them) enable spend-out-from-under-you attacks, especially
1493 // in shared-wallet situations.
1494 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1495 return HaveKeys(keys, keystore) == keys.size();
1501 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1503 vector<valtype> vSolutions;
1504 txnouttype whichType;
1505 if (!Solver(scriptPubKey, whichType, vSolutions))
1508 if (whichType == TX_PUBKEY)
1510 addressRet = CPubKey(vSolutions[0]).GetID();
1513 else if (whichType == TX_PUBKEYHASH)
1515 addressRet = CKeyID(uint160(vSolutions[0]));
1518 else if (whichType == TX_SCRIPTHASH)
1520 addressRet = CScriptID(uint160(vSolutions[0]));
1523 // Multisig txns have more than one address...
1527 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1530 typeRet = TX_NONSTANDARD;
1531 vector<valtype> vSolutions;
1532 if (!Solver(scriptPubKey, typeRet, vSolutions))
1535 if (typeRet == TX_MULTISIG)
1537 nRequiredRet = vSolutions.front()[0];
1538 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1540 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1541 addressRet.push_back(address);
1547 CTxDestination address;
1548 if (!ExtractDestination(scriptPubKey, address))
1550 addressRet.push_back(address);
1556 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1557 bool fValidatePayToScriptHash, int nHashType)
1559 vector<vector<unsigned char> > stack, stackCopy;
1560 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1562 if (fValidatePayToScriptHash)
1564 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1569 if (CastToBool(stack.back()) == false)
1572 // Additional validation for spend-to-script-hash transactions:
1573 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1575 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1576 return false; // or validation fails
1578 const valtype& pubKeySerialized = stackCopy.back();
1579 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1580 popstack(stackCopy);
1582 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
1584 if (stackCopy.empty())
1586 return CastToBool(stackCopy.back());
1593 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1595 assert(nIn < txTo.vin.size());
1596 CTxIn& txin = txTo.vin[nIn];
1598 // Leave out the signature from the hash, since a signature can't sign itself.
1599 // The checksig op will also drop the signatures from its hash.
1600 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1602 txnouttype whichType;
1603 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1606 if (whichType == TX_SCRIPTHASH)
1608 // Solver returns the subscript that need to be evaluated;
1609 // the final scriptSig is the signatures from that
1610 // and then the serialized subscript:
1611 CScript subscript = txin.scriptSig;
1613 // Recompute txn hash using subscript in place of scriptPubKey:
1614 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1616 if (!Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType))
1618 if (subType == TX_SCRIPTHASH)
1620 txin.scriptSig << static_cast<valtype>(subscript); // Append serialized subscript
1624 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, 0);
1627 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1629 assert(nIn < txTo.vin.size());
1630 CTxIn& txin = txTo.vin[nIn];
1631 assert(txin.prevout.n < txFrom.vout.size());
1632 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1634 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1637 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
1639 assert(nIn < txTo.vin.size());
1640 const CTxIn& txin = txTo.vin[nIn];
1641 if (txin.prevout.n >= txFrom.vout.size())
1643 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1645 if (txin.prevout.hash != txFrom.GetHash())
1648 return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType);
1651 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1654 const_iterator pc = begin();
1655 opcodetype lastOpcode = OP_INVALIDOPCODE;
1659 if (!GetOp(pc, opcode))
1661 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1663 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1665 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1666 n += DecodeOP_N(lastOpcode);
1670 lastOpcode = opcode;
1675 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1677 if (!IsPayToScriptHash())
1678 return GetSigOpCount(true);
1680 // This is a pay-to-script-hash scriptPubKey;
1681 // get the last item that the scriptSig
1682 // pushes onto the stack:
1683 const_iterator pc = scriptSig.begin();
1684 vector<unsigned char> data;
1685 while (pc < scriptSig.end())
1688 if (!scriptSig.GetOp(pc, opcode, data))
1694 /// ... and return it's opcount:
1695 CScript subscript(data.begin(), data.end());
1696 return subscript.GetSigOpCount(true);
1699 bool CScript::IsPayToScriptHash() const
1701 // Extra-fast test for pay-to-script-hash CScripts:
1702 return (this->size() == 23 &&
1703 this->at(0) == OP_HASH160 &&
1704 this->at(1) == 0x14 &&
1705 this->at(22) == OP_EQUAL);
1708 class CScriptVisitor : public boost::static_visitor<bool>
1713 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1715 bool operator()(const CNoDestination &dest) const {
1720 bool operator()(const CKeyID &keyID) const {
1722 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1726 bool operator()(const CScriptID &scriptID) const {
1728 *script << OP_HASH160 << scriptID << OP_EQUAL;
1733 void CScript::SetDestination(const CTxDestination& dest)
1735 boost::apply_visitor(CScriptVisitor(this), dest);
1738 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1742 *this << EncodeOP_N(nRequired);
1743 BOOST_FOREACH(const CKey& key, keys)
1744 *this << key.GetPubKey();
1745 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;