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";
108 case TX_NULL_DATA: return "nulldata";
114 const char* GetOpName(opcodetype opcode)
119 case OP_0 : return "0";
120 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
121 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
122 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
123 case OP_1NEGATE : return "-1";
124 case OP_RESERVED : return "OP_RESERVED";
125 case OP_1 : return "1";
126 case OP_2 : return "2";
127 case OP_3 : return "3";
128 case OP_4 : return "4";
129 case OP_5 : return "5";
130 case OP_6 : return "6";
131 case OP_7 : return "7";
132 case OP_8 : return "8";
133 case OP_9 : return "9";
134 case OP_10 : return "10";
135 case OP_11 : return "11";
136 case OP_12 : return "12";
137 case OP_13 : return "13";
138 case OP_14 : return "14";
139 case OP_15 : return "15";
140 case OP_16 : return "16";
143 case OP_NOP : return "OP_NOP";
144 case OP_VER : return "OP_VER";
145 case OP_IF : return "OP_IF";
146 case OP_NOTIF : return "OP_NOTIF";
147 case OP_VERIF : return "OP_VERIF";
148 case OP_VERNOTIF : return "OP_VERNOTIF";
149 case OP_ELSE : return "OP_ELSE";
150 case OP_ENDIF : return "OP_ENDIF";
151 case OP_VERIFY : return "OP_VERIFY";
152 case OP_RETURN : return "OP_RETURN";
155 case OP_TOALTSTACK : return "OP_TOALTSTACK";
156 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
157 case OP_2DROP : return "OP_2DROP";
158 case OP_2DUP : return "OP_2DUP";
159 case OP_3DUP : return "OP_3DUP";
160 case OP_2OVER : return "OP_2OVER";
161 case OP_2ROT : return "OP_2ROT";
162 case OP_2SWAP : return "OP_2SWAP";
163 case OP_IFDUP : return "OP_IFDUP";
164 case OP_DEPTH : return "OP_DEPTH";
165 case OP_DROP : return "OP_DROP";
166 case OP_DUP : return "OP_DUP";
167 case OP_NIP : return "OP_NIP";
168 case OP_OVER : return "OP_OVER";
169 case OP_PICK : return "OP_PICK";
170 case OP_ROLL : return "OP_ROLL";
171 case OP_ROT : return "OP_ROT";
172 case OP_SWAP : return "OP_SWAP";
173 case OP_TUCK : return "OP_TUCK";
176 case OP_CAT : return "OP_CAT";
177 case OP_SUBSTR : return "OP_SUBSTR";
178 case OP_LEFT : return "OP_LEFT";
179 case OP_RIGHT : return "OP_RIGHT";
180 case OP_SIZE : return "OP_SIZE";
183 case OP_INVERT : return "OP_INVERT";
184 case OP_AND : return "OP_AND";
185 case OP_OR : return "OP_OR";
186 case OP_XOR : return "OP_XOR";
187 case OP_EQUAL : return "OP_EQUAL";
188 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
189 case OP_RESERVED1 : return "OP_RESERVED1";
190 case OP_RESERVED2 : return "OP_RESERVED2";
193 case OP_1ADD : return "OP_1ADD";
194 case OP_1SUB : return "OP_1SUB";
195 case OP_2MUL : return "OP_2MUL";
196 case OP_2DIV : return "OP_2DIV";
197 case OP_NEGATE : return "OP_NEGATE";
198 case OP_ABS : return "OP_ABS";
199 case OP_NOT : return "OP_NOT";
200 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
201 case OP_ADD : return "OP_ADD";
202 case OP_SUB : return "OP_SUB";
203 case OP_MUL : return "OP_MUL";
204 case OP_DIV : return "OP_DIV";
205 case OP_MOD : return "OP_MOD";
206 case OP_LSHIFT : return "OP_LSHIFT";
207 case OP_RSHIFT : return "OP_RSHIFT";
208 case OP_BOOLAND : return "OP_BOOLAND";
209 case OP_BOOLOR : return "OP_BOOLOR";
210 case OP_NUMEQUAL : return "OP_NUMEQUAL";
211 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
212 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
213 case OP_LESSTHAN : return "OP_LESSTHAN";
214 case OP_GREATERTHAN : return "OP_GREATERTHAN";
215 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
216 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
217 case OP_MIN : return "OP_MIN";
218 case OP_MAX : return "OP_MAX";
219 case OP_WITHIN : return "OP_WITHIN";
222 case OP_RIPEMD160 : return "OP_RIPEMD160";
223 case OP_SHA1 : return "OP_SHA1";
224 case OP_SHA256 : return "OP_SHA256";
225 case OP_HASH160 : return "OP_HASH160";
226 case OP_HASH256 : return "OP_HASH256";
227 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
228 case OP_CHECKSIG : return "OP_CHECKSIG";
229 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
230 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
231 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
234 case OP_NOP1 : return "OP_NOP1";
235 case OP_NOP2 : return "OP_NOP2";
236 case OP_NOP3 : return "OP_NOP3";
237 case OP_NOP4 : return "OP_NOP4";
238 case OP_NOP5 : return "OP_NOP5";
239 case OP_NOP6 : return "OP_NOP6";
240 case OP_NOP7 : return "OP_NOP7";
241 case OP_NOP8 : return "OP_NOP8";
242 case OP_NOP9 : return "OP_NOP9";
243 case OP_NOP10 : return "OP_NOP10";
247 // template matching params
248 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
249 case OP_PUBKEY : return "OP_PUBKEY";
250 case OP_SMALLDATA : return "OP_SMALLDATA";
252 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
258 bool IsCanonicalPubKey(const valtype &vchPubKey) {
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) {
274 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
275 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
276 // Where R and S are not negative (their first byte has its highest bit not set), and not
277 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
278 // in which case a single 0 byte is necessary and even required).
279 if (vchSig.size() < 9)
280 return error("Non-canonical signature: too short");
281 if (vchSig.size() > 73)
282 return error("Non-canonical signature: too long");
283 if (vchSig[vchSig.size() - 1] & 0x7C)
284 return error("Non-canonical signature: unknown hashtype byte");
285 if (vchSig[0] != 0x30)
286 return error("Non-canonical signature: wrong type");
287 if (vchSig[1] != vchSig.size()-3)
288 return error("Non-canonical signature: wrong length marker");
289 unsigned int nLenR = vchSig[3];
290 if (5 + nLenR >= vchSig.size())
291 return error("Non-canonical signature: S length misplaced");
292 unsigned int nLenS = vchSig[5+nLenR];
293 if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
294 return error("Non-canonical signature: R+S length mismatch");
296 const unsigned char *R = &vchSig[4];
298 return error("Non-canonical signature: R value type mismatch");
300 return error("Non-canonical signature: R length is zero");
302 return error("Non-canonical signature: R value negative");
303 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
304 return error("Non-canonical signature: R value excessively padded");
306 const unsigned char *S = &vchSig[6+nLenR];
308 return error("Non-canonical signature: S value type mismatch");
310 return error("Non-canonical signature: S length is zero");
312 return error("Non-canonical signature: S value negative");
313 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
314 return error("Non-canonical signature: S value excessively padded");
319 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, bool fStrictEncodings, int nHashType)
322 CScript::const_iterator pc = script.begin();
323 CScript::const_iterator pend = script.end();
324 CScript::const_iterator pbegincodehash = script.begin();
326 valtype vchPushValue;
328 vector<valtype> altstack;
329 if (script.size() > 10000)
338 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
343 if (!script.GetOp(pc, opcode, vchPushValue))
345 if (vchPushValue.size() > 520)
347 if (opcode > OP_16 && ++nOpCount > 201)
350 if (opcode == OP_CAT ||
351 opcode == OP_SUBSTR ||
353 opcode == OP_RIGHT ||
354 opcode == OP_INVERT ||
363 opcode == OP_LSHIFT ||
367 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
368 stack.push_back(vchPushValue);
369 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
394 CBigNum bn((int)opcode - (int)(OP_1 - 1));
395 stack.push_back(bn.getvch());
404 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
405 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
411 // <expression> if [statements] [else [statements]] endif
415 if (stack.size() < 1)
417 valtype& vch = stacktop(-1);
418 fValue = CastToBool(vch);
419 if (opcode == OP_NOTIF)
423 vfExec.push_back(fValue);
431 vfExec.back() = !vfExec.back();
446 // (false -- false) and return
447 if (stack.size() < 1)
449 bool fValue = CastToBool(stacktop(-1));
469 if (stack.size() < 1)
471 altstack.push_back(stacktop(-1));
476 case OP_FROMALTSTACK:
478 if (altstack.size() < 1)
480 stack.push_back(altstacktop(-1));
488 if (stack.size() < 2)
497 // (x1 x2 -- x1 x2 x1 x2)
498 if (stack.size() < 2)
500 valtype vch1 = stacktop(-2);
501 valtype vch2 = stacktop(-1);
502 stack.push_back(vch1);
503 stack.push_back(vch2);
509 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
510 if (stack.size() < 3)
512 valtype vch1 = stacktop(-3);
513 valtype vch2 = stacktop(-2);
514 valtype vch3 = stacktop(-1);
515 stack.push_back(vch1);
516 stack.push_back(vch2);
517 stack.push_back(vch3);
523 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
524 if (stack.size() < 4)
526 valtype vch1 = stacktop(-4);
527 valtype vch2 = stacktop(-3);
528 stack.push_back(vch1);
529 stack.push_back(vch2);
535 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
536 if (stack.size() < 6)
538 valtype vch1 = stacktop(-6);
539 valtype vch2 = stacktop(-5);
540 stack.erase(stack.end()-6, stack.end()-4);
541 stack.push_back(vch1);
542 stack.push_back(vch2);
548 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
549 if (stack.size() < 4)
551 swap(stacktop(-4), stacktop(-2));
552 swap(stacktop(-3), stacktop(-1));
559 if (stack.size() < 1)
561 valtype vch = stacktop(-1);
563 stack.push_back(vch);
570 CBigNum bn(stack.size());
571 stack.push_back(bn.getvch());
578 if (stack.size() < 1)
587 if (stack.size() < 1)
589 valtype vch = stacktop(-1);
590 stack.push_back(vch);
597 if (stack.size() < 2)
599 stack.erase(stack.end() - 2);
605 // (x1 x2 -- x1 x2 x1)
606 if (stack.size() < 2)
608 valtype vch = stacktop(-2);
609 stack.push_back(vch);
616 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
617 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
618 if (stack.size() < 2)
620 int n = CastToBigNum(stacktop(-1)).getint();
622 if (n < 0 || n >= (int)stack.size())
624 valtype vch = stacktop(-n-1);
625 if (opcode == OP_ROLL)
626 stack.erase(stack.end()-n-1);
627 stack.push_back(vch);
633 // (x1 x2 x3 -- x2 x3 x1)
634 // x2 x1 x3 after first swap
635 // x2 x3 x1 after second swap
636 if (stack.size() < 3)
638 swap(stacktop(-3), stacktop(-2));
639 swap(stacktop(-2), stacktop(-1));
646 if (stack.size() < 2)
648 swap(stacktop(-2), stacktop(-1));
654 // (x1 x2 -- x2 x1 x2)
655 if (stack.size() < 2)
657 valtype vch = stacktop(-1);
658 stack.insert(stack.end()-2, vch);
669 if (stack.size() < 2)
671 valtype& vch1 = stacktop(-2);
672 valtype& vch2 = stacktop(-1);
673 vch1.insert(vch1.end(), vch2.begin(), vch2.end());
675 if (stacktop(-1).size() > 520)
682 // (in begin size -- out)
683 if (stack.size() < 3)
685 valtype& vch = stacktop(-3);
686 int nBegin = CastToBigNum(stacktop(-2)).getint();
687 int nEnd = nBegin + CastToBigNum(stacktop(-1)).getint();
688 if (nBegin < 0 || nEnd < nBegin)
690 if (nBegin > (int)vch.size())
692 if (nEnd > (int)vch.size())
694 vch.erase(vch.begin() + nEnd, vch.end());
695 vch.erase(vch.begin(), vch.begin() + nBegin);
705 if (stack.size() < 2)
707 valtype& vch = stacktop(-2);
708 int nSize = CastToBigNum(stacktop(-1)).getint();
711 if (nSize > (int)vch.size())
713 if (opcode == OP_LEFT)
714 vch.erase(vch.begin() + nSize, vch.end());
716 vch.erase(vch.begin(), vch.end() - nSize);
724 if (stack.size() < 1)
726 CBigNum bn(stacktop(-1).size());
727 stack.push_back(bn.getvch());
738 if (stack.size() < 1)
740 valtype& vch = stacktop(-1);
741 for (unsigned int i = 0; i < vch.size(); i++)
747 // WARNING: These disabled opcodes exhibit unexpected behavior
748 // when used on signed integers due to a bug in MakeSameSize()
749 // [see definition of MakeSameSize() above].
756 if (stack.size() < 2)
758 valtype& vch1 = stacktop(-2);
759 valtype& vch2 = stacktop(-1);
760 MakeSameSize(vch1, vch2); // <-- NOT SAFE FOR SIGNED VALUES
761 if (opcode == OP_AND)
763 for (unsigned int i = 0; i < vch1.size(); i++)
766 else if (opcode == OP_OR)
768 for (unsigned int i = 0; i < vch1.size(); i++)
771 else if (opcode == OP_XOR)
773 for (unsigned int i = 0; i < vch1.size(); i++)
782 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
785 if (stack.size() < 2)
787 valtype& vch1 = stacktop(-2);
788 valtype& vch2 = stacktop(-1);
789 bool fEqual = (vch1 == vch2);
790 // OP_NOTEQUAL is disabled because it would be too easy to say
791 // something like n != 1 and have some wiseguy pass in 1 with extra
792 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
793 //if (opcode == OP_NOTEQUAL)
797 stack.push_back(fEqual ? vchTrue : vchFalse);
798 if (opcode == OP_EQUALVERIFY)
822 if (stack.size() < 1)
824 CBigNum bn = CastToBigNum(stacktop(-1));
827 case OP_1ADD: bn += bnOne; break;
828 case OP_1SUB: bn -= bnOne; break;
829 case OP_2MUL: bn <<= 1; break;
830 case OP_2DIV: bn >>= 1; break;
831 case OP_NEGATE: bn = -bn; break;
832 case OP_ABS: if (bn < bnZero) bn = -bn; break;
833 case OP_NOT: bn = (bn == bnZero); break;
834 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
835 default: assert(!"invalid opcode"); break;
838 stack.push_back(bn.getvch());
852 case OP_NUMEQUALVERIFY:
856 case OP_LESSTHANOREQUAL:
857 case OP_GREATERTHANOREQUAL:
862 if (stack.size() < 2)
864 CBigNum bn1 = CastToBigNum(stacktop(-2));
865 CBigNum bn2 = CastToBigNum(stacktop(-1));
878 if (!BN_mul(&bn, &bn1, &bn2, pctx))
883 if (!BN_div(&bn, NULL, &bn1, &bn2, pctx))
888 if (!BN_mod(&bn, &bn1, &bn2, pctx))
893 if (bn2 < bnZero || bn2 > CBigNum(2048))
895 bn = bn1 << bn2.getulong();
899 if (bn2 < bnZero || bn2 > CBigNum(2048))
901 bn = bn1 >> bn2.getulong();
904 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
905 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
906 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
907 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
908 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
909 case OP_LESSTHAN: bn = (bn1 < bn2); break;
910 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
911 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
912 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
913 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
914 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
915 default: assert(!"invalid opcode"); break;
919 stack.push_back(bn.getvch());
921 if (opcode == OP_NUMEQUALVERIFY)
923 if (CastToBool(stacktop(-1)))
933 // (x min max -- out)
934 if (stack.size() < 3)
936 CBigNum bn1 = CastToBigNum(stacktop(-3));
937 CBigNum bn2 = CastToBigNum(stacktop(-2));
938 CBigNum bn3 = CastToBigNum(stacktop(-1));
939 bool fValue = (bn2 <= bn1 && bn1 < bn3);
943 stack.push_back(fValue ? vchTrue : vchFalse);
958 if (stack.size() < 1)
960 valtype& vch = stacktop(-1);
961 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
962 if (opcode == OP_RIPEMD160)
963 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
964 else if (opcode == OP_SHA1)
965 SHA1(&vch[0], vch.size(), &vchHash[0]);
966 else if (opcode == OP_SHA256)
967 SHA256(&vch[0], vch.size(), &vchHash[0]);
968 else if (opcode == OP_HASH160)
970 uint160 hash160 = Hash160(vch);
971 memcpy(&vchHash[0], &hash160, sizeof(hash160));
973 else if (opcode == OP_HASH256)
975 uint256 hash = Hash(vch.begin(), vch.end());
976 memcpy(&vchHash[0], &hash, sizeof(hash));
979 stack.push_back(vchHash);
983 case OP_CODESEPARATOR:
985 // Hash starts after the code separator
991 case OP_CHECKSIGVERIFY:
993 // (sig pubkey -- bool)
994 if (stack.size() < 2)
997 valtype& vchSig = stacktop(-2);
998 valtype& vchPubKey = stacktop(-1);
1001 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1002 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1004 // Subset of script starting at the most recent codeseparator
1005 CScript scriptCode(pbegincodehash, pend);
1007 // Drop the signature, since there's no way for a signature to sign itself
1008 scriptCode.FindAndDelete(CScript(vchSig));
1010 bool fSuccess = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1012 fSuccess = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1016 stack.push_back(fSuccess ? vchTrue : vchFalse);
1017 if (opcode == OP_CHECKSIGVERIFY)
1027 case OP_CHECKMULTISIG:
1028 case OP_CHECKMULTISIGVERIFY:
1030 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1033 if ((int)stack.size() < i)
1036 int nKeysCount = CastToBigNum(stacktop(-i)).getint();
1037 if (nKeysCount < 0 || nKeysCount > 20)
1039 nOpCount += nKeysCount;
1044 if ((int)stack.size() < i)
1047 int nSigsCount = CastToBigNum(stacktop(-i)).getint();
1048 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1052 if ((int)stack.size() < i)
1055 // Subset of script starting at the most recent codeseparator
1056 CScript scriptCode(pbegincodehash, pend);
1058 // Drop the signatures, since there's no way for a signature to sign itself
1059 for (int k = 0; k < nSigsCount; k++)
1061 valtype& vchSig = stacktop(-isig-k);
1062 scriptCode.FindAndDelete(CScript(vchSig));
1065 bool fSuccess = true;
1066 while (fSuccess && nSigsCount > 0)
1068 valtype& vchSig = stacktop(-isig);
1069 valtype& vchPubKey = stacktop(-ikey);
1072 bool fOk = (!fStrictEncodings || (IsCanonicalSignature(vchSig) && IsCanonicalPubKey(vchPubKey)));
1074 fOk = CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType);
1083 // If there are more signatures left than keys left,
1084 // then too many signatures have failed
1085 if (nSigsCount > nKeysCount)
1091 stack.push_back(fSuccess ? vchTrue : vchFalse);
1093 if (opcode == OP_CHECKMULTISIGVERIFY)
1108 if (stack.size() + altstack.size() > 1000)
1118 if (!vfExec.empty())
1132 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1134 if (nIn >= txTo.vin.size())
1136 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1139 CTransaction txTmp(txTo);
1141 // In case concatenating two scripts ends up with two codeseparators,
1142 // or an extra one at the end, this prevents all those possible incompatibilities.
1143 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1145 // Blank out other inputs' signatures
1146 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1147 txTmp.vin[i].scriptSig = CScript();
1148 txTmp.vin[nIn].scriptSig = scriptCode;
1150 // Blank out some of the outputs
1151 if ((nHashType & 0x1f) == SIGHASH_NONE)
1156 // Let the others update at will
1157 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1159 txTmp.vin[i].nSequence = 0;
1161 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1163 // Only lock-in the txout payee at same index as txin
1164 unsigned int nOut = nIn;
1165 if (nOut >= txTmp.vout.size())
1167 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1170 txTmp.vout.resize(nOut+1);
1171 for (unsigned int i = 0; i < nOut; i++)
1172 txTmp.vout[i].SetNull();
1174 // Let the others update at will
1175 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1177 txTmp.vin[i].nSequence = 0;
1180 // Blank out other inputs completely, not recommended for open transactions
1181 if (nHashType & SIGHASH_ANYONECANPAY)
1183 txTmp.vin[0] = txTmp.vin[nIn];
1184 txTmp.vin.resize(1);
1187 // Serialize and hash
1188 CDataStream ss(SER_GETHASH, 0);
1190 ss << txTmp << nHashType;
1191 return Hash(ss.begin(), ss.end());
1195 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1196 // twice for every transaction (once when accepted into memory pool, and
1197 // again when accepted into the block chain)
1199 class CSignatureCache
1202 // sigdata_type is (signature hash, signature, public key):
1203 typedef boost::tuple<uint256, std::vector<unsigned char>, std::vector<unsigned char> > sigdata_type;
1204 std::set< sigdata_type> setValid;
1205 CCriticalSection cs_sigcache;
1209 Get(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1213 sigdata_type k(hash, vchSig, pubKey);
1214 std::set<sigdata_type>::iterator mi = setValid.find(k);
1215 if (mi != setValid.end())
1220 void Set(uint256 hash, const std::vector<unsigned char>& vchSig, const std::vector<unsigned char>& pubKey)
1222 // DoS prevention: limit cache size to less than 10MB
1223 // (~200 bytes per cache entry times 50,000 entries)
1224 // Since there are a maximum of 20,000 signature operations per block
1225 // 50,000 is a reasonable default.
1226 int64 nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1227 if (nMaxCacheSize <= 0) return;
1231 while (static_cast<int64>(setValid.size()) > nMaxCacheSize)
1233 // Evict a random entry. Random because that helps
1234 // foil would-be DoS attackers who might try to pre-generate
1235 // and re-use a set of valid signatures just-slightly-greater
1236 // than our cache size.
1237 uint256 randomHash = GetRandHash();
1238 std::vector<unsigned char> unused;
1239 std::set<sigdata_type>::iterator it =
1240 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1241 if (it == setValid.end())
1242 it = setValid.begin();
1243 setValid.erase(*it);
1246 sigdata_type k(hash, vchSig, pubKey);
1251 bool CheckSig(vector<unsigned char> vchSig, vector<unsigned char> vchPubKey, CScript scriptCode,
1252 const CTransaction& txTo, unsigned int nIn, int nHashType)
1254 static CSignatureCache signatureCache;
1256 // Hash type is one byte tacked on to the end of the signature
1260 nHashType = vchSig.back();
1261 else if (nHashType != vchSig.back())
1265 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1267 if (signatureCache.Get(sighash, vchSig, vchPubKey))
1271 if (!key.SetPubKey(vchPubKey))
1274 if (!key.Verify(sighash, vchSig))
1277 signatureCache.Set(sighash, vchSig, vchPubKey);
1290 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1292 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1295 static map<txnouttype, CScript> mTemplates;
1296 if (mTemplates.empty())
1298 // Standard tx, sender provides pubkey, receiver adds signature
1299 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1301 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1302 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1304 // Sender provides N pubkeys, receivers provides M signatures
1305 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1307 // Empty, provably prunable, data-carrying output
1308 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1311 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1312 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1313 if (scriptPubKey.IsPayToScriptHash())
1315 typeRet = TX_SCRIPTHASH;
1316 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1317 vSolutionsRet.push_back(hashBytes);
1322 const CScript& script1 = scriptPubKey;
1323 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1325 const CScript& script2 = tplate.second;
1326 vSolutionsRet.clear();
1328 opcodetype opcode1, opcode2;
1329 vector<unsigned char> vch1, vch2;
1332 CScript::const_iterator pc1 = script1.begin();
1333 CScript::const_iterator pc2 = script2.begin();
1336 if (pc1 == script1.end() && pc2 == script2.end())
1339 typeRet = tplate.first;
1340 if (typeRet == TX_MULTISIG)
1342 // Additional checks for TX_MULTISIG:
1343 unsigned char m = vSolutionsRet.front()[0];
1344 unsigned char n = vSolutionsRet.back()[0];
1345 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1350 if (!script1.GetOp(pc1, opcode1, vch1))
1352 if (!script2.GetOp(pc2, opcode2, vch2))
1355 // Template matching opcodes:
1356 if (opcode2 == OP_PUBKEYS)
1358 while (vch1.size() >= 33 && vch1.size() <= 120)
1360 vSolutionsRet.push_back(vch1);
1361 if (!script1.GetOp(pc1, opcode1, vch1))
1364 if (!script2.GetOp(pc2, opcode2, vch2))
1366 // Normal situation is to fall through
1367 // to other if/else statements
1370 if (opcode2 == OP_PUBKEY)
1372 if (vch1.size() < 33 || vch1.size() > 120)
1374 vSolutionsRet.push_back(vch1);
1376 else if (opcode2 == OP_PUBKEYHASH)
1378 if (vch1.size() != sizeof(uint160))
1380 vSolutionsRet.push_back(vch1);
1382 else if (opcode2 == OP_SMALLINTEGER)
1383 { // Single-byte small integer pushed onto vSolutions
1384 if (opcode1 == OP_0 ||
1385 (opcode1 >= OP_1 && opcode1 <= OP_16))
1387 char n = (char)CScript::DecodeOP_N(opcode1);
1388 vSolutionsRet.push_back(valtype(1, n));
1393 else if (opcode2 == OP_SMALLDATA)
1395 // small pushdata, <= 80 bytes
1396 if (vch1.size() > 80)
1399 else if (opcode1 != opcode2 || vch1 != vch2)
1401 // Others must match exactly
1407 vSolutionsRet.clear();
1408 typeRet = TX_NONSTANDARD;
1413 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1416 if (!keystore.GetKey(address, key))
1419 vector<unsigned char> vchSig;
1420 if (!key.Sign(hash, vchSig))
1422 vchSig.push_back((unsigned char)nHashType);
1423 scriptSigRet << vchSig;
1428 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1431 int nRequired = multisigdata.front()[0];
1432 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1434 const valtype& pubkey = multisigdata[i];
1435 CKeyID keyID = CPubKey(pubkey).GetID();
1436 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1439 return nSigned==nRequired;
1443 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1444 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1445 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1446 // Returns false if scriptPubKey could not be completely satisfied.
1448 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1449 CScript& scriptSigRet, txnouttype& whichTypeRet)
1451 scriptSigRet.clear();
1453 vector<valtype> vSolutions;
1454 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1458 switch (whichTypeRet)
1460 case TX_NONSTANDARD:
1464 keyID = CPubKey(vSolutions[0]).GetID();
1465 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1467 keyID = CKeyID(uint160(vSolutions[0]));
1468 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1473 keystore.GetPubKey(keyID, vch);
1474 scriptSigRet << vch;
1478 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1481 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1482 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1487 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1491 case TX_NONSTANDARD:
1500 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1502 return vSolutions[0][0] + 1;
1504 return 1; // doesn't include args needed by the script
1509 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1511 vector<valtype> vSolutions;
1512 if (!Solver(scriptPubKey, whichType, vSolutions))
1515 if (whichType == TX_MULTISIG)
1517 unsigned char m = vSolutions.front()[0];
1518 unsigned char n = vSolutions.back()[0];
1519 // Support up to x-of-3 multisig txns as standard
1526 return whichType != TX_NONSTANDARD;
1530 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1532 unsigned int nResult = 0;
1533 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1535 CKeyID keyID = CPubKey(pubkey).GetID();
1536 if (keystore.HaveKey(keyID))
1543 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1546 const CKeyStore *keystore;
1548 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1549 bool operator()(const CNoDestination &dest) const { return false; }
1550 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1551 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1554 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1556 return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1559 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1561 vector<valtype> vSolutions;
1562 txnouttype whichType;
1563 if (!Solver(scriptPubKey, whichType, vSolutions))
1569 case TX_NONSTANDARD:
1573 keyID = CPubKey(vSolutions[0]).GetID();
1574 return keystore.HaveKey(keyID);
1576 keyID = CKeyID(uint160(vSolutions[0]));
1577 return keystore.HaveKey(keyID);
1581 if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1583 return IsMine(keystore, subscript);
1587 // Only consider transactions "mine" if we own ALL the
1588 // keys involved. multi-signature transactions that are
1589 // partially owned (somebody else has a key that can spend
1590 // them) enable spend-out-from-under-you attacks, especially
1591 // in shared-wallet situations.
1592 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1593 return HaveKeys(keys, keystore) == keys.size();
1599 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1601 const CKeyStore &keystore;
1602 std::vector<CKeyID> &vKeys;
1605 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1607 void Process(const CScript &script) {
1609 std::vector<CTxDestination> vDest;
1611 if (ExtractDestinations(script, type, vDest, nRequired)) {
1612 BOOST_FOREACH(const CTxDestination &dest, vDest)
1613 boost::apply_visitor(*this, dest);
1617 void operator()(const CKeyID &keyId) {
1618 if (keystore.HaveKey(keyId))
1619 vKeys.push_back(keyId);
1622 void operator()(const CScriptID &scriptId) {
1624 if (keystore.GetCScript(scriptId, script))
1628 void operator()(const CNoDestination &none) {}
1632 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1633 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1636 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1638 vector<valtype> vSolutions;
1639 txnouttype whichType;
1640 if (!Solver(scriptPubKey, whichType, vSolutions))
1643 if (whichType == TX_PUBKEY)
1645 addressRet = CPubKey(vSolutions[0]).GetID();
1648 else if (whichType == TX_PUBKEYHASH)
1650 addressRet = CKeyID(uint160(vSolutions[0]));
1653 else if (whichType == TX_SCRIPTHASH)
1655 addressRet = CScriptID(uint160(vSolutions[0]));
1658 // Multisig txns have more than one address...
1662 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1665 typeRet = TX_NONSTANDARD;
1666 vector<valtype> vSolutions;
1667 if (!Solver(scriptPubKey, typeRet, vSolutions))
1669 if (typeRet == TX_NULL_DATA)
1672 if (typeRet == TX_MULTISIG)
1674 nRequiredRet = vSolutions.front()[0];
1675 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1677 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1678 addressRet.push_back(address);
1684 CTxDestination address;
1685 if (!ExtractDestination(scriptPubKey, address))
1687 addressRet.push_back(address);
1693 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1694 bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1696 vector<vector<unsigned char> > stack, stackCopy;
1697 if (!EvalScript(stack, scriptSig, txTo, nIn, fStrictEncodings, nHashType))
1699 if (fValidatePayToScriptHash)
1701 if (!EvalScript(stack, scriptPubKey, txTo, nIn, fStrictEncodings, nHashType))
1706 if (CastToBool(stack.back()) == false)
1709 // Additional validation for spend-to-script-hash transactions:
1710 if (fValidatePayToScriptHash && scriptPubKey.IsPayToScriptHash())
1712 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1713 return false; // or validation fails
1715 const valtype& pubKeySerialized = stackCopy.back();
1716 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1717 popstack(stackCopy);
1719 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, fStrictEncodings, nHashType))
1721 if (stackCopy.empty())
1723 return CastToBool(stackCopy.back());
1730 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1732 assert(nIn < txTo.vin.size());
1733 CTxIn& txin = txTo.vin[nIn];
1735 // Leave out the signature from the hash, since a signature can't sign itself.
1736 // The checksig op will also drop the signatures from its hash.
1737 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1739 txnouttype whichType;
1740 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1743 if (whichType == TX_SCRIPTHASH)
1745 // Solver returns the subscript that need to be evaluated;
1746 // the final scriptSig is the signatures from that
1747 // and then the serialized subscript:
1748 CScript subscript = txin.scriptSig;
1750 // Recompute txn hash using subscript in place of scriptPubKey:
1751 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1755 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1756 // Append serialized subscript whether or not it is completely signed:
1757 txin.scriptSig << static_cast<valtype>(subscript);
1758 if (!fSolved) return false;
1762 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, true, true, 0);
1765 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1767 assert(nIn < txTo.vin.size());
1768 CTxIn& txin = txTo.vin[nIn];
1769 assert(txin.prevout.n < txFrom.vout.size());
1770 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1772 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1775 bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, bool fValidatePayToScriptHash, bool fStrictEncodings, int nHashType)
1777 assert(nIn < txTo.vin.size());
1778 const CTxIn& txin = txTo.vin[nIn];
1779 if (txin.prevout.n >= txFrom.vout.size())
1782 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1784 return VerifyScript(txin.scriptSig, txout.scriptPubKey, txTo, nIn, fValidatePayToScriptHash, fStrictEncodings, nHashType);
1787 static CScript PushAll(const vector<valtype>& values)
1790 BOOST_FOREACH(const valtype& v, values)
1795 static CScript CombineMultisig(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1796 const vector<valtype>& vSolutions,
1797 vector<valtype>& sigs1, vector<valtype>& sigs2)
1799 // Combine all the signatures we've got:
1800 set<valtype> allsigs;
1801 BOOST_FOREACH(const valtype& v, sigs1)
1806 BOOST_FOREACH(const valtype& v, sigs2)
1812 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1813 assert(vSolutions.size() > 1);
1814 unsigned int nSigsRequired = vSolutions.front()[0];
1815 unsigned int nPubKeys = vSolutions.size()-2;
1816 map<valtype, valtype> sigs;
1817 BOOST_FOREACH(const valtype& sig, allsigs)
1819 for (unsigned int i = 0; i < nPubKeys; i++)
1821 const valtype& pubkey = vSolutions[i+1];
1822 if (sigs.count(pubkey))
1823 continue; // Already got a sig for this pubkey
1825 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0))
1832 // Now build a merged CScript:
1833 unsigned int nSigsHave = 0;
1834 CScript result; result << OP_0; // pop-one-too-many workaround
1835 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1837 if (sigs.count(vSolutions[i+1]))
1839 result << sigs[vSolutions[i+1]];
1843 // Fill any missing with OP_0:
1844 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1850 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1851 const txnouttype txType, const vector<valtype>& vSolutions,
1852 vector<valtype>& sigs1, vector<valtype>& sigs2)
1856 case TX_NONSTANDARD:
1858 // Don't know anything about this, assume bigger one is correct:
1859 if (sigs1.size() >= sigs2.size())
1860 return PushAll(sigs1);
1861 return PushAll(sigs2);
1864 // Signatures are bigger than placeholders or empty scripts:
1865 if (sigs1.empty() || sigs1[0].empty())
1866 return PushAll(sigs2);
1867 return PushAll(sigs1);
1869 if (sigs1.empty() || sigs1.back().empty())
1870 return PushAll(sigs2);
1871 else if (sigs2.empty() || sigs2.back().empty())
1872 return PushAll(sigs1);
1875 // Recur to combine:
1876 valtype spk = sigs1.back();
1877 CScript pubKey2(spk.begin(), spk.end());
1880 vector<vector<unsigned char> > vSolutions2;
1881 Solver(pubKey2, txType2, vSolutions2);
1884 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1889 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1895 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1896 const CScript& scriptSig1, const CScript& scriptSig2)
1899 vector<vector<unsigned char> > vSolutions;
1900 Solver(scriptPubKey, txType, vSolutions);
1902 vector<valtype> stack1;
1903 EvalScript(stack1, scriptSig1, CTransaction(), 0, true, 0);
1904 vector<valtype> stack2;
1905 EvalScript(stack2, scriptSig2, CTransaction(), 0, true, 0);
1907 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1910 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1913 const_iterator pc = begin();
1914 opcodetype lastOpcode = OP_INVALIDOPCODE;
1918 if (!GetOp(pc, opcode))
1920 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1922 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1924 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1925 n += DecodeOP_N(lastOpcode);
1929 lastOpcode = opcode;
1934 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1936 if (!IsPayToScriptHash())
1937 return GetSigOpCount(true);
1939 // This is a pay-to-script-hash scriptPubKey;
1940 // get the last item that the scriptSig
1941 // pushes onto the stack:
1942 const_iterator pc = scriptSig.begin();
1943 vector<unsigned char> data;
1944 while (pc < scriptSig.end())
1947 if (!scriptSig.GetOp(pc, opcode, data))
1953 /// ... and return its opcount:
1954 CScript subscript(data.begin(), data.end());
1955 return subscript.GetSigOpCount(true);
1958 bool CScript::IsPayToScriptHash() const
1960 // Extra-fast test for pay-to-script-hash CScripts:
1961 return (this->size() == 23 &&
1962 this->at(0) == OP_HASH160 &&
1963 this->at(1) == 0x14 &&
1964 this->at(22) == OP_EQUAL);
1967 bool CScript::HasCanonicalPushes() const
1969 const_iterator pc = begin();
1973 std::vector<unsigned char> data;
1974 if (!GetOp(pc, opcode, data))
1978 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1979 // Could have used an OP_n code, rather than a 1-byte push.
1981 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1982 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1984 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1985 // Could have used an OP_PUSHDATA1.
1987 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1988 // Could have used an OP_PUSHDATA2.
1994 class CScriptVisitor : public boost::static_visitor<bool>
1999 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2001 bool operator()(const CNoDestination &dest) const {
2006 bool operator()(const CKeyID &keyID) const {
2008 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2012 bool operator()(const CScriptID &scriptID) const {
2014 *script << OP_HASH160 << scriptID << OP_EQUAL;
2019 void CScript::SetDestination(const CTxDestination& dest)
2021 boost::apply_visitor(CScriptVisitor(this), dest);
2024 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
2028 *this << EncodeOP_N(nRequired);
2029 BOOST_FOREACH(const CKey& key, keys)
2030 *this << key.GetPubKey();
2031 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
2034 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
2036 if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
2037 && script[2] == 20 && script[23] == OP_EQUALVERIFY
2038 && script[24] == OP_CHECKSIG) {
2039 memcpy(&hash, &script[3], 20);
2045 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
2047 if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
2048 && script[22] == OP_EQUAL) {
2049 memcpy(&hash, &script[2], 20);
2055 bool CScriptCompressor::IsToPubKey(std::vector<unsigned char> &pubkey) const
2057 if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
2058 && (script[1] == 0x02 || script[1] == 0x03)) {
2060 memcpy(&pubkey[0], &script[1], 33);
2063 if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
2064 && script[1] == 0x04) {
2066 memcpy(&pubkey[0], &script[1], 65);
2068 return (key.SetPubKey(CPubKey(pubkey))); // SetPubKey fails if this is not a valid public key, a case that would not be compressible
2073 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
2076 if (IsToKeyID(keyID)) {
2079 memcpy(&out[1], &keyID, 20);
2083 if (IsToScriptID(scriptID)) {
2086 memcpy(&out[1], &scriptID, 20);
2089 std::vector<unsigned char> pubkey;
2090 if (IsToPubKey(pubkey)) {
2092 memcpy(&out[1], &pubkey[1], 32);
2093 if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2096 } else if (pubkey[0] == 0x04) {
2097 out[0] = 0x04 | (pubkey[64] & 0x01);
2104 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2106 if (nSize == 0 || nSize == 1)
2108 if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2113 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2119 script[1] = OP_HASH160;
2121 memcpy(&script[3], &in[0], 20);
2122 script[23] = OP_EQUALVERIFY;
2123 script[24] = OP_CHECKSIG;
2127 script[0] = OP_HASH160;
2129 memcpy(&script[2], &in[0], 20);
2130 script[22] = OP_EQUAL;
2137 memcpy(&script[2], &in[0], 32);
2138 script[34] = OP_CHECKSIG;
2142 std::vector<unsigned char> vch(33, 0x00);
2144 memcpy(&vch[1], &in[0], 32);
2146 if (!key.SetPubKey(CPubKey(vch)))
2148 key.SetCompressedPubKey(false); // Decompress public key
2149 CPubKey pubkey = key.GetPubKey();
2152 memcpy(&script[1], &pubkey.Raw()[0], 65);
2153 script[66] = OP_CHECKSIG;