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_PUBKEY_DROP: return "pubkeydrop";
103 case TX_PUBKEYHASH: return "pubkeyhash";
104 case TX_SCRIPTHASH: return "scripthash";
105 case TX_MULTISIG: return "multisig";
106 case TX_NULL_DATA: return "nulldata";
112 const char* GetOpName(opcodetype opcode)
117 case OP_0 : return "0";
118 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
119 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
120 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
121 case OP_1NEGATE : return "-1";
122 case OP_RESERVED : return "OP_RESERVED";
123 case OP_1 : return "1";
124 case OP_2 : return "2";
125 case OP_3 : return "3";
126 case OP_4 : return "4";
127 case OP_5 : return "5";
128 case OP_6 : return "6";
129 case OP_7 : return "7";
130 case OP_8 : return "8";
131 case OP_9 : return "9";
132 case OP_10 : return "10";
133 case OP_11 : return "11";
134 case OP_12 : return "12";
135 case OP_13 : return "13";
136 case OP_14 : return "14";
137 case OP_15 : return "15";
138 case OP_16 : return "16";
141 case OP_NOP : return "OP_NOP";
142 case OP_VER : return "OP_VER";
143 case OP_IF : return "OP_IF";
144 case OP_NOTIF : return "OP_NOTIF";
145 case OP_VERIF : return "OP_VERIF";
146 case OP_VERNOTIF : return "OP_VERNOTIF";
147 case OP_ELSE : return "OP_ELSE";
148 case OP_ENDIF : return "OP_ENDIF";
149 case OP_VERIFY : return "OP_VERIFY";
150 case OP_RETURN : return "OP_RETURN";
153 case OP_TOALTSTACK : return "OP_TOALTSTACK";
154 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
155 case OP_2DROP : return "OP_2DROP";
156 case OP_2DUP : return "OP_2DUP";
157 case OP_3DUP : return "OP_3DUP";
158 case OP_2OVER : return "OP_2OVER";
159 case OP_2ROT : return "OP_2ROT";
160 case OP_2SWAP : return "OP_2SWAP";
161 case OP_IFDUP : return "OP_IFDUP";
162 case OP_DEPTH : return "OP_DEPTH";
163 case OP_DROP : return "OP_DROP";
164 case OP_DUP : return "OP_DUP";
165 case OP_NIP : return "OP_NIP";
166 case OP_OVER : return "OP_OVER";
167 case OP_PICK : return "OP_PICK";
168 case OP_ROLL : return "OP_ROLL";
169 case OP_ROT : return "OP_ROT";
170 case OP_SWAP : return "OP_SWAP";
171 case OP_TUCK : return "OP_TUCK";
174 case OP_CAT : return "OP_CAT";
175 case OP_SUBSTR : return "OP_SUBSTR";
176 case OP_LEFT : return "OP_LEFT";
177 case OP_RIGHT : return "OP_RIGHT";
178 case OP_SIZE : return "OP_SIZE";
181 case OP_INVERT : return "OP_INVERT";
182 case OP_AND : return "OP_AND";
183 case OP_OR : return "OP_OR";
184 case OP_XOR : return "OP_XOR";
185 case OP_EQUAL : return "OP_EQUAL";
186 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
187 case OP_RESERVED1 : return "OP_RESERVED1";
188 case OP_RESERVED2 : return "OP_RESERVED2";
191 case OP_1ADD : return "OP_1ADD";
192 case OP_1SUB : return "OP_1SUB";
193 case OP_2MUL : return "OP_2MUL";
194 case OP_2DIV : return "OP_2DIV";
195 case OP_NEGATE : return "OP_NEGATE";
196 case OP_ABS : return "OP_ABS";
197 case OP_NOT : return "OP_NOT";
198 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
199 case OP_ADD : return "OP_ADD";
200 case OP_SUB : return "OP_SUB";
201 case OP_MUL : return "OP_MUL";
202 case OP_DIV : return "OP_DIV";
203 case OP_MOD : return "OP_MOD";
204 case OP_LSHIFT : return "OP_LSHIFT";
205 case OP_RSHIFT : return "OP_RSHIFT";
206 case OP_BOOLAND : return "OP_BOOLAND";
207 case OP_BOOLOR : return "OP_BOOLOR";
208 case OP_NUMEQUAL : return "OP_NUMEQUAL";
209 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
210 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
211 case OP_LESSTHAN : return "OP_LESSTHAN";
212 case OP_GREATERTHAN : return "OP_GREATERTHAN";
213 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
214 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
215 case OP_MIN : return "OP_MIN";
216 case OP_MAX : return "OP_MAX";
217 case OP_WITHIN : return "OP_WITHIN";
220 case OP_RIPEMD160 : return "OP_RIPEMD160";
221 case OP_SHA1 : return "OP_SHA1";
222 case OP_SHA256 : return "OP_SHA256";
223 case OP_HASH160 : return "OP_HASH160";
224 case OP_HASH256 : return "OP_HASH256";
225 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
226 case OP_CHECKSIG : return "OP_CHECKSIG";
227 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
228 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
229 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
232 case OP_NOP1 : return "OP_NOP1";
233 case OP_NOP2 : return "OP_NOP2";
234 case OP_NOP3 : return "OP_NOP3";
235 case OP_NOP4 : return "OP_NOP4";
236 case OP_NOP5 : return "OP_NOP5";
237 case OP_NOP6 : return "OP_NOP6";
238 case OP_NOP7 : return "OP_NOP7";
239 case OP_NOP8 : return "OP_NOP8";
240 case OP_NOP9 : return "OP_NOP9";
241 case OP_NOP10 : return "OP_NOP10";
245 // template matching params
246 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
247 case OP_PUBKEY : return "OP_PUBKEY";
248 case OP_SMALLDATA : return "OP_SMALLDATA";
250 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
256 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
257 if (!(flags & SCRIPT_VERIFY_STRICTENC))
260 if (vchPubKey.size() < 33)
261 return error("Non-canonical public key: too short");
262 if (vchPubKey[0] == 0x04) {
263 if (vchPubKey.size() != 65)
264 return error("Non-canonical public key: invalid length for uncompressed key");
265 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
266 if (vchPubKey.size() != 33)
267 return error("Non-canonical public key: invalid length for compressed key");
269 return error("Non-canonical public key: compressed nor uncompressed");
274 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
275 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
276 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
277 // Where R and S are not negative (their first byte has its highest bit not set), and not
278 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
279 // in which case a single 0 byte is necessary and even required).
280 if (vchSig.size() < 9)
281 return error("Non-canonical signature: too short");
282 if (vchSig.size() > 73)
283 return error("Non-canonical signature: too long");
284 if (vchSig[0] != 0x30)
285 return error("Non-canonical signature: wrong type");
286 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
287 return error("Non-canonical signature: wrong length marker");
289 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
290 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
291 return error("Non-canonical signature: unknown hashtype byte");
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 + (fWithHashType ? 7 : 6)) != 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");
321 unsigned int nLenR = vchSig[3];
322 unsigned int nLenS = vchSig[5+nLenR];
323 const unsigned char *S = &vchSig[6+nLenR];
324 // If the S value is above the order of the curve divided by two, its
325 // complement modulo the order could have been used instead, which is
326 // one byte shorter when encoded correctly.
327 if (!CKey::CheckSignatureElement(S, nLenS, true))
328 return error("Non-canonical signature: S value is unnecessarily high");
334 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
335 if (!(flags & SCRIPT_VERIFY_STRICTENC))
338 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
341 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
344 CScript::const_iterator pc = script.begin();
345 CScript::const_iterator pend = script.end();
346 CScript::const_iterator pbegincodehash = script.begin();
348 valtype vchPushValue;
350 vector<valtype> altstack;
351 if (script.size() > 10000)
359 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
364 if (!script.GetOp(pc, opcode, vchPushValue))
366 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
368 if (opcode > OP_16 && ++nOpCount > 201)
371 if (opcode == OP_CAT ||
372 opcode == OP_SUBSTR ||
374 opcode == OP_RIGHT ||
375 opcode == OP_INVERT ||
384 opcode == OP_LSHIFT ||
386 return false; // Disabled opcodes.
388 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
389 stack.push_back(vchPushValue);
390 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
415 CBigNum bn((int)opcode - (int)(OP_1 - 1));
416 stack.push_back(bn.getvch());
425 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
426 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
432 // <expression> if [statements] [else [statements]] endif
436 if (stack.size() < 1)
438 valtype& vch = stacktop(-1);
439 fValue = CastToBool(vch);
440 if (opcode == OP_NOTIF)
444 vfExec.push_back(fValue);
452 vfExec.back() = !vfExec.back();
467 // (false -- false) and return
468 if (stack.size() < 1)
470 bool fValue = CastToBool(stacktop(-1));
490 if (stack.size() < 1)
492 altstack.push_back(stacktop(-1));
497 case OP_FROMALTSTACK:
499 if (altstack.size() < 1)
501 stack.push_back(altstacktop(-1));
509 if (stack.size() < 2)
518 // (x1 x2 -- x1 x2 x1 x2)
519 if (stack.size() < 2)
521 valtype vch1 = stacktop(-2);
522 valtype vch2 = stacktop(-1);
523 stack.push_back(vch1);
524 stack.push_back(vch2);
530 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
531 if (stack.size() < 3)
533 valtype vch1 = stacktop(-3);
534 valtype vch2 = stacktop(-2);
535 valtype vch3 = stacktop(-1);
536 stack.push_back(vch1);
537 stack.push_back(vch2);
538 stack.push_back(vch3);
544 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
545 if (stack.size() < 4)
547 valtype vch1 = stacktop(-4);
548 valtype vch2 = stacktop(-3);
549 stack.push_back(vch1);
550 stack.push_back(vch2);
556 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
557 if (stack.size() < 6)
559 valtype vch1 = stacktop(-6);
560 valtype vch2 = stacktop(-5);
561 stack.erase(stack.end()-6, stack.end()-4);
562 stack.push_back(vch1);
563 stack.push_back(vch2);
569 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
570 if (stack.size() < 4)
572 swap(stacktop(-4), stacktop(-2));
573 swap(stacktop(-3), stacktop(-1));
580 if (stack.size() < 1)
582 valtype vch = stacktop(-1);
584 stack.push_back(vch);
591 CBigNum bn((uint16_t) stack.size());
592 stack.push_back(bn.getvch());
599 if (stack.size() < 1)
608 if (stack.size() < 1)
610 valtype vch = stacktop(-1);
611 stack.push_back(vch);
618 if (stack.size() < 2)
620 stack.erase(stack.end() - 2);
626 // (x1 x2 -- x1 x2 x1)
627 if (stack.size() < 2)
629 valtype vch = stacktop(-2);
630 stack.push_back(vch);
637 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
638 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
639 if (stack.size() < 2)
641 int n = CastToBigNum(stacktop(-1)).getint32();
643 if (n < 0 || n >= (int)stack.size())
645 valtype vch = stacktop(-n-1);
646 if (opcode == OP_ROLL)
647 stack.erase(stack.end()-n-1);
648 stack.push_back(vch);
654 // (x1 x2 x3 -- x2 x3 x1)
655 // x2 x1 x3 after first swap
656 // x2 x3 x1 after second swap
657 if (stack.size() < 3)
659 swap(stacktop(-3), stacktop(-2));
660 swap(stacktop(-2), stacktop(-1));
667 if (stack.size() < 2)
669 swap(stacktop(-2), stacktop(-1));
675 // (x1 x2 -- x2 x1 x2)
676 if (stack.size() < 2)
678 valtype vch = stacktop(-1);
679 stack.insert(stack.end()-2, vch);
687 if (stack.size() < 1)
689 CBigNum bn((uint16_t) stacktop(-1).size());
690 stack.push_back(bn.getvch());
700 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
703 if (stack.size() < 2)
705 valtype& vch1 = stacktop(-2);
706 valtype& vch2 = stacktop(-1);
707 bool fEqual = (vch1 == vch2);
708 // OP_NOTEQUAL is disabled because it would be too easy to say
709 // something like n != 1 and have some wiseguy pass in 1 with extra
710 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
711 //if (opcode == OP_NOTEQUAL)
715 stack.push_back(fEqual ? vchTrue : vchFalse);
716 if (opcode == OP_EQUALVERIFY)
738 if (stack.size() < 1)
740 CBigNum bn = CastToBigNum(stacktop(-1));
743 case OP_1ADD: bn += bnOne; break;
744 case OP_1SUB: bn -= bnOne; break;
745 case OP_NEGATE: bn = -bn; break;
746 case OP_ABS: if (bn < bnZero) bn = -bn; break;
747 case OP_NOT: bn = (bn == bnZero); break;
748 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
749 default: assert(!"invalid opcode"); break;
752 stack.push_back(bn.getvch());
761 case OP_NUMEQUALVERIFY:
765 case OP_LESSTHANOREQUAL:
766 case OP_GREATERTHANOREQUAL:
771 if (stack.size() < 2)
773 CBigNum bn1 = CastToBigNum(stacktop(-2));
774 CBigNum bn2 = CastToBigNum(stacktop(-1));
786 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
787 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
788 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
789 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
790 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
791 case OP_LESSTHAN: bn = (bn1 < bn2); break;
792 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
793 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
794 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
795 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
796 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
797 default: assert(!"invalid opcode"); break;
801 stack.push_back(bn.getvch());
803 if (opcode == OP_NUMEQUALVERIFY)
805 if (CastToBool(stacktop(-1)))
815 // (x min max -- out)
816 if (stack.size() < 3)
818 CBigNum bn1 = CastToBigNum(stacktop(-3));
819 CBigNum bn2 = CastToBigNum(stacktop(-2));
820 CBigNum bn3 = CastToBigNum(stacktop(-1));
821 bool fValue = (bn2 <= bn1 && bn1 < bn3);
825 stack.push_back(fValue ? vchTrue : vchFalse);
840 if (stack.size() < 1)
842 valtype& vch = stacktop(-1);
843 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
844 if (opcode == OP_RIPEMD160)
845 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
846 else if (opcode == OP_SHA1)
847 SHA1(&vch[0], vch.size(), &vchHash[0]);
848 else if (opcode == OP_SHA256)
849 SHA256(&vch[0], vch.size(), &vchHash[0]);
850 else if (opcode == OP_HASH160)
852 uint160 hash160 = Hash160(vch);
853 memcpy(&vchHash[0], &hash160, sizeof(hash160));
855 else if (opcode == OP_HASH256)
857 uint256 hash = Hash(vch.begin(), vch.end());
858 memcpy(&vchHash[0], &hash, sizeof(hash));
861 stack.push_back(vchHash);
865 case OP_CODESEPARATOR:
867 // Hash starts after the code separator
873 case OP_CHECKSIGVERIFY:
875 // (sig pubkey -- bool)
876 if (stack.size() < 2)
879 valtype& vchSig = stacktop(-2);
880 valtype& vchPubKey = stacktop(-1);
883 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
884 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
886 // Subset of script starting at the most recent codeseparator
887 CScript scriptCode(pbegincodehash, pend);
889 // Drop the signature, since there's no way for a signature to sign itself
890 scriptCode.FindAndDelete(CScript(vchSig));
892 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
893 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
897 stack.push_back(fSuccess ? vchTrue : vchFalse);
898 if (opcode == OP_CHECKSIGVERIFY)
908 case OP_CHECKMULTISIG:
909 case OP_CHECKMULTISIGVERIFY:
911 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
914 if ((int)stack.size() < i)
917 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
918 if (nKeysCount < 0 || nKeysCount > 20)
920 nOpCount += nKeysCount;
925 if ((int)stack.size() < i)
928 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
929 if (nSigsCount < 0 || nSigsCount > nKeysCount)
933 if ((int)stack.size() < i)
936 // Subset of script starting at the most recent codeseparator
937 CScript scriptCode(pbegincodehash, pend);
939 // Drop the signatures, since there's no way for a signature to sign itself
940 for (int k = 0; k < nSigsCount; k++)
942 valtype& vchSig = stacktop(-isig-k);
943 scriptCode.FindAndDelete(CScript(vchSig));
946 bool fSuccess = true;
947 while (fSuccess && nSigsCount > 0)
949 valtype& vchSig = stacktop(-isig);
950 valtype& vchPubKey = stacktop(-ikey);
953 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
954 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
963 // If there are more signatures left than keys left,
964 // then too many signatures have failed
965 if (nSigsCount > nKeysCount)
972 // A bug causes CHECKMULTISIG to consume one extra argument
973 // whose contents were not checked in any way.
975 // Unfortunately this is a potential source of mutability,
976 // so optionally verify it is exactly equal to zero prior
977 // to removing it from the stack.
978 if (stack.size() < 1)
980 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
981 return error("CHECKMULTISIG dummy argument not null");
984 stack.push_back(fSuccess ? vchTrue : vchFalse);
986 if (opcode == OP_CHECKMULTISIGVERIFY)
1001 if (stack.size() + altstack.size() > 1000)
1011 if (!vfExec.empty())
1025 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1027 if (nIn >= txTo.vin.size())
1029 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1032 CTransaction txTmp(txTo);
1034 // In case concatenating two scripts ends up with two codeseparators,
1035 // or an extra one at the end, this prevents all those possible incompatibilities.
1036 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1038 // Blank out other inputs' signatures
1039 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1040 txTmp.vin[i].scriptSig = CScript();
1041 txTmp.vin[nIn].scriptSig = scriptCode;
1043 // Blank out some of the outputs
1044 if ((nHashType & 0x1f) == SIGHASH_NONE)
1049 // Let the others update at will
1050 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1052 txTmp.vin[i].nSequence = 0;
1054 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1056 // Only lock-in the txout payee at same index as txin
1057 unsigned int nOut = nIn;
1058 if (nOut >= txTmp.vout.size())
1060 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1063 txTmp.vout.resize(nOut+1);
1064 for (unsigned int i = 0; i < nOut; i++)
1065 txTmp.vout[i].SetNull();
1067 // Let the others update at will
1068 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1070 txTmp.vin[i].nSequence = 0;
1073 // Blank out other inputs completely, not recommended for open transactions
1074 if (nHashType & SIGHASH_ANYONECANPAY)
1076 txTmp.vin[0] = txTmp.vin[nIn];
1077 txTmp.vin.resize(1);
1080 // Serialize and hash
1081 CDataStream ss(SER_GETHASH, 0);
1083 ss << txTmp << nHashType;
1084 return Hash(ss.begin(), ss.end());
1088 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1089 // twice for every transaction (once when accepted into memory pool, and
1090 // again when accepted into the block chain)
1092 class CSignatureCache
1095 // sigdata_type is (signature hash, signature, public key):
1096 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1097 std::set< sigdata_type> setValid;
1098 boost::shared_mutex cs_sigcache;
1102 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1104 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1106 sigdata_type k(hash, vchSig, pubKey);
1107 std::set<sigdata_type>::iterator mi = setValid.find(k);
1108 if (mi != setValid.end())
1113 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1115 // DoS prevention: limit cache size to less than 10MB
1116 // (~200 bytes per cache entry times 50,000 entries)
1117 // Since there are a maximum of 20,000 signature operations per block
1118 // 50,000 is a reasonable default.
1119 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1120 if (nMaxCacheSize <= 0) return;
1122 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1124 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1126 // Evict a random entry. Random because that helps
1127 // foil would-be DoS attackers who might try to pre-generate
1128 // and re-use a set of valid signatures just-slightly-greater
1129 // than our cache size.
1130 uint256 randomHash = GetRandHash();
1131 std::vector<unsigned char> unused;
1132 std::set<sigdata_type>::iterator it =
1133 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1134 if (it == setValid.end())
1135 it = setValid.begin();
1136 setValid.erase(*it);
1139 sigdata_type k(hash, vchSig, pubKey);
1144 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1145 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1147 static CSignatureCache signatureCache;
1150 if (!key.SetPubKey(vchPubKey))
1152 CPubKey pubkey = key.GetPubKey();
1153 if (!pubkey.IsValid())
1156 // Hash type is one byte tacked on to the end of the signature
1160 nHashType = vchSig.back();
1161 else if (nHashType != vchSig.back())
1165 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1167 if (signatureCache.Get(sighash, vchSig, pubkey))
1170 if (!key.Verify(sighash, vchSig))
1173 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1174 signatureCache.Set(sighash, vchSig, pubkey);
1187 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1189 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1192 static map<txnouttype, CScript> mTemplates;
1193 if (mTemplates.empty())
1195 // Standard tx, sender provides pubkey, receiver adds signature
1196 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1198 if (GetTime() > SMALLDATA_SWITCH_TIME)
1200 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1201 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1204 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1205 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1207 // Sender provides N pubkeys, receivers provides M signatures
1208 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1210 // Empty, provably prunable, data-carrying output
1211 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1214 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1215 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1216 if (scriptPubKey.IsPayToScriptHash())
1218 typeRet = TX_SCRIPTHASH;
1219 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1220 vSolutionsRet.push_back(hashBytes);
1225 const CScript& script1 = scriptPubKey;
1226 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1228 const CScript& script2 = tplate.second;
1229 vSolutionsRet.clear();
1231 opcodetype opcode1, opcode2;
1232 vector<unsigned char> vch1, vch2;
1235 CScript::const_iterator pc1 = script1.begin();
1236 CScript::const_iterator pc2 = script2.begin();
1239 if (pc1 == script1.end() && pc2 == script2.end())
1242 typeRet = tplate.first;
1243 if (typeRet == TX_MULTISIG)
1245 // Additional checks for TX_MULTISIG:
1246 unsigned char m = vSolutionsRet.front()[0];
1247 unsigned char n = vSolutionsRet.back()[0];
1248 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1253 if (!script1.GetOp(pc1, opcode1, vch1))
1255 if (!script2.GetOp(pc2, opcode2, vch2))
1258 // Template matching opcodes:
1259 if (opcode2 == OP_PUBKEYS)
1261 while (vch1.size() >= 33 && vch1.size() <= 120)
1263 vSolutionsRet.push_back(vch1);
1264 if (!script1.GetOp(pc1, opcode1, vch1))
1267 if (!script2.GetOp(pc2, opcode2, vch2))
1269 // Normal situation is to fall through
1270 // to other if/else statements
1273 if (opcode2 == OP_PUBKEY)
1275 if (vch1.size() < 33 || vch1.size() > 120)
1277 vSolutionsRet.push_back(vch1);
1279 else if (opcode2 == OP_PUBKEYHASH)
1281 if (vch1.size() != sizeof(uint160))
1283 vSolutionsRet.push_back(vch1);
1285 else if (opcode2 == OP_SMALLINTEGER)
1286 { // Single-byte small integer pushed onto vSolutions
1287 if (opcode1 == OP_0 ||
1288 (opcode1 >= OP_1 && opcode1 <= OP_16))
1290 char n = (char)CScript::DecodeOP_N(opcode1);
1291 vSolutionsRet.push_back(valtype(1, n));
1296 else if (opcode2 == OP_SMALLDATA)
1298 // small pushdata, <= 1024 bytes
1299 if (vch1.size() > (GetTime() > SMALLDATA_SWITCH_TIME ? 1024 : 80))
1302 else if (opcode1 != opcode2 || vch1 != vch2)
1304 // Others must match exactly
1310 vSolutionsRet.clear();
1311 typeRet = TX_NONSTANDARD;
1316 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1319 if (!keystore.GetKey(address, key))
1322 vector<unsigned char> vchSig;
1323 if (!key.Sign(hash, vchSig))
1325 vchSig.push_back((unsigned char)nHashType);
1326 scriptSigRet << vchSig;
1331 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1334 if (!keystore.CreatePrivKey(pubKey, R, key))
1337 vector<unsigned char> vchSig;
1338 if (!key.Sign(hash, vchSig))
1340 vchSig.push_back((unsigned char)nHashType);
1341 scriptSigRet << vchSig;
1346 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1349 int nRequired = multisigdata.front()[0];
1350 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1352 const valtype& pubkey = multisigdata[i];
1353 CKeyID keyID = CPubKey(pubkey).GetID();
1354 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1357 return nSigned==nRequired;
1361 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1362 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1363 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1364 // Returns false if scriptPubKey could not be completely satisfied.
1366 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1367 CScript& scriptSigRet, txnouttype& whichTypeRet)
1369 scriptSigRet.clear();
1371 vector<valtype> vSolutions;
1372 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1376 switch (whichTypeRet)
1378 case TX_NONSTANDARD:
1382 keyID = CPubKey(vSolutions[0]).GetID();
1383 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1384 case TX_PUBKEY_DROP:
1386 CPubKey key = CPubKey(vSolutions[0]);
1387 CPubKey R = CPubKey(vSolutions[1]);
1388 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1391 keyID = CKeyID(uint160(vSolutions[0]));
1392 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1397 keystore.GetPubKey(keyID, vch);
1398 scriptSigRet << vch;
1402 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1405 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1406 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1411 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1415 case TX_NONSTANDARD:
1420 case TX_PUBKEY_DROP:
1425 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1427 return vSolutions[0][0] + 1;
1429 return 1; // doesn't include args needed by the script
1434 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1436 vector<valtype> vSolutions;
1437 if (!Solver(scriptPubKey, whichType, vSolutions))
1440 if (whichType == TX_MULTISIG)
1442 unsigned char m = vSolutions.front()[0];
1443 unsigned char n = vSolutions.back()[0];
1444 // Support up to x-of-3 multisig txns as standard
1451 return whichType != TX_NONSTANDARD;
1455 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1457 unsigned int nResult = 0;
1458 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1460 CKeyID keyID = CPubKey(pubkey).GetID();
1461 if (keystore.HaveKey(keyID))
1468 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1471 const CKeyStore *keystore;
1473 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1474 bool operator()(const CNoDestination &dest) const { return false; }
1475 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1476 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1479 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1482 script.SetDestination(dest);
1483 return IsMine(keystore, script);
1486 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1488 vector<valtype> vSolutions;
1489 txnouttype whichType;
1490 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1491 if (keystore.HaveWatchOnly(scriptPubKey))
1492 return MINE_WATCH_ONLY;
1499 case TX_NONSTANDARD:
1503 keyID = CPubKey(vSolutions[0]).GetID();
1504 if (keystore.HaveKey(keyID))
1505 return MINE_SPENDABLE;
1507 case TX_PUBKEY_DROP:
1509 CPubKey key = CPubKey(vSolutions[0]);
1510 CPubKey R = CPubKey(vSolutions[1]);
1511 if (keystore.CheckOwnership(key, R))
1512 return MINE_SPENDABLE;
1516 keyID = CKeyID(uint160(vSolutions[0]));
1517 if (keystore.HaveKey(keyID))
1518 return MINE_SPENDABLE;
1522 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1524 if (keystore.GetCScript(scriptID, subscript)) {
1525 isminetype ret = IsMine(keystore, subscript);
1526 if (ret == MINE_SPENDABLE)
1533 // Only consider transactions "mine" if we own ALL the
1534 // keys involved. multi-signature transactions that are
1535 // partially owned (somebody else has a key that can spend
1536 // them) enable spend-out-from-under-you attacks, especially
1537 // in shared-wallet situations.
1538 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1539 if (HaveKeys(keys, keystore) == keys.size())
1540 return MINE_SPENDABLE;
1545 if (keystore.HaveWatchOnly(scriptPubKey))
1546 return MINE_WATCH_ONLY;
1550 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1552 vector<valtype> vSolutions;
1553 txnouttype whichType;
1554 if (!Solver(scriptPubKey, whichType, vSolutions))
1557 if (whichType == TX_PUBKEY)
1559 addressRet = CPubKey(vSolutions[0]).GetID();
1562 else if (whichType == TX_PUBKEYHASH)
1564 addressRet = CKeyID(uint160(vSolutions[0]));
1567 else if (whichType == TX_SCRIPTHASH)
1569 addressRet = CScriptID(uint160(vSolutions[0]));
1572 // Multisig txns have more than one address...
1576 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1578 const CKeyStore &keystore;
1579 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1580 std::vector<CKeyID> &vKeys;
1583 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1585 void Process(const CScript &script) {
1587 std::vector<CTxDestination> vDest;
1589 if (ExtractDestinations(script, type, vDest, nRequired)) {
1590 BOOST_FOREACH(const CTxDestination &dest, vDest)
1591 boost::apply_visitor(*this, dest);
1595 void operator()(const CKeyID &keyId) {
1596 if (keystore.HaveKey(keyId))
1597 vKeys.push_back(keyId);
1600 void operator()(const CScriptID &scriptId) {
1602 if (keystore.GetCScript(scriptId, script))
1606 void operator()(const CNoDestination &none) {}
1610 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1611 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1614 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1617 typeRet = TX_NONSTANDARD;
1618 vector<valtype> vSolutions;
1619 if (!Solver(scriptPubKey, typeRet, vSolutions))
1621 if (typeRet == TX_NULL_DATA || typeRet == TX_PUBKEY_DROP)
1624 if (typeRet == TX_MULTISIG)
1626 nRequiredRet = vSolutions.front()[0];
1627 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1629 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1630 addressRet.push_back(address);
1636 CTxDestination address;
1637 if (!ExtractDestination(scriptPubKey, address))
1639 addressRet.push_back(address);
1645 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1646 unsigned int flags, int nHashType)
1648 vector<vector<unsigned char> > stack, stackCopy;
1649 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1651 if (flags & SCRIPT_VERIFY_P2SH)
1653 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1658 if (CastToBool(stack.back()) == false)
1661 // Additional validation for spend-to-script-hash transactions:
1662 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1664 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1665 return false; // or validation fails
1667 // stackCopy cannot be empty here, because if it was the
1668 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1669 // an empty stack and the EvalScript above would return false.
1670 assert(!stackCopy.empty());
1672 const valtype& pubKeySerialized = stackCopy.back();
1673 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1674 popstack(stackCopy);
1676 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1678 if (stackCopy.empty())
1680 return CastToBool(stackCopy.back());
1686 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1688 assert(nIn < txTo.vin.size());
1689 CTxIn& txin = txTo.vin[nIn];
1691 // Leave out the signature from the hash, since a signature can't sign itself.
1692 // The checksig op will also drop the signatures from its hash.
1693 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1695 txnouttype whichType;
1696 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1699 if (whichType == TX_SCRIPTHASH)
1701 // Solver returns the subscript that need to be evaluated;
1702 // the final scriptSig is the signatures from that
1703 // and then the serialized subscript:
1704 CScript subscript = txin.scriptSig;
1706 // Recompute txn hash using subscript in place of scriptPubKey:
1707 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1711 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1712 // Append serialized subscript whether or not it is completely signed:
1713 txin.scriptSig << static_cast<valtype>(subscript);
1714 if (!fSolved) return false;
1718 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1721 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1723 assert(nIn < txTo.vin.size());
1724 CTxIn& txin = txTo.vin[nIn];
1725 assert(txin.prevout.n < txFrom.vout.size());
1726 assert(txin.prevout.hash == txFrom.GetHash());
1727 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1729 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1732 static CScript PushAll(const vector<valtype>& values)
1735 BOOST_FOREACH(const valtype& v, values)
1740 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1741 const vector<valtype>& vSolutions,
1742 vector<valtype>& sigs1, vector<valtype>& sigs2)
1744 // Combine all the signatures we've got:
1745 set<valtype> allsigs;
1746 BOOST_FOREACH(const valtype& v, sigs1)
1751 BOOST_FOREACH(const valtype& v, sigs2)
1757 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1758 assert(vSolutions.size() > 1);
1759 unsigned int nSigsRequired = vSolutions.front()[0];
1760 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1761 map<valtype, valtype> sigs;
1762 BOOST_FOREACH(const valtype& sig, allsigs)
1764 for (unsigned int i = 0; i < nPubKeys; i++)
1766 const valtype& pubkey = vSolutions[i+1];
1767 if (sigs.count(pubkey))
1768 continue; // Already got a sig for this pubkey
1770 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1777 // Now build a merged CScript:
1778 unsigned int nSigsHave = 0;
1779 CScript result; result << OP_0; // pop-one-too-many workaround
1780 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1782 if (sigs.count(vSolutions[i+1]))
1784 result << sigs[vSolutions[i+1]];
1788 // Fill any missing with OP_0:
1789 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1795 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1796 const txnouttype txType, const vector<valtype>& vSolutions,
1797 vector<valtype>& sigs1, vector<valtype>& sigs2)
1801 case TX_NONSTANDARD:
1803 // Don't know anything about this, assume bigger one is correct:
1804 if (sigs1.size() >= sigs2.size())
1805 return PushAll(sigs1);
1806 return PushAll(sigs2);
1808 case TX_PUBKEY_DROP:
1810 // Signatures are bigger than placeholders or empty scripts:
1811 if (sigs1.empty() || sigs1[0].empty())
1812 return PushAll(sigs2);
1813 return PushAll(sigs1);
1815 if (sigs1.empty() || sigs1.back().empty())
1816 return PushAll(sigs2);
1817 else if (sigs2.empty() || sigs2.back().empty())
1818 return PushAll(sigs1);
1821 // Recur to combine:
1822 valtype spk = sigs1.back();
1823 CScript pubKey2(spk.begin(), spk.end());
1826 vector<vector<unsigned char> > vSolutions2;
1827 Solver(pubKey2, txType2, vSolutions2);
1830 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1835 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1841 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1842 const CScript& scriptSig1, const CScript& scriptSig2)
1845 vector<vector<unsigned char> > vSolutions;
1846 Solver(scriptPubKey, txType, vSolutions);
1848 vector<valtype> stack1;
1849 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1850 vector<valtype> stack2;
1851 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1853 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1856 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1859 const_iterator pc = begin();
1860 opcodetype lastOpcode = OP_INVALIDOPCODE;
1864 if (!GetOp(pc, opcode))
1866 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1868 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1870 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1871 n += DecodeOP_N(lastOpcode);
1875 lastOpcode = opcode;
1880 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1882 if (!IsPayToScriptHash())
1883 return GetSigOpCount(true);
1885 // This is a pay-to-script-hash scriptPubKey;
1886 // get the last item that the scriptSig
1887 // pushes onto the stack:
1888 const_iterator pc = scriptSig.begin();
1889 vector<unsigned char> data;
1890 while (pc < scriptSig.end())
1893 if (!scriptSig.GetOp(pc, opcode, data))
1899 /// ... and return its opcount:
1900 CScript subscript(data.begin(), data.end());
1901 return subscript.GetSigOpCount(true);
1904 bool CScript::IsPayToScriptHash() const
1906 // Extra-fast test for pay-to-script-hash CScripts:
1907 return (this->size() == 23 &&
1908 this->at(0) == OP_HASH160 &&
1909 this->at(1) == 0x14 &&
1910 this->at(22) == OP_EQUAL);
1913 bool CScript::HasCanonicalPushes() const
1915 const_iterator pc = begin();
1919 std::vector<unsigned char> data;
1920 if (!GetOp(pc, opcode, data))
1924 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1925 // Could have used an OP_n code, rather than a 1-byte push.
1927 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1928 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1930 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1931 // Could have used an OP_PUSHDATA1.
1933 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1934 // Could have used an OP_PUSHDATA2.
1940 class CScriptVisitor : public boost::static_visitor<bool>
1945 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1947 bool operator()(const CNoDestination &dest) const {
1952 bool operator()(const CKeyID &keyID) const {
1954 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1958 bool operator()(const CScriptID &scriptID) const {
1960 *script << OP_HASH160 << scriptID << OP_EQUAL;
1965 void CScript::SetDestination(const CTxDestination& dest)
1967 boost::apply_visitor(CScriptVisitor(this), dest);
1970 void CScript::SetDestination(const CPubKey& R, CPubKey& pubKeyVariant)
1973 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
1977 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
1981 *this << EncodeOP_N(nRequired);
1982 BOOST_FOREACH(const CKey& key, keys)
1983 *this << key.GetPubKey();
1984 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;