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, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
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)
55 // WARNING: This does not work as expected for signed integers; the sign-bit
56 // is left in place as the integer is zero-extended. The correct behavior
57 // would be to move the most significant bit of the last byte during the
58 // resize process. MakeSameSize() is currently only used by the disabled
59 // opcodes OP_AND, OP_OR, and OP_XOR.
61 void MakeSameSize(valtype& vch1, valtype& vch2)
63 // Lengthen the shorter one
64 if (vch1.size() < vch2.size())
66 // +unsigned char msb = vch1[vch1.size()-1];
67 // +vch1[vch1.size()-1] &= 0x7f;
68 // vch1.resize(vch2.size(), 0);
69 // +vch1[vch1.size()-1] = msb;
70 vch1.resize(vch2.size(), 0);
71 if (vch2.size() < vch1.size())
73 // +unsigned char msb = vch2[vch2.size()-1];
74 // +vch2[vch2.size()-1] &= 0x7f;
75 // vch2.resize(vch1.size(), 0);
76 // +vch2[vch2.size()-1] = msb;
77 vch2.resize(vch1.size(), 0);
83 // Script is a stack machine (like Forth) that evaluates a predicate
84 // returning a bool indicating valid or not. There are no loops.
86 #define stacktop(i) (stack.at(stack.size()+(i)))
87 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
88 static inline void popstack(vector<valtype>& stack)
91 throw runtime_error("popstack() : stack empty");
96 const char* GetTxnOutputType(txnouttype t)
100 case TX_NONSTANDARD: return "nonstandard";
101 case TX_PUBKEY: return "pubkey";
102 case TX_PUBKEYHASH: return "pubkeyhash";
103 case TX_SCRIPTHASH: return "scripthash";
104 case TX_MULTISIG: return "multisig";
105 case TX_NULL_DATA: return "nulldata";
111 const char* GetOpName(opcodetype opcode)
116 case OP_0 : return "0";
117 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
118 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
119 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
120 case OP_1NEGATE : return "-1";
121 case OP_RESERVED : return "OP_RESERVED";
122 case OP_1 : return "1";
123 case OP_2 : return "2";
124 case OP_3 : return "3";
125 case OP_4 : return "4";
126 case OP_5 : return "5";
127 case OP_6 : return "6";
128 case OP_7 : return "7";
129 case OP_8 : return "8";
130 case OP_9 : return "9";
131 case OP_10 : return "10";
132 case OP_11 : return "11";
133 case OP_12 : return "12";
134 case OP_13 : return "13";
135 case OP_14 : return "14";
136 case OP_15 : return "15";
137 case OP_16 : return "16";
140 case OP_NOP : return "OP_NOP";
141 case OP_VER : return "OP_VER";
142 case OP_IF : return "OP_IF";
143 case OP_NOTIF : return "OP_NOTIF";
144 case OP_VERIF : return "OP_VERIF";
145 case OP_VERNOTIF : return "OP_VERNOTIF";
146 case OP_ELSE : return "OP_ELSE";
147 case OP_ENDIF : return "OP_ENDIF";
148 case OP_VERIFY : return "OP_VERIFY";
149 case OP_RETURN : return "OP_RETURN";
152 case OP_TOALTSTACK : return "OP_TOALTSTACK";
153 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
154 case OP_2DROP : return "OP_2DROP";
155 case OP_2DUP : return "OP_2DUP";
156 case OP_3DUP : return "OP_3DUP";
157 case OP_2OVER : return "OP_2OVER";
158 case OP_2ROT : return "OP_2ROT";
159 case OP_2SWAP : return "OP_2SWAP";
160 case OP_IFDUP : return "OP_IFDUP";
161 case OP_DEPTH : return "OP_DEPTH";
162 case OP_DROP : return "OP_DROP";
163 case OP_DUP : return "OP_DUP";
164 case OP_NIP : return "OP_NIP";
165 case OP_OVER : return "OP_OVER";
166 case OP_PICK : return "OP_PICK";
167 case OP_ROLL : return "OP_ROLL";
168 case OP_ROT : return "OP_ROT";
169 case OP_SWAP : return "OP_SWAP";
170 case OP_TUCK : return "OP_TUCK";
173 case OP_CAT : return "OP_CAT";
174 case OP_SUBSTR : return "OP_SUBSTR";
175 case OP_LEFT : return "OP_LEFT";
176 case OP_RIGHT : return "OP_RIGHT";
177 case OP_SIZE : return "OP_SIZE";
180 case OP_INVERT : return "OP_INVERT";
181 case OP_AND : return "OP_AND";
182 case OP_OR : return "OP_OR";
183 case OP_XOR : return "OP_XOR";
184 case OP_EQUAL : return "OP_EQUAL";
185 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
186 case OP_RESERVED1 : return "OP_RESERVED1";
187 case OP_RESERVED2 : return "OP_RESERVED2";
190 case OP_1ADD : return "OP_1ADD";
191 case OP_1SUB : return "OP_1SUB";
192 case OP_2MUL : return "OP_2MUL";
193 case OP_2DIV : return "OP_2DIV";
194 case OP_NEGATE : return "OP_NEGATE";
195 case OP_ABS : return "OP_ABS";
196 case OP_NOT : return "OP_NOT";
197 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
198 case OP_ADD : return "OP_ADD";
199 case OP_SUB : return "OP_SUB";
200 case OP_MUL : return "OP_MUL";
201 case OP_DIV : return "OP_DIV";
202 case OP_MOD : return "OP_MOD";
203 case OP_LSHIFT : return "OP_LSHIFT";
204 case OP_RSHIFT : return "OP_RSHIFT";
205 case OP_BOOLAND : return "OP_BOOLAND";
206 case OP_BOOLOR : return "OP_BOOLOR";
207 case OP_NUMEQUAL : return "OP_NUMEQUAL";
208 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
209 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
210 case OP_LESSTHAN : return "OP_LESSTHAN";
211 case OP_GREATERTHAN : return "OP_GREATERTHAN";
212 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
213 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
214 case OP_MIN : return "OP_MIN";
215 case OP_MAX : return "OP_MAX";
216 case OP_WITHIN : return "OP_WITHIN";
219 case OP_RIPEMD160 : return "OP_RIPEMD160";
220 case OP_SHA1 : return "OP_SHA1";
221 case OP_SHA256 : return "OP_SHA256";
222 case OP_HASH160 : return "OP_HASH160";
223 case OP_HASH256 : return "OP_HASH256";
224 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
225 case OP_CHECKSIG : return "OP_CHECKSIG";
226 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
227 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
228 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
231 case OP_NOP1 : return "OP_NOP1";
232 case OP_NOP2 : return "OP_NOP2";
233 case OP_NOP3 : return "OP_NOP3";
234 case OP_NOP4 : return "OP_NOP4";
235 case OP_NOP5 : return "OP_NOP5";
236 case OP_NOP6 : return "OP_NOP6";
237 case OP_NOP7 : return "OP_NOP7";
238 case OP_NOP8 : return "OP_NOP8";
239 case OP_NOP9 : return "OP_NOP9";
240 case OP_NOP10 : return "OP_NOP10";
244 // template matching params
245 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
246 case OP_PUBKEY : return "OP_PUBKEY";
247 case OP_SMALLDATA : return "OP_SMALLDATA";
249 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
255 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
256 if (!(flags & SCRIPT_VERIFY_STRICTENC))
259 if (vchPubKey.size() < 33)
260 return error("Non-canonical public key: too short");
261 if (vchPubKey[0] == 0x04) {
262 if (vchPubKey.size() != 65)
263 return error("Non-canonical public key: invalid length for uncompressed key");
264 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
265 if (vchPubKey.size() != 33)
266 return error("Non-canonical public key: invalid length for compressed key");
268 return error("Non-canonical public key: compressed nor uncompressed");
273 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
274 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
275 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
276 // Where R and S are not negative (their first byte has its highest bit not set), and not
277 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
278 // in which case a single 0 byte is necessary and even required).
279 if (vchSig.size() < 9)
280 return error("Non-canonical signature: too short");
281 if (vchSig.size() > 73)
282 return error("Non-canonical signature: too long");
283 if (vchSig[0] != 0x30)
284 return error("Non-canonical signature: wrong type");
285 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
286 return error("Non-canonical signature: wrong length marker");
288 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
289 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
290 return error("Non-canonical signature: unknown hashtype byte");
292 unsigned int nLenR = vchSig[3];
293 if (5 + nLenR >= vchSig.size())
294 return error("Non-canonical signature: S length misplaced");
295 unsigned int nLenS = vchSig[5+nLenR];
296 if ((unsigned long)(nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
297 return error("Non-canonical signature: R+S length mismatch");
299 const unsigned char *R = &vchSig[4];
301 return error("Non-canonical signature: R value type mismatch");
303 return error("Non-canonical signature: R length is zero");
305 return error("Non-canonical signature: R value negative");
306 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
307 return error("Non-canonical signature: R value excessively padded");
309 const unsigned char *S = &vchSig[6+nLenR];
311 return error("Non-canonical signature: S value type mismatch");
313 return error("Non-canonical signature: S length is zero");
315 return error("Non-canonical signature: S value negative");
316 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
317 return error("Non-canonical signature: S value excessively padded");
320 unsigned int nLenR = vchSig[3];
321 unsigned int nLenS = vchSig[5+nLenR];
322 const unsigned char *S = &vchSig[6+nLenR];
323 // If the S value is above the order of the curve divided by two, its
324 // complement modulo the order could have been used instead, which is
325 // one byte shorter when encoded correctly.
326 if (!CKey::CheckSignatureElement(S, nLenS, true))
327 return error("Non-canonical signature: S value is unnecessarily high");
333 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
334 if (!(flags & SCRIPT_VERIFY_STRICTENC))
337 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
340 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
343 CScript::const_iterator pc = script.begin();
344 CScript::const_iterator pend = script.end();
345 CScript::const_iterator pbegincodehash = script.begin();
347 valtype vchPushValue;
349 vector<valtype> altstack;
350 if (script.size() > 10000)
358 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
363 if (!script.GetOp(pc, opcode, vchPushValue))
365 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
367 if (opcode > OP_16 && ++nOpCount > 201)
370 if (opcode == OP_CAT ||
371 opcode == OP_SUBSTR ||
373 opcode == OP_RIGHT ||
374 opcode == OP_INVERT ||
383 opcode == OP_LSHIFT ||
385 return false; // Disabled opcodes.
387 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
388 stack.push_back(vchPushValue);
389 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
414 CBigNum bn((int)opcode - (int)(OP_1 - 1));
415 stack.push_back(bn.getvch());
424 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
425 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
431 // <expression> if [statements] [else [statements]] endif
435 if (stack.size() < 1)
437 valtype& vch = stacktop(-1);
438 fValue = CastToBool(vch);
439 if (opcode == OP_NOTIF)
443 vfExec.push_back(fValue);
451 vfExec.back() = !vfExec.back();
466 // (false -- false) and return
467 if (stack.size() < 1)
469 bool fValue = CastToBool(stacktop(-1));
489 if (stack.size() < 1)
491 altstack.push_back(stacktop(-1));
496 case OP_FROMALTSTACK:
498 if (altstack.size() < 1)
500 stack.push_back(altstacktop(-1));
508 if (stack.size() < 2)
517 // (x1 x2 -- x1 x2 x1 x2)
518 if (stack.size() < 2)
520 valtype vch1 = stacktop(-2);
521 valtype vch2 = stacktop(-1);
522 stack.push_back(vch1);
523 stack.push_back(vch2);
529 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
530 if (stack.size() < 3)
532 valtype vch1 = stacktop(-3);
533 valtype vch2 = stacktop(-2);
534 valtype vch3 = stacktop(-1);
535 stack.push_back(vch1);
536 stack.push_back(vch2);
537 stack.push_back(vch3);
543 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
544 if (stack.size() < 4)
546 valtype vch1 = stacktop(-4);
547 valtype vch2 = stacktop(-3);
548 stack.push_back(vch1);
549 stack.push_back(vch2);
555 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
556 if (stack.size() < 6)
558 valtype vch1 = stacktop(-6);
559 valtype vch2 = stacktop(-5);
560 stack.erase(stack.end()-6, stack.end()-4);
561 stack.push_back(vch1);
562 stack.push_back(vch2);
568 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
569 if (stack.size() < 4)
571 swap(stacktop(-4), stacktop(-2));
572 swap(stacktop(-3), stacktop(-1));
579 if (stack.size() < 1)
581 valtype vch = stacktop(-1);
583 stack.push_back(vch);
590 CBigNum bn((uint16_t) stack.size());
591 stack.push_back(bn.getvch());
598 if (stack.size() < 1)
607 if (stack.size() < 1)
609 valtype vch = stacktop(-1);
610 stack.push_back(vch);
617 if (stack.size() < 2)
619 stack.erase(stack.end() - 2);
625 // (x1 x2 -- x1 x2 x1)
626 if (stack.size() < 2)
628 valtype vch = stacktop(-2);
629 stack.push_back(vch);
636 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
637 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
638 if (stack.size() < 2)
640 int n = CastToBigNum(stacktop(-1)).getint32();
642 if (n < 0 || n >= (int)stack.size())
644 valtype vch = stacktop(-n-1);
645 if (opcode == OP_ROLL)
646 stack.erase(stack.end()-n-1);
647 stack.push_back(vch);
653 // (x1 x2 x3 -- x2 x3 x1)
654 // x2 x1 x3 after first swap
655 // x2 x3 x1 after second swap
656 if (stack.size() < 3)
658 swap(stacktop(-3), stacktop(-2));
659 swap(stacktop(-2), stacktop(-1));
666 if (stack.size() < 2)
668 swap(stacktop(-2), stacktop(-1));
674 // (x1 x2 -- x2 x1 x2)
675 if (stack.size() < 2)
677 valtype vch = stacktop(-1);
678 stack.insert(stack.end()-2, vch);
686 if (stack.size() < 1)
688 CBigNum bn((uint16_t) stacktop(-1).size());
689 stack.push_back(bn.getvch());
699 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
702 if (stack.size() < 2)
704 valtype& vch1 = stacktop(-2);
705 valtype& vch2 = stacktop(-1);
706 bool fEqual = (vch1 == vch2);
707 // OP_NOTEQUAL is disabled because it would be too easy to say
708 // something like n != 1 and have some wiseguy pass in 1 with extra
709 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
710 //if (opcode == OP_NOTEQUAL)
714 stack.push_back(fEqual ? vchTrue : vchFalse);
715 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_NEGATE: bn = -bn; break;
745 case OP_ABS: if (bn < bnZero) bn = -bn; break;
746 case OP_NOT: bn = (bn == bnZero); break;
747 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
748 default: assert(!"invalid opcode"); break;
751 stack.push_back(bn.getvch());
760 case OP_NUMEQUALVERIFY:
764 case OP_LESSTHANOREQUAL:
765 case OP_GREATERTHANOREQUAL:
770 if (stack.size() < 2)
772 CBigNum bn1 = CastToBigNum(stacktop(-2));
773 CBigNum bn2 = CastToBigNum(stacktop(-1));
785 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
786 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
787 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
788 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
789 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
790 case OP_LESSTHAN: bn = (bn1 < bn2); break;
791 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
792 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
793 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
794 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
795 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
796 default: assert(!"invalid opcode"); break;
800 stack.push_back(bn.getvch());
802 if (opcode == OP_NUMEQUALVERIFY)
804 if (CastToBool(stacktop(-1)))
814 // (x min max -- out)
815 if (stack.size() < 3)
817 CBigNum bn1 = CastToBigNum(stacktop(-3));
818 CBigNum bn2 = CastToBigNum(stacktop(-2));
819 CBigNum bn3 = CastToBigNum(stacktop(-1));
820 bool fValue = (bn2 <= bn1 && bn1 < bn3);
824 stack.push_back(fValue ? vchTrue : vchFalse);
839 if (stack.size() < 1)
841 valtype& vch = stacktop(-1);
842 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
843 if (opcode == OP_RIPEMD160)
844 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
845 else if (opcode == OP_SHA1)
846 SHA1(&vch[0], vch.size(), &vchHash[0]);
847 else if (opcode == OP_SHA256)
848 SHA256(&vch[0], vch.size(), &vchHash[0]);
849 else if (opcode == OP_HASH160)
851 uint160 hash160 = Hash160(vch);
852 memcpy(&vchHash[0], &hash160, sizeof(hash160));
854 else if (opcode == OP_HASH256)
856 uint256 hash = Hash(vch.begin(), vch.end());
857 memcpy(&vchHash[0], &hash, sizeof(hash));
860 stack.push_back(vchHash);
864 case OP_CODESEPARATOR:
866 // Hash starts after the code separator
872 case OP_CHECKSIGVERIFY:
874 // (sig pubkey -- bool)
875 if (stack.size() < 2)
878 valtype& vchSig = stacktop(-2);
879 valtype& vchPubKey = stacktop(-1);
882 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
883 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
885 // Subset of script starting at the most recent codeseparator
886 CScript scriptCode(pbegincodehash, pend);
888 // Drop the signature, since there's no way for a signature to sign itself
889 scriptCode.FindAndDelete(CScript(vchSig));
891 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
892 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
896 stack.push_back(fSuccess ? vchTrue : vchFalse);
897 if (opcode == OP_CHECKSIGVERIFY)
907 case OP_CHECKMULTISIG:
908 case OP_CHECKMULTISIGVERIFY:
910 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
913 if ((int)stack.size() < i)
916 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
917 if (nKeysCount < 0 || nKeysCount > 20)
919 nOpCount += nKeysCount;
924 if ((int)stack.size() < i)
927 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
928 if (nSigsCount < 0 || nSigsCount > nKeysCount)
932 if ((int)stack.size() < i)
935 // Subset of script starting at the most recent codeseparator
936 CScript scriptCode(pbegincodehash, pend);
938 // Drop the signatures, since there's no way for a signature to sign itself
939 for (int k = 0; k < nSigsCount; k++)
941 valtype& vchSig = stacktop(-isig-k);
942 scriptCode.FindAndDelete(CScript(vchSig));
945 bool fSuccess = true;
946 while (fSuccess && nSigsCount > 0)
948 valtype& vchSig = stacktop(-isig);
949 valtype& vchPubKey = stacktop(-ikey);
952 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
953 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
962 // If there are more signatures left than keys left,
963 // then too many signatures have failed
964 if (nSigsCount > nKeysCount)
971 // A bug causes CHECKMULTISIG to consume one extra argument
972 // whose contents were not checked in any way.
974 // Unfortunately this is a potential source of mutability,
975 // so optionally verify it is exactly equal to zero prior
976 // to removing it from the stack.
977 if (stack.size() < 1)
979 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
980 return error("CHECKMULTISIG dummy argument not null");
983 stack.push_back(fSuccess ? vchTrue : vchFalse);
985 if (opcode == OP_CHECKMULTISIGVERIFY)
1000 if (stack.size() + altstack.size() > 1000)
1010 if (!vfExec.empty())
1024 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1026 if (nIn >= txTo.vin.size())
1028 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1031 CTransaction txTmp(txTo);
1033 // In case concatenating two scripts ends up with two codeseparators,
1034 // or an extra one at the end, this prevents all those possible incompatibilities.
1035 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1037 // Blank out other inputs' signatures
1038 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1039 txTmp.vin[i].scriptSig = CScript();
1040 txTmp.vin[nIn].scriptSig = scriptCode;
1042 // Blank out some of the outputs
1043 if ((nHashType & 0x1f) == SIGHASH_NONE)
1048 // Let the others update at will
1049 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1051 txTmp.vin[i].nSequence = 0;
1053 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1055 // Only lock-in the txout payee at same index as txin
1056 unsigned int nOut = nIn;
1057 if (nOut >= txTmp.vout.size())
1059 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1062 txTmp.vout.resize(nOut+1);
1063 for (unsigned int i = 0; i < nOut; i++)
1064 txTmp.vout[i].SetNull();
1066 // Let the others update at will
1067 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1069 txTmp.vin[i].nSequence = 0;
1072 // Blank out other inputs completely, not recommended for open transactions
1073 if (nHashType & SIGHASH_ANYONECANPAY)
1075 txTmp.vin[0] = txTmp.vin[nIn];
1076 txTmp.vin.resize(1);
1079 // Serialize and hash
1080 CDataStream ss(SER_GETHASH, 0);
1082 ss << txTmp << nHashType;
1083 return Hash(ss.begin(), ss.end());
1087 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1088 // twice for every transaction (once when accepted into memory pool, and
1089 // again when accepted into the block chain)
1091 class CSignatureCache
1094 // sigdata_type is (signature hash, signature, public key):
1095 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1096 std::set< sigdata_type> setValid;
1097 boost::shared_mutex cs_sigcache;
1101 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1103 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1105 sigdata_type k(hash, vchSig, pubKey);
1106 std::set<sigdata_type>::iterator mi = setValid.find(k);
1107 if (mi != setValid.end())
1112 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1114 // DoS prevention: limit cache size to less than 10MB
1115 // (~200 bytes per cache entry times 50,000 entries)
1116 // Since there are a maximum of 20,000 signature operations per block
1117 // 50,000 is a reasonable default.
1118 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1119 if (nMaxCacheSize <= 0) return;
1121 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1123 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1125 // Evict a random entry. Random because that helps
1126 // foil would-be DoS attackers who might try to pre-generate
1127 // and re-use a set of valid signatures just-slightly-greater
1128 // than our cache size.
1129 uint256 randomHash = GetRandHash();
1130 std::vector<unsigned char> unused;
1131 std::set<sigdata_type>::iterator it =
1132 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1133 if (it == setValid.end())
1134 it = setValid.begin();
1135 setValid.erase(*it);
1138 sigdata_type k(hash, vchSig, pubKey);
1143 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1144 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1146 static CSignatureCache signatureCache;
1149 if (!key.SetPubKey(vchPubKey))
1151 CPubKey pubkey = key.GetPubKey();
1152 if (!pubkey.IsValid())
1155 // Hash type is one byte tacked on to the end of the signature
1159 nHashType = vchSig.back();
1160 else if (nHashType != vchSig.back())
1164 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1166 if (signatureCache.Get(sighash, vchSig, pubkey))
1169 if (!key.Verify(sighash, vchSig))
1172 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1173 signatureCache.Set(sighash, vchSig, pubkey);
1186 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1188 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1191 static map<txnouttype, CScript> mTemplates;
1192 if (mTemplates.empty())
1194 // Standard tx, sender provides pubkey, receiver adds signature
1195 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1197 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1198 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1200 // Sender provides N pubkeys, receivers provides M signatures
1201 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1203 // Empty, provably prunable, data-carrying output
1204 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1207 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1208 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1209 if (scriptPubKey.IsPayToScriptHash())
1211 typeRet = TX_SCRIPTHASH;
1212 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1213 vSolutionsRet.push_back(hashBytes);
1218 const CScript& script1 = scriptPubKey;
1219 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1221 const CScript& script2 = tplate.second;
1222 vSolutionsRet.clear();
1224 opcodetype opcode1, opcode2;
1225 vector<unsigned char> vch1, vch2;
1228 CScript::const_iterator pc1 = script1.begin();
1229 CScript::const_iterator pc2 = script2.begin();
1232 if (pc1 == script1.end() && pc2 == script2.end())
1235 typeRet = tplate.first;
1236 if (typeRet == TX_MULTISIG)
1238 // Additional checks for TX_MULTISIG:
1239 unsigned char m = vSolutionsRet.front()[0];
1240 unsigned char n = vSolutionsRet.back()[0];
1241 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1246 if (!script1.GetOp(pc1, opcode1, vch1))
1248 if (!script2.GetOp(pc2, opcode2, vch2))
1251 // Template matching opcodes:
1252 if (opcode2 == OP_PUBKEYS)
1254 while (vch1.size() >= 33 && vch1.size() <= 120)
1256 vSolutionsRet.push_back(vch1);
1257 if (!script1.GetOp(pc1, opcode1, vch1))
1260 if (!script2.GetOp(pc2, opcode2, vch2))
1262 // Normal situation is to fall through
1263 // to other if/else statements
1266 if (opcode2 == OP_PUBKEY)
1268 if (vch1.size() < 33 || vch1.size() > 120)
1270 vSolutionsRet.push_back(vch1);
1272 else if (opcode2 == OP_PUBKEYHASH)
1274 if (vch1.size() != sizeof(uint160))
1276 vSolutionsRet.push_back(vch1);
1278 else if (opcode2 == OP_SMALLINTEGER)
1279 { // Single-byte small integer pushed onto vSolutions
1280 if (opcode1 == OP_0 ||
1281 (opcode1 >= OP_1 && opcode1 <= OP_16))
1283 char n = (char)CScript::DecodeOP_N(opcode1);
1284 vSolutionsRet.push_back(valtype(1, n));
1289 else if (opcode2 == OP_SMALLDATA)
1291 // small pushdata, <= 80 bytes
1292 if (vch1.size() > 80)
1295 else if (opcode1 != opcode2 || vch1 != vch2)
1297 // Others must match exactly
1303 vSolutionsRet.clear();
1304 typeRet = TX_NONSTANDARD;
1309 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1312 if (!keystore.GetKey(address, key))
1315 vector<unsigned char> vchSig;
1316 if (!key.Sign(hash, vchSig))
1318 vchSig.push_back((unsigned char)nHashType);
1319 scriptSigRet << vchSig;
1324 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1327 int nRequired = multisigdata.front()[0];
1328 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1330 const valtype& pubkey = multisigdata[i];
1331 CKeyID keyID = CPubKey(pubkey).GetID();
1332 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1335 return nSigned==nRequired;
1339 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1340 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1341 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1342 // Returns false if scriptPubKey could not be completely satisfied.
1344 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1345 CScript& scriptSigRet, txnouttype& whichTypeRet)
1347 scriptSigRet.clear();
1349 vector<valtype> vSolutions;
1350 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1354 switch (whichTypeRet)
1356 case TX_NONSTANDARD:
1360 keyID = CPubKey(vSolutions[0]).GetID();
1361 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1363 keyID = CKeyID(uint160(vSolutions[0]));
1364 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1369 keystore.GetPubKey(keyID, vch);
1370 scriptSigRet << vch;
1374 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1377 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1378 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1383 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1387 case TX_NONSTANDARD:
1396 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1398 return vSolutions[0][0] + 1;
1400 return 1; // doesn't include args needed by the script
1405 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1407 vector<valtype> vSolutions;
1408 if (!Solver(scriptPubKey, whichType, vSolutions))
1411 if (whichType == TX_MULTISIG)
1413 unsigned char m = vSolutions.front()[0];
1414 unsigned char n = vSolutions.back()[0];
1415 // Support up to x-of-3 multisig txns as standard
1422 return whichType != TX_NONSTANDARD;
1426 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1428 unsigned int nResult = 0;
1429 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1431 CKeyID keyID = CPubKey(pubkey).GetID();
1432 if (keystore.HaveKey(keyID))
1439 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1442 const CKeyStore *keystore;
1444 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1445 bool operator()(const CNoDestination &dest) const { return false; }
1446 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1447 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1450 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1453 script.SetDestination(dest);
1454 return IsMine(keystore, script);
1457 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1459 vector<valtype> vSolutions;
1460 txnouttype whichType;
1461 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1462 if (keystore.HaveWatchOnly(scriptPubKey))
1463 return MINE_WATCH_ONLY;
1470 case TX_NONSTANDARD:
1474 keyID = CPubKey(vSolutions[0]).GetID();
1475 if (keystore.HaveKey(keyID))
1476 return MINE_SPENDABLE;
1479 keyID = CKeyID(uint160(vSolutions[0]));
1480 if (keystore.HaveKey(keyID))
1481 return MINE_SPENDABLE;
1485 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1487 if (keystore.GetCScript(scriptID, subscript)) {
1488 isminetype ret = IsMine(keystore, subscript);
1489 if (ret == MINE_SPENDABLE)
1496 // Only consider transactions "mine" if we own ALL the
1497 // keys involved. multi-signature transactions that are
1498 // partially owned (somebody else has a key that can spend
1499 // them) enable spend-out-from-under-you attacks, especially
1500 // in shared-wallet situations.
1501 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1502 if (HaveKeys(keys, keystore) == keys.size())
1503 return MINE_SPENDABLE;
1508 if (keystore.HaveWatchOnly(scriptPubKey))
1509 return MINE_WATCH_ONLY;
1513 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1515 vector<valtype> vSolutions;
1516 txnouttype whichType;
1517 if (!Solver(scriptPubKey, whichType, vSolutions))
1520 if (whichType == TX_PUBKEY)
1522 addressRet = CPubKey(vSolutions[0]).GetID();
1525 else if (whichType == TX_PUBKEYHASH)
1527 addressRet = CKeyID(uint160(vSolutions[0]));
1530 else if (whichType == TX_SCRIPTHASH)
1532 addressRet = CScriptID(uint160(vSolutions[0]));
1535 // Multisig txns have more than one address...
1539 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1541 const CKeyStore &keystore;
1542 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1543 std::vector<CKeyID> &vKeys;
1546 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1548 void Process(const CScript &script) {
1550 std::vector<CTxDestination> vDest;
1552 if (ExtractDestinations(script, type, vDest, nRequired)) {
1553 BOOST_FOREACH(const CTxDestination &dest, vDest)
1554 boost::apply_visitor(*this, dest);
1558 void operator()(const CKeyID &keyId) {
1559 if (keystore.HaveKey(keyId))
1560 vKeys.push_back(keyId);
1563 void operator()(const CScriptID &scriptId) {
1565 if (keystore.GetCScript(scriptId, script))
1569 void operator()(const CNoDestination &none) {}
1573 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1574 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1577 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1580 typeRet = TX_NONSTANDARD;
1581 vector<valtype> vSolutions;
1582 if (!Solver(scriptPubKey, typeRet, vSolutions))
1584 if (typeRet == TX_NULL_DATA)
1587 if (typeRet == TX_MULTISIG)
1589 nRequiredRet = vSolutions.front()[0];
1590 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1592 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1593 addressRet.push_back(address);
1599 CTxDestination address;
1600 if (!ExtractDestination(scriptPubKey, address))
1602 addressRet.push_back(address);
1608 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1609 unsigned int flags, int nHashType)
1611 vector<vector<unsigned char> > stack, stackCopy;
1612 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1614 if (flags & SCRIPT_VERIFY_P2SH)
1616 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1621 if (CastToBool(stack.back()) == false)
1624 // Additional validation for spend-to-script-hash transactions:
1625 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1627 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1628 return false; // or validation fails
1630 // stackCopy cannot be empty here, because if it was the
1631 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1632 // an empty stack and the EvalScript above would return false.
1633 assert(!stackCopy.empty());
1635 const valtype& pubKeySerialized = stackCopy.back();
1636 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1637 popstack(stackCopy);
1639 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1641 if (stackCopy.empty())
1643 return CastToBool(stackCopy.back());
1649 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1651 assert(nIn < txTo.vin.size());
1652 CTxIn& txin = txTo.vin[nIn];
1654 // Leave out the signature from the hash, since a signature can't sign itself.
1655 // The checksig op will also drop the signatures from its hash.
1656 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1658 txnouttype whichType;
1659 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1662 if (whichType == TX_SCRIPTHASH)
1664 // Solver returns the subscript that need to be evaluated;
1665 // the final scriptSig is the signatures from that
1666 // and then the serialized subscript:
1667 CScript subscript = txin.scriptSig;
1669 // Recompute txn hash using subscript in place of scriptPubKey:
1670 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1674 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1675 // Append serialized subscript whether or not it is completely signed:
1676 txin.scriptSig << static_cast<valtype>(subscript);
1677 if (!fSolved) return false;
1681 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1684 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1686 assert(nIn < txTo.vin.size());
1687 CTxIn& txin = txTo.vin[nIn];
1688 assert(txin.prevout.n < txFrom.vout.size());
1689 assert(txin.prevout.hash == txFrom.GetHash());
1690 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1692 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1695 static CScript PushAll(const vector<valtype>& values)
1698 BOOST_FOREACH(const valtype& v, values)
1703 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1704 const vector<valtype>& vSolutions,
1705 vector<valtype>& sigs1, vector<valtype>& sigs2)
1707 // Combine all the signatures we've got:
1708 set<valtype> allsigs;
1709 BOOST_FOREACH(const valtype& v, sigs1)
1714 BOOST_FOREACH(const valtype& v, sigs2)
1720 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1721 assert(vSolutions.size() > 1);
1722 unsigned int nSigsRequired = vSolutions.front()[0];
1723 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1724 map<valtype, valtype> sigs;
1725 BOOST_FOREACH(const valtype& sig, allsigs)
1727 for (unsigned int i = 0; i < nPubKeys; i++)
1729 const valtype& pubkey = vSolutions[i+1];
1730 if (sigs.count(pubkey))
1731 continue; // Already got a sig for this pubkey
1733 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1740 // Now build a merged CScript:
1741 unsigned int nSigsHave = 0;
1742 CScript result; result << OP_0; // pop-one-too-many workaround
1743 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1745 if (sigs.count(vSolutions[i+1]))
1747 result << sigs[vSolutions[i+1]];
1751 // Fill any missing with OP_0:
1752 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1758 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1759 const txnouttype txType, const vector<valtype>& vSolutions,
1760 vector<valtype>& sigs1, vector<valtype>& sigs2)
1764 case TX_NONSTANDARD:
1766 // Don't know anything about this, assume bigger one is correct:
1767 if (sigs1.size() >= sigs2.size())
1768 return PushAll(sigs1);
1769 return PushAll(sigs2);
1772 // Signatures are bigger than placeholders or empty scripts:
1773 if (sigs1.empty() || sigs1[0].empty())
1774 return PushAll(sigs2);
1775 return PushAll(sigs1);
1777 if (sigs1.empty() || sigs1.back().empty())
1778 return PushAll(sigs2);
1779 else if (sigs2.empty() || sigs2.back().empty())
1780 return PushAll(sigs1);
1783 // Recur to combine:
1784 valtype spk = sigs1.back();
1785 CScript pubKey2(spk.begin(), spk.end());
1788 vector<vector<unsigned char> > vSolutions2;
1789 Solver(pubKey2, txType2, vSolutions2);
1792 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1797 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1803 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1804 const CScript& scriptSig1, const CScript& scriptSig2)
1807 vector<vector<unsigned char> > vSolutions;
1808 Solver(scriptPubKey, txType, vSolutions);
1810 vector<valtype> stack1;
1811 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1812 vector<valtype> stack2;
1813 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1815 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1818 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1821 const_iterator pc = begin();
1822 opcodetype lastOpcode = OP_INVALIDOPCODE;
1826 if (!GetOp(pc, opcode))
1828 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1830 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1832 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1833 n += DecodeOP_N(lastOpcode);
1837 lastOpcode = opcode;
1842 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1844 if (!IsPayToScriptHash())
1845 return GetSigOpCount(true);
1847 // This is a pay-to-script-hash scriptPubKey;
1848 // get the last item that the scriptSig
1849 // pushes onto the stack:
1850 const_iterator pc = scriptSig.begin();
1851 vector<unsigned char> data;
1852 while (pc < scriptSig.end())
1855 if (!scriptSig.GetOp(pc, opcode, data))
1861 /// ... and return its opcount:
1862 CScript subscript(data.begin(), data.end());
1863 return subscript.GetSigOpCount(true);
1866 bool CScript::IsPayToScriptHash() const
1868 // Extra-fast test for pay-to-script-hash CScripts:
1869 return (this->size() == 23 &&
1870 this->at(0) == OP_HASH160 &&
1871 this->at(1) == 0x14 &&
1872 this->at(22) == OP_EQUAL);
1875 bool CScript::HasCanonicalPushes() const
1877 const_iterator pc = begin();
1881 std::vector<unsigned char> data;
1882 if (!GetOp(pc, opcode, data))
1886 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1887 // Could have used an OP_n code, rather than a 1-byte push.
1889 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1890 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1892 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1893 // Could have used an OP_PUSHDATA1.
1895 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1896 // Could have used an OP_PUSHDATA2.
1902 class CScriptVisitor : public boost::static_visitor<bool>
1907 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1909 bool operator()(const CNoDestination &dest) const {
1914 bool operator()(const CKeyID &keyID) const {
1916 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1920 bool operator()(const CScriptID &scriptID) const {
1922 *script << OP_HASH160 << scriptID << OP_EQUAL;
1927 void CScript::SetDestination(const CTxDestination& dest)
1929 boost::apply_visitor(CScriptVisitor(this), dest);
1932 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1936 *this << EncodeOP_N(nRequired);
1937 BOOST_FOREACH(const CKey& key, keys)
1938 *this << key.GetPubKey();
1939 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;