1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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.
8 #include "crypto/ripemd160.h"
9 #include "crypto/sha1.h"
10 #include "crypto/sha2.h"
20 #include <boost/foreach.hpp>
21 #include <boost/tuple/tuple.hpp>
22 #include <boost/tuple/tuple_comparison.hpp>
25 using namespace boost;
27 typedef vector<unsigned char> valtype;
28 static const valtype vchFalse(0);
29 static const valtype vchZero(0);
30 static const valtype vchTrue(1, 1);
31 static const CScriptNum bnZero(0);
32 static const CScriptNum bnOne(1);
33 static const CScriptNum bnFalse(0);
34 static const CScriptNum bnTrue(1);
36 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
38 bool CastToBool(const valtype& vch)
40 for (unsigned int i = 0; i < vch.size(); i++)
44 // Can be negative zero
45 if (i == vch.size()-1 && vch[i] == 0x80)
56 // Script is a stack machine (like Forth) that evaluates a predicate
57 // returning a bool indicating valid or not. There are no loops.
59 #define stacktop(i) (stack.at(stack.size()+(i)))
60 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
61 static inline void popstack(vector<valtype>& stack)
64 throw runtime_error("popstack() : stack empty");
69 const char* GetTxnOutputType(txnouttype t)
73 case TX_NONSTANDARD: return "nonstandard";
74 case TX_PUBKEY: return "pubkey";
75 case TX_PUBKEYHASH: return "pubkeyhash";
76 case TX_SCRIPTHASH: return "scripthash";
77 case TX_MULTISIG: return "multisig";
78 case TX_NULL_DATA: return "nulldata";
84 const char* GetOpName(opcodetype opcode)
89 case OP_0 : return "0";
90 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
91 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
92 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
93 case OP_1NEGATE : return "-1";
94 case OP_RESERVED : return "OP_RESERVED";
95 case OP_1 : return "1";
96 case OP_2 : return "2";
97 case OP_3 : return "3";
98 case OP_4 : return "4";
99 case OP_5 : return "5";
100 case OP_6 : return "6";
101 case OP_7 : return "7";
102 case OP_8 : return "8";
103 case OP_9 : return "9";
104 case OP_10 : return "10";
105 case OP_11 : return "11";
106 case OP_12 : return "12";
107 case OP_13 : return "13";
108 case OP_14 : return "14";
109 case OP_15 : return "15";
110 case OP_16 : return "16";
113 case OP_NOP : return "OP_NOP";
114 case OP_VER : return "OP_VER";
115 case OP_IF : return "OP_IF";
116 case OP_NOTIF : return "OP_NOTIF";
117 case OP_VERIF : return "OP_VERIF";
118 case OP_VERNOTIF : return "OP_VERNOTIF";
119 case OP_ELSE : return "OP_ELSE";
120 case OP_ENDIF : return "OP_ENDIF";
121 case OP_VERIFY : return "OP_VERIFY";
122 case OP_RETURN : return "OP_RETURN";
125 case OP_TOALTSTACK : return "OP_TOALTSTACK";
126 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
127 case OP_2DROP : return "OP_2DROP";
128 case OP_2DUP : return "OP_2DUP";
129 case OP_3DUP : return "OP_3DUP";
130 case OP_2OVER : return "OP_2OVER";
131 case OP_2ROT : return "OP_2ROT";
132 case OP_2SWAP : return "OP_2SWAP";
133 case OP_IFDUP : return "OP_IFDUP";
134 case OP_DEPTH : return "OP_DEPTH";
135 case OP_DROP : return "OP_DROP";
136 case OP_DUP : return "OP_DUP";
137 case OP_NIP : return "OP_NIP";
138 case OP_OVER : return "OP_OVER";
139 case OP_PICK : return "OP_PICK";
140 case OP_ROLL : return "OP_ROLL";
141 case OP_ROT : return "OP_ROT";
142 case OP_SWAP : return "OP_SWAP";
143 case OP_TUCK : return "OP_TUCK";
146 case OP_CAT : return "OP_CAT";
147 case OP_SUBSTR : return "OP_SUBSTR";
148 case OP_LEFT : return "OP_LEFT";
149 case OP_RIGHT : return "OP_RIGHT";
150 case OP_SIZE : return "OP_SIZE";
153 case OP_INVERT : return "OP_INVERT";
154 case OP_AND : return "OP_AND";
155 case OP_OR : return "OP_OR";
156 case OP_XOR : return "OP_XOR";
157 case OP_EQUAL : return "OP_EQUAL";
158 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
159 case OP_RESERVED1 : return "OP_RESERVED1";
160 case OP_RESERVED2 : return "OP_RESERVED2";
163 case OP_1ADD : return "OP_1ADD";
164 case OP_1SUB : return "OP_1SUB";
165 case OP_2MUL : return "OP_2MUL";
166 case OP_2DIV : return "OP_2DIV";
167 case OP_NEGATE : return "OP_NEGATE";
168 case OP_ABS : return "OP_ABS";
169 case OP_NOT : return "OP_NOT";
170 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
171 case OP_ADD : return "OP_ADD";
172 case OP_SUB : return "OP_SUB";
173 case OP_MUL : return "OP_MUL";
174 case OP_DIV : return "OP_DIV";
175 case OP_MOD : return "OP_MOD";
176 case OP_LSHIFT : return "OP_LSHIFT";
177 case OP_RSHIFT : return "OP_RSHIFT";
178 case OP_BOOLAND : return "OP_BOOLAND";
179 case OP_BOOLOR : return "OP_BOOLOR";
180 case OP_NUMEQUAL : return "OP_NUMEQUAL";
181 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
182 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
183 case OP_LESSTHAN : return "OP_LESSTHAN";
184 case OP_GREATERTHAN : return "OP_GREATERTHAN";
185 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
186 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
187 case OP_MIN : return "OP_MIN";
188 case OP_MAX : return "OP_MAX";
189 case OP_WITHIN : return "OP_WITHIN";
192 case OP_RIPEMD160 : return "OP_RIPEMD160";
193 case OP_SHA1 : return "OP_SHA1";
194 case OP_SHA256 : return "OP_SHA256";
195 case OP_HASH160 : return "OP_HASH160";
196 case OP_HASH256 : return "OP_HASH256";
197 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
198 case OP_CHECKSIG : return "OP_CHECKSIG";
199 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
200 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
201 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
204 case OP_NOP1 : return "OP_NOP1";
205 case OP_NOP2 : return "OP_NOP2";
206 case OP_NOP3 : return "OP_NOP3";
207 case OP_NOP4 : return "OP_NOP4";
208 case OP_NOP5 : return "OP_NOP5";
209 case OP_NOP6 : return "OP_NOP6";
210 case OP_NOP7 : return "OP_NOP7";
211 case OP_NOP8 : return "OP_NOP8";
212 case OP_NOP9 : return "OP_NOP9";
213 case OP_NOP10 : return "OP_NOP10";
215 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
218 // The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
219 // as kind of implementation hack, they are *NOT* real opcodes. If found in real
220 // Script, just let the default: case deal with them.
227 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
228 if (!(flags & SCRIPT_VERIFY_STRICTENC))
231 if (vchPubKey.size() < 33)
232 return error("Non-canonical public key: too short");
233 if (vchPubKey[0] == 0x04) {
234 if (vchPubKey.size() != 65)
235 return error("Non-canonical public key: invalid length for uncompressed key");
236 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
237 if (vchPubKey.size() != 33)
238 return error("Non-canonical public key: invalid length for compressed key");
240 return error("Non-canonical public key: compressed nor uncompressed");
245 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
246 if (!(flags & SCRIPT_VERIFY_STRICTENC))
249 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
250 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
251 // Where R and S are not negative (their first byte has its highest bit not set), and not
252 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
253 // in which case a single 0 byte is necessary and even required).
254 if (vchSig.size() < 9)
255 return error("Non-canonical signature: too short");
256 if (vchSig.size() > 73)
257 return error("Non-canonical signature: too long");
258 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
259 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
260 return error("Non-canonical signature: unknown hashtype byte");
261 if (vchSig[0] != 0x30)
262 return error("Non-canonical signature: wrong type");
263 if (vchSig[1] != vchSig.size()-3)
264 return error("Non-canonical signature: wrong length marker");
265 unsigned int nLenR = vchSig[3];
266 if (5 + nLenR >= vchSig.size())
267 return error("Non-canonical signature: S length misplaced");
268 unsigned int nLenS = vchSig[5+nLenR];
269 if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
270 return error("Non-canonical signature: R+S length mismatch");
272 const unsigned char *R = &vchSig[4];
274 return error("Non-canonical signature: R value type mismatch");
276 return error("Non-canonical signature: R length is zero");
278 return error("Non-canonical signature: R value negative");
279 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
280 return error("Non-canonical signature: R value excessively padded");
282 const unsigned char *S = &vchSig[6+nLenR];
284 return error("Non-canonical signature: S value type mismatch");
286 return error("Non-canonical signature: S length is zero");
288 return error("Non-canonical signature: S value negative");
289 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
290 return error("Non-canonical signature: S value excessively padded");
292 if (flags & SCRIPT_VERIFY_LOW_S) {
293 // If the S value is above the order of the curve divided by two, its
294 // complement modulo the order could have been used instead, which is
295 // one byte shorter when encoded correctly.
296 if (!CKey::CheckSignatureElement(S, nLenS, true))
297 return error("Non-canonical signature: S value is unnecessarily high");
303 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
305 CScript::const_iterator pc = script.begin();
306 CScript::const_iterator pend = script.end();
307 CScript::const_iterator pbegincodehash = script.begin();
309 valtype vchPushValue;
311 vector<valtype> altstack;
312 if (script.size() > 10000)
320 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
325 if (!script.GetOp(pc, opcode, vchPushValue))
327 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
330 // Note how OP_RESERVED does not count towards the opcode limit.
331 if (opcode > OP_16 && ++nOpCount > 201)
334 if (opcode == OP_CAT ||
335 opcode == OP_SUBSTR ||
337 opcode == OP_RIGHT ||
338 opcode == OP_INVERT ||
347 opcode == OP_LSHIFT ||
349 return false; // Disabled opcodes.
351 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
352 stack.push_back(vchPushValue);
353 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
378 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
379 stack.push_back(bn.getvch());
388 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
389 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
395 // <expression> if [statements] [else [statements]] endif
399 if (stack.size() < 1)
401 valtype& vch = stacktop(-1);
402 fValue = CastToBool(vch);
403 if (opcode == OP_NOTIF)
407 vfExec.push_back(fValue);
415 vfExec.back() = !vfExec.back();
430 // (false -- false) and return
431 if (stack.size() < 1)
433 bool fValue = CastToBool(stacktop(-1));
453 if (stack.size() < 1)
455 altstack.push_back(stacktop(-1));
460 case OP_FROMALTSTACK:
462 if (altstack.size() < 1)
464 stack.push_back(altstacktop(-1));
472 if (stack.size() < 2)
481 // (x1 x2 -- x1 x2 x1 x2)
482 if (stack.size() < 2)
484 valtype vch1 = stacktop(-2);
485 valtype vch2 = stacktop(-1);
486 stack.push_back(vch1);
487 stack.push_back(vch2);
493 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
494 if (stack.size() < 3)
496 valtype vch1 = stacktop(-3);
497 valtype vch2 = stacktop(-2);
498 valtype vch3 = stacktop(-1);
499 stack.push_back(vch1);
500 stack.push_back(vch2);
501 stack.push_back(vch3);
507 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
508 if (stack.size() < 4)
510 valtype vch1 = stacktop(-4);
511 valtype vch2 = stacktop(-3);
512 stack.push_back(vch1);
513 stack.push_back(vch2);
519 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
520 if (stack.size() < 6)
522 valtype vch1 = stacktop(-6);
523 valtype vch2 = stacktop(-5);
524 stack.erase(stack.end()-6, stack.end()-4);
525 stack.push_back(vch1);
526 stack.push_back(vch2);
532 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
533 if (stack.size() < 4)
535 swap(stacktop(-4), stacktop(-2));
536 swap(stacktop(-3), stacktop(-1));
543 if (stack.size() < 1)
545 valtype vch = stacktop(-1);
547 stack.push_back(vch);
554 CScriptNum bn(stack.size());
555 stack.push_back(bn.getvch());
562 if (stack.size() < 1)
571 if (stack.size() < 1)
573 valtype vch = stacktop(-1);
574 stack.push_back(vch);
581 if (stack.size() < 2)
583 stack.erase(stack.end() - 2);
589 // (x1 x2 -- x1 x2 x1)
590 if (stack.size() < 2)
592 valtype vch = stacktop(-2);
593 stack.push_back(vch);
600 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
601 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
602 if (stack.size() < 2)
604 int n = CScriptNum(stacktop(-1)).getint();
606 if (n < 0 || n >= (int)stack.size())
608 valtype vch = stacktop(-n-1);
609 if (opcode == OP_ROLL)
610 stack.erase(stack.end()-n-1);
611 stack.push_back(vch);
617 // (x1 x2 x3 -- x2 x3 x1)
618 // x2 x1 x3 after first swap
619 // x2 x3 x1 after second swap
620 if (stack.size() < 3)
622 swap(stacktop(-3), stacktop(-2));
623 swap(stacktop(-2), stacktop(-1));
630 if (stack.size() < 2)
632 swap(stacktop(-2), stacktop(-1));
638 // (x1 x2 -- x2 x1 x2)
639 if (stack.size() < 2)
641 valtype vch = stacktop(-1);
642 stack.insert(stack.end()-2, vch);
650 if (stack.size() < 1)
652 CScriptNum bn(stacktop(-1).size());
653 stack.push_back(bn.getvch());
663 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
666 if (stack.size() < 2)
668 valtype& vch1 = stacktop(-2);
669 valtype& vch2 = stacktop(-1);
670 bool fEqual = (vch1 == vch2);
671 // OP_NOTEQUAL is disabled because it would be too easy to say
672 // something like n != 1 and have some wiseguy pass in 1 with extra
673 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
674 //if (opcode == OP_NOTEQUAL)
678 stack.push_back(fEqual ? vchTrue : vchFalse);
679 if (opcode == OP_EQUALVERIFY)
701 if (stack.size() < 1)
703 CScriptNum bn(stacktop(-1));
706 case OP_1ADD: bn += bnOne; break;
707 case OP_1SUB: bn -= bnOne; break;
708 case OP_NEGATE: bn = -bn; break;
709 case OP_ABS: if (bn < bnZero) bn = -bn; break;
710 case OP_NOT: bn = (bn == bnZero); break;
711 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
712 default: assert(!"invalid opcode"); break;
715 stack.push_back(bn.getvch());
724 case OP_NUMEQUALVERIFY:
728 case OP_LESSTHANOREQUAL:
729 case OP_GREATERTHANOREQUAL:
734 if (stack.size() < 2)
736 CScriptNum bn1(stacktop(-2));
737 CScriptNum bn2(stacktop(-1));
749 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
750 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
751 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
752 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
753 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
754 case OP_LESSTHAN: bn = (bn1 < bn2); break;
755 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
756 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
757 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
758 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
759 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
760 default: assert(!"invalid opcode"); break;
764 stack.push_back(bn.getvch());
766 if (opcode == OP_NUMEQUALVERIFY)
768 if (CastToBool(stacktop(-1)))
778 // (x min max -- out)
779 if (stack.size() < 3)
781 CScriptNum bn1(stacktop(-3));
782 CScriptNum bn2(stacktop(-2));
783 CScriptNum bn3(stacktop(-1));
784 bool fValue = (bn2 <= bn1 && bn1 < bn3);
788 stack.push_back(fValue ? vchTrue : vchFalse);
803 if (stack.size() < 1)
805 valtype& vch = stacktop(-1);
806 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
807 if (opcode == OP_RIPEMD160)
808 CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
809 else if (opcode == OP_SHA1)
810 CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
811 else if (opcode == OP_SHA256)
812 CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
813 else if (opcode == OP_HASH160)
814 CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
815 else if (opcode == OP_HASH256)
816 CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
818 stack.push_back(vchHash);
822 case OP_CODESEPARATOR:
824 // Hash starts after the code separator
830 case OP_CHECKSIGVERIFY:
832 // (sig pubkey -- bool)
833 if (stack.size() < 2)
836 valtype& vchSig = stacktop(-2);
837 valtype& vchPubKey = stacktop(-1);
839 // Subset of script starting at the most recent codeseparator
840 CScript scriptCode(pbegincodehash, pend);
842 // Drop the signature, since there's no way for a signature to sign itself
843 scriptCode.FindAndDelete(CScript(vchSig));
845 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
846 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
850 stack.push_back(fSuccess ? vchTrue : vchFalse);
851 if (opcode == OP_CHECKSIGVERIFY)
861 case OP_CHECKMULTISIG:
862 case OP_CHECKMULTISIGVERIFY:
864 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
867 if ((int)stack.size() < i)
870 int nKeysCount = CScriptNum(stacktop(-i)).getint();
871 if (nKeysCount < 0 || nKeysCount > 20)
873 nOpCount += nKeysCount;
878 if ((int)stack.size() < i)
881 int nSigsCount = CScriptNum(stacktop(-i)).getint();
882 if (nSigsCount < 0 || nSigsCount > nKeysCount)
886 if ((int)stack.size() < i)
889 // Subset of script starting at the most recent codeseparator
890 CScript scriptCode(pbegincodehash, pend);
892 // Drop the signatures, since there's no way for a signature to sign itself
893 for (int k = 0; k < nSigsCount; k++)
895 valtype& vchSig = stacktop(-isig-k);
896 scriptCode.FindAndDelete(CScript(vchSig));
899 bool fSuccess = true;
900 while (fSuccess && nSigsCount > 0)
902 valtype& vchSig = stacktop(-isig);
903 valtype& vchPubKey = stacktop(-ikey);
906 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
907 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
916 // If there are more signatures left than keys left,
917 // then too many signatures have failed
918 if (nSigsCount > nKeysCount)
922 // Clean up stack of actual arguments
926 // A bug causes CHECKMULTISIG to consume one extra argument
927 // whose contents were not checked in any way.
929 // Unfortunately this is a potential source of mutability,
930 // so optionally verify it is exactly equal to zero prior
931 // to removing it from the stack.
932 if (stack.size() < 1)
934 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
935 return error("CHECKMULTISIG dummy argument not null");
938 stack.push_back(fSuccess ? vchTrue : vchFalse);
940 if (opcode == OP_CHECKMULTISIGVERIFY)
955 if (stack.size() + altstack.size() > 1000)
979 /** Wrapper that serializes like CTransaction, but with the modifications
980 * required for the signature hash done in-place
982 class CTransactionSignatureSerializer {
984 const CTransaction &txTo; // reference to the spending transaction (the one being serialized)
985 const CScript &scriptCode; // output script being consumed
986 const unsigned int nIn; // input index of txTo being signed
987 const bool fAnyoneCanPay; // whether the hashtype has the SIGHASH_ANYONECANPAY flag set
988 const bool fHashSingle; // whether the hashtype is SIGHASH_SINGLE
989 const bool fHashNone; // whether the hashtype is SIGHASH_NONE
992 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
993 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
994 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
995 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
996 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
998 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
1000 void SerializeScriptCode(S &s, int nType, int nVersion) const {
1001 CScript::const_iterator it = scriptCode.begin();
1002 CScript::const_iterator itBegin = it;
1004 unsigned int nCodeSeparators = 0;
1005 while (scriptCode.GetOp(it, opcode)) {
1006 if (opcode == OP_CODESEPARATOR)
1009 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1011 while (scriptCode.GetOp(it, opcode)) {
1012 if (opcode == OP_CODESEPARATOR) {
1013 s.write((char*)&itBegin[0], it-itBegin-1);
1017 s.write((char*)&itBegin[0], it-itBegin);
1020 /** Serialize an input of txTo */
1021 template<typename S>
1022 void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
1023 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1026 // Serialize the prevout
1027 ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
1028 // Serialize the script
1030 // Blank out other inputs' signatures
1031 ::Serialize(s, CScript(), nType, nVersion);
1033 SerializeScriptCode(s, nType, nVersion);
1034 // Serialize the nSequence
1035 if (nInput != nIn && (fHashSingle || fHashNone))
1036 // let the others update at will
1037 ::Serialize(s, (int)0, nType, nVersion);
1039 ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
1042 /** Serialize an output of txTo */
1043 template<typename S>
1044 void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
1045 if (fHashSingle && nOutput != nIn)
1046 // Do not lock-in the txout payee at other indices as txin
1047 ::Serialize(s, CTxOut(), nType, nVersion);
1049 ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
1052 /** Serialize txTo */
1053 template<typename S>
1054 void Serialize(S &s, int nType, int nVersion) const {
1055 // Serialize nVersion
1056 ::Serialize(s, txTo.nVersion, nType, nVersion);
1058 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1059 ::WriteCompactSize(s, nInputs);
1060 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1061 SerializeInput(s, nInput, nType, nVersion);
1063 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1064 ::WriteCompactSize(s, nOutputs);
1065 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1066 SerializeOutput(s, nOutput, nType, nVersion);
1067 // Serialie nLockTime
1068 ::Serialize(s, txTo.nLockTime, nType, nVersion);
1074 uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1076 if (nIn >= txTo.vin.size()) {
1077 LogPrintf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1081 // Check for invalid use of SIGHASH_SINGLE
1082 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1083 if (nIn >= txTo.vout.size()) {
1084 LogPrintf("ERROR: SignatureHash() : nOut=%d out of range\n", nIn);
1089 // Wrapper to serialize only the necessary parts of the transaction being signed
1090 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1092 // Serialize and hash
1093 CHashWriter ss(SER_GETHASH, 0);
1094 ss << txTmp << nHashType;
1095 return ss.GetHash();
1098 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1099 // twice for every transaction (once when accepted into memory pool, and
1100 // again when accepted into the block chain)
1101 class CSignatureCache
1104 // sigdata_type is (signature hash, signature, public key):
1105 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
1106 std::set< sigdata_type> setValid;
1107 boost::shared_mutex cs_sigcache;
1111 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1113 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1115 sigdata_type k(hash, vchSig, pubKey);
1116 std::set<sigdata_type>::iterator mi = setValid.find(k);
1117 if (mi != setValid.end())
1122 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1124 // DoS prevention: limit cache size to less than 10MB
1125 // (~200 bytes per cache entry times 50,000 entries)
1126 // Since there are a maximum of 20,000 signature operations per block
1127 // 50,000 is a reasonable default.
1128 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1129 if (nMaxCacheSize <= 0) return;
1131 boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
1133 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1135 // Evict a random entry. Random because that helps
1136 // foil would-be DoS attackers who might try to pre-generate
1137 // and re-use a set of valid signatures just-slightly-greater
1138 // than our cache size.
1139 uint256 randomHash = GetRandHash();
1140 std::vector<unsigned char> unused;
1141 std::set<sigdata_type>::iterator it =
1142 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1143 if (it == setValid.end())
1144 it = setValid.begin();
1145 setValid.erase(*it);
1148 sigdata_type k(hash, vchSig, pubKey);
1153 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1154 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1156 static CSignatureCache signatureCache;
1158 CPubKey pubkey(vchPubKey);
1159 if (!pubkey.IsValid())
1162 // Hash type is one byte tacked on to the end of the signature
1166 nHashType = vchSig.back();
1167 else if (nHashType != vchSig.back())
1171 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1173 if (signatureCache.Get(sighash, vchSig, pubkey))
1176 if (!pubkey.Verify(sighash, vchSig))
1179 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1180 signatureCache.Set(sighash, vchSig, pubkey);
1194 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1196 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1199 static multimap<txnouttype, CScript> mTemplates;
1200 if (mTemplates.empty())
1202 // Standard tx, sender provides pubkey, receiver adds signature
1203 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1205 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1206 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1208 // Sender provides N pubkeys, receivers provides M signatures
1209 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1211 // Empty, provably prunable, data-carrying output
1212 if (GetBoolArg("-datacarrier", true))
1213 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1214 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
1217 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1218 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1219 if (scriptPubKey.IsPayToScriptHash())
1221 typeRet = TX_SCRIPTHASH;
1222 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1223 vSolutionsRet.push_back(hashBytes);
1228 const CScript& script1 = scriptPubKey;
1229 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1231 const CScript& script2 = tplate.second;
1232 vSolutionsRet.clear();
1234 opcodetype opcode1, opcode2;
1235 vector<unsigned char> vch1, vch2;
1238 CScript::const_iterator pc1 = script1.begin();
1239 CScript::const_iterator pc2 = script2.begin();
1242 if (pc1 == script1.end() && pc2 == script2.end())
1245 typeRet = tplate.first;
1246 if (typeRet == TX_MULTISIG)
1248 // Additional checks for TX_MULTISIG:
1249 unsigned char m = vSolutionsRet.front()[0];
1250 unsigned char n = vSolutionsRet.back()[0];
1251 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1256 if (!script1.GetOp(pc1, opcode1, vch1))
1258 if (!script2.GetOp(pc2, opcode2, vch2))
1261 // Template matching opcodes:
1262 if (opcode2 == OP_PUBKEYS)
1264 while (vch1.size() >= 33 && vch1.size() <= 65)
1266 vSolutionsRet.push_back(vch1);
1267 if (!script1.GetOp(pc1, opcode1, vch1))
1270 if (!script2.GetOp(pc2, opcode2, vch2))
1272 // Normal situation is to fall through
1273 // to other if/else statements
1276 if (opcode2 == OP_PUBKEY)
1278 if (vch1.size() < 33 || vch1.size() > 65)
1280 vSolutionsRet.push_back(vch1);
1282 else if (opcode2 == OP_PUBKEYHASH)
1284 if (vch1.size() != sizeof(uint160))
1286 vSolutionsRet.push_back(vch1);
1288 else if (opcode2 == OP_SMALLINTEGER)
1289 { // Single-byte small integer pushed onto vSolutions
1290 if (opcode1 == OP_0 ||
1291 (opcode1 >= OP_1 && opcode1 <= OP_16))
1293 char n = (char)CScript::DecodeOP_N(opcode1);
1294 vSolutionsRet.push_back(valtype(1, n));
1299 else if (opcode2 == OP_SMALLDATA)
1301 // small pushdata, <= MAX_OP_RETURN_RELAY bytes
1302 if (vch1.size() > MAX_OP_RETURN_RELAY)
1305 else if (opcode1 != opcode2 || vch1 != vch2)
1307 // Others must match exactly
1313 vSolutionsRet.clear();
1314 typeRet = TX_NONSTANDARD;
1319 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1322 if (!keystore.GetKey(address, key))
1325 vector<unsigned char> vchSig;
1326 if (!key.Sign(hash, vchSig))
1328 vchSig.push_back((unsigned char)nHashType);
1329 scriptSigRet << vchSig;
1334 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1337 int nRequired = multisigdata.front()[0];
1338 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1340 const valtype& pubkey = multisigdata[i];
1341 CKeyID keyID = CPubKey(pubkey).GetID();
1342 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1345 return nSigned==nRequired;
1349 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1350 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1351 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1352 // Returns false if scriptPubKey could not be completely satisfied.
1354 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1355 CScript& scriptSigRet, txnouttype& whichTypeRet)
1357 scriptSigRet.clear();
1359 vector<valtype> vSolutions;
1360 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1364 switch (whichTypeRet)
1366 case TX_NONSTANDARD:
1370 keyID = CPubKey(vSolutions[0]).GetID();
1371 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1373 keyID = CKeyID(uint160(vSolutions[0]));
1374 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1379 keystore.GetPubKey(keyID, vch);
1380 scriptSigRet << vch;
1384 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1387 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1388 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1393 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1397 case TX_NONSTANDARD:
1405 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1407 return vSolutions[0][0] + 1;
1409 return 1; // doesn't include args needed by the script
1414 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1416 vector<valtype> vSolutions;
1417 if (!Solver(scriptPubKey, whichType, vSolutions))
1420 if (whichType == TX_MULTISIG)
1422 unsigned char m = vSolutions.front()[0];
1423 unsigned char n = vSolutions.back()[0];
1424 // Support up to x-of-3 multisig txns as standard
1431 return whichType != TX_NONSTANDARD;
1435 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1437 unsigned int nResult = 0;
1438 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1440 CKeyID keyID = CPubKey(pubkey).GetID();
1441 if (keystore.HaveKey(keyID))
1447 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1450 script.SetDestination(dest);
1451 return IsMine(keystore, script);
1454 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1456 vector<valtype> vSolutions;
1457 txnouttype whichType;
1458 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1459 if (keystore.HaveWatchOnly(scriptPubKey))
1460 return ISMINE_WATCH_ONLY;
1467 case TX_NONSTANDARD:
1471 keyID = CPubKey(vSolutions[0]).GetID();
1472 if (keystore.HaveKey(keyID))
1473 return ISMINE_SPENDABLE;
1476 keyID = CKeyID(uint160(vSolutions[0]));
1477 if (keystore.HaveKey(keyID))
1478 return ISMINE_SPENDABLE;
1482 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1484 if (keystore.GetCScript(scriptID, subscript)) {
1485 isminetype ret = IsMine(keystore, subscript);
1486 if (ret == ISMINE_SPENDABLE)
1493 // Only consider transactions "mine" if we own ALL the
1494 // keys involved. multi-signature transactions that are
1495 // partially owned (somebody else has a key that can spend
1496 // them) enable spend-out-from-under-you attacks, especially
1497 // in shared-wallet situations.
1498 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1499 if (HaveKeys(keys, keystore) == keys.size())
1500 return ISMINE_SPENDABLE;
1505 if (keystore.HaveWatchOnly(scriptPubKey))
1506 return ISMINE_WATCH_ONLY;
1510 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1512 vector<valtype> vSolutions;
1513 txnouttype whichType;
1514 if (!Solver(scriptPubKey, whichType, vSolutions))
1517 if (whichType == TX_PUBKEY)
1519 addressRet = CPubKey(vSolutions[0]).GetID();
1522 else if (whichType == TX_PUBKEYHASH)
1524 addressRet = CKeyID(uint160(vSolutions[0]));
1527 else if (whichType == TX_SCRIPTHASH)
1529 addressRet = CScriptID(uint160(vSolutions[0]));
1532 // Multisig txns have more than one address...
1536 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1539 typeRet = TX_NONSTANDARD;
1540 vector<valtype> vSolutions;
1541 if (!Solver(scriptPubKey, typeRet, vSolutions))
1543 if (typeRet == TX_NULL_DATA){
1544 // This is data, not addresses
1548 if (typeRet == TX_MULTISIG)
1550 nRequiredRet = vSolutions.front()[0];
1551 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1553 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1554 addressRet.push_back(address);
1560 CTxDestination address;
1561 if (!ExtractDestination(scriptPubKey, address))
1563 addressRet.push_back(address);
1569 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1571 const CKeyStore &keystore;
1572 std::vector<CKeyID> &vKeys;
1575 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1577 void Process(const CScript &script) {
1579 std::vector<CTxDestination> vDest;
1581 if (ExtractDestinations(script, type, vDest, nRequired)) {
1582 BOOST_FOREACH(const CTxDestination &dest, vDest)
1583 boost::apply_visitor(*this, dest);
1587 void operator()(const CKeyID &keyId) {
1588 if (keystore.HaveKey(keyId))
1589 vKeys.push_back(keyId);
1592 void operator()(const CScriptID &scriptId) {
1594 if (keystore.GetCScript(scriptId, script))
1598 void operator()(const CNoDestination &none) {}
1601 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1602 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1605 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1606 unsigned int flags, int nHashType)
1608 vector<vector<unsigned char> > stack, stackCopy;
1609 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1611 if (flags & SCRIPT_VERIFY_P2SH)
1613 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1618 if (CastToBool(stack.back()) == false)
1621 // Additional validation for spend-to-script-hash transactions:
1622 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1624 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1625 return false; // or validation fails
1627 // stackCopy cannot be empty here, because if it was the
1628 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1629 // an empty stack and the EvalScript above would return false.
1630 assert(!stackCopy.empty());
1632 const valtype& pubKeySerialized = stackCopy.back();
1633 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1634 popstack(stackCopy);
1636 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1638 if (stackCopy.empty())
1640 return CastToBool(stackCopy.back());
1647 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1649 assert(nIn < txTo.vin.size());
1650 CTxIn& txin = txTo.vin[nIn];
1652 // Leave out the signature from the hash, since a signature can't sign itself.
1653 // The checksig op will also drop the signatures from its hash.
1654 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1656 txnouttype whichType;
1657 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1660 if (whichType == TX_SCRIPTHASH)
1662 // Solver returns the subscript that need to be evaluated;
1663 // the final scriptSig is the signatures from that
1664 // and then the serialized subscript:
1665 CScript subscript = txin.scriptSig;
1667 // Recompute txn hash using subscript in place of scriptPubKey:
1668 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1672 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1673 // Append serialized subscript whether or not it is completely signed:
1674 txin.scriptSig << static_cast<valtype>(subscript);
1675 if (!fSolved) return false;
1679 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0);
1682 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1684 assert(nIn < txTo.vin.size());
1685 CTxIn& txin = txTo.vin[nIn];
1686 assert(txin.prevout.n < txFrom.vout.size());
1687 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1689 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1692 static CScript PushAll(const vector<valtype>& values)
1695 BOOST_FOREACH(const valtype& v, values)
1700 static CScript CombineMultisig(CScript scriptPubKey, const CMutableTransaction& txTo, unsigned int nIn,
1701 const vector<valtype>& vSolutions,
1702 vector<valtype>& sigs1, vector<valtype>& sigs2)
1704 // Combine all the signatures we've got:
1705 set<valtype> allsigs;
1706 BOOST_FOREACH(const valtype& v, sigs1)
1711 BOOST_FOREACH(const valtype& v, sigs2)
1717 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1718 assert(vSolutions.size() > 1);
1719 unsigned int nSigsRequired = vSolutions.front()[0];
1720 unsigned int nPubKeys = vSolutions.size()-2;
1721 map<valtype, valtype> sigs;
1722 BOOST_FOREACH(const valtype& sig, allsigs)
1724 for (unsigned int i = 0; i < nPubKeys; i++)
1726 const valtype& pubkey = vSolutions[i+1];
1727 if (sigs.count(pubkey))
1728 continue; // Already got a sig for this pubkey
1730 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1737 // Now build a merged CScript:
1738 unsigned int nSigsHave = 0;
1739 CScript result; result << OP_0; // pop-one-too-many workaround
1740 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1742 if (sigs.count(vSolutions[i+1]))
1744 result << sigs[vSolutions[i+1]];
1748 // Fill any missing with OP_0:
1749 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1755 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1756 const txnouttype txType, const vector<valtype>& vSolutions,
1757 vector<valtype>& sigs1, vector<valtype>& sigs2)
1761 case TX_NONSTANDARD:
1763 // Don't know anything about this, assume bigger one is correct:
1764 if (sigs1.size() >= sigs2.size())
1765 return PushAll(sigs1);
1766 return PushAll(sigs2);
1769 // Signatures are bigger than placeholders or empty scripts:
1770 if (sigs1.empty() || sigs1[0].empty())
1771 return PushAll(sigs2);
1772 return PushAll(sigs1);
1774 if (sigs1.empty() || sigs1.back().empty())
1775 return PushAll(sigs2);
1776 else if (sigs2.empty() || sigs2.back().empty())
1777 return PushAll(sigs1);
1780 // Recur to combine:
1781 valtype spk = sigs1.back();
1782 CScript pubKey2(spk.begin(), spk.end());
1785 vector<vector<unsigned char> > vSolutions2;
1786 Solver(pubKey2, txType2, vSolutions2);
1789 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1794 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1800 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1801 const CScript& scriptSig1, const CScript& scriptSig2)
1804 vector<vector<unsigned char> > vSolutions;
1805 Solver(scriptPubKey, txType, vSolutions);
1807 vector<valtype> stack1;
1808 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1809 vector<valtype> stack2;
1810 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1812 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1815 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1818 const_iterator pc = begin();
1819 opcodetype lastOpcode = OP_INVALIDOPCODE;
1823 if (!GetOp(pc, opcode))
1825 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1827 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1829 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1830 n += DecodeOP_N(lastOpcode);
1834 lastOpcode = opcode;
1839 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1841 if (!IsPayToScriptHash())
1842 return GetSigOpCount(true);
1844 // This is a pay-to-script-hash scriptPubKey;
1845 // get the last item that the scriptSig
1846 // pushes onto the stack:
1847 const_iterator pc = scriptSig.begin();
1848 vector<unsigned char> data;
1849 while (pc < scriptSig.end())
1852 if (!scriptSig.GetOp(pc, opcode, data))
1858 /// ... and return its opcount:
1859 CScript subscript(data.begin(), data.end());
1860 return subscript.GetSigOpCount(true);
1863 bool CScript::IsPayToScriptHash() const
1865 // Extra-fast test for pay-to-script-hash CScripts:
1866 return (this->size() == 23 &&
1867 this->at(0) == OP_HASH160 &&
1868 this->at(1) == 0x14 &&
1869 this->at(22) == OP_EQUAL);
1872 bool CScript::IsPushOnly() const
1874 const_iterator pc = begin();
1878 if (!GetOp(pc, opcode))
1880 // Note that IsPushOnly() *does* consider OP_RESERVED to be a
1881 // push-type opcode, however execution of OP_RESERVED fails, so
1882 // it's not relevant to P2SH as the scriptSig would fail prior to
1883 // the P2SH special validation code being executed.
1890 bool CScript::HasCanonicalPushes() const
1892 const_iterator pc = begin();
1896 std::vector<unsigned char> data;
1897 if (!GetOp(pc, opcode, data))
1901 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1902 // Could have used an OP_n code, rather than a 1-byte push.
1904 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1905 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1907 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1908 // Could have used an OP_PUSHDATA1.
1910 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1911 // Could have used an OP_PUSHDATA2.
1917 class CScriptVisitor : public boost::static_visitor<bool>
1922 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1924 bool operator()(const CNoDestination &dest) const {
1929 bool operator()(const CKeyID &keyID) const {
1931 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1935 bool operator()(const CScriptID &scriptID) const {
1937 *script << OP_HASH160 << scriptID << OP_EQUAL;
1942 void CScript::SetDestination(const CTxDestination& dest)
1944 boost::apply_visitor(CScriptVisitor(this), dest);
1947 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
1951 *this << EncodeOP_N(nRequired);
1952 BOOST_FOREACH(const CPubKey& key, keys)
1954 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1957 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
1959 if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
1960 && script[2] == 20 && script[23] == OP_EQUALVERIFY
1961 && script[24] == OP_CHECKSIG) {
1962 memcpy(&hash, &script[3], 20);
1968 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
1970 if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
1971 && script[22] == OP_EQUAL) {
1972 memcpy(&hash, &script[2], 20);
1978 bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
1980 if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
1981 && (script[1] == 0x02 || script[1] == 0x03)) {
1982 pubkey.Set(&script[1], &script[34]);
1985 if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
1986 && script[1] == 0x04) {
1987 pubkey.Set(&script[1], &script[66]);
1988 return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
1993 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
1996 if (IsToKeyID(keyID)) {
1999 memcpy(&out[1], &keyID, 20);
2003 if (IsToScriptID(scriptID)) {
2006 memcpy(&out[1], &scriptID, 20);
2010 if (IsToPubKey(pubkey)) {
2012 memcpy(&out[1], &pubkey[1], 32);
2013 if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2016 } else if (pubkey[0] == 0x04) {
2017 out[0] = 0x04 | (pubkey[64] & 0x01);
2024 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2026 if (nSize == 0 || nSize == 1)
2028 if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2033 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2039 script[1] = OP_HASH160;
2041 memcpy(&script[3], &in[0], 20);
2042 script[23] = OP_EQUALVERIFY;
2043 script[24] = OP_CHECKSIG;
2047 script[0] = OP_HASH160;
2049 memcpy(&script[2], &in[0], 20);
2050 script[22] = OP_EQUAL;
2057 memcpy(&script[2], &in[0], 32);
2058 script[34] = OP_CHECKSIG;
2062 unsigned char vch[33] = {};
2064 memcpy(&vch[1], &in[0], 32);
2065 CPubKey pubkey(&vch[0], &vch[33]);
2066 if (!pubkey.Decompress())
2068 assert(pubkey.size() == 65);
2071 memcpy(&script[1], pubkey.begin(), 65);
2072 script[66] = OP_CHECKSIG;