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";
152 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
155 case OP_TOALTSTACK : return "OP_TOALTSTACK";
156 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
157 case OP_2DROP : return "OP_2DROP";
158 case OP_2DUP : return "OP_2DUP";
159 case OP_3DUP : return "OP_3DUP";
160 case OP_2OVER : return "OP_2OVER";
161 case OP_2ROT : return "OP_2ROT";
162 case OP_2SWAP : return "OP_2SWAP";
163 case OP_IFDUP : return "OP_IFDUP";
164 case OP_DEPTH : return "OP_DEPTH";
165 case OP_DROP : return "OP_DROP";
166 case OP_DUP : return "OP_DUP";
167 case OP_NIP : return "OP_NIP";
168 case OP_OVER : return "OP_OVER";
169 case OP_PICK : return "OP_PICK";
170 case OP_ROLL : return "OP_ROLL";
171 case OP_ROT : return "OP_ROT";
172 case OP_SWAP : return "OP_SWAP";
173 case OP_TUCK : return "OP_TUCK";
176 case OP_CAT : return "OP_CAT";
177 case OP_SUBSTR : return "OP_SUBSTR";
178 case OP_LEFT : return "OP_LEFT";
179 case OP_RIGHT : return "OP_RIGHT";
180 case OP_SIZE : return "OP_SIZE";
183 case OP_INVERT : return "OP_INVERT";
184 case OP_AND : return "OP_AND";
185 case OP_OR : return "OP_OR";
186 case OP_XOR : return "OP_XOR";
187 case OP_EQUAL : return "OP_EQUAL";
188 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
189 case OP_RESERVED1 : return "OP_RESERVED1";
190 case OP_RESERVED2 : return "OP_RESERVED2";
193 case OP_1ADD : return "OP_1ADD";
194 case OP_1SUB : return "OP_1SUB";
195 case OP_2MUL : return "OP_2MUL";
196 case OP_2DIV : return "OP_2DIV";
197 case OP_NEGATE : return "OP_NEGATE";
198 case OP_ABS : return "OP_ABS";
199 case OP_NOT : return "OP_NOT";
200 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
201 case OP_ADD : return "OP_ADD";
202 case OP_SUB : return "OP_SUB";
203 case OP_MUL : return "OP_MUL";
204 case OP_DIV : return "OP_DIV";
205 case OP_MOD : return "OP_MOD";
206 case OP_LSHIFT : return "OP_LSHIFT";
207 case OP_RSHIFT : return "OP_RSHIFT";
208 case OP_BOOLAND : return "OP_BOOLAND";
209 case OP_BOOLOR : return "OP_BOOLOR";
210 case OP_NUMEQUAL : return "OP_NUMEQUAL";
211 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
212 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
213 case OP_LESSTHAN : return "OP_LESSTHAN";
214 case OP_GREATERTHAN : return "OP_GREATERTHAN";
215 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
216 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
217 case OP_MIN : return "OP_MIN";
218 case OP_MAX : return "OP_MAX";
219 case OP_WITHIN : return "OP_WITHIN";
222 case OP_RIPEMD160 : return "OP_RIPEMD160";
223 case OP_SHA1 : return "OP_SHA1";
224 case OP_SHA256 : return "OP_SHA256";
225 case OP_HASH160 : return "OP_HASH160";
226 case OP_HASH256 : return "OP_HASH256";
227 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
228 case OP_CHECKSIG : return "OP_CHECKSIG";
229 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
230 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
231 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
234 case OP_NOP1 : return "OP_NOP1";
235 case OP_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_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())
522 case OP_CHECKSEQUENCEVERIFY:
524 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY))
525 // treat as a NOP if not enabled
527 if (stack.size() < 1)
529 const CBigNum nInvSequence = CastToBigNum(stacktop(-1));
531 // In the rare event that the argument may be < 0 due to
532 // some arithmetic being done first, you can always use
533 // 0 MAX CHECKSEQUENCEVERIFY.
534 if (nInvSequence < 0)
535 return false; // negative nSequence is senseless
537 // Relative lock times are supported by comparing the passed
538 // in lock time to the sequence number of the input. All other
539 // logic is the same, all that differs is what we are comparing
541 int64_t txToLockTime = (int64_t)~txTo.vin[nIn].nSequence;
542 if (txToLockTime >= SEQUENCE_THRESHOLD)
546 (txToLockTime < LOCKTIME_THRESHOLD && nInvSequence < LOCKTIME_THRESHOLD) ||
547 (txToLockTime >= LOCKTIME_THRESHOLD && nInvSequence >= LOCKTIME_THRESHOLD)
551 // Now that we know we're comparing apples-to-apples, the
552 // comparison is a simple numeric one.
553 if (nInvSequence > txToLockTime)
564 if (stack.size() < 1)
566 altstack.push_back(stacktop(-1));
571 case OP_FROMALTSTACK:
573 if (altstack.size() < 1)
575 stack.push_back(altstacktop(-1));
583 if (stack.size() < 2)
592 // (x1 x2 -- x1 x2 x1 x2)
593 if (stack.size() < 2)
595 valtype vch1 = stacktop(-2);
596 valtype vch2 = stacktop(-1);
597 stack.push_back(vch1);
598 stack.push_back(vch2);
604 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
605 if (stack.size() < 3)
607 valtype vch1 = stacktop(-3);
608 valtype vch2 = stacktop(-2);
609 valtype vch3 = stacktop(-1);
610 stack.push_back(vch1);
611 stack.push_back(vch2);
612 stack.push_back(vch3);
618 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
619 if (stack.size() < 4)
621 valtype vch1 = stacktop(-4);
622 valtype vch2 = stacktop(-3);
623 stack.push_back(vch1);
624 stack.push_back(vch2);
630 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
631 if (stack.size() < 6)
633 valtype vch1 = stacktop(-6);
634 valtype vch2 = stacktop(-5);
635 stack.erase(stack.end()-6, stack.end()-4);
636 stack.push_back(vch1);
637 stack.push_back(vch2);
643 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
644 if (stack.size() < 4)
646 swap(stacktop(-4), stacktop(-2));
647 swap(stacktop(-3), stacktop(-1));
654 if (stack.size() < 1)
656 valtype vch = stacktop(-1);
658 stack.push_back(vch);
665 CBigNum bn((uint16_t) stack.size());
666 stack.push_back(bn.getvch());
673 if (stack.size() < 1)
682 if (stack.size() < 1)
684 valtype vch = stacktop(-1);
685 stack.push_back(vch);
692 if (stack.size() < 2)
694 stack.erase(stack.end() - 2);
700 // (x1 x2 -- x1 x2 x1)
701 if (stack.size() < 2)
703 valtype vch = stacktop(-2);
704 stack.push_back(vch);
711 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
712 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
713 if (stack.size() < 2)
715 int n = CastToBigNum(stacktop(-1)).getint32();
717 if (n < 0 || n >= (int)stack.size())
719 valtype vch = stacktop(-n-1);
720 if (opcode == OP_ROLL)
721 stack.erase(stack.end()-n-1);
722 stack.push_back(vch);
728 // (x1 x2 x3 -- x2 x3 x1)
729 // x2 x1 x3 after first swap
730 // x2 x3 x1 after second swap
731 if (stack.size() < 3)
733 swap(stacktop(-3), stacktop(-2));
734 swap(stacktop(-2), stacktop(-1));
741 if (stack.size() < 2)
743 swap(stacktop(-2), stacktop(-1));
749 // (x1 x2 -- x2 x1 x2)
750 if (stack.size() < 2)
752 valtype vch = stacktop(-1);
753 stack.insert(stack.end()-2, vch);
761 if (stack.size() < 1)
763 CBigNum bn((uint16_t) stacktop(-1).size());
764 stack.push_back(bn.getvch());
774 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
777 if (stack.size() < 2)
779 valtype& vch1 = stacktop(-2);
780 valtype& vch2 = stacktop(-1);
781 bool fEqual = (vch1 == vch2);
782 // OP_NOTEQUAL is disabled because it would be too easy to say
783 // something like n != 1 and have some wiseguy pass in 1 with extra
784 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
785 //if (opcode == OP_NOTEQUAL)
789 stack.push_back(fEqual ? vchTrue : vchFalse);
790 if (opcode == OP_EQUALVERIFY)
812 if (stack.size() < 1)
814 CBigNum bn = CastToBigNum(stacktop(-1));
817 case OP_1ADD: bn += bnOne; break;
818 case OP_1SUB: bn -= bnOne; break;
819 case OP_NEGATE: bn = -bn; break;
820 case OP_ABS: if (bn < bnZero) bn = -bn; break;
821 case OP_NOT: bn = (bn == bnZero); break;
822 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
823 default: assert(!"invalid opcode"); break;
826 stack.push_back(bn.getvch());
835 case OP_NUMEQUALVERIFY:
839 case OP_LESSTHANOREQUAL:
840 case OP_GREATERTHANOREQUAL:
845 if (stack.size() < 2)
847 CBigNum bn1 = CastToBigNum(stacktop(-2));
848 CBigNum bn2 = CastToBigNum(stacktop(-1));
860 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
861 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
862 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
863 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
864 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
865 case OP_LESSTHAN: bn = (bn1 < bn2); break;
866 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
867 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
868 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
869 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
870 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
871 default: assert(!"invalid opcode"); break;
875 stack.push_back(bn.getvch());
877 if (opcode == OP_NUMEQUALVERIFY)
879 if (CastToBool(stacktop(-1)))
889 // (x min max -- out)
890 if (stack.size() < 3)
892 CBigNum bn1 = CastToBigNum(stacktop(-3));
893 CBigNum bn2 = CastToBigNum(stacktop(-2));
894 CBigNum bn3 = CastToBigNum(stacktop(-1));
895 bool fValue = (bn2 <= bn1 && bn1 < bn3);
899 stack.push_back(fValue ? vchTrue : vchFalse);
914 if (stack.size() < 1)
916 valtype& vch = stacktop(-1);
917 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
918 if (opcode == OP_RIPEMD160)
919 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
920 else if (opcode == OP_SHA1)
921 SHA1(&vch[0], vch.size(), &vchHash[0]);
922 else if (opcode == OP_SHA256)
923 SHA256(&vch[0], vch.size(), &vchHash[0]);
924 else if (opcode == OP_HASH160)
926 uint160 hash160 = Hash160(vch);
927 memcpy(&vchHash[0], &hash160, sizeof(hash160));
929 else if (opcode == OP_HASH256)
931 uint256 hash = Hash(vch.begin(), vch.end());
932 memcpy(&vchHash[0], &hash, sizeof(hash));
935 stack.push_back(vchHash);
939 case OP_CODESEPARATOR:
941 // Hash starts after the code separator
947 case OP_CHECKSIGVERIFY:
949 // (sig pubkey -- bool)
950 if (stack.size() < 2)
953 valtype& vchSig = stacktop(-2);
954 valtype& vchPubKey = stacktop(-1);
957 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
958 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
960 // Subset of script starting at the most recent codeseparator
961 CScript scriptCode(pbegincodehash, pend);
963 // Drop the signature, since there's no way for a signature to sign itself
964 scriptCode.FindAndDelete(CScript(vchSig));
966 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
967 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
971 stack.push_back(fSuccess ? vchTrue : vchFalse);
972 if (opcode == OP_CHECKSIGVERIFY)
982 case OP_CHECKMULTISIG:
983 case OP_CHECKMULTISIGVERIFY:
985 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
988 if ((int)stack.size() < i)
991 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
992 if (nKeysCount < 0 || nKeysCount > 20)
994 nOpCount += nKeysCount;
999 if ((int)stack.size() < i)
1002 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1003 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1007 if ((int)stack.size() < i)
1010 // Subset of script starting at the most recent codeseparator
1011 CScript scriptCode(pbegincodehash, pend);
1013 // Drop the signatures, since there's no way for a signature to sign itself
1014 for (int k = 0; k < nSigsCount; k++)
1016 valtype& vchSig = stacktop(-isig-k);
1017 scriptCode.FindAndDelete(CScript(vchSig));
1020 bool fSuccess = true;
1021 while (fSuccess && nSigsCount > 0)
1023 valtype& vchSig = stacktop(-isig);
1024 valtype& vchPubKey = stacktop(-ikey);
1027 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1028 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1037 // If there are more signatures left than keys left,
1038 // then too many signatures have failed
1039 if (nSigsCount > nKeysCount)
1046 // A bug causes CHECKMULTISIG to consume one extra argument
1047 // whose contents were not checked in any way.
1049 // Unfortunately this is a potential source of mutability,
1050 // so optionally verify it is exactly equal to zero prior
1051 // to removing it from the stack.
1052 if (stack.size() < 1)
1054 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1055 return error("CHECKMULTISIG dummy argument not null");
1058 stack.push_back(fSuccess ? vchTrue : vchFalse);
1060 if (opcode == OP_CHECKMULTISIGVERIFY)
1075 if (stack.size() + altstack.size() > 1000)
1085 if (!vfExec.empty())
1099 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1101 if (nIn >= txTo.vin.size())
1103 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1106 CTransaction txTmp(txTo);
1108 // In case concatenating two scripts ends up with two codeseparators,
1109 // or an extra one at the end, this prevents all those possible incompatibilities.
1110 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1112 // Blank out other inputs' signatures
1113 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1114 txTmp.vin[i].scriptSig = CScript();
1115 txTmp.vin[nIn].scriptSig = scriptCode;
1117 // Blank out some of the outputs
1118 if ((nHashType & 0x1f) == SIGHASH_NONE)
1123 // Let the others update at will
1124 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1126 txTmp.vin[i].nSequence = 0;
1128 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1130 // Only lock-in the txout payee at same index as txin
1131 unsigned int nOut = nIn;
1132 if (nOut >= txTmp.vout.size())
1134 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1137 txTmp.vout.resize(nOut+1);
1138 for (unsigned int i = 0; i < nOut; i++)
1139 txTmp.vout[i].SetNull();
1141 // Let the others update at will
1142 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1144 txTmp.vin[i].nSequence = 0;
1147 // Blank out other inputs completely, not recommended for open transactions
1148 if (nHashType & SIGHASH_ANYONECANPAY)
1150 txTmp.vin[0] = txTmp.vin[nIn];
1151 txTmp.vin.resize(1);
1154 // Serialize and hash
1155 CDataStream ss(SER_GETHASH, 0);
1157 ss << txTmp << nHashType;
1158 return Hash(ss.begin(), ss.end());
1162 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1163 // twice for every transaction (once when accepted into memory pool, and
1164 // again when accepted into the block chain)
1166 class CSignatureCache
1169 // sigdata_type is (signature hash, signature, public key):
1170 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1171 std::set< sigdata_type> setValid;
1172 boost::shared_mutex cs_sigcache;
1176 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1178 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1180 sigdata_type k(hash, vchSig, pubKey);
1181 std::set<sigdata_type>::iterator mi = setValid.find(k);
1182 if (mi != setValid.end())
1187 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1189 // DoS prevention: limit cache size to less than 10MB
1190 // (~200 bytes per cache entry times 50,000 entries)
1191 // Since there are a maximum of 20,000 signature operations per block
1192 // 50,000 is a reasonable default.
1193 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1194 if (nMaxCacheSize <= 0) return;
1196 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1198 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1200 // Evict a random entry. Random because that helps
1201 // foil would-be DoS attackers who might try to pre-generate
1202 // and re-use a set of valid signatures just-slightly-greater
1203 // than our cache size.
1204 uint256 randomHash = GetRandHash();
1205 std::vector<unsigned char> unused;
1206 std::set<sigdata_type>::iterator it =
1207 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1208 if (it == setValid.end())
1209 it = setValid.begin();
1210 setValid.erase(*it);
1213 sigdata_type k(hash, vchSig, pubKey);
1218 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1219 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1221 static CSignatureCache signatureCache;
1224 if (!key.SetPubKey(vchPubKey))
1226 CPubKey pubkey = key.GetPubKey();
1227 if (!pubkey.IsValid())
1230 // Hash type is one byte tacked on to the end of the signature
1234 nHashType = vchSig.back();
1235 else if (nHashType != vchSig.back())
1239 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1241 if (signatureCache.Get(sighash, vchSig, pubkey))
1244 if (!key.Verify(sighash, vchSig))
1247 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1248 signatureCache.Set(sighash, vchSig, pubkey);
1261 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1263 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1266 static map<txnouttype, CScript> mTemplates;
1267 if (mTemplates.empty())
1269 // Standard tx, sender provides pubkey, receiver adds signature
1270 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1272 if (fTestNet || GetTime() > SMALLDATA_SWITCH_TIME)
1274 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1275 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1278 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1279 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1281 // Sender provides N pubkeys, receivers provides M signatures
1282 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1284 // Empty, provably prunable, data-carrying output
1285 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1288 vSolutionsRet.clear();
1290 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1291 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1292 if (scriptPubKey.IsPayToScriptHash())
1294 typeRet = TX_SCRIPTHASH;
1295 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1296 vSolutionsRet.push_back(hashBytes);
1300 // Provably prunable, data-carrying output
1302 // So long as script passes the IsUnspendable() test and all but the first
1303 // byte passes the IsPushOnly() test we don't care what exactly is in the
1305 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1306 typeRet = TX_NULL_DATA;
1311 const CScript& script1 = scriptPubKey;
1312 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1314 const CScript& script2 = tplate.second;
1315 vSolutionsRet.clear();
1317 opcodetype opcode1, opcode2;
1318 vector<unsigned char> vch1, vch2;
1321 CScript::const_iterator pc1 = script1.begin();
1322 CScript::const_iterator pc2 = script2.begin();
1325 if (pc1 == script1.end() && pc2 == script2.end())
1328 typeRet = tplate.first;
1329 if (typeRet == TX_MULTISIG)
1331 // Additional checks for TX_MULTISIG:
1332 unsigned char m = vSolutionsRet.front()[0];
1333 unsigned char n = vSolutionsRet.back()[0];
1334 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1339 if (!script1.GetOp(pc1, opcode1, vch1))
1341 if (!script2.GetOp(pc2, opcode2, vch2))
1344 // Template matching opcodes:
1345 if (opcode2 == OP_PUBKEYS)
1347 while (vch1.size() >= 33 && vch1.size() <= 120)
1349 vSolutionsRet.push_back(vch1);
1350 if (!script1.GetOp(pc1, opcode1, vch1))
1353 if (!script2.GetOp(pc2, opcode2, vch2))
1355 // Normal situation is to fall through
1356 // to other if/else statements
1359 if (opcode2 == OP_PUBKEY)
1361 if (vch1.size() < 33 || vch1.size() > 120)
1363 vSolutionsRet.push_back(vch1);
1365 else if (opcode2 == OP_PUBKEYHASH)
1367 if (vch1.size() != sizeof(uint160))
1369 vSolutionsRet.push_back(vch1);
1371 else if (opcode2 == OP_SMALLINTEGER)
1372 { // Single-byte small integer pushed onto vSolutions
1373 if (opcode1 == OP_0 ||
1374 (opcode1 >= OP_1 && opcode1 <= OP_16))
1376 char n = (char)CScript::DecodeOP_N(opcode1);
1377 vSolutionsRet.push_back(valtype(1, n));
1382 else if (opcode2 == OP_INTEGER)
1383 { // Up to four-byte integer pushed onto vSolutions
1386 CBigNum bnVal = CastToBigNum(vch1);
1388 break; // It's better to use OP_0 ... OP_16 for small integers.
1389 vSolutionsRet.push_back(vch1);
1396 else if (opcode2 == OP_SMALLDATA)
1398 // small pushdata, <= 1024 bytes
1399 if (vch1.size() > (GetTime() > SMALLDATA_SWITCH_TIME ? 1024 : 80))
1402 else if (opcode1 != opcode2 || vch1 != vch2)
1404 // Others must match exactly
1410 vSolutionsRet.clear();
1411 typeRet = TX_NONSTANDARD;
1416 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1419 if (!keystore.GetKey(address, key))
1422 vector<unsigned char> vchSig;
1423 if (!key.Sign(hash, vchSig))
1425 vchSig.push_back((unsigned char)nHashType);
1426 scriptSigRet << vchSig;
1431 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1434 if (!keystore.CreatePrivKey(pubKey, R, key))
1437 vector<unsigned char> vchSig;
1438 if (!key.Sign(hash, vchSig))
1440 vchSig.push_back((unsigned char)nHashType);
1441 scriptSigRet << vchSig;
1446 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1449 int nRequired = multisigdata.front()[0];
1450 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1452 const valtype& pubkey = multisigdata[i];
1453 CKeyID keyID = CPubKey(pubkey).GetID();
1454 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1457 return nSigned==nRequired;
1461 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1462 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1463 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1464 // Returns false if scriptPubKey could not be completely satisfied.
1466 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1467 CScript& scriptSigRet, txnouttype& whichTypeRet)
1469 scriptSigRet.clear();
1471 vector<valtype> vSolutions;
1472 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1476 switch (whichTypeRet)
1478 case TX_NONSTANDARD:
1482 keyID = CPubKey(vSolutions[0]).GetID();
1483 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1484 case TX_PUBKEY_DROP:
1486 CPubKey key = CPubKey(vSolutions[0]);
1487 CPubKey R = CPubKey(vSolutions[1]);
1488 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1491 keyID = CKeyID(uint160(vSolutions[0]));
1492 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1497 keystore.GetPubKey(keyID, vch);
1498 scriptSigRet << vch;
1502 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1505 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1506 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1511 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1515 case TX_NONSTANDARD:
1520 case TX_PUBKEY_DROP:
1525 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1527 return vSolutions[0][0] + 1;
1529 return 1; // doesn't include args needed by the script
1534 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1536 vector<valtype> vSolutions;
1537 if (!Solver(scriptPubKey, whichType, vSolutions))
1540 if (whichType == TX_MULTISIG)
1542 unsigned char m = vSolutions.front()[0];
1543 unsigned char n = vSolutions.back()[0];
1544 // Support up to x-of-3 multisig txns as standard
1551 return whichType != TX_NONSTANDARD;
1555 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1557 unsigned int nResult = 0;
1558 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1560 CKeyID keyID = CPubKey(pubkey).GetID();
1561 if (keystore.HaveKey(keyID))
1568 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1571 const CKeyStore *keystore;
1573 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1574 bool operator()(const CNoDestination &dest) const { return false; }
1575 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1576 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1579 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1582 script.SetDestination(dest);
1583 return IsMine(keystore, script);
1586 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1588 vector<valtype> vSolutions;
1589 txnouttype whichType;
1590 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1591 if (keystore.HaveWatchOnly(scriptPubKey))
1592 return MINE_WATCH_ONLY;
1599 case TX_NONSTANDARD:
1603 keyID = CPubKey(vSolutions[0]).GetID();
1604 if (keystore.HaveKey(keyID))
1605 return MINE_SPENDABLE;
1607 case TX_PUBKEY_DROP:
1609 CPubKey key = CPubKey(vSolutions[0]);
1610 CPubKey R = CPubKey(vSolutions[1]);
1611 if (keystore.CheckOwnership(key, R))
1612 return MINE_SPENDABLE;
1616 keyID = CKeyID(uint160(vSolutions[0]));
1617 if (keystore.HaveKey(keyID))
1618 return MINE_SPENDABLE;
1622 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1624 if (keystore.GetCScript(scriptID, subscript)) {
1625 isminetype ret = IsMine(keystore, subscript);
1626 if (ret == MINE_SPENDABLE)
1633 // Only consider transactions "mine" if we own ALL the
1634 // keys involved. multi-signature transactions that are
1635 // partially owned (somebody else has a key that can spend
1636 // them) enable spend-out-from-under-you attacks, especially
1637 // in shared-wallet situations.
1638 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1639 if (HaveKeys(keys, keystore) == keys.size())
1640 return MINE_SPENDABLE;
1645 if (keystore.HaveWatchOnly(scriptPubKey))
1646 return MINE_WATCH_ONLY;
1650 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1652 vector<valtype> vSolutions;
1653 txnouttype whichType;
1654 if (!Solver(scriptPubKey, whichType, vSolutions))
1657 if (whichType == TX_PUBKEY)
1659 addressRet = CPubKey(vSolutions[0]).GetID();
1662 else if (whichType == TX_PUBKEYHASH)
1664 addressRet = CKeyID(uint160(vSolutions[0]));
1667 else if (whichType == TX_SCRIPTHASH)
1669 addressRet = CScriptID(uint160(vSolutions[0]));
1672 // Multisig txns have more than one address...
1676 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1678 const CKeyStore &keystore;
1679 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1680 std::vector<CKeyID> &vKeys;
1683 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1685 void Process(const CScript &script) {
1687 std::vector<CTxDestination> vDest;
1689 if (ExtractDestinations(script, type, vDest, nRequired)) {
1690 BOOST_FOREACH(const CTxDestination &dest, vDest)
1691 boost::apply_visitor(*this, dest);
1695 void operator()(const CKeyID &keyId) {
1696 if (keystore.HaveKey(keyId))
1697 vKeys.push_back(keyId);
1700 void operator()(const CScriptID &scriptId) {
1702 if (keystore.GetCScript(scriptId, script))
1706 void operator()(const CNoDestination &none) {}
1710 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1711 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1714 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1717 typeRet = TX_NONSTANDARD;
1718 vector<valtype> vSolutions;
1719 if (!Solver(scriptPubKey, typeRet, vSolutions))
1721 if (typeRet == TX_NULL_DATA)
1727 if (typeRet == TX_MULTISIG)
1729 nRequiredRet = vSolutions.front()[0];
1730 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1732 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1733 addressRet.push_back(address);
1739 if (typeRet == TX_PUBKEY_DROP)
1741 CTxDestination address;
1742 if (!ExtractDestination(scriptPubKey, address))
1744 addressRet.push_back(address);
1750 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1751 unsigned int flags, int nHashType)
1753 vector<vector<unsigned char> > stack, stackCopy;
1754 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1756 if (flags & SCRIPT_VERIFY_P2SH)
1758 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1763 if (CastToBool(stack.back()) == false)
1766 // Additional validation for spend-to-script-hash transactions:
1767 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1769 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1770 return false; // or validation fails
1772 // stackCopy cannot be empty here, because if it was the
1773 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1774 // an empty stack and the EvalScript above would return false.
1775 assert(!stackCopy.empty());
1777 const valtype& pubKeySerialized = stackCopy.back();
1778 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1779 popstack(stackCopy);
1781 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1783 if (stackCopy.empty())
1785 return CastToBool(stackCopy.back());
1791 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1793 assert(nIn < txTo.vin.size());
1794 CTxIn& txin = txTo.vin[nIn];
1796 // Leave out the signature from the hash, since a signature can't sign itself.
1797 // The checksig op will also drop the signatures from its hash.
1798 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1800 txnouttype whichType;
1801 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1804 if (whichType == TX_SCRIPTHASH)
1806 // Solver returns the subscript that need to be evaluated;
1807 // the final scriptSig is the signatures from that
1808 // and then the serialized subscript:
1809 CScript subscript = txin.scriptSig;
1811 // Recompute txn hash using subscript in place of scriptPubKey:
1812 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1816 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1817 // Append serialized subscript whether or not it is completely signed:
1818 txin.scriptSig << static_cast<valtype>(subscript);
1819 if (!fSolved) return false;
1823 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1826 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1828 assert(nIn < txTo.vin.size());
1829 CTxIn& txin = txTo.vin[nIn];
1830 assert(txin.prevout.n < txFrom.vout.size());
1831 assert(txin.prevout.hash == txFrom.GetHash());
1832 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1834 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1837 static CScript PushAll(const vector<valtype>& values)
1840 BOOST_FOREACH(const valtype& v, values)
1845 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1846 const vector<valtype>& vSolutions,
1847 vector<valtype>& sigs1, vector<valtype>& sigs2)
1849 // Combine all the signatures we've got:
1850 set<valtype> allsigs;
1851 BOOST_FOREACH(const valtype& v, sigs1)
1856 BOOST_FOREACH(const valtype& v, sigs2)
1862 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1863 assert(vSolutions.size() > 1);
1864 unsigned int nSigsRequired = vSolutions.front()[0];
1865 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1866 map<valtype, valtype> sigs;
1867 BOOST_FOREACH(const valtype& sig, allsigs)
1869 for (unsigned int i = 0; i < nPubKeys; i++)
1871 const valtype& pubkey = vSolutions[i+1];
1872 if (sigs.count(pubkey))
1873 continue; // Already got a sig for this pubkey
1875 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1882 // Now build a merged CScript:
1883 unsigned int nSigsHave = 0;
1884 CScript result; result << OP_0; // pop-one-too-many workaround
1885 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1887 if (sigs.count(vSolutions[i+1]))
1889 result << sigs[vSolutions[i+1]];
1893 // Fill any missing with OP_0:
1894 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1900 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1901 const txnouttype txType, const vector<valtype>& vSolutions,
1902 vector<valtype>& sigs1, vector<valtype>& sigs2)
1906 case TX_NONSTANDARD:
1908 // Don't know anything about this, assume bigger one is correct:
1909 if (sigs1.size() >= sigs2.size())
1910 return PushAll(sigs1);
1911 return PushAll(sigs2);
1913 case TX_PUBKEY_DROP:
1915 // Signatures are bigger than placeholders or empty scripts:
1916 if (sigs1.empty() || sigs1[0].empty())
1917 return PushAll(sigs2);
1918 return PushAll(sigs1);
1920 if (sigs1.empty() || sigs1.back().empty())
1921 return PushAll(sigs2);
1922 else if (sigs2.empty() || sigs2.back().empty())
1923 return PushAll(sigs1);
1926 // Recur to combine:
1927 valtype spk = sigs1.back();
1928 CScript pubKey2(spk.begin(), spk.end());
1931 vector<vector<unsigned char> > vSolutions2;
1932 Solver(pubKey2, txType2, vSolutions2);
1935 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1940 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1946 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1947 const CScript& scriptSig1, const CScript& scriptSig2)
1950 vector<vector<unsigned char> > vSolutions;
1951 Solver(scriptPubKey, txType, vSolutions);
1953 vector<valtype> stack1;
1954 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1955 vector<valtype> stack2;
1956 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1958 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1961 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1964 const_iterator pc = begin();
1965 opcodetype lastOpcode = OP_INVALIDOPCODE;
1969 if (!GetOp(pc, opcode))
1971 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1973 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1975 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1976 n += DecodeOP_N(lastOpcode);
1980 lastOpcode = opcode;
1985 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1987 if (!IsPayToScriptHash())
1988 return GetSigOpCount(true);
1990 // This is a pay-to-script-hash scriptPubKey;
1991 // get the last item that the scriptSig
1992 // pushes onto the stack:
1993 const_iterator pc = scriptSig.begin();
1994 vector<unsigned char> data;
1995 while (pc < scriptSig.end())
1998 if (!scriptSig.GetOp(pc, opcode, data))
2004 /// ... and return its opcount:
2005 CScript subscript(data.begin(), data.end());
2006 return subscript.GetSigOpCount(true);
2009 bool CScript::IsPayToScriptHash() const
2011 // Extra-fast test for pay-to-script-hash CScripts:
2012 return (this->size() == 23 &&
2013 this->at(0) == OP_HASH160 &&
2014 this->at(1) == 0x14 &&
2015 this->at(22) == OP_EQUAL);
2018 bool CScript::HasCanonicalPushes() const
2020 const_iterator pc = begin();
2024 std::vector<unsigned char> data;
2025 if (!GetOp(pc, opcode, data))
2029 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2030 // Could have used an OP_n code, rather than a 1-byte push.
2032 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2033 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2035 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2036 // Could have used an OP_PUSHDATA1.
2038 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2039 // Could have used an OP_PUSHDATA2.
2045 class CScriptVisitor : public boost::static_visitor<bool>
2050 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2052 bool operator()(const CNoDestination &dest) const {
2057 bool operator()(const CKeyID &keyID) const {
2059 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2063 bool operator()(const CScriptID &scriptID) const {
2065 *script << OP_HASH160 << scriptID << OP_EQUAL;
2070 void CScript::SetDestination(const CTxDestination& dest)
2072 boost::apply_visitor(CScriptVisitor(this), dest);
2075 void CScript::SetDestination(const CPubKey& R, CPubKey& pubKeyVariant)
2078 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2082 void CScript::SetMultisig(int nRequired, const std::vector<CKey>& keys)
2086 *this << EncodeOP_N(nRequired);
2087 BOOST_FOREACH(const CKey& key, keys)
2088 *this << key.GetPubKey();
2089 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;