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 IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
274 if (!(flags & SCRIPT_VERIFY_STRICTENC))
277 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
278 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
279 // Where R and S are not negative (their first byte has its highest bit not set), and not
280 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
281 // in which case a single 0 byte is necessary and even required).
282 if (vchSig.size() < 9)
283 return error("Non-canonical signature: too short");
284 if (vchSig.size() > 73)
285 return error("Non-canonical signature: too long");
286 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
287 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
288 return error("Non-canonical signature: unknown hashtype byte");
289 if (vchSig[0] != 0x30)
290 return error("Non-canonical signature: wrong type");
291 if (vchSig[1] != vchSig.size()-3)
292 return error("Non-canonical signature: wrong length marker");
293 unsigned int nLenR = vchSig[3];
294 if (5 + nLenR >= vchSig.size())
295 return error("Non-canonical signature: S length misplaced");
296 unsigned int nLenS = vchSig[5+nLenR];
297 if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
298 return error("Non-canonical signature: R+S length mismatch");
300 const unsigned char *R = &vchSig[4];
302 return error("Non-canonical signature: R value type mismatch");
304 return error("Non-canonical signature: R length is zero");
306 return error("Non-canonical signature: R value negative");
307 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
308 return error("Non-canonical signature: R value excessively padded");
310 const unsigned char *S = &vchSig[6+nLenR];
312 return error("Non-canonical signature: S value type mismatch");
314 return error("Non-canonical signature: S length is zero");
316 return error("Non-canonical signature: S value negative");
317 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
318 return error("Non-canonical signature: S value excessively padded");
320 if (flags & SCRIPT_VERIFY_LOW_S) {
321 if (!CKey::CheckSignatureElement(S, nLenS, true))
322 return error("Non-canonical signature: S value is unnecessarily high");
328 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
331 CScript::const_iterator pc = script.begin();
332 CScript::const_iterator pend = script.end();
333 CScript::const_iterator pbegincodehash = script.begin();
335 valtype vchPushValue;
337 vector<valtype> altstack;
338 if (script.size() > 10000)
346 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
351 if (!script.GetOp(pc, opcode, vchPushValue))
353 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
355 if (opcode > OP_16 && ++nOpCount > 201)
358 if (opcode == OP_CAT ||
359 opcode == OP_SUBSTR ||
361 opcode == OP_RIGHT ||
362 opcode == OP_INVERT ||
371 opcode == OP_LSHIFT ||
373 return false; // Disabled opcodes.
375 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
376 stack.push_back(vchPushValue);
377 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
402 CBigNum bn((int)opcode - (int)(OP_1 - 1));
403 stack.push_back(bn.getvch());
412 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
413 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
419 // <expression> if [statements] [else [statements]] endif
423 if (stack.size() < 1)
425 valtype& vch = stacktop(-1);
426 fValue = CastToBool(vch);
427 if (opcode == OP_NOTIF)
431 vfExec.push_back(fValue);
439 vfExec.back() = !vfExec.back();
454 // (false -- false) and return
455 if (stack.size() < 1)
457 bool fValue = CastToBool(stacktop(-1));
477 if (stack.size() < 1)
479 altstack.push_back(stacktop(-1));
484 case OP_FROMALTSTACK:
486 if (altstack.size() < 1)
488 stack.push_back(altstacktop(-1));
496 if (stack.size() < 2)
505 // (x1 x2 -- x1 x2 x1 x2)
506 if (stack.size() < 2)
508 valtype vch1 = stacktop(-2);
509 valtype vch2 = stacktop(-1);
510 stack.push_back(vch1);
511 stack.push_back(vch2);
517 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
518 if (stack.size() < 3)
520 valtype vch1 = stacktop(-3);
521 valtype vch2 = stacktop(-2);
522 valtype vch3 = stacktop(-1);
523 stack.push_back(vch1);
524 stack.push_back(vch2);
525 stack.push_back(vch3);
531 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
532 if (stack.size() < 4)
534 valtype vch1 = stacktop(-4);
535 valtype vch2 = stacktop(-3);
536 stack.push_back(vch1);
537 stack.push_back(vch2);
543 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
544 if (stack.size() < 6)
546 valtype vch1 = stacktop(-6);
547 valtype vch2 = stacktop(-5);
548 stack.erase(stack.end()-6, stack.end()-4);
549 stack.push_back(vch1);
550 stack.push_back(vch2);
556 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
557 if (stack.size() < 4)
559 swap(stacktop(-4), stacktop(-2));
560 swap(stacktop(-3), stacktop(-1));
567 if (stack.size() < 1)
569 valtype vch = stacktop(-1);
571 stack.push_back(vch);
578 CBigNum bn(stack.size());
579 stack.push_back(bn.getvch());
586 if (stack.size() < 1)
595 if (stack.size() < 1)
597 valtype vch = stacktop(-1);
598 stack.push_back(vch);
605 if (stack.size() < 2)
607 stack.erase(stack.end() - 2);
613 // (x1 x2 -- x1 x2 x1)
614 if (stack.size() < 2)
616 valtype vch = stacktop(-2);
617 stack.push_back(vch);
624 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
625 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
626 if (stack.size() < 2)
628 int n = CastToBigNum(stacktop(-1)).getint();
630 if (n < 0 || n >= (int)stack.size())
632 valtype vch = stacktop(-n-1);
633 if (opcode == OP_ROLL)
634 stack.erase(stack.end()-n-1);
635 stack.push_back(vch);
641 // (x1 x2 x3 -- x2 x3 x1)
642 // x2 x1 x3 after first swap
643 // x2 x3 x1 after second swap
644 if (stack.size() < 3)
646 swap(stacktop(-3), stacktop(-2));
647 swap(stacktop(-2), stacktop(-1));
654 if (stack.size() < 2)
656 swap(stacktop(-2), stacktop(-1));
662 // (x1 x2 -- x2 x1 x2)
663 if (stack.size() < 2)
665 valtype vch = stacktop(-1);
666 stack.insert(stack.end()-2, vch);
674 if (stack.size() < 1)
676 CBigNum bn(stacktop(-1).size());
677 stack.push_back(bn.getvch());
687 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
690 if (stack.size() < 2)
692 valtype& vch1 = stacktop(-2);
693 valtype& vch2 = stacktop(-1);
694 bool fEqual = (vch1 == vch2);
695 // OP_NOTEQUAL is disabled because it would be too easy to say
696 // something like n != 1 and have some wiseguy pass in 1 with extra
697 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
698 //if (opcode == OP_NOTEQUAL)
702 stack.push_back(fEqual ? vchTrue : vchFalse);
703 if (opcode == OP_EQUALVERIFY)
725 if (stack.size() < 1)
727 CBigNum bn = CastToBigNum(stacktop(-1));
730 case OP_1ADD: bn += bnOne; break;
731 case OP_1SUB: bn -= bnOne; break;
732 case OP_NEGATE: bn = -bn; break;
733 case OP_ABS: if (bn < bnZero) bn = -bn; break;
734 case OP_NOT: bn = (bn == bnZero); break;
735 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
736 default: assert(!"invalid opcode"); break;
739 stack.push_back(bn.getvch());
748 case OP_NUMEQUALVERIFY:
752 case OP_LESSTHANOREQUAL:
753 case OP_GREATERTHANOREQUAL:
758 if (stack.size() < 2)
760 CBigNum bn1 = CastToBigNum(stacktop(-2));
761 CBigNum bn2 = CastToBigNum(stacktop(-1));
773 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
774 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
775 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
776 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
777 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
778 case OP_LESSTHAN: bn = (bn1 < bn2); break;
779 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
780 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
781 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
782 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
783 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
784 default: assert(!"invalid opcode"); break;
788 stack.push_back(bn.getvch());
790 if (opcode == OP_NUMEQUALVERIFY)
792 if (CastToBool(stacktop(-1)))
802 // (x min max -- out)
803 if (stack.size() < 3)
805 CBigNum bn1 = CastToBigNum(stacktop(-3));
806 CBigNum bn2 = CastToBigNum(stacktop(-2));
807 CBigNum bn3 = CastToBigNum(stacktop(-1));
808 bool fValue = (bn2 <= bn1 && bn1 < bn3);
812 stack.push_back(fValue ? vchTrue : vchFalse);
827 if (stack.size() < 1)
829 valtype& vch = stacktop(-1);
830 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
831 if (opcode == OP_RIPEMD160)
832 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
833 else if (opcode == OP_SHA1)
834 SHA1(&vch[0], vch.size(), &vchHash[0]);
835 else if (opcode == OP_SHA256)
836 SHA256(&vch[0], vch.size(), &vchHash[0]);
837 else if (opcode == OP_HASH160)
839 uint160 hash160 = Hash160(vch);
840 memcpy(&vchHash[0], &hash160, sizeof(hash160));
842 else if (opcode == OP_HASH256)
844 uint256 hash = Hash(vch.begin(), vch.end());
845 memcpy(&vchHash[0], &hash, sizeof(hash));
848 stack.push_back(vchHash);
852 case OP_CODESEPARATOR:
854 // Hash starts after the code separator
860 case OP_CHECKSIGVERIFY:
862 // (sig pubkey -- bool)
863 if (stack.size() < 2)
866 valtype& vchSig = stacktop(-2);
867 valtype& vchPubKey = stacktop(-1);
870 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
871 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
873 // Subset of script starting at the most recent codeseparator
874 CScript scriptCode(pbegincodehash, pend);
876 // Drop the signature, since there's no way for a signature to sign itself
877 scriptCode.FindAndDelete(CScript(vchSig));
879 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
880 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
884 stack.push_back(fSuccess ? vchTrue : vchFalse);
885 if (opcode == OP_CHECKSIGVERIFY)
895 case OP_CHECKMULTISIG:
896 case OP_CHECKMULTISIGVERIFY:
898 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
901 if ((int)stack.size() < i)
904 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
905 if (nKeysCount < 0 || nKeysCount > 20)
907 nOpCount += nKeysCount;
912 if ((int)stack.size() < i)
915 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
916 if (nSigsCount < 0 || nSigsCount > nKeysCount)
920 if ((int)stack.size() < i)
923 // Subset of script starting at the most recent codeseparator
924 CScript scriptCode(pbegincodehash, pend);
926 // Drop the signatures, since there's no way for a signature to sign itself
927 for (int k = 0; k < nSigsCount; k++)
929 valtype& vchSig = stacktop(-isig-k);
930 scriptCode.FindAndDelete(CScript(vchSig));
933 bool fSuccess = true;
934 while (fSuccess && nSigsCount > 0)
936 valtype& vchSig = stacktop(-isig);
937 valtype& vchPubKey = stacktop(-ikey);
940 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
941 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
950 // If there are more signatures left than keys left,
951 // then too many signatures have failed
952 if (nSigsCount > nKeysCount)
959 // A bug causes CHECKMULTISIG to consume one extra argument
960 // whose contents were not checked in any way.
962 // Unfortunately this is a potential source of mutability,
963 // so optionally verify it is exactly equal to zero prior
964 // to removing it from the stack.
965 if (stack.size() < 1)
967 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
968 return error("CHECKMULTISIG dummy argument not null");
971 stack.push_back(fSuccess ? vchTrue : vchFalse);
973 if (opcode == OP_CHECKMULTISIGVERIFY)
988 if (stack.size() + altstack.size() > 1000)
1012 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1014 if (nIn >= txTo.vin.size())
1016 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1019 CTransaction txTmp(txTo);
1021 // In case concatenating two scripts ends up with two codeseparators,
1022 // or an extra one at the end, this prevents all those possible incompatibilities.
1023 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1025 // Blank out other inputs' signatures
1026 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1027 txTmp.vin[i].scriptSig = CScript();
1028 txTmp.vin[nIn].scriptSig = scriptCode;
1030 // Blank out some of the outputs
1031 if ((nHashType & 0x1f) == SIGHASH_NONE)
1036 // Let the others update at will
1037 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1039 txTmp.vin[i].nSequence = 0;
1041 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1043 // Only lock-in the txout payee at same index as txin
1044 unsigned int nOut = nIn;
1045 if (nOut >= txTmp.vout.size())
1047 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1050 txTmp.vout.resize(nOut+1);
1051 for (unsigned int i = 0; i < nOut; i++)
1052 txTmp.vout[i].SetNull();
1054 // Let the others update at will
1055 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1057 txTmp.vin[i].nSequence = 0;
1060 // Blank out other inputs completely, not recommended for open transactions
1061 if (nHashType & SIGHASH_ANYONECANPAY)
1063 txTmp.vin[0] = txTmp.vin[nIn];
1064 txTmp.vin.resize(1);
1067 // Serialize and hash
1068 CDataStream ss(SER_GETHASH, 0);
1070 ss << txTmp << nHashType;
1071 return Hash(ss.begin(), ss.end());
1075 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1076 // twice for every transaction (once when accepted into memory pool, and
1077 // again when accepted into the block chain)
1079 class CSignatureCache
1082 // sigdata_type is (signature hash, signature, public key):
1083 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1084 std::set< sigdata_type> setValid;
1085 boost::shared_mutex cs_sigcache;
1089 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1091 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1093 sigdata_type k(hash, vchSig, pubKey);
1094 std::set<sigdata_type>::iterator mi = setValid.find(k);
1095 if (mi != setValid.end())
1100 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1102 // DoS prevention: limit cache size to less than 10MB
1103 // (~200 bytes per cache entry times 50,000 entries)
1104 // Since there are a maximum of 20,000 signature operations per block
1105 // 50,000 is a reasonable default.
1106 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1107 if (nMaxCacheSize <= 0) return;
1109 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1111 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1113 // Evict a random entry. Random because that helps
1114 // foil would-be DoS attackers who might try to pre-generate
1115 // and re-use a set of valid signatures just-slightly-greater
1116 // than our cache size.
1117 uint256 randomHash = GetRandHash();
1118 std::vector<unsigned char> unused;
1119 std::set<sigdata_type>::iterator it =
1120 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1121 if (it == setValid.end())
1122 it = setValid.begin();
1123 setValid.erase(*it);
1126 sigdata_type k(hash, vchSig, pubKey);
1131 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1132 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1134 static CSignatureCache signatureCache;
1137 if (!key.SetPubKey(vchPubKey))
1139 CPubKey pubkey = key.GetPubKey();
1140 if (!pubkey.IsValid())
1143 // Hash type is one byte tacked on to the end of the signature
1147 nHashType = vchSig.back();
1148 else if (nHashType != vchSig.back())
1152 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1154 if (signatureCache.Get(sighash, vchSig, pubkey))
1157 if (!key.Verify(sighash, vchSig))
1160 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1161 signatureCache.Set(sighash, vchSig, pubkey);
1174 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1176 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1179 static map<txnouttype, CScript> mTemplates;
1180 if (mTemplates.empty())
1182 // Standard tx, sender provides pubkey, receiver adds signature
1183 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1185 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1186 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1188 // Sender provides N pubkeys, receivers provides M signatures
1189 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1191 // Empty, provably prunable, data-carrying output
1192 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1195 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1196 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1197 if (scriptPubKey.IsPayToScriptHash())
1199 typeRet = TX_SCRIPTHASH;
1200 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1201 vSolutionsRet.push_back(hashBytes);
1206 const CScript& script1 = scriptPubKey;
1207 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1209 const CScript& script2 = tplate.second;
1210 vSolutionsRet.clear();
1212 opcodetype opcode1, opcode2;
1213 vector<unsigned char> vch1, vch2;
1216 CScript::const_iterator pc1 = script1.begin();
1217 CScript::const_iterator pc2 = script2.begin();
1220 if (pc1 == script1.end() && pc2 == script2.end())
1223 typeRet = tplate.first;
1224 if (typeRet == TX_MULTISIG)
1226 // Additional checks for TX_MULTISIG:
1227 unsigned char m = vSolutionsRet.front()[0];
1228 unsigned char n = vSolutionsRet.back()[0];
1229 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1234 if (!script1.GetOp(pc1, opcode1, vch1))
1236 if (!script2.GetOp(pc2, opcode2, vch2))
1239 // Template matching opcodes:
1240 if (opcode2 == OP_PUBKEYS)
1242 while (vch1.size() >= 33 && vch1.size() <= 120)
1244 vSolutionsRet.push_back(vch1);
1245 if (!script1.GetOp(pc1, opcode1, vch1))
1248 if (!script2.GetOp(pc2, opcode2, vch2))
1250 // Normal situation is to fall through
1251 // to other if/else statements
1254 if (opcode2 == OP_PUBKEY)
1256 if (vch1.size() < 33 || vch1.size() > 120)
1258 vSolutionsRet.push_back(vch1);
1260 else if (opcode2 == OP_PUBKEYHASH)
1262 if (vch1.size() != sizeof(uint160))
1264 vSolutionsRet.push_back(vch1);
1266 else if (opcode2 == OP_SMALLINTEGER)
1267 { // Single-byte small integer pushed onto vSolutions
1268 if (opcode1 == OP_0 ||
1269 (opcode1 >= OP_1 && opcode1 <= OP_16))
1271 char n = (char)CScript::DecodeOP_N(opcode1);
1272 vSolutionsRet.push_back(valtype(1, n));
1277 else if (opcode2 == OP_SMALLDATA)
1279 // small pushdata, <= 80 bytes
1280 if (vch1.size() > 80)
1283 else if (opcode1 != opcode2 || vch1 != vch2)
1285 // Others must match exactly
1291 vSolutionsRet.clear();
1292 typeRet = TX_NONSTANDARD;
1297 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1300 if (!keystore.GetKey(address, key))
1303 vector<unsigned char> vchSig;
1304 if (!key.Sign(hash, vchSig))
1306 vchSig.push_back((unsigned char)nHashType);
1307 scriptSigRet << vchSig;
1312 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1315 int nRequired = multisigdata.front()[0];
1316 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1318 const valtype& pubkey = multisigdata[i];
1319 CKeyID keyID = CPubKey(pubkey).GetID();
1320 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1323 return nSigned==nRequired;
1327 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1328 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1329 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1330 // Returns false if scriptPubKey could not be completely satisfied.
1332 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1333 CScript& scriptSigRet, txnouttype& whichTypeRet)
1335 scriptSigRet.clear();
1337 vector<valtype> vSolutions;
1338 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1342 switch (whichTypeRet)
1344 case TX_NONSTANDARD:
1348 keyID = CPubKey(vSolutions[0]).GetID();
1349 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1351 keyID = CKeyID(uint160(vSolutions[0]));
1352 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1357 keystore.GetPubKey(keyID, vch);
1358 scriptSigRet << vch;
1362 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1365 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1366 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1371 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1375 case TX_NONSTANDARD:
1384 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1386 return vSolutions[0][0] + 1;
1388 return 1; // doesn't include args needed by the script
1393 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1395 vector<valtype> vSolutions;
1396 if (!Solver(scriptPubKey, whichType, vSolutions))
1399 if (whichType == TX_MULTISIG)
1401 unsigned char m = vSolutions.front()[0];
1402 unsigned char n = vSolutions.back()[0];
1403 // Support up to x-of-3 multisig txns as standard
1410 return whichType != TX_NONSTANDARD;
1414 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1416 unsigned int nResult = 0;
1417 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1419 CKeyID keyID = CPubKey(pubkey).GetID();
1420 if (keystore.HaveKey(keyID))
1427 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1430 const CKeyStore *keystore;
1432 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1433 bool operator()(const CNoDestination &dest) const { return false; }
1434 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1435 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1438 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1441 script.SetDestination(dest);
1442 return IsMine(keystore, script);
1445 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1447 vector<valtype> vSolutions;
1448 txnouttype whichType;
1449 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1450 if (keystore.HaveWatchOnly(scriptPubKey))
1451 return MINE_WATCH_ONLY;
1458 case TX_NONSTANDARD:
1462 keyID = CPubKey(vSolutions[0]).GetID();
1463 if (keystore.HaveKey(keyID))
1464 return MINE_SPENDABLE;
1467 keyID = CKeyID(uint160(vSolutions[0]));
1468 if (keystore.HaveKey(keyID))
1469 return MINE_SPENDABLE;
1473 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1475 if (keystore.GetCScript(scriptID, subscript)) {
1476 isminetype ret = IsMine(keystore, subscript);
1477 if (ret == MINE_SPENDABLE)
1484 // Only consider transactions "mine" if we own ALL the
1485 // keys involved. multi-signature transactions that are
1486 // partially owned (somebody else has a key that can spend
1487 // them) enable spend-out-from-under-you attacks, especially
1488 // in shared-wallet situations.
1489 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1490 if (HaveKeys(keys, keystore) == keys.size())
1491 return MINE_SPENDABLE;
1496 if (keystore.HaveWatchOnly(scriptPubKey))
1497 return MINE_WATCH_ONLY;
1501 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1503 vector<valtype> vSolutions;
1504 txnouttype whichType;
1505 if (!Solver(scriptPubKey, whichType, vSolutions))
1508 if (whichType == TX_PUBKEY)
1510 addressRet = CPubKey(vSolutions[0]).GetID();
1513 else if (whichType == TX_PUBKEYHASH)
1515 addressRet = CKeyID(uint160(vSolutions[0]));
1518 else if (whichType == TX_SCRIPTHASH)
1520 addressRet = CScriptID(uint160(vSolutions[0]));
1523 // Multisig txns have more than one address...
1527 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1529 const CKeyStore &keystore;
1530 std::vector<CKeyID> &vKeys;
1533 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1535 void Process(const CScript &script) {
1537 std::vector<CTxDestination> vDest;
1539 if (ExtractDestinations(script, type, vDest, nRequired)) {
1540 BOOST_FOREACH(const CTxDestination &dest, vDest)
1541 boost::apply_visitor(*this, dest);
1545 void operator()(const CKeyID &keyId) {
1546 if (keystore.HaveKey(keyId))
1547 vKeys.push_back(keyId);
1550 void operator()(const CScriptID &scriptId) {
1552 if (keystore.GetCScript(scriptId, script))
1556 void operator()(const CNoDestination &none) {}
1560 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1561 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1564 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1567 typeRet = TX_NONSTANDARD;
1568 vector<valtype> vSolutions;
1569 if (!Solver(scriptPubKey, typeRet, vSolutions))
1571 if (typeRet == TX_NULL_DATA)
1574 if (typeRet == TX_MULTISIG)
1576 nRequiredRet = vSolutions.front()[0];
1577 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1579 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1580 addressRet.push_back(address);
1586 CTxDestination address;
1587 if (!ExtractDestination(scriptPubKey, address))
1589 addressRet.push_back(address);
1595 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1596 unsigned int flags, int nHashType)
1598 vector<vector<unsigned char> > stack, stackCopy;
1599 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1601 if (flags & SCRIPT_VERIFY_P2SH)
1603 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1608 if (CastToBool(stack.back()) == false)
1611 // Additional validation for spend-to-script-hash transactions:
1612 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1614 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1615 return false; // or validation fails
1617 // stackCopy cannot be empty here, because if it was the
1618 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1619 // an empty stack and the EvalScript above would return false.
1620 assert(!stackCopy.empty());
1622 const valtype& pubKeySerialized = stackCopy.back();
1623 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1624 popstack(stackCopy);
1626 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1628 if (stackCopy.empty())
1630 return CastToBool(stackCopy.back());
1636 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1638 assert(nIn < txTo.vin.size());
1639 CTxIn& txin = txTo.vin[nIn];
1641 // Leave out the signature from the hash, since a signature can't sign itself.
1642 // The checksig op will also drop the signatures from its hash.
1643 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1645 txnouttype whichType;
1646 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1649 if (whichType == TX_SCRIPTHASH)
1651 // Solver returns the subscript that need to be evaluated;
1652 // the final scriptSig is the signatures from that
1653 // and then the serialized subscript:
1654 CScript subscript = txin.scriptSig;
1656 // Recompute txn hash using subscript in place of scriptPubKey:
1657 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1661 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1662 // Append serialized subscript whether or not it is completely signed:
1663 txin.scriptSig << static_cast<valtype>(subscript);
1664 if (!fSolved) return false;
1668 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1671 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1673 assert(nIn < txTo.vin.size());
1674 CTxIn& txin = txTo.vin[nIn];
1675 assert(txin.prevout.n < txFrom.vout.size());
1676 assert(txin.prevout.hash == txFrom.GetHash());
1677 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1679 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1682 static CScript PushAll(const vector<valtype>& values)
1685 BOOST_FOREACH(const valtype& v, values)
1690 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1691 const vector<valtype>& vSolutions,
1692 vector<valtype>& sigs1, vector<valtype>& sigs2)
1694 // Combine all the signatures we've got:
1695 set<valtype> allsigs;
1696 BOOST_FOREACH(const valtype& v, sigs1)
1701 BOOST_FOREACH(const valtype& v, sigs2)
1707 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1708 assert(vSolutions.size() > 1);
1709 unsigned int nSigsRequired = vSolutions.front()[0];
1710 unsigned int nPubKeys = vSolutions.size()-2;
1711 map<valtype, valtype> sigs;
1712 BOOST_FOREACH(const valtype& sig, allsigs)
1714 for (unsigned int i = 0; i < nPubKeys; i++)
1716 const valtype& pubkey = vSolutions[i+1];
1717 if (sigs.count(pubkey))
1718 continue; // Already got a sig for this pubkey
1720 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1727 // Now build a merged CScript:
1728 unsigned int nSigsHave = 0;
1729 CScript result; result << OP_0; // pop-one-too-many workaround
1730 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1732 if (sigs.count(vSolutions[i+1]))
1734 result << sigs[vSolutions[i+1]];
1738 // Fill any missing with OP_0:
1739 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1745 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1746 const txnouttype txType, const vector<valtype>& vSolutions,
1747 vector<valtype>& sigs1, vector<valtype>& sigs2)
1751 case TX_NONSTANDARD:
1753 // Don't know anything about this, assume bigger one is correct:
1754 if (sigs1.size() >= sigs2.size())
1755 return PushAll(sigs1);
1756 return PushAll(sigs2);
1759 // Signatures are bigger than placeholders or empty scripts:
1760 if (sigs1.empty() || sigs1[0].empty())
1761 return PushAll(sigs2);
1762 return PushAll(sigs1);
1764 if (sigs1.empty() || sigs1.back().empty())
1765 return PushAll(sigs2);
1766 else if (sigs2.empty() || sigs2.back().empty())
1767 return PushAll(sigs1);
1770 // Recur to combine:
1771 valtype spk = sigs1.back();
1772 CScript pubKey2(spk.begin(), spk.end());
1775 vector<vector<unsigned char> > vSolutions2;
1776 Solver(pubKey2, txType2, vSolutions2);
1779 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1784 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1790 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1791 const CScript& scriptSig1, const CScript& scriptSig2)
1794 vector<vector<unsigned char> > vSolutions;
1795 Solver(scriptPubKey, txType, vSolutions);
1797 vector<valtype> stack1;
1798 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1799 vector<valtype> stack2;
1800 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1802 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1805 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1808 const_iterator pc = begin();
1809 opcodetype lastOpcode = OP_INVALIDOPCODE;
1813 if (!GetOp(pc, opcode))
1815 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1817 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1819 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1820 n += DecodeOP_N(lastOpcode);
1824 lastOpcode = opcode;
1829 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1831 if (!IsPayToScriptHash())
1832 return GetSigOpCount(true);
1834 // This is a pay-to-script-hash scriptPubKey;
1835 // get the last item that the scriptSig
1836 // pushes onto the stack:
1837 const_iterator pc = scriptSig.begin();
1838 vector<unsigned char> data;
1839 while (pc < scriptSig.end())
1842 if (!scriptSig.GetOp(pc, opcode, data))
1848 /// ... and return its opcount:
1849 CScript subscript(data.begin(), data.end());
1850 return subscript.GetSigOpCount(true);
1853 bool CScript::IsPayToScriptHash() const
1855 // Extra-fast test for pay-to-script-hash CScripts:
1856 return (this->size() == 23 &&
1857 this->at(0) == OP_HASH160 &&
1858 this->at(1) == 0x14 &&
1859 this->at(22) == OP_EQUAL);
1862 bool CScript::HasCanonicalPushes() const
1864 const_iterator pc = begin();
1868 std::vector<unsigned char> data;
1869 if (!GetOp(pc, opcode, data))
1873 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1874 // Could have used an OP_n code, rather than a 1-byte push.
1876 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1877 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1879 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1880 // Could have used an OP_PUSHDATA1.
1882 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1883 // Could have used an OP_PUSHDATA2.
1889 class CScriptVisitor : public boost::static_visitor<bool>
1894 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1896 bool operator()(const CNoDestination &dest) const {
1901 bool operator()(const CKeyID &keyID) const {
1903 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1907 bool operator()(const CScriptID &scriptID) const {
1909 *script << OP_HASH160 << scriptID << OP_EQUAL;
1914 void CScript::SetDestination(const CTxDestination& dest)
1916 boost::apply_visitor(CScriptVisitor(this), dest);
1919 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1923 *this << EncodeOP_N(nRequired);
1924 BOOST_FOREACH(const CKey& key, keys)
1925 *this << key.GetPubKey();
1926 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;