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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #include <boost/foreach.hpp>
16 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
20 typedef vector<unsigned char> valtype;
21 static const valtype vchFalse(0);
22 static const valtype vchZero(0);
23 static const valtype vchTrue(1, 1);
24 static const CBigNum bnZero(0);
25 static const CBigNum bnOne(1);
26 static const CBigNum bnFalse(0);
27 static const CBigNum bnTrue(1);
28 static const size_t nMaxNumSize = 4;
31 CBigNum CastToBigNum(const valtype& vch)
33 if (vch.size() > nMaxNumSize)
34 throw runtime_error("CastToBigNum() : overflow");
35 // Get rid of extra leading zeros
36 return CBigNum(CBigNum(vch).getvch());
39 bool CastToBool(const valtype& vch)
41 for (unsigned int i = 0; i < vch.size(); i++)
45 // Can be negative zero
46 if (i == vch.size()-1 && vch[i] == 0x80)
54 void MakeSameSize(valtype& vch1, valtype& vch2)
56 // Lengthen the shorter one
57 if (vch1.size() < vch2.size())
58 vch1.resize(vch2.size(), 0);
59 if (vch2.size() < vch1.size())
60 vch2.resize(vch1.size(), 0);
66 // Script is a stack machine (like Forth) that evaluates a predicate
67 // returning a bool indicating valid or not. There are no loops.
69 #define stacktop(i) (stack.at(stack.size()+(i)))
70 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
71 static inline void popstack(vector<valtype>& stack)
74 throw runtime_error("popstack() : stack empty");
79 const char* GetTxnOutputType(txnouttype t)
83 case TX_NONSTANDARD: return "nonstandard";
84 case TX_PUBKEY: return "pubkey";
85 case TX_PUBKEYHASH: return "pubkeyhash";
86 case TX_SCRIPTHASH: return "scripthash";
87 case TX_MULTISIG: return "multisig";
93 const char* GetOpName(opcodetype opcode)
98 case OP_0 : return "0";
99 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
100 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
101 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
102 case OP_1NEGATE : return "-1";
103 case OP_RESERVED : return "OP_RESERVED";
104 case OP_1 : return "1";
105 case OP_2 : return "2";
106 case OP_3 : return "3";
107 case OP_4 : return "4";
108 case OP_5 : return "5";
109 case OP_6 : return "6";
110 case OP_7 : return "7";
111 case OP_8 : return "8";
112 case OP_9 : return "9";
113 case OP_10 : return "10";
114 case OP_11 : return "11";
115 case OP_12 : return "12";
116 case OP_13 : return "13";
117 case OP_14 : return "14";
118 case OP_15 : return "15";
119 case OP_16 : return "16";
122 case OP_NOP : return "OP_NOP";
123 case OP_VER : return "OP_VER";
124 case OP_IF : return "OP_IF";
125 case OP_NOTIF : return "OP_NOTIF";
126 case OP_VERIF : return "OP_VERIF";
127 case OP_VERNOTIF : return "OP_VERNOTIF";
128 case OP_ELSE : return "OP_ELSE";
129 case OP_ENDIF : return "OP_ENDIF";
130 case OP_VERIFY : return "OP_VERIFY";
131 case OP_RETURN : return "OP_RETURN";
134 case OP_TOALTSTACK : return "OP_TOALTSTACK";
135 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
136 case OP_2DROP : return "OP_2DROP";
137 case OP_2DUP : return "OP_2DUP";
138 case OP_3DUP : return "OP_3DUP";
139 case OP_2OVER : return "OP_2OVER";
140 case OP_2ROT : return "OP_2ROT";
141 case OP_2SWAP : return "OP_2SWAP";
142 case OP_IFDUP : return "OP_IFDUP";
143 case OP_DEPTH : return "OP_DEPTH";
144 case OP_DROP : return "OP_DROP";
145 case OP_DUP : return "OP_DUP";
146 case OP_NIP : return "OP_NIP";
147 case OP_OVER : return "OP_OVER";
148 case OP_PICK : return "OP_PICK";
149 case OP_ROLL : return "OP_ROLL";
150 case OP_ROT : return "OP_ROT";
151 case OP_SWAP : return "OP_SWAP";
152 case OP_TUCK : return "OP_TUCK";
155 case OP_CAT : return "OP_CAT";
156 case OP_SUBSTR : return "OP_SUBSTR";
157 case OP_LEFT : return "OP_LEFT";
158 case OP_RIGHT : return "OP_RIGHT";
159 case OP_SIZE : return "OP_SIZE";
162 case OP_INVERT : return "OP_INVERT";
163 case OP_AND : return "OP_AND";
164 case OP_OR : return "OP_OR";
165 case OP_XOR : return "OP_XOR";
166 case OP_EQUAL : return "OP_EQUAL";
167 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
168 case OP_RESERVED1 : return "OP_RESERVED1";
169 case OP_RESERVED2 : return "OP_RESERVED2";
172 case OP_1ADD : return "OP_1ADD";
173 case OP_1SUB : return "OP_1SUB";
174 case OP_2MUL : return "OP_2MUL";
175 case OP_2DIV : return "OP_2DIV";
176 case OP_NEGATE : return "OP_NEGATE";
177 case OP_ABS : return "OP_ABS";
178 case OP_NOT : return "OP_NOT";
179 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
180 case OP_ADD : return "OP_ADD";
181 case OP_SUB : return "OP_SUB";
182 case OP_MUL : return "OP_MUL";
183 case OP_DIV : return "OP_DIV";
184 case OP_MOD : return "OP_MOD";
185 case OP_LSHIFT : return "OP_LSHIFT";
186 case OP_RSHIFT : return "OP_RSHIFT";
187 case OP_BOOLAND : return "OP_BOOLAND";
188 case OP_BOOLOR : return "OP_BOOLOR";
189 case OP_NUMEQUAL : return "OP_NUMEQUAL";
190 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
191 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
192 case OP_LESSTHAN : return "OP_LESSTHAN";
193 case OP_GREATERTHAN : return "OP_GREATERTHAN";
194 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
195 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
196 case OP_MIN : return "OP_MIN";
197 case OP_MAX : return "OP_MAX";
198 case OP_WITHIN : return "OP_WITHIN";
201 case OP_RIPEMD160 : return "OP_RIPEMD160";
202 case OP_SHA1 : return "OP_SHA1";
203 case OP_SHA256 : return "OP_SHA256";
204 case OP_HASH160 : return "OP_HASH160";
205 case OP_HASH256 : return "OP_HASH256";
206 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
207 case OP_CHECKSIG : return "OP_CHECKSIG";
208 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
209 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
210 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
213 case OP_NOP1 : return "OP_NOP1";
214 case OP_NOP2 : return "OP_NOP2";
215 case OP_NOP3 : return "OP_NOP3";
216 case OP_NOP4 : return "OP_NOP4";
217 case OP_NOP5 : return "OP_NOP5";
218 case OP_NOP6 : return "OP_NOP6";
219 case OP_NOP7 : return "OP_NOP7";
220 case OP_NOP8 : return "OP_NOP8";
221 case OP_NOP9 : return "OP_NOP9";
222 case OP_NOP10 : return "OP_NOP10";
226 // template matching params
227 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
228 case OP_PUBKEY : return "OP_PUBKEY";
230 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
236 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, int nHashType)
239 CScript::const_iterator pc = script.begin();
240 CScript::const_iterator pend = script.end();
241 CScript::const_iterator pbegincodehash = script.begin();
243 valtype vchPushValue;
245 vector<valtype> altstack;
246 if (script.size() > 10000)
255 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
260 if (!script.GetOp(pc, opcode, vchPushValue))
262 if (vchPushValue.size() > 520)
264 if (opcode > OP_16 && ++nOpCount > 201)
267 if (opcode == OP_CAT ||
268 opcode == OP_SUBSTR ||
270 opcode == OP_RIGHT ||
271 opcode == OP_INVERT ||
280 opcode == OP_LSHIFT ||
284 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
285 stack.push_back(vchPushValue);
286 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
311 CBigNum bn((int)opcode - (int)(OP_1 - 1));
312 stack.push_back(bn.getvch());
321 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
322 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
328 // <expression> if [statements] [else [statements]] endif
332 if (stack.size() < 1)
334 valtype& vch = stacktop(-1);
335 fValue = CastToBool(vch);
336 if (opcode == OP_NOTIF)
340 vfExec.push_back(fValue);
348 vfExec.back() = !vfExec.back();
363 // (false -- false) and return
364 if (stack.size() < 1)
366 bool fValue = CastToBool(stacktop(-1));
386 if (stack.size() < 1)
388 altstack.push_back(stacktop(-1));
393 case OP_FROMALTSTACK:
395 if (altstack.size() < 1)
397 stack.push_back(altstacktop(-1));
405 if (stack.size() < 2)
414 // (x1 x2 -- x1 x2 x1 x2)
415 if (stack.size() < 2)
417 valtype vch1 = stacktop(-2);
418 valtype vch2 = stacktop(-1);
419 stack.push_back(vch1);
420 stack.push_back(vch2);
426 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
427 if (stack.size() < 3)
429 valtype vch1 = stacktop(-3);
430 valtype vch2 = stacktop(-2);
431 valtype vch3 = stacktop(-1);
432 stack.push_back(vch1);
433 stack.push_back(vch2);
434 stack.push_back(vch3);
440 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
441 if (stack.size() < 4)
443 valtype vch1 = stacktop(-4);
444 valtype vch2 = stacktop(-3);
445 stack.push_back(vch1);
446 stack.push_back(vch2);
452 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
453 if (stack.size() < 6)
455 valtype vch1 = stacktop(-6);
456 valtype vch2 = stacktop(-5);
457 stack.erase(stack.end()-6, stack.end()-4);
458 stack.push_back(vch1);
459 stack.push_back(vch2);
465 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
466 if (stack.size() < 4)
468 swap(stacktop(-4), stacktop(-2));
469 swap(stacktop(-3), stacktop(-1));
476 if (stack.size() < 1)
478 valtype vch = stacktop(-1);
480 stack.push_back(vch);
487 CBigNum bn(stack.size());
488 stack.push_back(bn.getvch());
495 if (stack.size() < 1)
504 if (stack.size() < 1)
506 valtype vch = stacktop(-1);
507 stack.push_back(vch);
514 if (stack.size() < 2)
516 stack.erase(stack.end() - 2);
522 // (x1 x2 -- x1 x2 x1)
523 if (stack.size() < 2)
525 valtype vch = stacktop(-2);
526 stack.push_back(vch);
533 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
534 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
535 if (stack.size() < 2)
537 int n = CastToBigNum(stacktop(-1)).getint();
539 if (n < 0 || n >= (int)stack.size())
541 valtype vch = stacktop(-n-1);
542 if (opcode == OP_ROLL)
543 stack.erase(stack.end()-n-1);
544 stack.push_back(vch);
550 // (x1 x2 x3 -- x2 x3 x1)
551 // x2 x1 x3 after first swap
552 // x2 x3 x1 after second swap
553 if (stack.size() < 3)
555 swap(stacktop(-3), stacktop(-2));
556 swap(stacktop(-2), stacktop(-1));
563 if (stack.size() < 2)
565 swap(stacktop(-2), stacktop(-1));
571 // (x1 x2 -- x2 x1 x2)
572 if (stack.size() < 2)
574 valtype vch = stacktop(-1);
575 stack.insert(stack.end()-2, vch);
586 if (stack.size() < 2)
588 valtype& vch1 = stacktop(-2);
589 valtype& vch2 = stacktop(-1);
590 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
592 if (stacktop(-1).size() > 520)
599 // (in begin size -- out)
600 if (stack.size() < 3)
602 valtype& vch = stacktop(-3);
603 int nBegin = CastToBigNum(stacktop(-2)).getint();
604 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
605 if (nBegin < 0 || nEnd < nBegin)
607 if (nBegin > (int)vch.size())
609 if (nEnd > (int)vch.size())
611 vch.erase(vch.begin() + nEnd, vch.end());
612 vch.erase(vch.begin(), vch.begin() + nBegin);
622 if (stack.size() < 2)
624 valtype& vch = stacktop(-2);
625 int nSize = CastToBigNum(stacktop(-1)).getint();
628 if (nSize > (int)vch.size())
630 if (opcode == OP_LEFT)
631 vch.erase(vch.begin() + nSize, vch.end());
633 vch.erase(vch.begin(), vch.end() - nSize);
641 if (stack.size() < 1)
643 CBigNum bn(stacktop(-1).size());
644 stack.push_back(bn.getvch());
655 if (stack.size() < 1)
657 valtype& vch = stacktop(-1);
658 for (unsigned int i = 0; i < vch.size(); i++)
668 if (stack.size() < 2)
670 valtype& vch1 = stacktop(-2);
671 valtype& vch2 = stacktop(-1);
672 MakeSameSize(vch1, vch2);
673 if (opcode == OP_AND)
675 for (unsigned int i = 0; i < vch1.size(); i++)
678 else if (opcode == OP_OR)
680 for (unsigned int i = 0; i < vch1.size(); i++)
683 else if (opcode == OP_XOR)
685 for (unsigned int i = 0; i < vch1.size(); i++)
694 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
697 if (stack.size() < 2)
699 valtype& vch1 = stacktop(-2);
700 valtype& vch2 = stacktop(-1);
701 bool fEqual = (vch1 == vch2);
702 // OP_NOTEQUAL is disabled because it would be too easy to say
703 // something like n != 1 and have some wiseguy pass in 1 with extra
704 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
705 //if (opcode == OP_NOTEQUAL)
709 stack.push_back(fEqual ? vchTrue : vchFalse);
710 if (opcode == OP_EQUALVERIFY)
734 if (stack.size() < 1)
736 CBigNum bn = CastToBigNum(stacktop(-1));
739 case OP_1ADD: bn += bnOne; break;
740 case OP_1SUB: bn -= bnOne; break;
741 case OP_2MUL: bn <<= 1; break;
742 case OP_2DIV: bn >>= 1; break;
743 case OP_NEGATE: bn = -bn; break;
744 case OP_ABS: if (bn < bnZero) bn = -bn; break;
745 case OP_NOT: bn = (bn == bnZero); break;
746 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
747 default: assert(!"invalid opcode"); break;
750 stack.push_back(bn.getvch());
764 case OP_NUMEQUALVERIFY:
768 case OP_LESSTHANOREQUAL:
769 case OP_GREATERTHANOREQUAL:
774 if (stack.size() < 2)
776 CBigNum bn1 = CastToBigNum(stacktop(-2));
777 CBigNum bn2 = CastToBigNum(stacktop(-1));
790 if (!BN_mul(&bn, &bn1, &bn2, pctx))
795 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
800 if (!BN_mod(&bn, &bn1, &bn2, pctx))
805 if (bn2 < bnZero || bn2 > CBigNum(2048))
807 bn = bn1 << bn2.getulong();
811 if (bn2 < bnZero || bn2 > CBigNum(2048))
813 bn = bn1 >> bn2.getulong();
816 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
817 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
818 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
819 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
820 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
821 case OP_LESSTHAN: bn = (bn1 < bn2); break;
822 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
823 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
824 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
825 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
826 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
827 default: assert(!"invalid opcode"); break;
831 stack.push_back(bn.getvch());
833 if (opcode == OP_NUMEQUALVERIFY)
835 if (CastToBool(stacktop(-1)))
845 // (x min max -- out)
846 if (stack.size() < 3)
848 CBigNum bn1 = CastToBigNum(stacktop(-3));
849 CBigNum bn2 = CastToBigNum(stacktop(-2));
850 CBigNum bn3 = CastToBigNum(stacktop(-1));
851 bool fValue = (bn2 <= bn1 && bn1 < bn3);
855 stack.push_back(fValue ? vchTrue : vchFalse);
870 if (stack.size() < 1)
872 valtype& vch = stacktop(-1);
873 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
874 if (opcode == OP_RIPEMD160)
875 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
876 else if (opcode == OP_SHA1)
877 SHA1(&vch[0], vch.size(), &vchHash[0]);
878 else if (opcode == OP_SHA256)
879 SHA256(&vch[0], vch.size(), &vchHash[0]);
880 else if (opcode == OP_HASH160)
882 uint160 hash160 = Hash160(vch);
883 memcpy(&vchHash[0], &hash160, sizeof(hash160));
885 else if (opcode == OP_HASH256)
887 uint256 hash = Hash(vch.begin(), vch.end());
888 memcpy(&vchHash[0], &hash, sizeof(hash));
891 stack.push_back(vchHash);
895 case OP_CODESEPARATOR:
897 // Hash starts after the code separator
903 case OP_CHECKSIGVERIFY:
905 // (sig pubkey -- bool)
906 if (stack.size() < 2)
909 valtype& vchSig = stacktop(-2);
910 valtype& vchPubKey = stacktop(-1);
913 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
914 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
916 // Subset of script starting at the most recent codeseparator
917 CScript scriptCode(pbegincodehash, pend);
919 // Drop the signature, since there's no way for a signature to sign itself
920 scriptCode.FindAndDelete(CScript(vchSig));
922 bool fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
926 stack.push_back(fSuccess ? vchTrue : vchFalse);
927 if (opcode == OP_CHECKSIGVERIFY)
937 case OP_CHECKMULTISIG:
938 case OP_CHECKMULTISIGVERIFY:
940 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
943 if (stack.size() < i)
946 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
947 if (nKeysCount < 0 || nKeysCount > 20)
949 nOpCount += nKeysCount;
954 if (stack.size() < i)
957 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
958 if (nSigsCount < 0 || nSigsCount > nKeysCount)
962 if (stack.size() < i)
965 // Subset of script starting at the most recent codeseparator
966 CScript scriptCode(pbegincodehash, pend);
968 // Drop the signatures, since there's no way for a signature to sign itself
969 for (int k = 0; k < nSigsCount; k++)
971 valtype& vchSig = stacktop(-isig-k);
972 scriptCode.FindAndDelete(CScript(vchSig));
975 bool fSuccess = true;
976 while (fSuccess && nSigsCount > 0)
978 valtype& vchSig = stacktop(-isig);
979 valtype& vchPubKey = stacktop(-ikey);
982 if (CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType))
990 // If there are more signatures left than keys left,
991 // then too many signatures have failed
992 if (nSigsCount > nKeysCount)
998 stack.push_back(fSuccess ? vchTrue : vchFalse);
1000 if (opcode == OP_CHECKMULTISIGVERIFY)
1015 if (stack.size() + altstack.size() > 1000)
1025 if (!vfExec.empty())
1039 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1041 if (nIn >= txTo.vin.size())
1043 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1046 CTransaction txTmp(txTo);
1048 // In case concatenating two scripts ends up with two codeseparators,
1049 // or an extra one at the end, this prevents all those possible incompatibilities.
1050 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1052 // Blank out other inputs' signatures
1053 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1054 txTmp.vin[i].scriptSig = CScript();
1055 txTmp.vin[nIn].scriptSig = scriptCode;
1057 // Blank out some of the outputs
1058 if ((nHashType & 0x1f) == SIGHASH_NONE)
1063 // Let the others update at will
1064 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1066 txTmp.vin[i].nSequence = 0;
1068 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1070 // Only lockin the txout payee at same index as txin
1071 unsigned int nOut = nIn;
1072 if (nOut >= txTmp.vout.size())
1074 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1077 txTmp.vout.resize(nOut+1);
1078 for (unsigned int i = 0; i < nOut; i++)
1079 txTmp.vout[i].SetNull();
1081 // Let the others update at will
1082 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1084 txTmp.vin[i].nSequence = 0;
1087 // Blank out other inputs completely, not recommended for open transactions
1088 if (nHashType & SIGHASH_ANYONECANPAY)
1090 txTmp.vin[0] = txTmp.vin[nIn];
1091 txTmp.vin.resize(1);
1094 // Serialize and hash
1095 CDataStream ss(SER_GETHASH, 0);
1097 ss << txTmp << nHashType;
1098 return Hash(ss.begin(), ss.end());
1102 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1103 const CTransaction& txTo, unsigned int nIn, int nHashType)
1106 if (!key.SetPubKey(vchPubKey))
1109 // Hash type is one byte tacked on to the end of the signature
1113 nHashType = vchSig.back();
1114 else if (nHashType != vchSig.back())
1118 return key.Verify(SignatureHash(scriptCode, txTo, nIn, nHashType), vchSig);
1130 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1132 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1135 static map<txnouttype, CScript> mTemplates;
1136 if (mTemplates.empty())
1138 // Standard tx, sender provides pubkey, receiver adds signature
1139 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1141 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1142 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1144 // Sender provides N pubkeys, receivers provides M signatures
1145 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1148 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1149 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1150 if (scriptPubKey.IsPayToScriptHash())
1152 typeRet = TX_SCRIPTHASH;
1153 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1154 vSolutionsRet.push_back(hashBytes);
1159 const CScript& script1 = scriptPubKey;
1160 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1162 const CScript& script2 = tplate.second;
1163 vSolutionsRet.clear();
1165 opcodetype opcode1, opcode2;
1166 vector<unsigned char> vch1, vch2;
1169 CScript::const_iterator pc1 = script1.begin();
1170 CScript::const_iterator pc2 = script2.begin();
1173 if (pc1 == script1.end() && pc2 == script2.end())
1176 typeRet = tplate.first;
1177 if (typeRet == TX_MULTISIG)
1179 // Additional checks for TX_MULTISIG:
1180 unsigned char m = vSolutionsRet.front()[0];
1181 unsigned char n = vSolutionsRet.back()[0];
1182 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1187 if (!script1.GetOp(pc1, opcode1, vch1))
1189 if (!script2.GetOp(pc2, opcode2, vch2))
1192 // Template matching opcodes:
1193 if (opcode2 == OP_PUBKEYS)
1195 while (vch1.size() >= 33 && vch1.size() <= 120)
1197 vSolutionsRet.push_back(vch1);
1198 if (!script1.GetOp(pc1, opcode1, vch1))
1201 if (!script2.GetOp(pc2, opcode2, vch2))
1203 // Normal situation is to fall through
1204 // to other if/else statments
1207 if (opcode2 == OP_PUBKEY)
1209 if (vch1.size() < 33 || vch1.size() > 120)
1211 vSolutionsRet.push_back(vch1);
1213 else if (opcode2 == OP_PUBKEYHASH)
1215 if (vch1.size() != sizeof(uint160))
1217 vSolutionsRet.push_back(vch1);
1219 else if (opcode2 == OP_SMALLINTEGER)
1220 { // Single-byte small integer pushed onto vSolutions
1221 if (opcode1 == OP_0 ||
1222 (opcode1 >= OP_1 && opcode1 <= OP_16))
1224 char n = (char)CScript::DecodeOP_N(opcode1);
1225 vSolutionsRet.push_back(valtype(1, n));
1230 else if (opcode1 != opcode2 || vch1 != vch2)
1232 // Others must match exactly
1238 vSolutionsRet.clear();
1239 typeRet = TX_NONSTANDARD;
1244 bool Sign1(const CBitcoinAddress& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1247 if (!keystore.GetKey(address, key))
1250 vector<unsigned char> vchSig;
1251 if (!key.Sign(hash, vchSig))
1253 vchSig.push_back((unsigned char)nHashType);
1254 scriptSigRet << vchSig;
1259 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1262 int nRequired = multisigdata.front()[0];
1263 for (vector<valtype>::const_iterator it = multisigdata.begin()+1; it != multisigdata.begin()+multisigdata.size()-1; it++)
1265 const valtype& pubkey = *it;
1266 CBitcoinAddress address;
1267 address.SetPubKey(pubkey);
1268 if (Sign1(address, keystore, hash, nHashType, scriptSigRet))
1271 if (nSigned == nRequired) break;
1274 return nSigned==nRequired;
1278 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1279 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1280 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1281 // Returns false if scriptPubKey could not be completely satisified.
1283 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1284 CScript& scriptSigRet, txnouttype& whichTypeRet)
1286 scriptSigRet.clear();
1288 vector<valtype> vSolutions;
1289 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1292 CBitcoinAddress address;
1293 switch (whichTypeRet)
1295 case TX_NONSTANDARD:
1298 address.SetPubKey(vSolutions[0]);
1299 return Sign1(address, keystore, hash, nHashType, scriptSigRet);
1301 address.SetHash160(uint160(vSolutions[0]));
1302 if (!Sign1(address, keystore, hash, nHashType, scriptSigRet))
1307 keystore.GetPubKey(address, vch);
1308 scriptSigRet << vch;
1312 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1315 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1316 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1321 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1325 case TX_NONSTANDARD:
1332 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1334 return vSolutions[0][0] + 1;
1336 return 1; // doesn't include args needed by the script
1341 bool IsStandard(const CScript& scriptPubKey)
1343 vector<valtype> vSolutions;
1344 txnouttype whichType;
1345 if (!Solver(scriptPubKey, whichType, vSolutions))
1348 if (whichType == TX_MULTISIG)
1350 unsigned char m = vSolutions.front()[0];
1351 unsigned char n = vSolutions.back()[0];
1352 // Support up to x-of-3 multisig txns as standard
1359 return whichType != TX_NONSTANDARD;
1363 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1365 unsigned int nResult = 0;
1366 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1368 CBitcoinAddress address;
1369 address.SetPubKey(pubkey);
1370 if (keystore.HaveKey(address))
1376 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1378 vector<valtype> vSolutions;
1379 txnouttype whichType;
1380 if (!Solver(scriptPubKey, whichType, vSolutions))
1383 CBitcoinAddress address;
1386 case TX_NONSTANDARD:
1389 address.SetPubKey(vSolutions[0]);
1390 return keystore.HaveKey(address);
1392 address.SetHash160(uint160(vSolutions[0]));
1393 return keystore.HaveKey(address);
1397 if (!keystore.GetCScript(uint160(vSolutions[0]), subscript))
1399 return IsMine(keystore, subscript);
1403 // Only consider transactions "mine" if we own ALL the
1404 // keys involved. multi-signature transactions that are
1405 // partially owned (somebody else has a key that can spend
1406 // them) enable spend-out-from-under-you attacks, especially
1407 // in shared-wallet situations.
1408 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1409 return HaveKeys(keys, keystore) == keys.size();
1415 bool ExtractAddress(const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1417 vector<valtype> vSolutions;
1418 txnouttype whichType;
1419 if (!Solver(scriptPubKey, whichType, vSolutions))
1422 if (whichType == TX_PUBKEY)
1424 addressRet.SetPubKey(vSolutions[0]);
1427 else if (whichType == TX_PUBKEYHASH)
1429 addressRet.SetHash160(uint160(vSolutions[0]));
1432 else if (whichType == TX_SCRIPTHASH)
1434 addressRet.SetScriptHash160(uint160(vSolutions[0]));
1437 // Multisig txns have more than one address...
1441 bool ExtractAddresses(const CScript& scriptPubKey, txnouttype& typeRet, vector<CBitcoinAddress>& addressRet, int& nRequiredRet)
1444 typeRet = TX_NONSTANDARD;
1445 vector<valtype> vSolutions;
1446 if (!Solver(scriptPubKey, typeRet, vSolutions))
1449 if (typeRet == TX_MULTISIG)
1451 nRequiredRet = vSolutions.front()[0];
1452 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1454 CBitcoinAddress address;
1455 address.SetPubKey(vSolutions[i]);
1456 addressRet.push_back(address);
1462 CBitcoinAddress address;
1463 if (typeRet == TX_PUBKEYHASH)
1464 address.SetHash160(uint160(vSolutions.front()));
1465 else if (typeRet == TX_SCRIPTHASH)
1466 address.SetScriptHash160(uint160(vSolutions.front()));
1467 else if (typeRet == TX_PUBKEY)
1468 address.SetPubKey(vSolutions.front());
1469 addressRet.push_back(address);
1475 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1476 bool fValidatePayToScriptHash, int nHashType)
1478 vector<vector<unsigned char> > stack, stackCopy;
1479 if (!EvalScript(stack, scriptSig, txTo, nIn, nHashType))
1481 if (fValidatePayToScriptHash)
1483 if (!EvalScript(stack, scriptPubKey, txTo, nIn, nHashType))
1488 if (CastToBool(stack.back()) == false)
1491 // Additional validation for spend-to-script-hash transactions:
1492 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1494 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1495 return false; // or validation fails
1497 const valtype& pubKeySerialized = stackCopy.back();
1498 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1499 popstack(stackCopy);
1501 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, nHashType))
1503 if (stackCopy.empty())
1505 return CastToBool(stackCopy.back());
1512 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1514 assert(nIn < txTo.vin.size());
1515 CTxIn& txin = txTo.vin[nIn];
1516 assert(txin.prevout.n < txFrom.vout.size());
1517 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1519 // Leave out the signature from the hash, since a signature can't sign itself.
1520 // The checksig op will also drop the signatures from its hash.
1521 uint256 hash = SignatureHash(txout.scriptPubKey, txTo, nIn, nHashType);
1523 txnouttype whichType;
1524 if (!Solver(keystore, txout.scriptPubKey, hash, nHashType, txin.scriptSig, whichType))
1527 if (whichType == TX_SCRIPTHASH)
1529 // Solver returns the subscript that need to be evaluated;
1530 // the final scriptSig is the signatures from that
1531 // and then the serialized subscript:
1532 CScript subscript = txin.scriptSig;
1534 // Recompute txn hash using subscript in place of scriptPubKey:
1535 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1537 if (!Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType))
1539 if (subType == TX_SCRIPTHASH)
1541 txin.scriptSig << static_cast<valtype>(subscript); // Append serialized subscript
1545 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, true, 0))
1552 bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, int nHashType)
1554 assert(nIn < txTo.vin.size());
1555 const CTxIn& txin = txTo.vin[nIn];
1556 if (txin.prevout.n >= txFrom.vout.size())
1558 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1560 if (txin.prevout.hash != txFrom.GetHash())
1563 if (!VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, nHashType))
1569 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1572 const_iterator pc = begin();
1573 opcodetype lastOpcode = OP_INVALIDOPCODE;
1577 if (!GetOp(pc, opcode))
1579 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1581 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1583 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1584 n += DecodeOP_N(lastOpcode);
1588 lastOpcode = opcode;
1593 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1595 if (!IsPayToScriptHash())
1596 return GetSigOpCount(true);
1598 // This is a pay-to-script-hash scriptPubKey;
1599 // get the last item that the scriptSig
1600 // pushes onto the stack:
1601 const_iterator pc = scriptSig.begin();
1602 vector<unsigned char> data;
1603 while (pc < scriptSig.end())
1606 if (!scriptSig.GetOp(pc, opcode, data))
1612 /// ... and return it's opcount:
1613 CScript subscript(data.begin(), data.end());
1614 return subscript.GetSigOpCount(true);
1617 bool CScript::IsPayToScriptHash() const
1619 // Extra-fast test for pay-to-script-hash CScripts:
1620 return (this->size() == 23 &&
1621 this->at(0) == OP_HASH160 &&
1622 this->at(1) == 0x14 &&
1623 this->at(22) == OP_EQUAL);
1626 void CScript::SetBitcoinAddress(const CBitcoinAddress& address)
1629 if (address.IsScript())
1630 *this << OP_HASH160 << address.GetHash160() << OP_EQUAL;
1632 *this << OP_DUP << OP_HASH160 << address.GetHash160() << OP_EQUALVERIFY << OP_CHECKSIG;
1635 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1639 *this << EncodeOP_N(nRequired);
1640 BOOST_FOREACH(const CKey& key, keys)
1641 *this << key.GetPubKey();
1642 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1645 void CScript::SetPayToScriptHash(const CScript& subscript)
1647 assert(!subscript.empty());
1648 uint160 subscriptHash = Hash160(subscript);
1650 *this << OP_HASH160 << subscriptHash << OP_EQUAL;