1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #include <boost/foreach.hpp>
6 #include <boost/tuple/tuple.hpp>
19 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
21 static const valtype vchFalse(0);
22 static const valtype vchZero(0);
23 static const valtype vchTrue(1, 1);
24 static const CBigNum bnZero(0);
25 static const CBigNum bnOne(1);
26 static const CBigNum bnFalse(0);
27 static const CBigNum bnTrue(1);
28 static const size_t nMaxNumSize = 4;
31 CBigNum CastToBigNum(const valtype& vch)
33 if (vch.size() > nMaxNumSize)
34 throw runtime_error("CastToBigNum() : overflow");
35 // Get rid of extra leading zeros
36 return CBigNum(CBigNum(vch).getvch());
39 bool CastToBool(const valtype& vch)
41 for (unsigned int i = 0; i < vch.size(); i++)
45 // Can be negative zero
46 if (i == vch.size()-1 && vch[i] == 0x80)
55 // WARNING: This does not work as expected for signed integers; the sign-bit
56 // is left in place as the integer is zero-extended. The correct behavior
57 // would be to move the most significant bit of the last byte during the
58 // resize process. MakeSameSize() is currently only used by the disabled
59 // opcodes OP_AND, OP_OR, and OP_XOR.
61 void MakeSameSize(valtype& vch1, valtype& vch2)
63 // Lengthen the shorter one
64 if (vch1.size() < vch2.size())
66 // +unsigned char msb = vch1[vch1.size()-1];
67 // +vch1[vch1.size()-1] &= 0x7f;
68 // vch1.resize(vch2.size(), 0);
69 // +vch1[vch1.size()-1] = msb;
70 vch1.resize(vch2.size(), 0);
71 if (vch2.size() < vch1.size())
73 // +unsigned char msb = vch2[vch2.size()-1];
74 // +vch2[vch2.size()-1] &= 0x7f;
75 // vch2.resize(vch1.size(), 0);
76 // +vch2[vch2.size()-1] = msb;
77 vch2.resize(vch1.size(), 0);
83 // Script is a stack machine (like Forth) that evaluates a predicate
84 // returning a bool indicating valid or not. There are no loops.
86 #define stacktop(i) (stack.at(stack.size()+(i)))
87 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
88 static inline void popstack(vector<valtype>& stack)
91 throw runtime_error("popstack() : stack empty");
96 const char* GetTxnOutputType(txnouttype t)
100 case TX_NONSTANDARD: return "nonstandard";
101 case TX_PUBKEY: return "pubkey";
102 case TX_PUBKEY_DROP: return "pubkeydrop";
103 case TX_PUBKEYHASH: return "pubkeyhash";
104 case TX_SCRIPTHASH: return "scripthash";
105 case TX_MULTISIG: return "multisig";
106 case TX_NULL_DATA: return "nulldata";
112 const char* GetOpName(opcodetype opcode)
117 case OP_0 : return "0";
118 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
119 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
120 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
121 case OP_1NEGATE : return "-1";
122 case OP_RESERVED : return "OP_RESERVED";
123 case OP_1 : return "1";
124 case OP_2 : return "2";
125 case OP_3 : return "3";
126 case OP_4 : return "4";
127 case OP_5 : return "5";
128 case OP_6 : return "6";
129 case OP_7 : return "7";
130 case OP_8 : return "8";
131 case OP_9 : return "9";
132 case OP_10 : return "10";
133 case OP_11 : return "11";
134 case OP_12 : return "12";
135 case OP_13 : return "13";
136 case OP_14 : return "14";
137 case OP_15 : return "15";
138 case OP_16 : return "16";
141 case OP_NOP : return "OP_NOP";
142 case OP_VER : return "OP_VER";
143 case OP_IF : return "OP_IF";
144 case OP_NOTIF : return "OP_NOTIF";
145 case OP_VERIF : return "OP_VERIF";
146 case OP_VERNOTIF : return "OP_VERNOTIF";
147 case OP_ELSE : return "OP_ELSE";
148 case OP_ENDIF : return "OP_ENDIF";
149 case OP_VERIFY : return "OP_VERIFY";
150 case OP_RETURN : return "OP_RETURN";
151 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
154 case OP_TOALTSTACK : return "OP_TOALTSTACK";
155 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
156 case OP_2DROP : return "OP_2DROP";
157 case OP_2DUP : return "OP_2DUP";
158 case OP_3DUP : return "OP_3DUP";
159 case OP_2OVER : return "OP_2OVER";
160 case OP_2ROT : return "OP_2ROT";
161 case OP_2SWAP : return "OP_2SWAP";
162 case OP_IFDUP : return "OP_IFDUP";
163 case OP_DEPTH : return "OP_DEPTH";
164 case OP_DROP : return "OP_DROP";
165 case OP_DUP : return "OP_DUP";
166 case OP_NIP : return "OP_NIP";
167 case OP_OVER : return "OP_OVER";
168 case OP_PICK : return "OP_PICK";
169 case OP_ROLL : return "OP_ROLL";
170 case OP_ROT : return "OP_ROT";
171 case OP_SWAP : return "OP_SWAP";
172 case OP_TUCK : return "OP_TUCK";
175 case OP_CAT : return "OP_CAT";
176 case OP_SUBSTR : return "OP_SUBSTR";
177 case OP_LEFT : return "OP_LEFT";
178 case OP_RIGHT : return "OP_RIGHT";
179 case OP_SIZE : return "OP_SIZE";
182 case OP_INVERT : return "OP_INVERT";
183 case OP_AND : return "OP_AND";
184 case OP_OR : return "OP_OR";
185 case OP_XOR : return "OP_XOR";
186 case OP_EQUAL : return "OP_EQUAL";
187 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
188 case OP_RESERVED1 : return "OP_RESERVED1";
189 case OP_RESERVED2 : return "OP_RESERVED2";
192 case OP_1ADD : return "OP_1ADD";
193 case OP_1SUB : return "OP_1SUB";
194 case OP_2MUL : return "OP_2MUL";
195 case OP_2DIV : return "OP_2DIV";
196 case OP_NEGATE : return "OP_NEGATE";
197 case OP_ABS : return "OP_ABS";
198 case OP_NOT : return "OP_NOT";
199 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
200 case OP_ADD : return "OP_ADD";
201 case OP_SUB : return "OP_SUB";
202 case OP_MUL : return "OP_MUL";
203 case OP_DIV : return "OP_DIV";
204 case OP_MOD : return "OP_MOD";
205 case OP_LSHIFT : return "OP_LSHIFT";
206 case OP_RSHIFT : return "OP_RSHIFT";
207 case OP_BOOLAND : return "OP_BOOLAND";
208 case OP_BOOLOR : return "OP_BOOLOR";
209 case OP_NUMEQUAL : return "OP_NUMEQUAL";
210 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
211 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
212 case OP_LESSTHAN : return "OP_LESSTHAN";
213 case OP_GREATERTHAN : return "OP_GREATERTHAN";
214 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
215 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
216 case OP_MIN : return "OP_MIN";
217 case OP_MAX : return "OP_MAX";
218 case OP_WITHIN : return "OP_WITHIN";
221 case OP_RIPEMD160 : return "OP_RIPEMD160";
222 case OP_SHA1 : return "OP_SHA1";
223 case OP_SHA256 : return "OP_SHA256";
224 case OP_HASH160 : return "OP_HASH160";
225 case OP_HASH256 : return "OP_HASH256";
226 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
227 case OP_CHECKSIG : return "OP_CHECKSIG";
228 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
229 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
230 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
233 case OP_NOP1 : return "OP_NOP1";
234 case OP_NOP3 : return "OP_NOP3";
235 case OP_NOP4 : return "OP_NOP4";
236 case OP_NOP5 : return "OP_NOP5";
237 case OP_NOP6 : return "OP_NOP6";
238 case OP_NOP7 : return "OP_NOP7";
239 case OP_NOP8 : return "OP_NOP8";
240 case OP_NOP9 : return "OP_NOP9";
241 case OP_NOP10 : return "OP_NOP10";
245 // template matching params
246 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
247 case OP_PUBKEY : return "OP_PUBKEY";
248 case OP_SMALLDATA : return "OP_SMALLDATA";
250 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
256 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
257 if (!(flags & SCRIPT_VERIFY_STRICTENC))
260 if (vchPubKey.size() < 33)
261 return error("Non-canonical public key: too short");
262 if (vchPubKey[0] == 0x04) {
263 if (vchPubKey.size() != 65)
264 return error("Non-canonical public key: invalid length for uncompressed key");
265 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
266 if (vchPubKey.size() != 33)
267 return error("Non-canonical public key: invalid length for compressed key");
269 return error("Non-canonical public key: compressed nor uncompressed");
274 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
275 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
276 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
277 // Where R and S are not negative (their first byte has its highest bit not set), and not
278 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
279 // in which case a single 0 byte is necessary and even required).
280 if (vchSig.size() < 9)
281 return error("Non-canonical signature: too short");
282 if (vchSig.size() > 73)
283 return error("Non-canonical signature: too long");
284 if (vchSig[0] != 0x30)
285 return error("Non-canonical signature: wrong type");
286 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
287 return error("Non-canonical signature: wrong length marker");
289 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
290 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
291 return error("Non-canonical signature: unknown hashtype byte");
293 unsigned int nLenR = vchSig[3];
294 if (5 + nLenR >= vchSig.size())
295 return error("Non-canonical signature: S length misplaced");
296 unsigned int nLenS = vchSig[5+nLenR];
297 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
298 return error("Non-canonical signature: R+S length mismatch");
300 const unsigned char *R = &vchSig[4];
302 return error("Non-canonical signature: R value type mismatch");
304 return error("Non-canonical signature: R length is zero");
306 return error("Non-canonical signature: R value negative");
307 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
308 return error("Non-canonical signature: R value excessively padded");
310 const unsigned char *S = &vchSig[6+nLenR];
312 return error("Non-canonical signature: S value type mismatch");
314 return error("Non-canonical signature: S length is zero");
316 return error("Non-canonical signature: S value negative");
317 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
318 return error("Non-canonical signature: S value excessively padded");
321 unsigned int nLenR = vchSig[3];
322 unsigned int nLenS = vchSig[5+nLenR];
323 const unsigned char *S = &vchSig[6+nLenR];
324 // If the S value is above the order of the curve divided by two, its
325 // complement modulo the order could have been used instead, which is
326 // one byte shorter when encoded correctly.
327 if (!CKey::CheckSignatureElement(S, nLenS, true))
328 return error("Non-canonical signature: S value is unnecessarily high");
334 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
335 if (!(flags & SCRIPT_VERIFY_STRICTENC))
338 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
341 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
344 CScript::const_iterator pc = script.begin();
345 CScript::const_iterator pend = script.end();
346 CScript::const_iterator pbegincodehash = script.begin();
348 valtype vchPushValue;
350 vector<valtype> altstack;
351 if (script.size() > 10000)
359 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
364 if (!script.GetOp(pc, opcode, vchPushValue))
366 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
368 if (opcode > OP_16 && ++nOpCount > 201)
371 if (opcode == OP_CAT ||
372 opcode == OP_SUBSTR ||
374 opcode == OP_RIGHT ||
375 opcode == OP_INVERT ||
384 opcode == OP_LSHIFT ||
386 return false; // Disabled opcodes.
388 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
389 stack.push_back(vchPushValue);
390 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
415 CBigNum bn((int)opcode - (int)(OP_1 - 1));
416 stack.push_back(bn.getvch());
425 case OP_NOP1: case OP_NOP3: case OP_NOP4: case OP_NOP5:
426 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
432 // <expression> if [statements] [else [statements]] endif
436 if (stack.size() < 1)
438 valtype& vch = stacktop(-1);
439 fValue = CastToBool(vch);
440 if (opcode == OP_NOTIF)
444 vfExec.push_back(fValue);
452 vfExec.back() = !vfExec.back();
467 // (false -- false) and return
468 if (stack.size() < 1)
470 bool fValue = CastToBool(stacktop(-1));
484 case OP_CHECKLOCKTIMEVERIFY:
486 // CHECKLOCKTIMEVERIFY
488 // (nLockTime -- nLockTime)
489 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY))
490 break; // treat as a NOP is not enabled
491 if (stack.size() < 1)
493 const CBigNum nLockTime = CastToBigNum(stacktop(-1));
495 return false; // Negative argument is senseless.
497 if (!( // We can have either lock-by-blockheight or lock-by-blocktime.
498 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
499 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
503 // Now we can perform a simple numerical comparison
504 if (nLockTime > (int64_t)txTo.nLockTime)
507 // Finally the nLockTime feature can be disabled and thus
508 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
509 // finalized by setting nSequence to maxint. The
510 // transaction would be allowed into the blockchain, making
511 // the opcode ineffective.
513 // Testing if this vin is not final is sufficient to
514 // prevent this condition. Alternatively we could test all
515 // inputs, but testing just this input minimizes the data
516 // required to prove correct CHECKLOCKTIMEVERIFY execution.
517 if (txTo.vin[nIn].IsFinal())
527 if (stack.size() < 1)
529 altstack.push_back(stacktop(-1));
534 case OP_FROMALTSTACK:
536 if (altstack.size() < 1)
538 stack.push_back(altstacktop(-1));
546 if (stack.size() < 2)
555 // (x1 x2 -- x1 x2 x1 x2)
556 if (stack.size() < 2)
558 valtype vch1 = stacktop(-2);
559 valtype vch2 = stacktop(-1);
560 stack.push_back(vch1);
561 stack.push_back(vch2);
567 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
568 if (stack.size() < 3)
570 valtype vch1 = stacktop(-3);
571 valtype vch2 = stacktop(-2);
572 valtype vch3 = stacktop(-1);
573 stack.push_back(vch1);
574 stack.push_back(vch2);
575 stack.push_back(vch3);
581 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
582 if (stack.size() < 4)
584 valtype vch1 = stacktop(-4);
585 valtype vch2 = stacktop(-3);
586 stack.push_back(vch1);
587 stack.push_back(vch2);
593 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
594 if (stack.size() < 6)
596 valtype vch1 = stacktop(-6);
597 valtype vch2 = stacktop(-5);
598 stack.erase(stack.end()-6, stack.end()-4);
599 stack.push_back(vch1);
600 stack.push_back(vch2);
606 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
607 if (stack.size() < 4)
609 swap(stacktop(-4), stacktop(-2));
610 swap(stacktop(-3), stacktop(-1));
617 if (stack.size() < 1)
619 valtype vch = stacktop(-1);
621 stack.push_back(vch);
628 CBigNum bn((uint16_t) stack.size());
629 stack.push_back(bn.getvch());
636 if (stack.size() < 1)
645 if (stack.size() < 1)
647 valtype vch = stacktop(-1);
648 stack.push_back(vch);
655 if (stack.size() < 2)
657 stack.erase(stack.end() - 2);
663 // (x1 x2 -- x1 x2 x1)
664 if (stack.size() < 2)
666 valtype vch = stacktop(-2);
667 stack.push_back(vch);
674 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
675 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
676 if (stack.size() < 2)
678 int n = CastToBigNum(stacktop(-1)).getint32();
680 if (n < 0 || n >= (int)stack.size())
682 valtype vch = stacktop(-n-1);
683 if (opcode == OP_ROLL)
684 stack.erase(stack.end()-n-1);
685 stack.push_back(vch);
691 // (x1 x2 x3 -- x2 x3 x1)
692 // x2 x1 x3 after first swap
693 // x2 x3 x1 after second swap
694 if (stack.size() < 3)
696 swap(stacktop(-3), stacktop(-2));
697 swap(stacktop(-2), stacktop(-1));
704 if (stack.size() < 2)
706 swap(stacktop(-2), stacktop(-1));
712 // (x1 x2 -- x2 x1 x2)
713 if (stack.size() < 2)
715 valtype vch = stacktop(-1);
716 stack.insert(stack.end()-2, vch);
724 if (stack.size() < 1)
726 CBigNum bn((uint16_t) stacktop(-1).size());
727 stack.push_back(bn.getvch());
737 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
740 if (stack.size() < 2)
742 valtype& vch1 = stacktop(-2);
743 valtype& vch2 = stacktop(-1);
744 bool fEqual = (vch1 == vch2);
745 // OP_NOTEQUAL is disabled because it would be too easy to say
746 // something like n != 1 and have some wiseguy pass in 1 with extra
747 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
748 //if (opcode == OP_NOTEQUAL)
752 stack.push_back(fEqual ? vchTrue : vchFalse);
753 if (opcode == OP_EQUALVERIFY)
775 if (stack.size() < 1)
777 CBigNum bn = CastToBigNum(stacktop(-1));
780 case OP_1ADD: bn += bnOne; break;
781 case OP_1SUB: bn -= bnOne; break;
782 case OP_NEGATE: bn = -bn; break;
783 case OP_ABS: if (bn < bnZero) bn = -bn; break;
784 case OP_NOT: bn = (bn == bnZero); break;
785 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
786 default: assert(!"invalid opcode"); break;
789 stack.push_back(bn.getvch());
798 case OP_NUMEQUALVERIFY:
802 case OP_LESSTHANOREQUAL:
803 case OP_GREATERTHANOREQUAL:
808 if (stack.size() < 2)
810 CBigNum bn1 = CastToBigNum(stacktop(-2));
811 CBigNum bn2 = CastToBigNum(stacktop(-1));
823 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
824 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
825 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
826 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
827 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
828 case OP_LESSTHAN: bn = (bn1 < bn2); break;
829 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
830 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
831 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
832 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
833 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
834 default: assert(!"invalid opcode"); break;
838 stack.push_back(bn.getvch());
840 if (opcode == OP_NUMEQUALVERIFY)
842 if (CastToBool(stacktop(-1)))
852 // (x min max -- out)
853 if (stack.size() < 3)
855 CBigNum bn1 = CastToBigNum(stacktop(-3));
856 CBigNum bn2 = CastToBigNum(stacktop(-2));
857 CBigNum bn3 = CastToBigNum(stacktop(-1));
858 bool fValue = (bn2 <= bn1 && bn1 < bn3);
862 stack.push_back(fValue ? vchTrue : vchFalse);
877 if (stack.size() < 1)
879 valtype& vch = stacktop(-1);
880 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
881 if (opcode == OP_RIPEMD160)
882 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
883 else if (opcode == OP_SHA1)
884 SHA1(&vch[0], vch.size(), &vchHash[0]);
885 else if (opcode == OP_SHA256)
886 SHA256(&vch[0], vch.size(), &vchHash[0]);
887 else if (opcode == OP_HASH160)
889 uint160 hash160 = Hash160(vch);
890 memcpy(&vchHash[0], &hash160, sizeof(hash160));
892 else if (opcode == OP_HASH256)
894 uint256 hash = Hash(vch.begin(), vch.end());
895 memcpy(&vchHash[0], &hash, sizeof(hash));
898 stack.push_back(vchHash);
902 case OP_CODESEPARATOR:
904 // Hash starts after the code separator
910 case OP_CHECKSIGVERIFY:
912 // (sig pubkey -- bool)
913 if (stack.size() < 2)
916 valtype& vchSig = stacktop(-2);
917 valtype& vchPubKey = stacktop(-1);
920 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
921 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
923 // Subset of script starting at the most recent codeseparator
924 CScript scriptCode(pbegincodehash, pend);
926 // Drop the signature, since there's no way for a signature to sign itself
927 scriptCode.FindAndDelete(CScript(vchSig));
929 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
930 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
934 stack.push_back(fSuccess ? vchTrue : vchFalse);
935 if (opcode == OP_CHECKSIGVERIFY)
945 case OP_CHECKMULTISIG:
946 case OP_CHECKMULTISIGVERIFY:
948 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
951 if ((int)stack.size() < i)
954 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
955 if (nKeysCount < 0 || nKeysCount > 20)
957 nOpCount += nKeysCount;
962 if ((int)stack.size() < i)
965 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
966 if (nSigsCount < 0 || nSigsCount > nKeysCount)
970 if ((int)stack.size() < i)
973 // Subset of script starting at the most recent codeseparator
974 CScript scriptCode(pbegincodehash, pend);
976 // Drop the signatures, since there's no way for a signature to sign itself
977 for (int k = 0; k < nSigsCount; k++)
979 valtype& vchSig = stacktop(-isig-k);
980 scriptCode.FindAndDelete(CScript(vchSig));
983 bool fSuccess = true;
984 while (fSuccess && nSigsCount > 0)
986 valtype& vchSig = stacktop(-isig);
987 valtype& vchPubKey = stacktop(-ikey);
990 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
991 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1000 // If there are more signatures left than keys left,
1001 // then too many signatures have failed
1002 if (nSigsCount > nKeysCount)
1009 // A bug causes CHECKMULTISIG to consume one extra argument
1010 // whose contents were not checked in any way.
1012 // Unfortunately this is a potential source of mutability,
1013 // so optionally verify it is exactly equal to zero prior
1014 // to removing it from the stack.
1015 if (stack.size() < 1)
1017 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1018 return error("CHECKMULTISIG dummy argument not null");
1021 stack.push_back(fSuccess ? vchTrue : vchFalse);
1023 if (opcode == OP_CHECKMULTISIGVERIFY)
1038 if (stack.size() + altstack.size() > 1000)
1048 if (!vfExec.empty())
1062 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1064 if (nIn >= txTo.vin.size())
1066 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1069 CTransaction txTmp(txTo);
1071 // In case concatenating two scripts ends up with two codeseparators,
1072 // or an extra one at the end, this prevents all those possible incompatibilities.
1073 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1075 // Blank out other inputs' signatures
1076 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1077 txTmp.vin[i].scriptSig = CScript();
1078 txTmp.vin[nIn].scriptSig = scriptCode;
1080 // Blank out some of the outputs
1081 if ((nHashType & 0x1f) == SIGHASH_NONE)
1086 // Let the others update at will
1087 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1089 txTmp.vin[i].nSequence = 0;
1091 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1093 // Only lock-in the txout payee at same index as txin
1094 unsigned int nOut = nIn;
1095 if (nOut >= txTmp.vout.size())
1097 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1100 txTmp.vout.resize(nOut+1);
1101 for (unsigned int i = 0; i < nOut; i++)
1102 txTmp.vout[i].SetNull();
1104 // Let the others update at will
1105 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1107 txTmp.vin[i].nSequence = 0;
1110 // Blank out other inputs completely, not recommended for open transactions
1111 if (nHashType & SIGHASH_ANYONECANPAY)
1113 txTmp.vin[0] = txTmp.vin[nIn];
1114 txTmp.vin.resize(1);
1117 // Serialize and hash
1118 CDataStream ss(SER_GETHASH, 0);
1120 ss << txTmp << nHashType;
1121 return Hash(ss.begin(), ss.end());
1125 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1126 // twice for every transaction (once when accepted into memory pool, and
1127 // again when accepted into the block chain)
1129 class CSignatureCache
1132 // sigdata_type is (signature hash, signature, public key):
1133 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1134 std::set< sigdata_type> setValid;
1135 boost::shared_mutex cs_sigcache;
1139 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1141 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1143 sigdata_type k(hash, vchSig, pubKey);
1144 std::set<sigdata_type>::iterator mi = setValid.find(k);
1145 if (mi != setValid.end())
1150 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1152 // DoS prevention: limit cache size to less than 10MB
1153 // (~200 bytes per cache entry times 50,000 entries)
1154 // Since there are a maximum of 20,000 signature operations per block
1155 // 50,000 is a reasonable default.
1156 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1157 if (nMaxCacheSize <= 0) return;
1159 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1161 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1163 // Evict a random entry. Random because that helps
1164 // foil would-be DoS attackers who might try to pre-generate
1165 // and re-use a set of valid signatures just-slightly-greater
1166 // than our cache size.
1167 uint256 randomHash = GetRandHash();
1168 std::vector<unsigned char> unused;
1169 std::set<sigdata_type>::iterator it =
1170 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1171 if (it == setValid.end())
1172 it = setValid.begin();
1173 setValid.erase(*it);
1176 sigdata_type k(hash, vchSig, pubKey);
1181 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1182 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1184 static CSignatureCache signatureCache;
1187 if (!key.SetPubKey(vchPubKey))
1189 CPubKey pubkey = key.GetPubKey();
1190 if (!pubkey.IsValid())
1193 // Hash type is one byte tacked on to the end of the signature
1197 nHashType = vchSig.back();
1198 else if (nHashType != vchSig.back())
1202 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1204 if (signatureCache.Get(sighash, vchSig, pubkey))
1207 if (!key.Verify(sighash, vchSig))
1210 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1211 signatureCache.Set(sighash, vchSig, pubkey);
1224 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1226 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1229 static map<txnouttype, CScript> mTemplates;
1230 if (mTemplates.empty())
1232 // Standard tx, sender provides pubkey, receiver adds signature
1233 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1235 if (fTestNet || GetTime() > SMALLDATA_SWITCH_TIME)
1237 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1238 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1241 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1242 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1244 // Sender provides N pubkeys, receivers provides M signatures
1245 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1247 // Empty, provably prunable, data-carrying output
1248 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1251 vSolutionsRet.clear();
1253 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1254 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1255 if (scriptPubKey.IsPayToScriptHash())
1257 typeRet = TX_SCRIPTHASH;
1258 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1259 vSolutionsRet.push_back(hashBytes);
1263 // Provably prunable, data-carrying output
1265 // So long as script passes the IsUnspendable() test and all but the first
1266 // byte passes the IsPushOnly() test we don't care what exactly is in the
1268 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1269 typeRet = TX_NULL_DATA;
1274 const CScript& script1 = scriptPubKey;
1275 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1277 const CScript& script2 = tplate.second;
1278 vSolutionsRet.clear();
1280 opcodetype opcode1, opcode2;
1281 vector<unsigned char> vch1, vch2;
1284 CScript::const_iterator pc1 = script1.begin();
1285 CScript::const_iterator pc2 = script2.begin();
1288 if (pc1 == script1.end() && pc2 == script2.end())
1291 typeRet = tplate.first;
1292 if (typeRet == TX_MULTISIG)
1294 // Additional checks for TX_MULTISIG:
1295 unsigned char m = vSolutionsRet.front()[0];
1296 unsigned char n = vSolutionsRet.back()[0];
1297 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1302 if (!script1.GetOp(pc1, opcode1, vch1))
1304 if (!script2.GetOp(pc2, opcode2, vch2))
1307 // Template matching opcodes:
1308 if (opcode2 == OP_PUBKEYS)
1310 while (vch1.size() >= 33 && vch1.size() <= 120)
1312 vSolutionsRet.push_back(vch1);
1313 if (!script1.GetOp(pc1, opcode1, vch1))
1316 if (!script2.GetOp(pc2, opcode2, vch2))
1318 // Normal situation is to fall through
1319 // to other if/else statements
1322 if (opcode2 == OP_PUBKEY)
1324 if (vch1.size() < 33 || vch1.size() > 120)
1326 vSolutionsRet.push_back(vch1);
1328 else if (opcode2 == OP_PUBKEYHASH)
1330 if (vch1.size() != sizeof(uint160))
1332 vSolutionsRet.push_back(vch1);
1334 else if (opcode2 == OP_SMALLINTEGER)
1335 { // Single-byte small integer pushed onto vSolutions
1336 if (opcode1 == OP_0 ||
1337 (opcode1 >= OP_1 && opcode1 <= OP_16))
1339 char n = (char)CScript::DecodeOP_N(opcode1);
1340 vSolutionsRet.push_back(valtype(1, n));
1345 else if (opcode2 == OP_INTEGER)
1346 { // Up to four-byte integer pushed onto vSolutions
1349 CBigNum bnVal = CastToBigNum(vch1);
1351 break; // It's better to use OP_0 ... OP_16 for small integers.
1352 vSolutionsRet.push_back(vch1);
1359 else if (opcode2 == OP_SMALLDATA)
1361 // small pushdata, <= 1024 bytes
1362 if (vch1.size() > (GetTime() > SMALLDATA_SWITCH_TIME ? 1024 : 80))
1365 else if (opcode1 != opcode2 || vch1 != vch2)
1367 // Others must match exactly
1373 vSolutionsRet.clear();
1374 typeRet = TX_NONSTANDARD;
1379 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1382 if (!keystore.GetKey(address, key))
1385 vector<unsigned char> vchSig;
1386 if (!key.Sign(hash, vchSig))
1388 vchSig.push_back((unsigned char)nHashType);
1389 scriptSigRet << vchSig;
1394 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1397 if (!keystore.CreatePrivKey(pubKey, R, key))
1400 vector<unsigned char> vchSig;
1401 if (!key.Sign(hash, vchSig))
1403 vchSig.push_back((unsigned char)nHashType);
1404 scriptSigRet << vchSig;
1409 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1412 int nRequired = multisigdata.front()[0];
1413 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1415 const valtype& pubkey = multisigdata[i];
1416 CKeyID keyID = CPubKey(pubkey).GetID();
1417 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1420 return nSigned==nRequired;
1424 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1425 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1426 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1427 // Returns false if scriptPubKey could not be completely satisfied.
1429 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1430 CScript& scriptSigRet, txnouttype& whichTypeRet)
1432 scriptSigRet.clear();
1434 vector<valtype> vSolutions;
1435 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1439 switch (whichTypeRet)
1441 case TX_NONSTANDARD:
1445 keyID = CPubKey(vSolutions[0]).GetID();
1446 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1447 case TX_PUBKEY_DROP:
1449 CPubKey key = CPubKey(vSolutions[0]);
1450 CPubKey R = CPubKey(vSolutions[1]);
1451 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1454 keyID = CKeyID(uint160(vSolutions[0]));
1455 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1460 keystore.GetPubKey(keyID, vch);
1461 scriptSigRet << vch;
1465 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1468 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1469 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1474 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1478 case TX_NONSTANDARD:
1483 case TX_PUBKEY_DROP:
1488 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1490 return vSolutions[0][0] + 1;
1492 return 1; // doesn't include args needed by the script
1497 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1499 vector<valtype> vSolutions;
1500 if (!Solver(scriptPubKey, whichType, vSolutions))
1503 if (whichType == TX_MULTISIG)
1505 unsigned char m = vSolutions.front()[0];
1506 unsigned char n = vSolutions.back()[0];
1507 // Support up to x-of-3 multisig txns as standard
1514 return whichType != TX_NONSTANDARD;
1518 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1520 unsigned int nResult = 0;
1521 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1523 CKeyID keyID = CPubKey(pubkey).GetID();
1524 if (keystore.HaveKey(keyID))
1531 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1534 const CKeyStore *keystore;
1536 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1537 bool operator()(const CNoDestination &dest) const { return false; }
1538 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1539 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1542 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1545 script.SetDestination(dest);
1546 return IsMine(keystore, script);
1549 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1551 vector<valtype> vSolutions;
1552 txnouttype whichType;
1553 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1554 if (keystore.HaveWatchOnly(scriptPubKey))
1555 return MINE_WATCH_ONLY;
1562 case TX_NONSTANDARD:
1566 keyID = CPubKey(vSolutions[0]).GetID();
1567 if (keystore.HaveKey(keyID))
1568 return MINE_SPENDABLE;
1570 case TX_PUBKEY_DROP:
1572 CPubKey key = CPubKey(vSolutions[0]);
1573 CPubKey R = CPubKey(vSolutions[1]);
1574 if (keystore.CheckOwnership(key, R))
1575 return MINE_SPENDABLE;
1579 keyID = CKeyID(uint160(vSolutions[0]));
1580 if (keystore.HaveKey(keyID))
1581 return MINE_SPENDABLE;
1585 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1587 if (keystore.GetCScript(scriptID, subscript)) {
1588 isminetype ret = IsMine(keystore, subscript);
1589 if (ret == MINE_SPENDABLE)
1596 // Only consider transactions "mine" if we own ALL the
1597 // keys involved. multi-signature transactions that are
1598 // partially owned (somebody else has a key that can spend
1599 // them) enable spend-out-from-under-you attacks, especially
1600 // in shared-wallet situations.
1601 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1602 if (HaveKeys(keys, keystore) == keys.size())
1603 return MINE_SPENDABLE;
1608 if (keystore.HaveWatchOnly(scriptPubKey))
1609 return MINE_WATCH_ONLY;
1613 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1615 vector<valtype> vSolutions;
1616 txnouttype whichType;
1617 if (!Solver(scriptPubKey, whichType, vSolutions))
1620 if (whichType == TX_PUBKEY)
1622 addressRet = CPubKey(vSolutions[0]).GetID();
1625 else if (whichType == TX_PUBKEYHASH)
1627 addressRet = CKeyID(uint160(vSolutions[0]));
1630 else if (whichType == TX_SCRIPTHASH)
1632 addressRet = CScriptID(uint160(vSolutions[0]));
1635 // Multisig txns have more than one address...
1639 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1641 const CKeyStore &keystore;
1642 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1643 std::vector<CKeyID> &vKeys;
1646 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1648 void Process(const CScript &script) {
1650 std::vector<CTxDestination> vDest;
1652 if (ExtractDestinations(script, type, vDest, nRequired)) {
1653 BOOST_FOREACH(const CTxDestination &dest, vDest)
1654 boost::apply_visitor(*this, dest);
1658 void operator()(const CKeyID &keyId) {
1659 if (keystore.HaveKey(keyId))
1660 vKeys.push_back(keyId);
1663 void operator()(const CScriptID &scriptId) {
1665 if (keystore.GetCScript(scriptId, script))
1669 void operator()(const CNoDestination &none) {}
1673 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1674 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1677 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1680 typeRet = TX_NONSTANDARD;
1681 vector<valtype> vSolutions;
1682 if (!Solver(scriptPubKey, typeRet, vSolutions))
1684 if (typeRet == TX_NULL_DATA)
1690 if (typeRet == TX_MULTISIG)
1692 nRequiredRet = vSolutions.front()[0];
1693 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1695 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1696 addressRet.push_back(address);
1702 if (typeRet == TX_PUBKEY_DROP)
1704 CTxDestination address;
1705 if (!ExtractDestination(scriptPubKey, address))
1707 addressRet.push_back(address);
1713 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1714 unsigned int flags, int nHashType)
1716 vector<vector<unsigned char> > stack, stackCopy;
1717 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1719 if (flags & SCRIPT_VERIFY_P2SH)
1721 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1726 if (CastToBool(stack.back()) == false)
1729 // Additional validation for spend-to-script-hash transactions:
1730 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1732 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1733 return false; // or validation fails
1735 // stackCopy cannot be empty here, because if it was the
1736 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1737 // an empty stack and the EvalScript above would return false.
1738 assert(!stackCopy.empty());
1740 const valtype& pubKeySerialized = stackCopy.back();
1741 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1742 popstack(stackCopy);
1744 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1746 if (stackCopy.empty())
1748 return CastToBool(stackCopy.back());
1754 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1756 assert(nIn < txTo.vin.size());
1757 CTxIn& txin = txTo.vin[nIn];
1759 // Leave out the signature from the hash, since a signature can't sign itself.
1760 // The checksig op will also drop the signatures from its hash.
1761 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1763 txnouttype whichType;
1764 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1767 if (whichType == TX_SCRIPTHASH)
1769 // Solver returns the subscript that need to be evaluated;
1770 // the final scriptSig is the signatures from that
1771 // and then the serialized subscript:
1772 CScript subscript = txin.scriptSig;
1774 // Recompute txn hash using subscript in place of scriptPubKey:
1775 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1779 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1780 // Append serialized subscript whether or not it is completely signed:
1781 txin.scriptSig << static_cast<valtype>(subscript);
1782 if (!fSolved) return false;
1786 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1789 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1791 assert(nIn < txTo.vin.size());
1792 CTxIn& txin = txTo.vin[nIn];
1793 assert(txin.prevout.n < txFrom.vout.size());
1794 assert(txin.prevout.hash == txFrom.GetHash());
1795 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1797 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1800 static CScript PushAll(const vector<valtype>& values)
1803 BOOST_FOREACH(const valtype& v, values)
1808 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1809 const vector<valtype>& vSolutions,
1810 vector<valtype>& sigs1, vector<valtype>& sigs2)
1812 // Combine all the signatures we've got:
1813 set<valtype> allsigs;
1814 BOOST_FOREACH(const valtype& v, sigs1)
1819 BOOST_FOREACH(const valtype& v, sigs2)
1825 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1826 assert(vSolutions.size() > 1);
1827 unsigned int nSigsRequired = vSolutions.front()[0];
1828 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1829 map<valtype, valtype> sigs;
1830 BOOST_FOREACH(const valtype& sig, allsigs)
1832 for (unsigned int i = 0; i < nPubKeys; i++)
1834 const valtype& pubkey = vSolutions[i+1];
1835 if (sigs.count(pubkey))
1836 continue; // Already got a sig for this pubkey
1838 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1845 // Now build a merged CScript:
1846 unsigned int nSigsHave = 0;
1847 CScript result; result << OP_0; // pop-one-too-many workaround
1848 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1850 if (sigs.count(vSolutions[i+1]))
1852 result << sigs[vSolutions[i+1]];
1856 // Fill any missing with OP_0:
1857 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1863 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1864 const txnouttype txType, const vector<valtype>& vSolutions,
1865 vector<valtype>& sigs1, vector<valtype>& sigs2)
1869 case TX_NONSTANDARD:
1871 // Don't know anything about this, assume bigger one is correct:
1872 if (sigs1.size() >= sigs2.size())
1873 return PushAll(sigs1);
1874 return PushAll(sigs2);
1876 case TX_PUBKEY_DROP:
1878 // Signatures are bigger than placeholders or empty scripts:
1879 if (sigs1.empty() || sigs1[0].empty())
1880 return PushAll(sigs2);
1881 return PushAll(sigs1);
1883 if (sigs1.empty() || sigs1.back().empty())
1884 return PushAll(sigs2);
1885 else if (sigs2.empty() || sigs2.back().empty())
1886 return PushAll(sigs1);
1889 // Recur to combine:
1890 valtype spk = sigs1.back();
1891 CScript pubKey2(spk.begin(), spk.end());
1894 vector<vector<unsigned char> > vSolutions2;
1895 Solver(pubKey2, txType2, vSolutions2);
1898 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1903 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1909 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1910 const CScript& scriptSig1, const CScript& scriptSig2)
1913 vector<vector<unsigned char> > vSolutions;
1914 Solver(scriptPubKey, txType, vSolutions);
1916 vector<valtype> stack1;
1917 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1918 vector<valtype> stack2;
1919 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1921 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1924 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1927 const_iterator pc = begin();
1928 opcodetype lastOpcode = OP_INVALIDOPCODE;
1932 if (!GetOp(pc, opcode))
1934 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1936 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1938 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1939 n += DecodeOP_N(lastOpcode);
1943 lastOpcode = opcode;
1948 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1950 if (!IsPayToScriptHash())
1951 return GetSigOpCount(true);
1953 // This is a pay-to-script-hash scriptPubKey;
1954 // get the last item that the scriptSig
1955 // pushes onto the stack:
1956 const_iterator pc = scriptSig.begin();
1957 vector<unsigned char> data;
1958 while (pc < scriptSig.end())
1961 if (!scriptSig.GetOp(pc, opcode, data))
1967 /// ... and return its opcount:
1968 CScript subscript(data.begin(), data.end());
1969 return subscript.GetSigOpCount(true);
1972 bool CScript::IsPayToScriptHash() const
1974 // Extra-fast test for pay-to-script-hash CScripts:
1975 return (this->size() == 23 &&
1976 this->at(0) == OP_HASH160 &&
1977 this->at(1) == 0x14 &&
1978 this->at(22) == OP_EQUAL);
1981 bool CScript::HasCanonicalPushes() const
1983 const_iterator pc = begin();
1987 std::vector<unsigned char> data;
1988 if (!GetOp(pc, opcode, data))
1992 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1993 // Could have used an OP_n code, rather than a 1-byte push.
1995 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1996 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1998 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1999 // Could have used an OP_PUSHDATA1.
2001 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2002 // Could have used an OP_PUSHDATA2.
2008 class CScriptVisitor : public boost::static_visitor<bool>
2013 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2015 bool operator()(const CNoDestination &dest) const {
2020 bool operator()(const CKeyID &keyID) const {
2022 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2026 bool operator()(const CScriptID &scriptID) const {
2028 *script << OP_HASH160 << scriptID << OP_EQUAL;
2033 void CScript::SetDestination(const CTxDestination& dest)
2035 boost::apply_visitor(CScriptVisitor(this), dest);
2038 void CScript::SetDestination(const CPubKey& R, CPubKey& pubKeyVariant)
2041 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2045 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
2049 *this << EncodeOP_N(nRequired);
2050 BOOST_FOREACH(const CKey& key, keys)
2051 *this << key.GetPubKey();
2052 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;