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, vector<unsigned char> vchPubKey, CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType);
23 typedef vector<unsigned char> valtype;
24 static const valtype vchFalse(0);
25 static const valtype vchZero(0);
26 static const valtype vchTrue(1, 1);
27 static const CBigNum bnZero(0);
28 static const CBigNum bnOne(1);
29 static const CBigNum bnFalse(0);
30 static const CBigNum bnTrue(1);
31 static const size_t nMaxNumSize = 4;
34 CBigNum CastToBigNum(const valtype& vch)
36 if (vch.size() > nMaxNumSize)
37 throw runtime_error("CastToBigNum() : overflow");
38 // Get rid of extra leading zeros
39 return CBigNum(CBigNum(vch).getvch());
42 bool CastToBool(const valtype& vch)
44 for (unsigned int i = 0; i < vch.size(); i++)
48 // Can be negative zero
49 if (i == vch.size()-1 && vch[i] == 0x80)
58 // WARNING: This does not work as expected for signed integers; the sign-bit
59 // is left in place as the integer is zero-extended. The correct behavior
60 // would be to move the most significant bit of the last byte during the
61 // resize process. MakeSameSize() is currently only used by the disabled
62 // opcodes OP_AND, OP_OR, and OP_XOR.
64 void MakeSameSize(valtype& vch1, valtype& vch2)
66 // Lengthen the shorter one
67 if (vch1.size() < vch2.size())
69 // +unsigned char msb = vch1[vch1.size()-1];
70 // +vch1[vch1.size()-1] &= 0x7f;
71 // vch1.resize(vch2.size(), 0);
72 // +vch1[vch1.size()-1] = msb;
73 vch1.resize(vch2.size(), 0);
74 if (vch2.size() < vch1.size())
76 // +unsigned char msb = vch2[vch2.size()-1];
77 // +vch2[vch2.size()-1] &= 0x7f;
78 // vch2.resize(vch1.size(), 0);
79 // +vch2[vch2.size()-1] = msb;
80 vch2.resize(vch1.size(), 0);
86 // Script is a stack machine (like Forth) that evaluates a predicate
87 // returning a bool indicating valid or not. There are no loops.
89 #define stacktop(i) (stack.at(stack.size()+(i)))
90 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
91 static inline void popstack(vector<valtype>& stack)
94 throw runtime_error("popstack() : stack empty");
99 const char* GetTxnOutputType(txnouttype t)
103 case TX_NONSTANDARD: return "nonstandard";
104 case TX_PUBKEY: return "pubkey";
105 case TX_PUBKEYHASH: return "pubkeyhash";
106 case TX_SCRIPTHASH: return "scripthash";
107 case TX_MULTISIG: return "multisig";
113 const char* GetOpName(opcodetype opcode)
118 case OP_0 : return "0";
119 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
120 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
121 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
122 case OP_1NEGATE : return "-1";
123 case OP_RESERVED : return "OP_RESERVED";
124 case OP_1 : return "1";
125 case OP_2 : return "2";
126 case OP_3 : return "3";
127 case OP_4 : return "4";
128 case OP_5 : return "5";
129 case OP_6 : return "6";
130 case OP_7 : return "7";
131 case OP_8 : return "8";
132 case OP_9 : return "9";
133 case OP_10 : return "10";
134 case OP_11 : return "11";
135 case OP_12 : return "12";
136 case OP_13 : return "13";
137 case OP_14 : return "14";
138 case OP_15 : return "15";
139 case OP_16 : return "16";
142 case OP_NOP : return "OP_NOP";
143 case OP_VER : return "OP_VER";
144 case OP_IF : return "OP_IF";
145 case OP_NOTIF : return "OP_NOTIF";
146 case OP_VERIF : return "OP_VERIF";
147 case OP_VERNOTIF : return "OP_VERNOTIF";
148 case OP_ELSE : return "OP_ELSE";
149 case OP_ENDIF : return "OP_ENDIF";
150 case OP_VERIFY : return "OP_VERIFY";
151 case OP_RETURN : return "OP_RETURN";
154 case OP_TOALTSTACK : return "OP_TOALTSTACK";
155 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
156 case OP_2DROP : return "OP_2DROP";
157 case OP_2DUP : return "OP_2DUP";
158 case OP_3DUP : return "OP_3DUP";
159 case OP_2OVER : return "OP_2OVER";
160 case OP_2ROT : return "OP_2ROT";
161 case OP_2SWAP : return "OP_2SWAP";
162 case OP_IFDUP : return "OP_IFDUP";
163 case OP_DEPTH : return "OP_DEPTH";
164 case OP_DROP : return "OP_DROP";
165 case OP_DUP : return "OP_DUP";
166 case OP_NIP : return "OP_NIP";
167 case OP_OVER : return "OP_OVER";
168 case OP_PICK : return "OP_PICK";
169 case OP_ROLL : return "OP_ROLL";
170 case OP_ROT : return "OP_ROT";
171 case OP_SWAP : return "OP_SWAP";
172 case OP_TUCK : return "OP_TUCK";
175 case OP_CAT : return "OP_CAT";
176 case OP_SUBSTR : return "OP_SUBSTR";
177 case OP_LEFT : return "OP_LEFT";
178 case OP_RIGHT : return "OP_RIGHT";
179 case OP_SIZE : return "OP_SIZE";
182 case OP_INVERT : return "OP_INVERT";
183 case OP_AND : return "OP_AND";
184 case OP_OR : return "OP_OR";
185 case OP_XOR : return "OP_XOR";
186 case OP_EQUAL : return "OP_EQUAL";
187 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
188 case OP_RESERVED1 : return "OP_RESERVED1";
189 case OP_RESERVED2 : return "OP_RESERVED2";
192 case OP_1ADD : return "OP_1ADD";
193 case OP_1SUB : return "OP_1SUB";
194 case OP_2MUL : return "OP_2MUL";
195 case OP_2DIV : return "OP_2DIV";
196 case OP_NEGATE : return "OP_NEGATE";
197 case OP_ABS : return "OP_ABS";
198 case OP_NOT : return "OP_NOT";
199 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
200 case OP_ADD : return "OP_ADD";
201 case OP_SUB : return "OP_SUB";
202 case OP_MUL : return "OP_MUL";
203 case OP_DIV : return "OP_DIV";
204 case OP_MOD : return "OP_MOD";
205 case OP_LSHIFT : return "OP_LSHIFT";
206 case OP_RSHIFT : return "OP_RSHIFT";
207 case OP_BOOLAND : return "OP_BOOLAND";
208 case OP_BOOLOR : return "OP_BOOLOR";
209 case OP_NUMEQUAL : return "OP_NUMEQUAL";
210 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
211 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
212 case OP_LESSTHAN : return "OP_LESSTHAN";
213 case OP_GREATERTHAN : return "OP_GREATERTHAN";
214 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
215 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
216 case OP_MIN : return "OP_MIN";
217 case OP_MAX : return "OP_MAX";
218 case OP_WITHIN : return "OP_WITHIN";
221 case OP_RIPEMD160 : return "OP_RIPEMD160";
222 case OP_SHA1 : return "OP_SHA1";
223 case OP_SHA256 : return "OP_SHA256";
224 case OP_HASH160 : return "OP_HASH160";
225 case OP_HASH256 : return "OP_HASH256";
226 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
227 case OP_CHECKSIG : return "OP_CHECKSIG";
228 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
229 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
230 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
233 case OP_NOP1 : return "OP_NOP1";
234 case OP_NOP2 : return "OP_NOP2";
235 case OP_NOP3 : return "OP_NOP3";
236 case OP_NOP4 : return "OP_NOP4";
237 case OP_NOP5 : return "OP_NOP5";
238 case OP_NOP6 : return "OP_NOP6";
239 case OP_NOP7 : return "OP_NOP7";
240 case OP_NOP8 : return "OP_NOP8";
241 case OP_NOP9 : return "OP_NOP9";
242 case OP_NOP10 : return "OP_NOP10";
246 // template matching params
247 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
248 case OP_PUBKEY : return "OP_PUBKEY";
250 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
256 bool IsCanonicalPubKey(const valtype &vchPubKey) {
257 if (vchPubKey.size() < 33)
258 return error("Non-canonical public key: too short");
259 if (vchPubKey[0] == 0x04) {
260 if (vchPubKey.size() != 65)
261 return error("Non-canonical public key: invalid length for uncompressed key");
262 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
263 if (vchPubKey.size() != 33)
264 return error("Non-canonical public key: invalid length for compressed key");
266 return error("Non-canonical public key: compressed nor uncompressed");
271 bool IsCanonicalSignature(const valtype &vchSig) {
272 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
273 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
274 // Where R and S are not negative (their first byte has its highest bit not set), and not
275 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
276 // in which case a single 0 byte is necessary and even required).
277 if (vchSig.size() < 9)
278 return error("Non-canonical signature: too short");
279 if (vchSig.size() > 73)
280 return error("Non-canonical signature: too long");
281 if (vchSig[vchSig.size() - 1] & 0x7C)
282 return error("Non-canonical signature: unknown hashtype byte");
283 if (vchSig[0] != 0x30)
284 return error("Non-canonical signature: wrong type");
285 if (vchSig[1] != vchSig.size()-3)
286 return error("Non-canonical signature: wrong length marker");
287 unsigned int nLenR = vchSig[3];
288 if (5 + nLenR >= vchSig.size())
289 return error("Non-canonical signature: S length misplaced");
290 unsigned int nLenS = vchSig[5+nLenR];
291 if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
292 return error("Non-canonical signature: R+S length mismatch");
294 const unsigned char *R = &vchSig[4];
296 return error("Non-canonical signature: R value type mismatch");
298 return error("Non-canonical signature: R length is zero");
300 return error("Non-canonical signature: R value negative");
301 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
302 return error("Non-canonical signature: R value excessively padded");
304 const unsigned char *S = &vchSig[6+nLenR];
306 return error("Non-canonical signature: S value type mismatch");
308 return error("Non-canonical signature: S length is zero");
310 return error("Non-canonical signature: S value negative");
311 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
312 return error("Non-canonical signature: S value excessively padded");
317 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType)
320 CScript::const_iterator pc = script.begin();
321 CScript::const_iterator pend = script.end();
322 CScript::const_iterator pbegincodehash = script.begin();
324 valtype vchPushValue;
326 vector<valtype> altstack;
327 if (script.size() > 10000)
336 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
341 if (!script.GetOp(pc, opcode, vchPushValue))
343 if (vchPushValue.size() > 520)
345 if (opcode > OP_16 && ++nOpCount > 201)
348 if (opcode == OP_CAT ||
349 opcode == OP_SUBSTR ||
351 opcode == OP_RIGHT ||
352 opcode == OP_INVERT ||
361 opcode == OP_LSHIFT ||
365 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
366 stack.push_back(vchPushValue);
367 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
392 CBigNum bn((int)opcode - (int)(OP_1 - 1));
393 stack.push_back(bn.getvch());
402 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
403 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
409 // <expression> if [statements] [else [statements]] endif
413 if (stack.size() < 1)
415 valtype& vch = stacktop(-1);
416 fValue = CastToBool(vch);
417 if (opcode == OP_NOTIF)
421 vfExec.push_back(fValue);
429 vfExec.back() = !vfExec.back();
444 // (false -- false) and return
445 if (stack.size() < 1)
447 bool fValue = CastToBool(stacktop(-1));
467 if (stack.size() < 1)
469 altstack.push_back(stacktop(-1));
474 case OP_FROMALTSTACK:
476 if (altstack.size() < 1)
478 stack.push_back(altstacktop(-1));
486 if (stack.size() < 2)
495 // (x1 x2 -- x1 x2 x1 x2)
496 if (stack.size() < 2)
498 valtype vch1 = stacktop(-2);
499 valtype vch2 = stacktop(-1);
500 stack.push_back(vch1);
501 stack.push_back(vch2);
507 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
508 if (stack.size() < 3)
510 valtype vch1 = stacktop(-3);
511 valtype vch2 = stacktop(-2);
512 valtype vch3 = stacktop(-1);
513 stack.push_back(vch1);
514 stack.push_back(vch2);
515 stack.push_back(vch3);
521 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
522 if (stack.size() < 4)
524 valtype vch1 = stacktop(-4);
525 valtype vch2 = stacktop(-3);
526 stack.push_back(vch1);
527 stack.push_back(vch2);
533 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
534 if (stack.size() < 6)
536 valtype vch1 = stacktop(-6);
537 valtype vch2 = stacktop(-5);
538 stack.erase(stack.end()-6, stack.end()-4);
539 stack.push_back(vch1);
540 stack.push_back(vch2);
546 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
547 if (stack.size() < 4)
549 swap(stacktop(-4), stacktop(-2));
550 swap(stacktop(-3), stacktop(-1));
557 if (stack.size() < 1)
559 valtype vch = stacktop(-1);
561 stack.push_back(vch);
568 CBigNum bn(stack.size());
569 stack.push_back(bn.getvch());
576 if (stack.size() < 1)
585 if (stack.size() < 1)
587 valtype vch = stacktop(-1);
588 stack.push_back(vch);
595 if (stack.size() < 2)
597 stack.erase(stack.end() - 2);
603 // (x1 x2 -- x1 x2 x1)
604 if (stack.size() < 2)
606 valtype vch = stacktop(-2);
607 stack.push_back(vch);
614 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
615 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
616 if (stack.size() < 2)
618 int n = CastToBigNum(stacktop(-1)).getint();
620 if (n < 0 || n >= (int)stack.size())
622 valtype vch = stacktop(-n-1);
623 if (opcode == OP_ROLL)
624 stack.erase(stack.end()-n-1);
625 stack.push_back(vch);
631 // (x1 x2 x3 -- x2 x3 x1)
632 // x2 x1 x3 after first swap
633 // x2 x3 x1 after second swap
634 if (stack.size() < 3)
636 swap(stacktop(-3), stacktop(-2));
637 swap(stacktop(-2), stacktop(-1));
644 if (stack.size() < 2)
646 swap(stacktop(-2), stacktop(-1));
652 // (x1 x2 -- x2 x1 x2)
653 if (stack.size() < 2)
655 valtype vch = stacktop(-1);
656 stack.insert(stack.end()-2, vch);
667 if (stack.size() < 2)
669 valtype& vch1 = stacktop(-2);
670 valtype& vch2 = stacktop(-1);
671 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
673 if (stacktop(-1).size() > 520)
680 // (in begin size -- out)
681 if (stack.size() < 3)
683 valtype& vch = stacktop(-3);
684 int nBegin = CastToBigNum(stacktop(-2)).getint();
685 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
686 if (nBegin < 0 || nEnd < nBegin)
688 if (nBegin > (int)vch.size())
690 if (nEnd > (int)vch.size())
692 vch.erase(vch.begin() + nEnd, vch.end());
693 vch.erase(vch.begin(), vch.begin() + nBegin);
703 if (stack.size() < 2)
705 valtype& vch = stacktop(-2);
706 int nSize = CastToBigNum(stacktop(-1)).getint();
709 if (nSize > (int)vch.size())
711 if (opcode == OP_LEFT)
712 vch.erase(vch.begin() + nSize, vch.end());
714 vch.erase(vch.begin(), vch.end() - nSize);
722 if (stack.size() < 1)
724 CBigNum bn(stacktop(-1).size());
725 stack.push_back(bn.getvch());
736 if (stack.size() < 1)
738 valtype& vch = stacktop(-1);
739 for (unsigned int i = 0; i < vch.size(); i++)
745 // WARNING: These disabled opcodes exhibit unexpected behavior
746 // when used on signed integers due to a bug in MakeSameSize()
747 // [see definition of MakeSameSize() above].
754 if (stack.size() < 2)
756 valtype& vch1 = stacktop(-2);
757 valtype& vch2 = stacktop(-1);
758 MakeSameSize(vch1, vch2); // <-- NOT SAFE FOR SIGNED VALUES
759 if (opcode == OP_AND)
761 for (unsigned int i = 0; i < vch1.size(); i++)
764 else if (opcode == OP_OR)
766 for (unsigned int i = 0; i < vch1.size(); i++)
769 else if (opcode == OP_XOR)
771 for (unsigned int i = 0; i < vch1.size(); i++)
780 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
783 if (stack.size() < 2)
785 valtype& vch1 = stacktop(-2);
786 valtype& vch2 = stacktop(-1);
787 bool fEqual = (vch1 == vch2);
788 // OP_NOTEQUAL is disabled because it would be too easy to say
789 // something like n != 1 and have some wiseguy pass in 1 with extra
790 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
791 //if (opcode == OP_NOTEQUAL)
795 stack.push_back(fEqual ? vchTrue : vchFalse);
796 if (opcode == OP_EQUALVERIFY)
820 if (stack.size() < 1)
822 CBigNum bn = CastToBigNum(stacktop(-1));
825 case OP_1ADD: bn += bnOne; break;
826 case OP_1SUB: bn -= bnOne; break;
827 case OP_2MUL: bn <<= 1; break;
828 case OP_2DIV: bn >>= 1; break;
829 case OP_NEGATE: bn = -bn; break;
830 case OP_ABS: if (bn < bnZero) bn = -bn; break;
831 case OP_NOT: bn = (bn == bnZero); break;
832 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
833 default: assert(!"invalid opcode"); break;
836 stack.push_back(bn.getvch());
850 case OP_NUMEQUALVERIFY:
854 case OP_LESSTHANOREQUAL:
855 case OP_GREATERTHANOREQUAL:
860 if (stack.size() < 2)
862 CBigNum bn1 = CastToBigNum(stacktop(-2));
863 CBigNum bn2 = CastToBigNum(stacktop(-1));
876 if (!BN_mul(&bn, &bn1, &bn2, pctx))
881 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
886 if (!BN_mod(&bn, &bn1, &bn2, pctx))
891 if (bn2 < bnZero || bn2 > CBigNum(2048))
893 bn = bn1 << bn2.getulong();
897 if (bn2 < bnZero || bn2 > CBigNum(2048))
899 bn = bn1 >> bn2.getulong();
902 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
903 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
904 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
905 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
906 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
907 case OP_LESSTHAN: bn = (bn1 < bn2); break;
908 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
909 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
910 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
911 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
912 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
913 default: assert(!"invalid opcode"); break;
917 stack.push_back(bn.getvch());
919 if (opcode == OP_NUMEQUALVERIFY)
921 if (CastToBool(stacktop(-1)))
931 // (x min max -- out)
932 if (stack.size() < 3)
934 CBigNum bn1 = CastToBigNum(stacktop(-3));
935 CBigNum bn2 = CastToBigNum(stacktop(-2));
936 CBigNum bn3 = CastToBigNum(stacktop(-1));
937 bool fValue = (bn2 <= bn1 && bn1 < bn3);
941 stack.push_back(fValue ? vchTrue : vchFalse);
956 if (stack.size() < 1)
958 valtype& vch = stacktop(-1);
959 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
960 if (opcode == OP_RIPEMD160)
961 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
962 else if (opcode == OP_SHA1)
963 SHA1(&vch[0], vch.size(), &vchHash[0]);
964 else if (opcode == OP_SHA256)
965 SHA256(&vch[0], vch.size(), &vchHash[0]);
966 else if (opcode == OP_HASH160)
968 uint160 hash160 = Hash160(vch);
969 memcpy(&vchHash[0], &hash160, sizeof(hash160));
971 else if (opcode == OP_HASH256)
973 uint256 hash = Hash(vch.begin(), vch.end());
974 memcpy(&vchHash[0], &hash, sizeof(hash));
977 stack.push_back(vchHash);
981 case OP_CODESEPARATOR:
983 // Hash starts after the code separator
989 case OP_CHECKSIGVERIFY:
991 // (sig pubkey -- bool)
992 if (stack.size() < 2)
995 valtype& vchSig = stacktop(-2);
996 valtype& vchPubKey = stacktop(-1);
999 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1000 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1002 // Subset of script starting at the most recent codeseparator
1003 CScript scriptCode(pbegincodehash, pend);
1005 // Drop the signature, since there's no way for a signature to sign itself
1006 scriptCode.FindAndDelete(CScript(vchSig));
1008 bool fSuccess = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1010 fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1014 stack.push_back(fSuccess ? vchTrue : vchFalse);
1015 if (opcode == OP_CHECKSIGVERIFY)
1025 case OP_CHECKMULTISIG:
1026 case OP_CHECKMULTISIGVERIFY:
1028 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1031 if ((int)stack.size() < i)
1034 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
1035 if (nKeysCount < 0 || nKeysCount > 20)
1037 nOpCount += nKeysCount;
1042 if ((int)stack.size() < i)
1045 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
1046 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1050 if ((int)stack.size() < i)
1053 // Subset of script starting at the most recent codeseparator
1054 CScript scriptCode(pbegincodehash, pend);
1056 // Drop the signatures, since there's no way for a signature to sign itself
1057 for (int k = 0; k < nSigsCount; k++)
1059 valtype& vchSig = stacktop(-isig-k);
1060 scriptCode.FindAndDelete(CScript(vchSig));
1063 bool fSuccess = true;
1064 while (fSuccess && nSigsCount > 0)
1066 valtype& vchSig = stacktop(-isig);
1067 valtype& vchPubKey = stacktop(-ikey);
1070 bool fOk = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1072 fOk = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1081 // If there are more signatures left than keys left,
1082 // then too many signatures have failed
1083 if (nSigsCount > nKeysCount)
1089 stack.push_back(fSuccess ? vchTrue : vchFalse);
1091 if (opcode == OP_CHECKMULTISIGVERIFY)
1106 if (stack.size() + altstack.size() > 1000)
1116 if (!vfExec.empty())
1130 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1132 if (nIn >= txTo.vin.size())
1134 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1137 CTransaction txTmp(txTo);
1139 // In case concatenating two scripts ends up with two codeseparators,
1140 // or an extra one at the end, this prevents all those possible incompatibilities.
1141 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1143 // Blank out other inputs' signatures
1144 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1145 txTmp.vin[i].scriptSig = CScript();
1146 txTmp.vin[nIn].scriptSig = scriptCode;
1148 // Blank out some of the outputs
1149 if ((nHashType & 0x1f) == SIGHASH_NONE)
1154 // Let the others update at will
1155 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1157 txTmp.vin[i].nSequence = 0;
1159 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1161 // Only lock-in the txout payee at same index as txin
1162 unsigned int nOut = nIn;
1163 if (nOut >= txTmp.vout.size())
1165 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1168 txTmp.vout.resize(nOut+1);
1169 for (unsigned int i = 0; i < nOut; i++)
1170 txTmp.vout[i].SetNull();
1172 // Let the others update at will
1173 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1175 txTmp.vin[i].nSequence = 0;
1178 // Blank out other inputs completely, not recommended for open transactions
1179 if (nHashType & SIGHASH_ANYONECANPAY)
1181 txTmp.vin[0] = txTmp.vin[nIn];
1182 txTmp.vin.resize(1);
1185 // Serialize and hash
1186 CDataStream ss(SER_GETHASH, 0);
1188 ss << txTmp << nHashType;
1189 return Hash(ss.begin(), ss.end());
1193 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1194 // twice for every transaction (once when accepted into memory pool, and
1195 // again when accepted into the block chain)
1197 class CSignatureCache
1200 // sigdata_type is (signature hash, signature, public key):
1201 typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1202 std::set< sigdata_type> setValid;
1203 CCriticalSection cs_sigcache;
1207 Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1211 sigdata_type k(hash, vchSig, pubKey);
1212 std::set<sigdata_type>::iterator mi = setValid.find(k);
1213 if (mi != setValid.end())
1218 void Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1220 // DoS prevention: limit cache size to less than 10MB
1221 // (~200 bytes per cache entry times 50,000 entries)
1222 // Since there are a maximum of 20,000 signature operations per block
1223 // 50,000 is a reasonable default.
1224 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1225 if (nMaxCacheSize <= 0) return;
1229 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1231 // Evict a random entry. Random because that helps
1232 // foil would-be DoS attackers who might try to pre-generate
1233 // and re-use a set of valid signatures just-slightly-greater
1234 // than our cache size.
1235 uint256 randomHash = GetRandHash();
1236 std::vector<unsigned char> unused;
1237 std::set<sigdata_type>::iterator it =
1238 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1239 if (it == setValid.end())
1240 it = setValid.begin();
1241 setValid.erase(*it);
1244 sigdata_type k(hash, vchSig, pubKey);
1249 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1250 const CTransaction& txTo, unsigned int nIn, int nHashType)
1252 static CSignatureCache signatureCache;
1254 // Hash type is one byte tacked on to the end of the signature
1258 nHashType = vchSig.back();
1259 else if (nHashType != vchSig.back())
1263 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1265 if (signatureCache.Get(sighash, vchSig, vchPubKey))
1269 if (!key.SetPubKey(vchPubKey))
1272 if (!key.Verify(sighash, vchSig))
1275 signatureCache.Set(sighash, vchSig, vchPubKey);
1288 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1290 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1293 static map<txnouttype, CScript> mTemplates;
1294 if (mTemplates.empty())
1296 // Standard tx, sender provides pubkey, receiver adds signature
1297 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1299 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1300 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1302 // Sender provides N pubkeys, receivers provides M signatures
1303 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1306 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1307 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1308 if (scriptPubKey.IsPayToScriptHash())
1310 typeRet = TX_SCRIPTHASH;
1311 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1312 vSolutionsRet.push_back(hashBytes);
1317 const CScript& script1 = scriptPubKey;
1318 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1320 const CScript& script2 = tplate.second;
1321 vSolutionsRet.clear();
1323 opcodetype opcode1, opcode2;
1324 vector<unsigned char> vch1, vch2;
1327 CScript::const_iterator pc1 = script1.begin();
1328 CScript::const_iterator pc2 = script2.begin();
1331 if (pc1 == script1.end() && pc2 == script2.end())
1334 typeRet = tplate.first;
1335 if (typeRet == TX_MULTISIG)
1337 // Additional checks for TX_MULTISIG:
1338 unsigned char m = vSolutionsRet.front()[0];
1339 unsigned char n = vSolutionsRet.back()[0];
1340 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1345 if (!script1.GetOp(pc1, opcode1, vch1))
1347 if (!script2.GetOp(pc2, opcode2, vch2))
1350 // Template matching opcodes:
1351 if (opcode2 == OP_PUBKEYS)
1353 while (vch1.size() >= 33 && vch1.size() <= 120)
1355 vSolutionsRet.push_back(vch1);
1356 if (!script1.GetOp(pc1, opcode1, vch1))
1359 if (!script2.GetOp(pc2, opcode2, vch2))
1361 // Normal situation is to fall through
1362 // to other if/else statements
1365 if (opcode2 == OP_PUBKEY)
1367 if (vch1.size() < 33 || vch1.size() > 120)
1369 vSolutionsRet.push_back(vch1);
1371 else if (opcode2 == OP_PUBKEYHASH)
1373 if (vch1.size() != sizeof(uint160))
1375 vSolutionsRet.push_back(vch1);
1377 else if (opcode2 == OP_SMALLINTEGER)
1378 { // Single-byte small integer pushed onto vSolutions
1379 if (opcode1 == OP_0 ||
1380 (opcode1 >= OP_1 && opcode1 <= OP_16))
1382 char n = (char)CScript::DecodeOP_N(opcode1);
1383 vSolutionsRet.push_back(valtype(1, n));
1388 else if (opcode1 != opcode2 || vch1 != vch2)
1390 // Others must match exactly
1396 vSolutionsRet.clear();
1397 typeRet = TX_NONSTANDARD;
1402 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1405 if (!keystore.GetKey(address, key))
1408 vector<unsigned char> vchSig;
1409 if (!key.Sign(hash, vchSig))
1411 vchSig.push_back((unsigned char)nHashType);
1412 scriptSigRet << vchSig;
1417 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1420 int nRequired = multisigdata.front()[0];
1421 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1423 const valtype& pubkey = multisigdata[i];
1424 CKeyID keyID = CPubKey(pubkey).GetID();
1425 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1428 return nSigned==nRequired;
1432 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1433 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1434 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1435 // Returns false if scriptPubKey could not be completely satisfied.
1437 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1438 CScript& scriptSigRet, txnouttype& whichTypeRet)
1440 scriptSigRet.clear();
1442 vector<valtype> vSolutions;
1443 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1447 switch (whichTypeRet)
1449 case TX_NONSTANDARD:
1452 keyID = CPubKey(vSolutions[0]).GetID();
1453 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1455 keyID = CKeyID(uint160(vSolutions[0]));
1456 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1461 keystore.GetPubKey(keyID, vch);
1462 scriptSigRet << vch;
1466 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1469 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1470 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1475 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1479 case TX_NONSTANDARD:
1486 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1488 return vSolutions[0][0] + 1;
1490 return 1; // doesn't include args needed by the script
1495 bool IsStandard(const CScript& scriptPubKey)
1497 vector<valtype> vSolutions;
1498 txnouttype whichType;
1499 if (!Solver(scriptPubKey, whichType, vSolutions))
1502 if (whichType == TX_MULTISIG)
1504 unsigned char m = vSolutions.front()[0];
1505 unsigned char n = vSolutions.back()[0];
1506 // Support up to x-of-3 multisig txns as standard
1513 return whichType != TX_NONSTANDARD;
1517 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1519 unsigned int nResult = 0;
1520 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1522 CKeyID keyID = CPubKey(pubkey).GetID();
1523 if (keystore.HaveKey(keyID))
1530 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1533 const CKeyStore *keystore;
1535 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1536 bool operator()(const CNoDestination &dest) const { return false; }
1537 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1538 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1541 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1543 return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1546 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1548 vector<valtype> vSolutions;
1549 txnouttype whichType;
1550 if (!Solver(scriptPubKey, whichType, vSolutions))
1556 case TX_NONSTANDARD:
1559 keyID = CPubKey(vSolutions[0]).GetID();
1560 return keystore.HaveKey(keyID);
1562 keyID = CKeyID(uint160(vSolutions[0]));
1563 return keystore.HaveKey(keyID);
1567 if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1569 return IsMine(keystore, subscript);
1573 // Only consider transactions "mine" if we own ALL the
1574 // keys involved. multi-signature transactions that are
1575 // partially owned (somebody else has a key that can spend
1576 // them) enable spend-out-from-under-you attacks, especially
1577 // in shared-wallet situations.
1578 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1579 return HaveKeys(keys, keystore) == keys.size();
1585 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1587 const CKeyStore &keystore;
1588 std::vector<CKeyID> &vKeys;
1591 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1593 void Process(const CScript &script) {
1595 std::vector<CTxDestination> vDest;
1597 if (ExtractDestinations(script, type, vDest, nRequired)) {
1598 BOOST_FOREACH(const CTxDestination &dest, vDest)
1599 boost::apply_visitor(*this, dest);
1603 void operator()(const CKeyID &keyId) {
1604 if (keystore.HaveKey(keyId))
1605 vKeys.push_back(keyId);
1608 void operator()(const CScriptID &scriptId) {
1610 if (keystore.GetCScript(scriptId, script))
1614 void operator()(const CNoDestination &none) {}
1618 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1619 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1622 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1624 vector<valtype> vSolutions;
1625 txnouttype whichType;
1626 if (!Solver(scriptPubKey, whichType, vSolutions))
1629 if (whichType == TX_PUBKEY)
1631 addressRet = CPubKey(vSolutions[0]).GetID();
1634 else if (whichType == TX_PUBKEYHASH)
1636 addressRet = CKeyID(uint160(vSolutions[0]));
1639 else if (whichType == TX_SCRIPTHASH)
1641 addressRet = CScriptID(uint160(vSolutions[0]));
1644 // Multisig txns have more than one address...
1648 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1651 typeRet = TX_NONSTANDARD;
1652 vector<valtype> vSolutions;
1653 if (!Solver(scriptPubKey, typeRet, vSolutions))
1656 if (typeRet == TX_MULTISIG)
1658 nRequiredRet = vSolutions.front()[0];
1659 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1661 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1662 addressRet.push_back(address);
1668 CTxDestination address;
1669 if (!ExtractDestination(scriptPubKey, address))
1671 addressRet.push_back(address);
1677 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1678 bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1680 vector<vector<unsigned char> > stack, stackCopy;
1681 if (!EvalScript(stack, scriptSig, txTo, nIn, fStrictEncodings, nHashType))
1683 if (fValidatePayToScriptHash)
1685 if (!EvalScript(stack, scriptPubKey, txTo, nIn, fStrictEncodings, nHashType))
1690 if (CastToBool(stack.back()) == false)
1693 // Additional validation for spend-to-script-hash transactions:
1694 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1696 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1697 return false; // or validation fails
1699 const valtype& pubKeySerialized = stackCopy.back();
1700 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1701 popstack(stackCopy);
1703 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, fStrictEncodings, nHashType))
1705 if (stackCopy.empty())
1707 return CastToBool(stackCopy.back());
1714 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1716 assert(nIn < txTo.vin.size());
1717 CTxIn& txin = txTo.vin[nIn];
1719 // Leave out the signature from the hash, since a signature can't sign itself.
1720 // The checksig op will also drop the signatures from its hash.
1721 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1723 txnouttype whichType;
1724 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1727 if (whichType == TX_SCRIPTHASH)
1729 // Solver returns the subscript that need to be evaluated;
1730 // the final scriptSig is the signatures from that
1731 // and then the serialized subscript:
1732 CScript subscript = txin.scriptSig;
1734 // Recompute txn hash using subscript in place of scriptPubKey:
1735 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1739 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1740 // Append serialized subscript whether or not it is completely signed:
1741 txin.scriptSig << static_cast<valtype>(subscript);
1742 if (!fSolved) return false;
1746 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, true, 0);
1749 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1751 assert(nIn < txTo.vin.size());
1752 CTxIn& txin = txTo.vin[nIn];
1753 assert(txin.prevout.n < txFrom.vout.size());
1754 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1756 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1759 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1761 assert(nIn < txTo.vin.size());
1762 const CTxIn& txin = txTo.vin[nIn];
1763 if (txin.prevout.n >= txFrom.vout.size())
1766 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1768 return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, fStrictEncodings, nHashType);
1771 static CScript PushAll(const vector<valtype>& values)
1774 BOOST_FOREACH(const valtype& v, values)
1779 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1780 const vector<valtype>& vSolutions,
1781 vector<valtype>& sigs1, vector<valtype>& sigs2)
1783 // Combine all the signatures we've got:
1784 set<valtype> allsigs;
1785 BOOST_FOREACH(const valtype& v, sigs1)
1790 BOOST_FOREACH(const valtype& v, sigs2)
1796 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1797 assert(vSolutions.size() > 1);
1798 unsigned int nSigsRequired = vSolutions.front()[0];
1799 unsigned int nPubKeys = vSolutions.size()-2;
1800 map<valtype, valtype> sigs;
1801 BOOST_FOREACH(const valtype& sig, allsigs)
1803 for (unsigned int i = 0; i < nPubKeys; i++)
1805 const valtype& pubkey = vSolutions[i+1];
1806 if (sigs.count(pubkey))
1807 continue; // Already got a sig for this pubkey
1809 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0))
1816 // Now build a merged CScript:
1817 unsigned int nSigsHave = 0;
1818 CScript result; result << OP_0; // pop-one-too-many workaround
1819 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1821 if (sigs.count(vSolutions[i+1]))
1823 result << sigs[vSolutions[i+1]];
1827 // Fill any missing with OP_0:
1828 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1834 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1835 const txnouttype txType, const vector<valtype>& vSolutions,
1836 vector<valtype>& sigs1, vector<valtype>& sigs2)
1840 case TX_NONSTANDARD:
1841 // Don't know anything about this, assume bigger one is correct:
1842 if (sigs1.size() >= sigs2.size())
1843 return PushAll(sigs1);
1844 return PushAll(sigs2);
1847 // Signatures are bigger than placeholders or empty scripts:
1848 if (sigs1.empty() || sigs1[0].empty())
1849 return PushAll(sigs2);
1850 return PushAll(sigs1);
1852 if (sigs1.empty() || sigs1.back().empty())
1853 return PushAll(sigs2);
1854 else if (sigs2.empty() || sigs2.back().empty())
1855 return PushAll(sigs1);
1858 // Recur to combine:
1859 valtype spk = sigs1.back();
1860 CScript pubKey2(spk.begin(), spk.end());
1863 vector<vector<unsigned char> > vSolutions2;
1864 Solver(pubKey2, txType2, vSolutions2);
1867 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1872 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1878 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1879 const CScript& scriptSig1, const CScript& scriptSig2)
1882 vector<vector<unsigned char> > vSolutions;
1883 Solver(scriptPubKey, txType, vSolutions);
1885 vector<valtype> stack1;
1886 EvalScript(stack1, scriptSig1, CTransaction(), 0, true, 0);
1887 vector<valtype> stack2;
1888 EvalScript(stack2, scriptSig2, CTransaction(), 0, true, 0);
1890 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1893 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1896 const_iterator pc = begin();
1897 opcodetype lastOpcode = OP_INVALIDOPCODE;
1901 if (!GetOp(pc, opcode))
1903 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1905 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1907 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1908 n += DecodeOP_N(lastOpcode);
1912 lastOpcode = opcode;
1917 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1919 if (!IsPayToScriptHash())
1920 return GetSigOpCount(true);
1922 // This is a pay-to-script-hash scriptPubKey;
1923 // get the last item that the scriptSig
1924 // pushes onto the stack:
1925 const_iterator pc = scriptSig.begin();
1926 vector<unsigned char> data;
1927 while (pc < scriptSig.end())
1930 if (!scriptSig.GetOp(pc, opcode, data))
1936 /// ... and return its opcount:
1937 CScript subscript(data.begin(), data.end());
1938 return subscript.GetSigOpCount(true);
1941 bool CScript::IsPayToScriptHash() const
1943 // Extra-fast test for pay-to-script-hash CScripts:
1944 return (this->size() == 23 &&
1945 this->at(0) == OP_HASH160 &&
1946 this->at(1) == 0x14 &&
1947 this->at(22) == OP_EQUAL);
1950 bool CScript::HasCanonicalPushes() const
1952 const_iterator pc = begin();
1956 std::vector<unsigned char> data;
1957 if (!GetOp(pc, opcode, data))
1961 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1962 // Could have used an OP_n code, rather than a 1-byte push.
1964 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1965 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1967 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1968 // Could have used an OP_PUSHDATA1.
1970 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1971 // Could have used an OP_PUSHDATA2.
1977 class CScriptVisitor : public boost::static_visitor<bool>
1982 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1984 bool operator()(const CNoDestination &dest) const {
1989 bool operator()(const CKeyID &keyID) const {
1991 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1995 bool operator()(const CScriptID &scriptID) const {
1997 *script << OP_HASH160 << scriptID << OP_EQUAL;
2002 void CScript::SetDestination(const CTxDestination& dest)
2004 boost::apply_visitor(CScriptVisitor(this), dest);
2007 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
2011 *this << EncodeOP_N(nRequired);
2012 BOOST_FOREACH(const CKey& key, keys)
2013 *this << key.GetPubKey();
2014 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
2017 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
2019 if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
2020 && script[2] == 20 && script[23] == OP_EQUALVERIFY
2021 && script[24] == OP_CHECKSIG) {
2022 memcpy(&hash, &script[3], 20);
2028 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
2030 if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
2031 && script[22] == OP_EQUAL) {
2032 memcpy(&hash, &script[2], 20);
2038 bool CScriptCompressor::IsToPubKey(std::vector<unsigned char> &pubkey) const
2040 if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
2041 && (script[1] == 0x02 || script[1] == 0x03)) {
2043 memcpy(&pubkey[0], &script[1], 33);
2046 if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
2047 && script[1] == 0x04) {
2049 memcpy(&pubkey[0], &script[1], 65);
2051 return (key.SetPubKey(CPubKey(pubkey))); // SetPubKey fails if this is not a valid public key, a case that would not be compressible
2056 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
2059 if (IsToKeyID(keyID)) {
2062 memcpy(&out[1], &keyID, 20);
2066 if (IsToScriptID(scriptID)) {
2069 memcpy(&out[1], &scriptID, 20);
2072 std::vector<unsigned char> pubkey;
2073 if (IsToPubKey(pubkey)) {
2075 memcpy(&out[1], &pubkey[1], 32);
2076 if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2079 } else if (pubkey[0] == 0x04) {
2080 out[0] = 0x04 | (pubkey[64] & 0x01);
2087 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2089 if (nSize == 0 || nSize == 1)
2091 if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2096 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2102 script[1] = OP_HASH160;
2104 memcpy(&script[3], &in[0], 20);
2105 script[23] = OP_EQUALVERIFY;
2106 script[24] = OP_CHECKSIG;
2110 script[0] = OP_HASH160;
2112 memcpy(&script[2], &in[0], 20);
2113 script[22] = OP_EQUAL;
2120 memcpy(&script[2], &in[0], 32);
2121 script[34] = OP_CHECKSIG;
2125 std::vector<unsigned char> vch(33, 0x00);
2127 memcpy(&vch[1], &in[0], 32);
2129 if (!key.SetPubKey(CPubKey(vch)))
2131 key.SetCompressedPubKey(false); // Decompress public key
2132 CPubKey pubkey = key.GetPubKey();
2135 memcpy(&script[1], &pubkey.Raw()[0], 65);
2136 script[66] = OP_CHECKSIG;