1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #include <boost/foreach.hpp>
7 #include <boost/tuple/tuple.hpp>
10 using namespace boost;
19 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
23 static const valtype vchFalse(0);
24 static const valtype vchZero(0);
25 static const valtype vchTrue(1, 1);
26 static const CBigNum bnZero(0);
27 static const CBigNum bnOne(1);
28 static const CBigNum bnFalse(0);
29 static const CBigNum bnTrue(1);
30 static const size_t nMaxNumSize = 4;
33 CBigNum CastToBigNum(const valtype& vch)
35 if (vch.size() > nMaxNumSize)
36 throw runtime_error("CastToBigNum() : overflow");
37 // Get rid of extra leading zeros
38 return CBigNum(CBigNum(vch).getvch());
41 bool CastToBool(const valtype& vch)
43 for (unsigned int i = 0; i < vch.size(); i++)
47 // Can be negative zero
48 if (i == vch.size()-1 && vch[i] == 0x80)
56 void MakeSameSize(valtype& vch1, valtype& vch2)
58 // Lengthen the shorter one
59 if (vch1.size() < vch2.size())
60 vch1.resize(vch2.size(), 0);
61 if (vch2.size() < vch1.size())
62 vch2.resize(vch1.size(), 0);
68 // Script is a stack machine (like Forth) that evaluates a predicate
69 // returning a bool indicating valid or not. There are no loops.
71 #define stacktop(i) (stack.at(stack.size()+(i)))
72 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
73 static inline void popstack(vector<valtype>& stack)
76 throw runtime_error("popstack() : stack empty");
81 const char* GetTxnOutputType(txnouttype t)
85 case TX_NONSTANDARD: return "nonstandard";
86 case TX_PUBKEY: return "pubkey";
87 case TX_PUBKEYHASH: return "pubkeyhash";
88 case TX_SCRIPTHASH: return "scripthash";
89 case TX_MULTISIG: return "multisig";
95 const char* GetOpName(opcodetype opcode)
100 case OP_0 : return "0";
101 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
102 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
103 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
104 case OP_1NEGATE : return "-1";
105 case OP_RESERVED : return "OP_RESERVED";
106 case OP_1 : return "1";
107 case OP_2 : return "2";
108 case OP_3 : return "3";
109 case OP_4 : return "4";
110 case OP_5 : return "5";
111 case OP_6 : return "6";
112 case OP_7 : return "7";
113 case OP_8 : return "8";
114 case OP_9 : return "9";
115 case OP_10 : return "10";
116 case OP_11 : return "11";
117 case OP_12 : return "12";
118 case OP_13 : return "13";
119 case OP_14 : return "14";
120 case OP_15 : return "15";
121 case OP_16 : return "16";
124 case OP_NOP : return "OP_NOP";
125 case OP_VER : return "OP_VER";
126 case OP_IF : return "OP_IF";
127 case OP_NOTIF : return "OP_NOTIF";
128 case OP_VERIF : return "OP_VERIF";
129 case OP_VERNOTIF : return "OP_VERNOTIF";
130 case OP_ELSE : return "OP_ELSE";
131 case OP_ENDIF : return "OP_ENDIF";
132 case OP_VERIFY : return "OP_VERIFY";
133 case OP_RETURN : return "OP_RETURN";
136 case OP_TOALTSTACK : return "OP_TOALTSTACK";
137 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
138 case OP_2DROP : return "OP_2DROP";
139 case OP_2DUP : return "OP_2DUP";
140 case OP_3DUP : return "OP_3DUP";
141 case OP_2OVER : return "OP_2OVER";
142 case OP_2ROT : return "OP_2ROT";
143 case OP_2SWAP : return "OP_2SWAP";
144 case OP_IFDUP : return "OP_IFDUP";
145 case OP_DEPTH : return "OP_DEPTH";
146 case OP_DROP : return "OP_DROP";
147 case OP_DUP : return "OP_DUP";
148 case OP_NIP : return "OP_NIP";
149 case OP_OVER : return "OP_OVER";
150 case OP_PICK : return "OP_PICK";
151 case OP_ROLL : return "OP_ROLL";
152 case OP_ROT : return "OP_ROT";
153 case OP_SWAP : return "OP_SWAP";
154 case OP_TUCK : return "OP_TUCK";
157 case OP_CAT : return "OP_CAT";
158 case OP_SUBSTR : return "OP_SUBSTR";
159 case OP_LEFT : return "OP_LEFT";
160 case OP_RIGHT : return "OP_RIGHT";
161 case OP_SIZE : return "OP_SIZE";
164 case OP_INVERT : return "OP_INVERT";
165 case OP_AND : return "OP_AND";
166 case OP_OR : return "OP_OR";
167 case OP_XOR : return "OP_XOR";
168 case OP_EQUAL : return "OP_EQUAL";
169 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
170 case OP_RESERVED1 : return "OP_RESERVED1";
171 case OP_RESERVED2 : return "OP_RESERVED2";
174 case OP_1ADD : return "OP_1ADD";
175 case OP_1SUB : return "OP_1SUB";
176 case OP_2MUL : return "OP_2MUL";
177 case OP_2DIV : return "OP_2DIV";
178 case OP_NEGATE : return "OP_NEGATE";
179 case OP_ABS : return "OP_ABS";
180 case OP_NOT : return "OP_NOT";
181 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
182 case OP_ADD : return "OP_ADD";
183 case OP_SUB : return "OP_SUB";
184 case OP_MUL : return "OP_MUL";
185 case OP_DIV : return "OP_DIV";
186 case OP_MOD : return "OP_MOD";
187 case OP_LSHIFT : return "OP_LSHIFT";
188 case OP_RSHIFT : return "OP_RSHIFT";
189 case OP_BOOLAND : return "OP_BOOLAND";
190 case OP_BOOLOR : return "OP_BOOLOR";
191 case OP_NUMEQUAL : return "OP_NUMEQUAL";
192 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
193 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
194 case OP_LESSTHAN : return "OP_LESSTHAN";
195 case OP_GREATERTHAN : return "OP_GREATERTHAN";
196 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
197 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
198 case OP_MIN : return "OP_MIN";
199 case OP_MAX : return "OP_MAX";
200 case OP_WITHIN : return "OP_WITHIN";
203 case OP_RIPEMD160 : return "OP_RIPEMD160";
204 case OP_SHA1 : return "OP_SHA1";
205 case OP_SHA256 : return "OP_SHA256";
206 case OP_HASH160 : return "OP_HASH160";
207 case OP_HASH256 : return "OP_HASH256";
208 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
209 case OP_CHECKSIG : return "OP_CHECKSIG";
210 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
211 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
212 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
215 case OP_NOP1 : return "OP_NOP1";
216 case OP_NOP2 : return "OP_NOP2";
217 case OP_NOP3 : return "OP_NOP3";
218 case OP_NOP4 : return "OP_NOP4";
219 case OP_NOP5 : return "OP_NOP5";
220 case OP_NOP6 : return "OP_NOP6";
221 case OP_NOP7 : return "OP_NOP7";
222 case OP_NOP8 : return "OP_NOP8";
223 case OP_NOP9 : return "OP_NOP9";
224 case OP_NOP10 : return "OP_NOP10";
228 // template matching params
229 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
230 case OP_PUBKEY : return "OP_PUBKEY";
232 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
238 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
241 CScript::const_iterator pc = script.begin();
242 CScript::const_iterator pend = script.end();
243 CScript::const_iterator pbegincodehash = script.begin();
245 valtype vchPushValue;
247 vector<valtype> altstack;
248 if (script.size() > 10000)
257 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
262 if (!script.GetOp(pc, opcode, vchPushValue))
264 if (vchPushValue.size() > 520)
266 if (opcode > OP_16 && ++nOpCount > 201)
269 if (opcode == OP_CAT ||
270 opcode == OP_SUBSTR ||
272 opcode == OP_RIGHT ||
273 opcode == OP_INVERT ||
282 opcode == OP_LSHIFT ||
286 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
287 stack.push_back(vchPushValue);
288 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
313 CBigNum bn((int)opcode - (int)(OP_1 - 1));
314 stack.push_back(bn.getvch());
323 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
324 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
330 // <expression> if [statements] [else [statements]] endif
334 if (stack.size() < 1)
336 valtype& vch = stacktop(-1);
337 fValue = CastToBool(vch);
338 if (opcode == OP_NOTIF)
342 vfExec.push_back(fValue);
350 vfExec.back() = !vfExec.back();
365 // (false -- false) and return
366 if (stack.size() < 1)
368 bool fValue = CastToBool(stacktop(-1));
388 if (stack.size() < 1)
390 altstack.push_back(stacktop(-1));
395 case OP_FROMALTSTACK:
397 if (altstack.size() < 1)
399 stack.push_back(altstacktop(-1));
407 if (stack.size() < 2)
416 // (x1 x2 -- x1 x2 x1 x2)
417 if (stack.size() < 2)
419 valtype vch1 = stacktop(-2);
420 valtype vch2 = stacktop(-1);
421 stack.push_back(vch1);
422 stack.push_back(vch2);
428 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
429 if (stack.size() < 3)
431 valtype vch1 = stacktop(-3);
432 valtype vch2 = stacktop(-2);
433 valtype vch3 = stacktop(-1);
434 stack.push_back(vch1);
435 stack.push_back(vch2);
436 stack.push_back(vch3);
442 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
443 if (stack.size() < 4)
445 valtype vch1 = stacktop(-4);
446 valtype vch2 = stacktop(-3);
447 stack.push_back(vch1);
448 stack.push_back(vch2);
454 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
455 if (stack.size() < 6)
457 valtype vch1 = stacktop(-6);
458 valtype vch2 = stacktop(-5);
459 stack.erase(stack.end()-6, stack.end()-4);
460 stack.push_back(vch1);
461 stack.push_back(vch2);
467 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
468 if (stack.size() < 4)
470 swap(stacktop(-4), stacktop(-2));
471 swap(stacktop(-3), stacktop(-1));
478 if (stack.size() < 1)
480 valtype vch = stacktop(-1);
482 stack.push_back(vch);
489 CBigNum bn(stack.size());
490 stack.push_back(bn.getvch());
497 if (stack.size() < 1)
506 if (stack.size() < 1)
508 valtype vch = stacktop(-1);
509 stack.push_back(vch);
516 if (stack.size() < 2)
518 stack.erase(stack.end() - 2);
524 // (x1 x2 -- x1 x2 x1)
525 if (stack.size() < 2)
527 valtype vch = stacktop(-2);
528 stack.push_back(vch);
535 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
536 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
537 if (stack.size() < 2)
539 int n = CastToBigNum(stacktop(-1)).getint();
541 if (n < 0 || n >= (int)stack.size())
543 valtype vch = stacktop(-n-1);
544 if (opcode == OP_ROLL)
545 stack.erase(stack.end()-n-1);
546 stack.push_back(vch);
552 // (x1 x2 x3 -- x2 x3 x1)
553 // x2 x1 x3 after first swap
554 // x2 x3 x1 after second swap
555 if (stack.size() < 3)
557 swap(stacktop(-3), stacktop(-2));
558 swap(stacktop(-2), stacktop(-1));
565 if (stack.size() < 2)
567 swap(stacktop(-2), stacktop(-1));
573 // (x1 x2 -- x2 x1 x2)
574 if (stack.size() < 2)
576 valtype vch = stacktop(-1);
577 stack.insert(stack.end()-2, vch);
588 if (stack.size() < 2)
590 valtype& vch1 = stacktop(-2);
591 valtype& vch2 = stacktop(-1);
592 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
594 if (stacktop(-1).size() > 520)
601 // (in begin size -- out)
602 if (stack.size() < 3)
604 valtype& vch = stacktop(-3);
605 int nBegin = CastToBigNum(stacktop(-2)).getint();
606 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
607 if (nBegin < 0 || nEnd < nBegin)
609 if (nBegin > (int)vch.size())
611 if (nEnd > (int)vch.size())
613 vch.erase(vch.begin() + nEnd, vch.end());
614 vch.erase(vch.begin(), vch.begin() + nBegin);
624 if (stack.size() < 2)
626 valtype& vch = stacktop(-2);
627 int nSize = CastToBigNum(stacktop(-1)).getint();
630 if (nSize > (int)vch.size())
632 if (opcode == OP_LEFT)
633 vch.erase(vch.begin() + nSize, vch.end());
635 vch.erase(vch.begin(), vch.end() - nSize);
643 if (stack.size() < 1)
645 CBigNum bn(stacktop(-1).size());
646 stack.push_back(bn.getvch());
657 if (stack.size() < 1)
659 valtype& vch = stacktop(-1);
660 for (unsigned int i = 0; i < vch.size(); i++)
670 if (stack.size() < 2)
672 valtype& vch1 = stacktop(-2);
673 valtype& vch2 = stacktop(-1);
674 MakeSameSize(vch1, vch2);
675 if (opcode == OP_AND)
677 for (unsigned int i = 0; i < vch1.size(); i++)
680 else if (opcode == OP_OR)
682 for (unsigned int i = 0; i < vch1.size(); i++)
685 else if (opcode == OP_XOR)
687 for (unsigned int i = 0; i < vch1.size(); i++)
696 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
699 if (stack.size() < 2)
701 valtype& vch1 = stacktop(-2);
702 valtype& vch2 = stacktop(-1);
703 bool fEqual = (vch1 == vch2);
704 // OP_NOTEQUAL is disabled because it would be too easy to say
705 // something like n != 1 and have some wiseguy pass in 1 with extra
706 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
707 //if (opcode == OP_NOTEQUAL)
711 stack.push_back(fEqual ? vchTrue : vchFalse);
712 if (opcode == OP_EQUALVERIFY)
736 if (stack.size() < 1)
738 CBigNum bn = CastToBigNum(stacktop(-1));
741 case OP_1ADD: bn += bnOne; break;
742 case OP_1SUB: bn -= bnOne; break;
743 case OP_2MUL: bn <<= 1; break;
744 case OP_2DIV: bn >>= 1; break;
745 case OP_NEGATE: bn = -bn; break;
746 case OP_ABS: if (bn < bnZero) bn = -bn; break;
747 case OP_NOT: bn = (bn == bnZero); break;
748 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
749 default: assert(!"invalid opcode"); break;
752 stack.push_back(bn.getvch());
766 case OP_NUMEQUALVERIFY:
770 case OP_LESSTHANOREQUAL:
771 case OP_GREATERTHANOREQUAL:
776 if (stack.size() < 2)
778 CBigNum bn1 = CastToBigNum(stacktop(-2));
779 CBigNum bn2 = CastToBigNum(stacktop(-1));
792 if (!BN_mul(&bn, &bn1, &bn2, pctx))
797 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
802 if (!BN_mod(&bn, &bn1, &bn2, pctx))
807 if (bn2 < bnZero || bn2 > CBigNum(2048))
809 bn = bn1 << bn2.getulong();
813 if (bn2 < bnZero || bn2 > CBigNum(2048))
815 bn = bn1 >> bn2.getulong();
818 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
819 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
820 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
821 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
822 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
823 case OP_LESSTHAN: bn = (bn1 < bn2); break;
824 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
825 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
826 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
827 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
828 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
829 default: assert(!"invalid opcode"); break;
833 stack.push_back(bn.getvch());
835 if (opcode == OP_NUMEQUALVERIFY)
837 if (CastToBool(stacktop(-1)))
847 // (x min max -- out)
848 if (stack.size() < 3)
850 CBigNum bn1 = CastToBigNum(stacktop(-3));
851 CBigNum bn2 = CastToBigNum(stacktop(-2));
852 CBigNum bn3 = CastToBigNum(stacktop(-1));
853 bool fValue = (bn2 <= bn1 && bn1 < bn3);
857 stack.push_back(fValue ? vchTrue : vchFalse);
872 if (stack.size() < 1)
874 valtype& vch = stacktop(-1);
875 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
876 if (opcode == OP_RIPEMD160)
877 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
878 else if (opcode == OP_SHA1)
879 SHA1(&vch[0], vch.size(), &vchHash[0]);
880 else if (opcode == OP_SHA256)
881 SHA256(&vch[0], vch.size(), &vchHash[0]);
882 else if (opcode == OP_HASH160)
884 uint160 hash160 = Hash160(vch);
885 memcpy(&vchHash[0], &hash160, sizeof(hash160));
887 else if (opcode == OP_HASH256)
889 uint256 hash = Hash(vch.begin(), vch.end());
890 memcpy(&vchHash[0], &hash, sizeof(hash));
893 stack.push_back(vchHash);
897 case OP_CODESEPARATOR:
899 // Hash starts after the code separator
905 case OP_CHECKSIGVERIFY:
907 // (sig pubkey -- bool)
908 if (stack.size() < 2)
911 valtype& vchSig = stacktop(-2);
912 valtype& vchPubKey = stacktop(-1);
915 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
916 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
918 // Subset of script starting at the most recent codeseparator
919 CScript scriptCode(pbegincodehash, pend);
921 // Drop the signature, since there's no way for a signature to sign itself
922 scriptCode.FindAndDelete(CScript(vchSig));
924 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
928 stack.push_back(fSuccess ? vchTrue : vchFalse);
929 if (opcode == OP_CHECKSIGVERIFY)
939 case OP_CHECKMULTISIG:
940 case OP_CHECKMULTISIGVERIFY:
942 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
945 if (stack.size() < i)
948 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
949 if (nKeysCount < 0 || nKeysCount > 20)
951 nOpCount += nKeysCount;
956 if (stack.size() < i)
959 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
960 if (nSigsCount < 0 || nSigsCount > nKeysCount)
964 if (stack.size() < i)
967 // Subset of script starting at the most recent codeseparator
968 CScript scriptCode(pbegincodehash, pend);
970 // Drop the signatures, since there's no way for a signature to sign itself
971 for (int k = 0; k < nSigsCount; k++)
973 valtype& vchSig = stacktop(-isig-k);
974 scriptCode.FindAndDelete(CScript(vchSig));
977 bool fSuccess = true;
978 while (fSuccess && nSigsCount > 0)
980 valtype& vchSig = stacktop(-isig);
981 valtype& vchPubKey = stacktop(-ikey);
984 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
992 // If there are more signatures left than keys left,
993 // then too many signatures have failed
994 if (nSigsCount > nKeysCount)
1000 stack.push_back(fSuccess ? vchTrue : vchFalse);
1002 if (opcode == OP_CHECKMULTISIGVERIFY)
1017 if (stack.size() + altstack.size() > 1000)
1027 if (!vfExec.empty())
1041 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1043 if (nIn >= txTo.vin.size())
1045 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1048 CTransaction txTmp(txTo);
1050 // In case concatenating two scripts ends up with two codeseparators,
1051 // or an extra one at the end, this prevents all those possible incompatibilities.
1052 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1054 // Blank out other inputs' signatures
1055 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1056 txTmp.vin[i].scriptSig = CScript();
1057 txTmp.vin[nIn].scriptSig = scriptCode;
1059 // Blank out some of the outputs
1060 if ((nHashType & 0x1f) == SIGHASH_NONE)
1065 // Let the others update at will
1066 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1068 txTmp.vin[i].nSequence = 0;
1070 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1072 // Only lockin the txout payee at same index as txin
1073 unsigned int nOut = nIn;
1074 if (nOut >= txTmp.vout.size())
1076 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1079 txTmp.vout.resize(nOut+1);
1080 for (unsigned int i = 0; i < nOut; i++)
1081 txTmp.vout[i].SetNull();
1083 // Let the others update at will
1084 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1086 txTmp.vin[i].nSequence = 0;
1089 // Blank out other inputs completely, not recommended for open transactions
1090 if (nHashType & SIGHASH_ANYONECANPAY)
1092 txTmp.vin[0] = txTmp.vin[nIn];
1093 txTmp.vin.resize(1);
1096 // Serialize and hash
1097 CDataStream ss(SER_GETHASH, 0);
1099 ss << txTmp << nHashType;
1100 return Hash(ss.begin(), ss.end());
1104 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1105 // twice for every transaction (once when accepted into memory pool, and
1106 // again when accepted into the block chain)
1108 class CSignatureCache
1111 // sigdata_type is (signature hash, signature, public key):
1112 typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1113 std::set< sigdata_type> setValid;
1114 CCriticalSection cs_sigcache;
1118 Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1122 sigdata_type k(hash, vchSig, pubKey);
1123 std::set<sigdata_type>::iterator mi = setValid.find(k);
1124 if (mi != setValid.end())
1130 Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1132 // DoS prevention: limit cache size to less than 10MB
1133 // (~200 bytes per cache entry times 50,000 entries)
1134 // Since there are a maximum of 20,000 signature operations per block
1135 // 50,000 is a reasonable default.
1136 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1137 if (nMaxCacheSize <= 0) return;
1141 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1143 // Evict a random entry. Random because that helps
1144 // foil would-be DoS attackers who might try to pre-generate
1145 // and re-use a set of valid signatures just-slightly-greater
1146 // than our cache size.
1147 uint256 randomHash = GetRandHash();
1148 std::vector<unsigned char> unused;
1149 std::set<sigdata_type>::iterator it =
1150 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1151 if (it == setValid.end())
1152 it = setValid.begin();
1153 setValid.erase(*it);
1156 sigdata_type k(hash, vchSig, pubKey);
1161 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1162 const CTransaction& txTo, unsigned int nIn, int nHashType)
1164 static CSignatureCache signatureCache;
1166 // Hash type is one byte tacked on to the end of the signature
1170 nHashType = vchSig.back();
1171 else if (nHashType != vchSig.back())
1175 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1177 if (signatureCache.Get(sighash, vchSig, vchPubKey))
1181 if (!key.SetPubKey(vchPubKey))
1184 if (!key.Verify(sighash, vchSig))
1187 signatureCache.Set(sighash, vchSig, vchPubKey);
1200 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1202 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1205 static map<txnouttype, CScript> mTemplates;
1206 if (mTemplates.empty())
1208 // Standard tx, sender provides pubkey, receiver adds signature
1209 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1211 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1212 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1214 // Sender provides N pubkeys, receivers provides M signatures
1215 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1218 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1219 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1220 if (scriptPubKey.IsPayToScriptHash())
1222 typeRet = TX_SCRIPTHASH;
1223 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1224 vSolutionsRet.push_back(hashBytes);
1229 const CScript& script1 = scriptPubKey;
1230 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1232 const CScript& script2 = tplate.second;
1233 vSolutionsRet.clear();
1235 opcodetype opcode1, opcode2;
1236 vector<unsigned char> vch1, vch2;
1239 CScript::const_iterator pc1 = script1.begin();
1240 CScript::const_iterator pc2 = script2.begin();
1243 if (pc1 == script1.end() && pc2 == script2.end())
1246 typeRet = tplate.first;
1247 if (typeRet == TX_MULTISIG)
1249 // Additional checks for TX_MULTISIG:
1250 unsigned char m = vSolutionsRet.front()[0];
1251 unsigned char n = vSolutionsRet.back()[0];
1252 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1257 if (!script1.GetOp(pc1, opcode1, vch1))
1259 if (!script2.GetOp(pc2, opcode2, vch2))
1262 // Template matching opcodes:
1263 if (opcode2 == OP_PUBKEYS)
1265 while (vch1.size() >= 33 && vch1.size() <= 120)
1267 vSolutionsRet.push_back(vch1);
1268 if (!script1.GetOp(pc1, opcode1, vch1))
1271 if (!script2.GetOp(pc2, opcode2, vch2))
1273 // Normal situation is to fall through
1274 // to other if/else statments
1277 if (opcode2 == OP_PUBKEY)
1279 if (vch1.size() < 33 || vch1.size() > 120)
1281 vSolutionsRet.push_back(vch1);
1283 else if (opcode2 == OP_PUBKEYHASH)
1285 if (vch1.size() != sizeof(uint160))
1287 vSolutionsRet.push_back(vch1);
1289 else if (opcode2 == OP_SMALLINTEGER)
1290 { // Single-byte small integer pushed onto vSolutions
1291 if (opcode1 == OP_0 ||
1292 (opcode1 >= OP_1 && opcode1 <= OP_16))
1294 char n = (char)CScript::DecodeOP_N(opcode1);
1295 vSolutionsRet.push_back(valtype(1, n));
1300 else if (opcode1 != opcode2 || vch1 != vch2)
1302 // Others must match exactly
1308 vSolutionsRet.clear();
1309 typeRet = TX_NONSTANDARD;
1314 bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1317 if (!keystore.GetKey(address, key))
1320 vector<unsigned char> vchSig;
1321 if (!key.Sign(hash, vchSig))
1323 vchSig.push_back((unsigned char)nHashType);
1324 scriptSigRet << vchSig;
1329 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1332 int nRequired = multisigdata.front()[0];
1333 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1335 const valtype& pubkey = *it;
1336 CBitcoinAddress address;
1337 address.SetPubKey(pubkey);
1338 if (Sign1(address, 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))
1362 CBitcoinAddress address;
1363 switch (whichTypeRet)
1365 case TX_NONSTANDARD:
1368 address.SetPubKey(vSolutions[0]);
1369 return Sign1(address, keystore, hash, nHashType, scriptSigRet);
1371 address.SetHash160(uint160(vSolutions[0]));
1372 if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
1377 keystore.GetPubKey(address, 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 CBitcoinAddress address;
1439 address.SetPubKey(pubkey);
1440 if (keystore.HaveKey(address))
1446 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1448 vector<valtype> vSolutions;
1449 txnouttype whichType;
1450 if (!Solver(scriptPubKey, whichType, vSolutions))
1453 CBitcoinAddress address;
1456 case TX_NONSTANDARD:
1459 address.SetPubKey(vSolutions[0]);
1460 return keystore.HaveKey(address);
1462 address.SetHash160(uint160(vSolutions[0]));
1463 return keystore.HaveKey(address);
1467 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1469 return IsMine(keystore, subscript);
1473 // Only consider transactions "mine" if we own ALL the
1474 // keys involved. multi-signature transactions that are
1475 // partially owned (somebody else has a key that can spend
1476 // them) enable spend-out-from-under-you attacks, especially
1477 // in shared-wallet situations.
1478 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1479 return HaveKeys(keys, keystore) == keys.size();
1485 bool ExtractAddress(const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1487 vector<valtype> vSolutions;
1488 txnouttype whichType;
1489 if (!Solver(scriptPubKey, whichType, vSolutions))
1492 if (whichType == TX_PUBKEY)
1494 addressRet.SetPubKey(vSolutions[0]);
1497 else if (whichType == TX_PUBKEYHASH)
1499 addressRet.SetHash160(uint160(vSolutions[0]));
1502 else if (whichType == TX_SCRIPTHASH)
1504 addressRet.SetScriptHash160(uint160(vSolutions[0]));
1507 // Multisig txns have more than one address...
1511 bool ExtractAddresses(const CScript& scriptPubKey, txnouttype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
1514 typeRet = TX_NONSTANDARD;
1515 vector<valtype> vSolutions;
1516 if (!Solver(scriptPubKey, typeRet, vSolutions))
1519 if (typeRet == TX_MULTISIG)
1521 nRequiredRet = vSolutions.front()[0];
1522 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1524 CBitcoinAddress address;
1525 address.SetPubKey(vSolutions[i]);
1526 addressRet.push_back(address);
1532 CBitcoinAddress address;
1533 if (typeRet == TX_PUBKEYHASH)
1534 address.SetHash160(uint160(vSolutions.front()));
1535 else if (typeRet == TX_SCRIPTHASH)
1536 address.SetScriptHash160(uint160(vSolutions.front()));
1537 else if (typeRet == TX_PUBKEY)
1538 address.SetPubKey(vSolutions.front());
1539 addressRet.push_back(address);
1545 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1546 bool fValidatePayToScriptHash, int nHashType)
1548 vector<vector<unsigned char> > stack, stackCopy;
1549 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1551 if (fValidatePayToScriptHash)
1553 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1558 if (CastToBool(stack.back()) == false)
1561 // Additional validation for spend-to-script-hash transactions:
1562 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1564 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1565 return false; // or validation fails
1567 const valtype& pubKeySerialized = stackCopy.back();
1568 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1569 popstack(stackCopy);
1571 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
1573 if (stackCopy.empty())
1575 return CastToBool(stackCopy.back());
1582 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1584 assert(nIn < txTo.vin.size());
1585 CTxIn& txin = txTo.vin[nIn];
1586 assert(txin.prevout.n < txFrom.vout.size());
1587 assert(txin.prevout.hash == txFrom.GetHash());
1588 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1590 // Leave out the signature from the hash, since a signature can't sign itself.
1591 // The checksig op will also drop the signatures from its hash.
1592 uint256 hash = SignatureHash(txout.scriptPubKey, txTo, nIn, nHashType);
1594 txnouttype whichType;
1595 if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig, whichType))
1598 if (whichType == TX_SCRIPTHASH)
1600 // Solver returns the subscript that need to be evaluated;
1601 // the final scriptSig is the signatures from that
1602 // and then the serialized subscript:
1603 CScript subscript = txin.scriptSig;
1605 // Recompute txn hash using subscript in place of scriptPubKey:
1606 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1608 if (!Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType))
1610 if (subType == TX_SCRIPTHASH)
1612 txin.scriptSig << static_cast<valtype>(subscript); // Append serialized subscript
1616 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, true, 0))
1623 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
1625 assert(nIn < txTo.vin.size());
1626 const CTxIn& txin = txTo.vin[nIn];
1627 if (txin.prevout.n >= txFrom.vout.size())
1629 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1631 if (txin.prevout.hash != txFrom.GetHash())
1634 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType))
1640 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1643 const_iterator pc = begin();
1644 opcodetype lastOpcode = OP_INVALIDOPCODE;
1648 if (!GetOp(pc, opcode))
1650 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1652 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1654 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1655 n += DecodeOP_N(lastOpcode);
1659 lastOpcode = opcode;
1664 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1666 if (!IsPayToScriptHash())
1667 return GetSigOpCount(true);
1669 // This is a pay-to-script-hash scriptPubKey;
1670 // get the last item that the scriptSig
1671 // pushes onto the stack:
1672 const_iterator pc = scriptSig.begin();
1673 vector<unsigned char> data;
1674 while (pc < scriptSig.end())
1677 if (!scriptSig.GetOp(pc, opcode, data))
1683 /// ... and return it's opcount:
1684 CScript subscript(data.begin(), data.end());
1685 return subscript.GetSigOpCount(true);
1688 bool CScript::IsPayToScriptHash() const
1690 // Extra-fast test for pay-to-script-hash CScripts:
1691 return (this->size() == 23 &&
1692 this->at(0) == OP_HASH160 &&
1693 this->at(1) == 0x14 &&
1694 this->at(22) == OP_EQUAL);
1697 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
1700 if (address.IsScript())
1701 *this << OP_HASH160 << address.GetHash160() << OP_EQUAL;
1703 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
1706 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1710 *this << EncodeOP_N(nRequired);
1711 BOOST_FOREACH(const CKey& key, keys)
1712 *this << key.GetPubKey();
1713 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1716 void CScript::SetPayToScriptHash(const CScript& subscript)
1718 assert(!subscript.empty());
1719 uint160 subscriptHash = Hash160(subscript);
1721 *this << OP_HASH160 << subscriptHash << OP_EQUAL;