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.
12 #include "crypto/sha1.h"
13 #include "crypto/sha2.h"
14 #include "crypto/ripemd160.h"
19 #include <boost/foreach.hpp>
20 #include <boost/tuple/tuple.hpp>
21 #include <boost/tuple/tuple_comparison.hpp>
24 using namespace boost;
26 typedef vector<unsigned char> valtype;
27 static const valtype vchFalse(0);
28 static const valtype vchZero(0);
29 static const valtype vchTrue(1, 1);
30 static const CScriptNum bnZero(0);
31 static const CScriptNum bnOne(1);
32 static const CScriptNum bnFalse(0);
33 static const CScriptNum bnTrue(1);
35 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
37 bool CastToBool(const valtype& vch)
39 for (unsigned int i = 0; i < vch.size(); i++)
43 // Can be negative zero
44 if (i == vch.size()-1 && vch[i] == 0x80)
55 // Script is a stack machine (like Forth) that evaluates a predicate
56 // returning a bool indicating valid or not. There are no loops.
58 #define stacktop(i) (stack.at(stack.size()+(i)))
59 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
60 static inline void popstack(vector<valtype>& stack)
63 throw runtime_error("popstack() : stack empty");
68 const char* GetTxnOutputType(txnouttype t)
72 case TX_NONSTANDARD: return "nonstandard";
73 case TX_PUBKEY: return "pubkey";
74 case TX_PUBKEYHASH: return "pubkeyhash";
75 case TX_SCRIPTHASH: return "scripthash";
76 case TX_MULTISIG: return "multisig";
77 case TX_NULL_DATA: return "nulldata";
83 const char* GetOpName(opcodetype opcode)
88 case OP_0 : return "0";
89 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
90 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
91 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
92 case OP_1NEGATE : return "-1";
93 case OP_RESERVED : return "OP_RESERVED";
94 case OP_1 : return "1";
95 case OP_2 : return "2";
96 case OP_3 : return "3";
97 case OP_4 : return "4";
98 case OP_5 : return "5";
99 case OP_6 : return "6";
100 case OP_7 : return "7";
101 case OP_8 : return "8";
102 case OP_9 : return "9";
103 case OP_10 : return "10";
104 case OP_11 : return "11";
105 case OP_12 : return "12";
106 case OP_13 : return "13";
107 case OP_14 : return "14";
108 case OP_15 : return "15";
109 case OP_16 : return "16";
112 case OP_NOP : return "OP_NOP";
113 case OP_VER : return "OP_VER";
114 case OP_IF : return "OP_IF";
115 case OP_NOTIF : return "OP_NOTIF";
116 case OP_VERIF : return "OP_VERIF";
117 case OP_VERNOTIF : return "OP_VERNOTIF";
118 case OP_ELSE : return "OP_ELSE";
119 case OP_ENDIF : return "OP_ENDIF";
120 case OP_VERIFY : return "OP_VERIFY";
121 case OP_RETURN : return "OP_RETURN";
124 case OP_TOALTSTACK : return "OP_TOALTSTACK";
125 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
126 case OP_2DROP : return "OP_2DROP";
127 case OP_2DUP : return "OP_2DUP";
128 case OP_3DUP : return "OP_3DUP";
129 case OP_2OVER : return "OP_2OVER";
130 case OP_2ROT : return "OP_2ROT";
131 case OP_2SWAP : return "OP_2SWAP";
132 case OP_IFDUP : return "OP_IFDUP";
133 case OP_DEPTH : return "OP_DEPTH";
134 case OP_DROP : return "OP_DROP";
135 case OP_DUP : return "OP_DUP";
136 case OP_NIP : return "OP_NIP";
137 case OP_OVER : return "OP_OVER";
138 case OP_PICK : return "OP_PICK";
139 case OP_ROLL : return "OP_ROLL";
140 case OP_ROT : return "OP_ROT";
141 case OP_SWAP : return "OP_SWAP";
142 case OP_TUCK : return "OP_TUCK";
145 case OP_CAT : return "OP_CAT";
146 case OP_SUBSTR : return "OP_SUBSTR";
147 case OP_LEFT : return "OP_LEFT";
148 case OP_RIGHT : return "OP_RIGHT";
149 case OP_SIZE : return "OP_SIZE";
152 case OP_INVERT : return "OP_INVERT";
153 case OP_AND : return "OP_AND";
154 case OP_OR : return "OP_OR";
155 case OP_XOR : return "OP_XOR";
156 case OP_EQUAL : return "OP_EQUAL";
157 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
158 case OP_RESERVED1 : return "OP_RESERVED1";
159 case OP_RESERVED2 : return "OP_RESERVED2";
162 case OP_1ADD : return "OP_1ADD";
163 case OP_1SUB : return "OP_1SUB";
164 case OP_2MUL : return "OP_2MUL";
165 case OP_2DIV : return "OP_2DIV";
166 case OP_NEGATE : return "OP_NEGATE";
167 case OP_ABS : return "OP_ABS";
168 case OP_NOT : return "OP_NOT";
169 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
170 case OP_ADD : return "OP_ADD";
171 case OP_SUB : return "OP_SUB";
172 case OP_MUL : return "OP_MUL";
173 case OP_DIV : return "OP_DIV";
174 case OP_MOD : return "OP_MOD";
175 case OP_LSHIFT : return "OP_LSHIFT";
176 case OP_RSHIFT : return "OP_RSHIFT";
177 case OP_BOOLAND : return "OP_BOOLAND";
178 case OP_BOOLOR : return "OP_BOOLOR";
179 case OP_NUMEQUAL : return "OP_NUMEQUAL";
180 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
181 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
182 case OP_LESSTHAN : return "OP_LESSTHAN";
183 case OP_GREATERTHAN : return "OP_GREATERTHAN";
184 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
185 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
186 case OP_MIN : return "OP_MIN";
187 case OP_MAX : return "OP_MAX";
188 case OP_WITHIN : return "OP_WITHIN";
191 case OP_RIPEMD160 : return "OP_RIPEMD160";
192 case OP_SHA1 : return "OP_SHA1";
193 case OP_SHA256 : return "OP_SHA256";
194 case OP_HASH160 : return "OP_HASH160";
195 case OP_HASH256 : return "OP_HASH256";
196 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
197 case OP_CHECKSIG : return "OP_CHECKSIG";
198 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
199 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
200 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
203 case OP_NOP1 : return "OP_NOP1";
204 case OP_NOP2 : return "OP_NOP2";
205 case OP_NOP3 : return "OP_NOP3";
206 case OP_NOP4 : return "OP_NOP4";
207 case OP_NOP5 : return "OP_NOP5";
208 case OP_NOP6 : return "OP_NOP6";
209 case OP_NOP7 : return "OP_NOP7";
210 case OP_NOP8 : return "OP_NOP8";
211 case OP_NOP9 : return "OP_NOP9";
212 case OP_NOP10 : return "OP_NOP10";
214 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
217 // The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
218 // as kind of implementation hack, they are *NOT* real opcodes. If found in real
219 // Script, just let the default: case deal with them.
226 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
227 if (!(flags & SCRIPT_VERIFY_STRICTENC))
230 if (vchPubKey.size() < 33)
231 return error("Non-canonical public key: too short");
232 if (vchPubKey[0] == 0x04) {
233 if (vchPubKey.size() != 65)
234 return error("Non-canonical public key: invalid length for uncompressed key");
235 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
236 if (vchPubKey.size() != 33)
237 return error("Non-canonical public key: invalid length for compressed key");
239 return error("Non-canonical public key: compressed nor uncompressed");
244 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
245 if (!(flags & SCRIPT_VERIFY_STRICTENC))
248 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
249 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
250 // Where R and S are not negative (their first byte has its highest bit not set), and not
251 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
252 // in which case a single 0 byte is necessary and even required).
253 if (vchSig.size() < 9)
254 return error("Non-canonical signature: too short");
255 if (vchSig.size() > 73)
256 return error("Non-canonical signature: too long");
257 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
258 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
259 return error("Non-canonical signature: unknown hashtype byte");
260 if (vchSig[0] != 0x30)
261 return error("Non-canonical signature: wrong type");
262 if (vchSig[1] != vchSig.size()-3)
263 return error("Non-canonical signature: wrong length marker");
264 unsigned int nLenR = vchSig[3];
265 if (5 + nLenR >= vchSig.size())
266 return error("Non-canonical signature: S length misplaced");
267 unsigned int nLenS = vchSig[5+nLenR];
268 if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
269 return error("Non-canonical signature: R+S length mismatch");
271 const unsigned char *R = &vchSig[4];
273 return error("Non-canonical signature: R value type mismatch");
275 return error("Non-canonical signature: R length is zero");
277 return error("Non-canonical signature: R value negative");
278 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
279 return error("Non-canonical signature: R value excessively padded");
281 const unsigned char *S = &vchSig[6+nLenR];
283 return error("Non-canonical signature: S value type mismatch");
285 return error("Non-canonical signature: S length is zero");
287 return error("Non-canonical signature: S value negative");
288 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
289 return error("Non-canonical signature: S value excessively padded");
291 if (flags & SCRIPT_VERIFY_LOW_S) {
292 // If the S value is above the order of the curve divided by two, its
293 // complement modulo the order could have been used instead, which is
294 // one byte shorter when encoded correctly.
295 if (!CKey::CheckSignatureElement(S, nLenS, true))
296 return error("Non-canonical signature: S value is unnecessarily high");
302 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
304 CScript::const_iterator pc = script.begin();
305 CScript::const_iterator pend = script.end();
306 CScript::const_iterator pbegincodehash = script.begin();
308 valtype vchPushValue;
310 vector<valtype> altstack;
311 if (script.size() > 10000)
319 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
324 if (!script.GetOp(pc, opcode, vchPushValue))
326 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
329 // Note how OP_RESERVED does not count towards the opcode limit.
330 if (opcode > OP_16 && ++nOpCount > 201)
333 if (opcode == OP_CAT ||
334 opcode == OP_SUBSTR ||
336 opcode == OP_RIGHT ||
337 opcode == OP_INVERT ||
346 opcode == OP_LSHIFT ||
348 return false; // Disabled opcodes.
350 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
351 stack.push_back(vchPushValue);
352 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
377 CScriptNum bn((int)opcode - (int)(OP_1 - 1));
378 stack.push_back(bn.getvch());
387 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
388 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
394 // <expression> if [statements] [else [statements]] endif
398 if (stack.size() < 1)
400 valtype& vch = stacktop(-1);
401 fValue = CastToBool(vch);
402 if (opcode == OP_NOTIF)
406 vfExec.push_back(fValue);
414 vfExec.back() = !vfExec.back();
429 // (false -- false) and return
430 if (stack.size() < 1)
432 bool fValue = CastToBool(stacktop(-1));
452 if (stack.size() < 1)
454 altstack.push_back(stacktop(-1));
459 case OP_FROMALTSTACK:
461 if (altstack.size() < 1)
463 stack.push_back(altstacktop(-1));
471 if (stack.size() < 2)
480 // (x1 x2 -- x1 x2 x1 x2)
481 if (stack.size() < 2)
483 valtype vch1 = stacktop(-2);
484 valtype vch2 = stacktop(-1);
485 stack.push_back(vch1);
486 stack.push_back(vch2);
492 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
493 if (stack.size() < 3)
495 valtype vch1 = stacktop(-3);
496 valtype vch2 = stacktop(-2);
497 valtype vch3 = stacktop(-1);
498 stack.push_back(vch1);
499 stack.push_back(vch2);
500 stack.push_back(vch3);
506 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
507 if (stack.size() < 4)
509 valtype vch1 = stacktop(-4);
510 valtype vch2 = stacktop(-3);
511 stack.push_back(vch1);
512 stack.push_back(vch2);
518 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
519 if (stack.size() < 6)
521 valtype vch1 = stacktop(-6);
522 valtype vch2 = stacktop(-5);
523 stack.erase(stack.end()-6, stack.end()-4);
524 stack.push_back(vch1);
525 stack.push_back(vch2);
531 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
532 if (stack.size() < 4)
534 swap(stacktop(-4), stacktop(-2));
535 swap(stacktop(-3), stacktop(-1));
542 if (stack.size() < 1)
544 valtype vch = stacktop(-1);
546 stack.push_back(vch);
553 CScriptNum bn(stack.size());
554 stack.push_back(bn.getvch());
561 if (stack.size() < 1)
570 if (stack.size() < 1)
572 valtype vch = stacktop(-1);
573 stack.push_back(vch);
580 if (stack.size() < 2)
582 stack.erase(stack.end() - 2);
588 // (x1 x2 -- x1 x2 x1)
589 if (stack.size() < 2)
591 valtype vch = stacktop(-2);
592 stack.push_back(vch);
599 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
600 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
601 if (stack.size() < 2)
603 int n = CScriptNum(stacktop(-1)).getint();
605 if (n < 0 || n >= (int)stack.size())
607 valtype vch = stacktop(-n-1);
608 if (opcode == OP_ROLL)
609 stack.erase(stack.end()-n-1);
610 stack.push_back(vch);
616 // (x1 x2 x3 -- x2 x3 x1)
617 // x2 x1 x3 after first swap
618 // x2 x3 x1 after second swap
619 if (stack.size() < 3)
621 swap(stacktop(-3), stacktop(-2));
622 swap(stacktop(-2), stacktop(-1));
629 if (stack.size() < 2)
631 swap(stacktop(-2), stacktop(-1));
637 // (x1 x2 -- x2 x1 x2)
638 if (stack.size() < 2)
640 valtype vch = stacktop(-1);
641 stack.insert(stack.end()-2, vch);
649 if (stack.size() < 1)
651 CScriptNum bn(stacktop(-1).size());
652 stack.push_back(bn.getvch());
662 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
665 if (stack.size() < 2)
667 valtype& vch1 = stacktop(-2);
668 valtype& vch2 = stacktop(-1);
669 bool fEqual = (vch1 == vch2);
670 // OP_NOTEQUAL is disabled because it would be too easy to say
671 // something like n != 1 and have some wiseguy pass in 1 with extra
672 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
673 //if (opcode == OP_NOTEQUAL)
677 stack.push_back(fEqual ? vchTrue : vchFalse);
678 if (opcode == OP_EQUALVERIFY)
700 if (stack.size() < 1)
702 CScriptNum bn(stacktop(-1));
705 case OP_1ADD: bn += bnOne; break;
706 case OP_1SUB: bn -= bnOne; break;
707 case OP_NEGATE: bn = -bn; break;
708 case OP_ABS: if (bn < bnZero) bn = -bn; break;
709 case OP_NOT: bn = (bn == bnZero); break;
710 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
711 default: assert(!"invalid opcode"); break;
714 stack.push_back(bn.getvch());
723 case OP_NUMEQUALVERIFY:
727 case OP_LESSTHANOREQUAL:
728 case OP_GREATERTHANOREQUAL:
733 if (stack.size() < 2)
735 CScriptNum bn1(stacktop(-2));
736 CScriptNum bn2(stacktop(-1));
748 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
749 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
750 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
751 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
752 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
753 case OP_LESSTHAN: bn = (bn1 < bn2); break;
754 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
755 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
756 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
757 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
758 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
759 default: assert(!"invalid opcode"); break;
763 stack.push_back(bn.getvch());
765 if (opcode == OP_NUMEQUALVERIFY)
767 if (CastToBool(stacktop(-1)))
777 // (x min max -- out)
778 if (stack.size() < 3)
780 CScriptNum bn1(stacktop(-3));
781 CScriptNum bn2(stacktop(-2));
782 CScriptNum bn3(stacktop(-1));
783 bool fValue = (bn2 <= bn1 && bn1 < bn3);
787 stack.push_back(fValue ? vchTrue : vchFalse);
802 if (stack.size() < 1)
804 valtype& vch = stacktop(-1);
805 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
806 if (opcode == OP_RIPEMD160)
807 CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
808 else if (opcode == OP_SHA1)
809 CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
810 else if (opcode == OP_SHA256)
811 CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
812 else if (opcode == OP_HASH160)
813 CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
814 else if (opcode == OP_HASH256)
815 CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
817 stack.push_back(vchHash);
821 case OP_CODESEPARATOR:
823 // Hash starts after the code separator
829 case OP_CHECKSIGVERIFY:
831 // (sig pubkey -- bool)
832 if (stack.size() < 2)
835 valtype& vchSig = stacktop(-2);
836 valtype& vchPubKey = stacktop(-1);
838 // Subset of script starting at the most recent codeseparator
839 CScript scriptCode(pbegincodehash, pend);
841 // Drop the signature, since there's no way for a signature to sign itself
842 scriptCode.FindAndDelete(CScript(vchSig));
844 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
845 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
849 stack.push_back(fSuccess ? vchTrue : vchFalse);
850 if (opcode == OP_CHECKSIGVERIFY)
860 case OP_CHECKMULTISIG:
861 case OP_CHECKMULTISIGVERIFY:
863 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
866 if ((int)stack.size() < i)
869 int nKeysCount = CScriptNum(stacktop(-i)).getint();
870 if (nKeysCount < 0 || nKeysCount > 20)
872 nOpCount += nKeysCount;
877 if ((int)stack.size() < i)
880 int nSigsCount = CScriptNum(stacktop(-i)).getint();
881 if (nSigsCount < 0 || nSigsCount > nKeysCount)
885 if ((int)stack.size() < i)
888 // Subset of script starting at the most recent codeseparator
889 CScript scriptCode(pbegincodehash, pend);
891 // Drop the signatures, since there's no way for a signature to sign itself
892 for (int k = 0; k < nSigsCount; k++)
894 valtype& vchSig = stacktop(-isig-k);
895 scriptCode.FindAndDelete(CScript(vchSig));
898 bool fSuccess = true;
899 while (fSuccess && nSigsCount > 0)
901 valtype& vchSig = stacktop(-isig);
902 valtype& vchPubKey = stacktop(-ikey);
905 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
906 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
915 // If there are more signatures left than keys left,
916 // then too many signatures have failed
917 if (nSigsCount > nKeysCount)
921 // Clean up stack of actual arguments
925 // A bug causes CHECKMULTISIG to consume one extra argument
926 // whose contents were not checked in any way.
928 // Unfortunately this is a potential source of mutability,
929 // so optionally verify it is exactly equal to zero prior
930 // to removing it from the stack.
931 if (stack.size() < 1)
933 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
934 return error("CHECKMULTISIG dummy argument not null");
937 stack.push_back(fSuccess ? vchTrue : vchFalse);
939 if (opcode == OP_CHECKMULTISIGVERIFY)
954 if (stack.size() + altstack.size() > 1000)
977 /** Wrapper that serializes like CTransaction, but with the modifications
978 * required for the signature hash done in-place
980 class CTransactionSignatureSerializer {
982 const CTransaction &txTo; // reference to the spending transaction (the one being serialized)
983 const CScript &scriptCode; // output script being consumed
984 const unsigned int nIn; // input index of txTo being signed
985 const bool fAnyoneCanPay; // whether the hashtype has the SIGHASH_ANYONECANPAY flag set
986 const bool fHashSingle; // whether the hashtype is SIGHASH_SINGLE
987 const bool fHashNone; // whether the hashtype is SIGHASH_NONE
990 CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
991 txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
992 fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
993 fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
994 fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
996 /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
998 void SerializeScriptCode(S &s, int nType, int nVersion) const {
999 CScript::const_iterator it = scriptCode.begin();
1000 CScript::const_iterator itBegin = it;
1002 unsigned int nCodeSeparators = 0;
1003 while (scriptCode.GetOp(it, opcode)) {
1004 if (opcode == OP_CODESEPARATOR)
1007 ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1009 while (scriptCode.GetOp(it, opcode)) {
1010 if (opcode == OP_CODESEPARATOR) {
1011 s.write((char*)&itBegin[0], it-itBegin-1);
1015 s.write((char*)&itBegin[0], it-itBegin);
1018 /** Serialize an input of txTo */
1019 template<typename S>
1020 void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
1021 // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1024 // Serialize the prevout
1025 ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
1026 // Serialize the script
1028 // Blank out other inputs' signatures
1029 ::Serialize(s, CScript(), nType, nVersion);
1031 SerializeScriptCode(s, nType, nVersion);
1032 // Serialize the nSequence
1033 if (nInput != nIn && (fHashSingle || fHashNone))
1034 // let the others update at will
1035 ::Serialize(s, (int)0, nType, nVersion);
1037 ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
1040 /** Serialize an output of txTo */
1041 template<typename S>
1042 void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
1043 if (fHashSingle && nOutput != nIn)
1044 // Do not lock-in the txout payee at other indices as txin
1045 ::Serialize(s, CTxOut(), nType, nVersion);
1047 ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
1050 /** Serialize txTo */
1051 template<typename S>
1052 void Serialize(S &s, int nType, int nVersion) const {
1053 // Serialize nVersion
1054 ::Serialize(s, txTo.nVersion, nType, nVersion);
1056 unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1057 ::WriteCompactSize(s, nInputs);
1058 for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1059 SerializeInput(s, nInput, nType, nVersion);
1061 unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1062 ::WriteCompactSize(s, nOutputs);
1063 for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1064 SerializeOutput(s, nOutput, nType, nVersion);
1065 // Serialie nLockTime
1066 ::Serialize(s, txTo.nLockTime, nType, nVersion);
1071 uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1073 if (nIn >= txTo.vin.size()) {
1074 LogPrintf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1078 // Check for invalid use of SIGHASH_SINGLE
1079 if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1080 if (nIn >= txTo.vout.size()) {
1081 LogPrintf("ERROR: SignatureHash() : nOut=%d out of range\n", nIn);
1086 // Wrapper to serialize only the necessary parts of the transaction being signed
1087 CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1089 // Serialize and hash
1090 CHashWriter ss(SER_GETHASH, 0);
1091 ss << txTmp << nHashType;
1092 return ss.GetHash();
1096 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1097 // twice for every transaction (once when accepted into memory pool, and
1098 // again when accepted into the block chain)
1100 class CSignatureCache
1103 // sigdata_type is (signature hash, signature, public key):
1104 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
1105 std::set< sigdata_type> setValid;
1106 boost::shared_mutex cs_sigcache;
1110 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1112 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1114 sigdata_type k(hash, vchSig, pubKey);
1115 std::set<sigdata_type>::iterator mi = setValid.find(k);
1116 if (mi != setValid.end())
1121 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1123 // DoS prevention: limit cache size to less than 10MB
1124 // (~200 bytes per cache entry times 50,000 entries)
1125 // Since there are a maximum of 20,000 signature operations per block
1126 // 50,000 is a reasonable default.
1127 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1128 if (nMaxCacheSize <= 0) return;
1130 boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
1132 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1134 // Evict a random entry. Random because that helps
1135 // foil would-be DoS attackers who might try to pre-generate
1136 // and re-use a set of valid signatures just-slightly-greater
1137 // than our cache size.
1138 uint256 randomHash = GetRandHash();
1139 std::vector<unsigned char> unused;
1140 std::set<sigdata_type>::iterator it =
1141 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1142 if (it == setValid.end())
1143 it = setValid.begin();
1144 setValid.erase(*it);
1147 sigdata_type k(hash, vchSig, pubKey);
1152 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1153 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1155 static CSignatureCache signatureCache;
1157 CPubKey pubkey(vchPubKey);
1158 if (!pubkey.IsValid())
1161 // Hash type is one byte tacked on to the end of the signature
1165 nHashType = vchSig.back();
1166 else if (nHashType != vchSig.back())
1170 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1172 if (signatureCache.Get(sighash, vchSig, pubkey))
1175 if (!pubkey.Verify(sighash, vchSig))
1178 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1179 signatureCache.Set(sighash, vchSig, pubkey);
1193 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1195 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1198 static multimap<txnouttype, CScript> mTemplates;
1199 if (mTemplates.empty())
1201 // Standard tx, sender provides pubkey, receiver adds signature
1202 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1204 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1205 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1207 // Sender provides N pubkeys, receivers provides M signatures
1208 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1210 // Empty, provably prunable, data-carrying output
1211 if (GetBoolArg("-datacarrier", true))
1212 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1213 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
1216 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1217 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1218 if (scriptPubKey.IsPayToScriptHash())
1220 typeRet = TX_SCRIPTHASH;
1221 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1222 vSolutionsRet.push_back(hashBytes);
1227 const CScript& script1 = scriptPubKey;
1228 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1230 const CScript& script2 = tplate.second;
1231 vSolutionsRet.clear();
1233 opcodetype opcode1, opcode2;
1234 vector<unsigned char> vch1, vch2;
1237 CScript::const_iterator pc1 = script1.begin();
1238 CScript::const_iterator pc2 = script2.begin();
1241 if (pc1 == script1.end() && pc2 == script2.end())
1244 typeRet = tplate.first;
1245 if (typeRet == TX_MULTISIG)
1247 // Additional checks for TX_MULTISIG:
1248 unsigned char m = vSolutionsRet.front()[0];
1249 unsigned char n = vSolutionsRet.back()[0];
1250 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1255 if (!script1.GetOp(pc1, opcode1, vch1))
1257 if (!script2.GetOp(pc2, opcode2, vch2))
1260 // Template matching opcodes:
1261 if (opcode2 == OP_PUBKEYS)
1263 while (vch1.size() >= 33 && vch1.size() <= 65)
1265 vSolutionsRet.push_back(vch1);
1266 if (!script1.GetOp(pc1, opcode1, vch1))
1269 if (!script2.GetOp(pc2, opcode2, vch2))
1271 // Normal situation is to fall through
1272 // to other if/else statements
1275 if (opcode2 == OP_PUBKEY)
1277 if (vch1.size() < 33 || vch1.size() > 65)
1279 vSolutionsRet.push_back(vch1);
1281 else if (opcode2 == OP_PUBKEYHASH)
1283 if (vch1.size() != sizeof(uint160))
1285 vSolutionsRet.push_back(vch1);
1287 else if (opcode2 == OP_SMALLINTEGER)
1288 { // Single-byte small integer pushed onto vSolutions
1289 if (opcode1 == OP_0 ||
1290 (opcode1 >= OP_1 && opcode1 <= OP_16))
1292 char n = (char)CScript::DecodeOP_N(opcode1);
1293 vSolutionsRet.push_back(valtype(1, n));
1298 else if (opcode2 == OP_SMALLDATA)
1300 // small pushdata, <= MAX_OP_RETURN_RELAY bytes
1301 if (vch1.size() > MAX_OP_RETURN_RELAY)
1304 else if (opcode1 != opcode2 || vch1 != vch2)
1306 // Others must match exactly
1312 vSolutionsRet.clear();
1313 typeRet = TX_NONSTANDARD;
1318 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1321 if (!keystore.GetKey(address, key))
1324 vector<unsigned char> vchSig;
1325 if (!key.Sign(hash, vchSig))
1327 vchSig.push_back((unsigned char)nHashType);
1328 scriptSigRet << vchSig;
1333 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1336 int nRequired = multisigdata.front()[0];
1337 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1339 const valtype& pubkey = multisigdata[i];
1340 CKeyID keyID = CPubKey(pubkey).GetID();
1341 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1344 return nSigned==nRequired;
1348 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1349 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1350 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1351 // Returns false if scriptPubKey could not be completely satisfied.
1353 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1354 CScript& scriptSigRet, txnouttype& whichTypeRet)
1356 scriptSigRet.clear();
1358 vector<valtype> vSolutions;
1359 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1363 switch (whichTypeRet)
1365 case TX_NONSTANDARD:
1369 keyID = CPubKey(vSolutions[0]).GetID();
1370 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1372 keyID = CKeyID(uint160(vSolutions[0]));
1373 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1378 keystore.GetPubKey(keyID, vch);
1379 scriptSigRet << vch;
1383 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1386 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1387 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1392 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1396 case TX_NONSTANDARD:
1404 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1406 return vSolutions[0][0] + 1;
1408 return 1; // doesn't include args needed by the script
1413 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1415 vector<valtype> vSolutions;
1416 if (!Solver(scriptPubKey, whichType, vSolutions))
1419 if (whichType == TX_MULTISIG)
1421 unsigned char m = vSolutions.front()[0];
1422 unsigned char n = vSolutions.back()[0];
1423 // Support up to x-of-3 multisig txns as standard
1430 return whichType != TX_NONSTANDARD;
1434 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1436 unsigned int nResult = 0;
1437 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1439 CKeyID keyID = CPubKey(pubkey).GetID();
1440 if (keystore.HaveKey(keyID))
1447 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1450 const CKeyStore *keystore;
1452 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1453 bool operator()(const CNoDestination &dest) const { return false; }
1454 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1455 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1458 bool IsMine(const CKeyStore &keystore, const CTxDestination &dest)
1460 return boost::apply_visitor(CKeyStoreIsMineVisitor(&keystore), dest);
1463 bool IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1465 vector<valtype> vSolutions;
1466 txnouttype whichType;
1467 if (!Solver(scriptPubKey, whichType, vSolutions))
1473 case TX_NONSTANDARD:
1477 keyID = CPubKey(vSolutions[0]).GetID();
1478 return keystore.HaveKey(keyID);
1480 keyID = CKeyID(uint160(vSolutions[0]));
1481 return keystore.HaveKey(keyID);
1485 if (!keystore.GetCScript(CScriptID(uint160(vSolutions[0])), subscript))
1487 return IsMine(keystore, subscript);
1491 // Only consider transactions "mine" if we own ALL the
1492 // keys involved. multi-signature transactions that are
1493 // partially owned (somebody else has a key that can spend
1494 // them) enable spend-out-from-under-you attacks, especially
1495 // in shared-wallet situations.
1496 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1497 return HaveKeys(keys, keystore) == keys.size();
1503 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1505 vector<valtype> vSolutions;
1506 txnouttype whichType;
1507 if (!Solver(scriptPubKey, whichType, vSolutions))
1510 if (whichType == TX_PUBKEY)
1512 addressRet = CPubKey(vSolutions[0]).GetID();
1515 else if (whichType == TX_PUBKEYHASH)
1517 addressRet = CKeyID(uint160(vSolutions[0]));
1520 else if (whichType == TX_SCRIPTHASH)
1522 addressRet = CScriptID(uint160(vSolutions[0]));
1525 // Multisig txns have more than one address...
1529 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1532 typeRet = TX_NONSTANDARD;
1533 vector<valtype> vSolutions;
1534 if (!Solver(scriptPubKey, typeRet, vSolutions))
1536 if (typeRet == TX_NULL_DATA){
1537 // This is data, not addresses
1541 if (typeRet == TX_MULTISIG)
1543 nRequiredRet = vSolutions.front()[0];
1544 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1546 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1547 addressRet.push_back(address);
1553 CTxDestination address;
1554 if (!ExtractDestination(scriptPubKey, address))
1556 addressRet.push_back(address);
1562 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1564 const CKeyStore &keystore;
1565 std::vector<CKeyID> &vKeys;
1568 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1570 void Process(const CScript &script) {
1572 std::vector<CTxDestination> vDest;
1574 if (ExtractDestinations(script, type, vDest, nRequired)) {
1575 BOOST_FOREACH(const CTxDestination &dest, vDest)
1576 boost::apply_visitor(*this, dest);
1580 void operator()(const CKeyID &keyId) {
1581 if (keystore.HaveKey(keyId))
1582 vKeys.push_back(keyId);
1585 void operator()(const CScriptID &scriptId) {
1587 if (keystore.GetCScript(scriptId, script))
1591 void operator()(const CNoDestination &none) {}
1594 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1595 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1598 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1599 unsigned int flags, int nHashType)
1601 vector<vector<unsigned char> > stack, stackCopy;
1602 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1604 if (flags & SCRIPT_VERIFY_P2SH)
1606 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1611 if (CastToBool(stack.back()) == false)
1614 // Additional validation for spend-to-script-hash transactions:
1615 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1617 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1618 return false; // or validation fails
1620 // stackCopy cannot be empty here, because if it was the
1621 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1622 // an empty stack and the EvalScript above would return false.
1623 assert(!stackCopy.empty());
1625 const valtype& pubKeySerialized = stackCopy.back();
1626 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1627 popstack(stackCopy);
1629 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1631 if (stackCopy.empty())
1633 return CastToBool(stackCopy.back());
1640 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1642 assert(nIn < txTo.vin.size());
1643 CTxIn& txin = txTo.vin[nIn];
1645 // Leave out the signature from the hash, since a signature can't sign itself.
1646 // The checksig op will also drop the signatures from its hash.
1647 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1649 txnouttype whichType;
1650 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1653 if (whichType == TX_SCRIPTHASH)
1655 // Solver returns the subscript that need to be evaluated;
1656 // the final scriptSig is the signatures from that
1657 // and then the serialized subscript:
1658 CScript subscript = txin.scriptSig;
1660 // Recompute txn hash using subscript in place of scriptPubKey:
1661 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1665 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1666 // Append serialized subscript whether or not it is completely signed:
1667 txin.scriptSig << static_cast<valtype>(subscript);
1668 if (!fSolved) return false;
1672 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0);
1675 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1677 assert(nIn < txTo.vin.size());
1678 CTxIn& txin = txTo.vin[nIn];
1679 assert(txin.prevout.n < txFrom.vout.size());
1680 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1682 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1685 static CScript PushAll(const vector<valtype>& values)
1688 BOOST_FOREACH(const valtype& v, values)
1693 static CScript CombineMultisig(CScript scriptPubKey, const CMutableTransaction& txTo, unsigned int nIn,
1694 const vector<valtype>& vSolutions,
1695 vector<valtype>& sigs1, vector<valtype>& sigs2)
1697 // Combine all the signatures we've got:
1698 set<valtype> allsigs;
1699 BOOST_FOREACH(const valtype& v, sigs1)
1704 BOOST_FOREACH(const valtype& v, sigs2)
1710 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1711 assert(vSolutions.size() > 1);
1712 unsigned int nSigsRequired = vSolutions.front()[0];
1713 unsigned int nPubKeys = vSolutions.size()-2;
1714 map<valtype, valtype> sigs;
1715 BOOST_FOREACH(const valtype& sig, allsigs)
1717 for (unsigned int i = 0; i < nPubKeys; i++)
1719 const valtype& pubkey = vSolutions[i+1];
1720 if (sigs.count(pubkey))
1721 continue; // Already got a sig for this pubkey
1723 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1730 // Now build a merged CScript:
1731 unsigned int nSigsHave = 0;
1732 CScript result; result << OP_0; // pop-one-too-many workaround
1733 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1735 if (sigs.count(vSolutions[i+1]))
1737 result << sigs[vSolutions[i+1]];
1741 // Fill any missing with OP_0:
1742 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1748 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1749 const txnouttype txType, const vector<valtype>& vSolutions,
1750 vector<valtype>& sigs1, vector<valtype>& sigs2)
1754 case TX_NONSTANDARD:
1756 // Don't know anything about this, assume bigger one is correct:
1757 if (sigs1.size() >= sigs2.size())
1758 return PushAll(sigs1);
1759 return PushAll(sigs2);
1762 // Signatures are bigger than placeholders or empty scripts:
1763 if (sigs1.empty() || sigs1[0].empty())
1764 return PushAll(sigs2);
1765 return PushAll(sigs1);
1767 if (sigs1.empty() || sigs1.back().empty())
1768 return PushAll(sigs2);
1769 else if (sigs2.empty() || sigs2.back().empty())
1770 return PushAll(sigs1);
1773 // Recur to combine:
1774 valtype spk = sigs1.back();
1775 CScript pubKey2(spk.begin(), spk.end());
1778 vector<vector<unsigned char> > vSolutions2;
1779 Solver(pubKey2, txType2, vSolutions2);
1782 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1787 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1793 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1794 const CScript& scriptSig1, const CScript& scriptSig2)
1797 vector<vector<unsigned char> > vSolutions;
1798 Solver(scriptPubKey, txType, vSolutions);
1800 vector<valtype> stack1;
1801 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1802 vector<valtype> stack2;
1803 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1805 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1808 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1811 const_iterator pc = begin();
1812 opcodetype lastOpcode = OP_INVALIDOPCODE;
1816 if (!GetOp(pc, opcode))
1818 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1820 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1822 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1823 n += DecodeOP_N(lastOpcode);
1827 lastOpcode = opcode;
1832 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1834 if (!IsPayToScriptHash())
1835 return GetSigOpCount(true);
1837 // This is a pay-to-script-hash scriptPubKey;
1838 // get the last item that the scriptSig
1839 // pushes onto the stack:
1840 const_iterator pc = scriptSig.begin();
1841 vector<unsigned char> data;
1842 while (pc < scriptSig.end())
1845 if (!scriptSig.GetOp(pc, opcode, data))
1851 /// ... and return its opcount:
1852 CScript subscript(data.begin(), data.end());
1853 return subscript.GetSigOpCount(true);
1856 bool CScript::IsPayToScriptHash() const
1858 // Extra-fast test for pay-to-script-hash CScripts:
1859 return (this->size() == 23 &&
1860 this->at(0) == OP_HASH160 &&
1861 this->at(1) == 0x14 &&
1862 this->at(22) == OP_EQUAL);
1865 bool CScript::IsPushOnly() const
1867 const_iterator pc = begin();
1871 if (!GetOp(pc, opcode))
1873 // Note that IsPushOnly() *does* consider OP_RESERVED to be a
1874 // push-type opcode, however execution of OP_RESERVED fails, so
1875 // it's not relevant to P2SH as the scriptSig would fail prior to
1876 // the P2SH special validation code being executed.
1883 bool CScript::HasCanonicalPushes() const
1885 const_iterator pc = begin();
1889 std::vector<unsigned char> data;
1890 if (!GetOp(pc, opcode, data))
1894 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1895 // Could have used an OP_n code, rather than a 1-byte push.
1897 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1898 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1900 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1901 // Could have used an OP_PUSHDATA1.
1903 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1904 // Could have used an OP_PUSHDATA2.
1910 class CScriptVisitor : public boost::static_visitor<bool>
1915 CScriptVisitor(CScript *scriptin) { script = scriptin; }
1917 bool operator()(const CNoDestination &dest) const {
1922 bool operator()(const CKeyID &keyID) const {
1924 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1928 bool operator()(const CScriptID &scriptID) const {
1930 *script << OP_HASH160 << scriptID << OP_EQUAL;
1935 void CScript::SetDestination(const CTxDestination& dest)
1937 boost::apply_visitor(CScriptVisitor(this), dest);
1940 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
1944 *this << EncodeOP_N(nRequired);
1945 BOOST_FOREACH(const CPubKey& key, keys)
1947 *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1950 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
1952 if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
1953 && script[2] == 20 && script[23] == OP_EQUALVERIFY
1954 && script[24] == OP_CHECKSIG) {
1955 memcpy(&hash, &script[3], 20);
1961 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
1963 if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
1964 && script[22] == OP_EQUAL) {
1965 memcpy(&hash, &script[2], 20);
1971 bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
1973 if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
1974 && (script[1] == 0x02 || script[1] == 0x03)) {
1975 pubkey.Set(&script[1], &script[34]);
1978 if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
1979 && script[1] == 0x04) {
1980 pubkey.Set(&script[1], &script[66]);
1981 return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
1986 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
1989 if (IsToKeyID(keyID)) {
1992 memcpy(&out[1], &keyID, 20);
1996 if (IsToScriptID(scriptID)) {
1999 memcpy(&out[1], &scriptID, 20);
2003 if (IsToPubKey(pubkey)) {
2005 memcpy(&out[1], &pubkey[1], 32);
2006 if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2009 } else if (pubkey[0] == 0x04) {
2010 out[0] = 0x04 | (pubkey[64] & 0x01);
2017 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2019 if (nSize == 0 || nSize == 1)
2021 if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2026 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2032 script[1] = OP_HASH160;
2034 memcpy(&script[3], &in[0], 20);
2035 script[23] = OP_EQUALVERIFY;
2036 script[24] = OP_CHECKSIG;
2040 script[0] = OP_HASH160;
2042 memcpy(&script[2], &in[0], 20);
2043 script[22] = OP_EQUAL;
2050 memcpy(&script[2], &in[0], 32);
2051 script[34] = OP_CHECKSIG;
2055 unsigned char vch[33] = {};
2057 memcpy(&vch[1], &in[0], 32);
2058 CPubKey pubkey(&vch[0], &vch[33]);
2059 if (!pubkey.Decompress())
2061 assert(pubkey.size() == 65);
2064 memcpy(&script[1], pubkey.begin(), 65);
2065 script[66] = OP_CHECKSIG;