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.
16 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
18 static const valtype vchFalse(0);
19 static const valtype vchZero(0);
20 static const valtype vchTrue(1, 1);
21 static const CBigNum bnZero(0);
22 static const CBigNum bnOne(1);
23 static const CBigNum bnFalse(0);
24 static const CBigNum bnTrue(1);
25 static const size_t nMaxNumSize = 4;
28 CBigNum CastToBigNum(const valtype& vch)
30 if (vch.size() > nMaxNumSize)
31 throw runtime_error("CastToBigNum() : overflow");
32 // Get rid of extra leading zeros
33 return CBigNum(CBigNum(vch).getvch());
36 bool CastToBool(const valtype& vch)
38 for (unsigned int i = 0; i < vch.size(); i++)
42 // Can be negative zero
43 if (i == vch.size()-1 && vch[i] == 0x80)
52 // WARNING: This does not work as expected for signed integers; the sign-bit
53 // is left in place as the integer is zero-extended. The correct behavior
54 // would be to move the most significant bit of the last byte during the
55 // resize process. MakeSameSize() is currently only used by the disabled
56 // opcodes OP_AND, OP_OR, and OP_XOR.
58 void MakeSameSize(valtype& vch1, valtype& vch2)
60 // Lengthen the shorter one
61 if (vch1.size() < vch2.size())
63 // +unsigned char msb = vch1[vch1.size()-1];
64 // +vch1[vch1.size()-1] &= 0x7f;
65 // vch1.resize(vch2.size(), 0);
66 // +vch1[vch1.size()-1] = msb;
67 vch1.resize(vch2.size(), 0);
68 if (vch2.size() < vch1.size())
70 // +unsigned char msb = vch2[vch2.size()-1];
71 // +vch2[vch2.size()-1] &= 0x7f;
72 // vch2.resize(vch1.size(), 0);
73 // +vch2[vch2.size()-1] = msb;
74 vch2.resize(vch1.size(), 0);
80 // Script is a stack machine (like Forth) that evaluates a predicate
81 // returning a bool indicating valid or not. There are no loops.
83 #define stacktop(i) (stack.at(stack.size()+(i)))
84 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
85 static inline void popstack(vector<valtype>& stack)
88 throw runtime_error("popstack() : stack empty");
93 const char* GetTxnOutputType(txnouttype t)
97 case TX_NONSTANDARD: return "nonstandard";
98 case TX_PUBKEY: return "pubkey";
99 case TX_PUBKEY_DROP: return "pubkeydrop";
100 case TX_PUBKEYHASH: return "pubkeyhash";
101 case TX_SCRIPTHASH: return "scripthash";
102 case TX_MULTISIG: return "multisig";
103 case TX_NULL_DATA: return "nulldata";
109 const char* GetOpName(opcodetype opcode)
114 case OP_0 : return "0";
115 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
116 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
117 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
118 case OP_1NEGATE : return "-1";
119 case OP_RESERVED : return "OP_RESERVED";
120 case OP_1 : return "1";
121 case OP_2 : return "2";
122 case OP_3 : return "3";
123 case OP_4 : return "4";
124 case OP_5 : return "5";
125 case OP_6 : return "6";
126 case OP_7 : return "7";
127 case OP_8 : return "8";
128 case OP_9 : return "9";
129 case OP_10 : return "10";
130 case OP_11 : return "11";
131 case OP_12 : return "12";
132 case OP_13 : return "13";
133 case OP_14 : return "14";
134 case OP_15 : return "15";
135 case OP_16 : return "16";
138 case OP_NOP : return "OP_NOP";
139 case OP_VER : return "OP_VER";
140 case OP_IF : return "OP_IF";
141 case OP_NOTIF : return "OP_NOTIF";
142 case OP_VERIF : return "OP_VERIF";
143 case OP_VERNOTIF : return "OP_VERNOTIF";
144 case OP_ELSE : return "OP_ELSE";
145 case OP_ENDIF : return "OP_ENDIF";
146 case OP_VERIFY : return "OP_VERIFY";
147 case OP_RETURN : return "OP_RETURN";
148 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
149 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
152 case OP_TOALTSTACK : return "OP_TOALTSTACK";
153 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
154 case OP_2DROP : return "OP_2DROP";
155 case OP_2DUP : return "OP_2DUP";
156 case OP_3DUP : return "OP_3DUP";
157 case OP_2OVER : return "OP_2OVER";
158 case OP_2ROT : return "OP_2ROT";
159 case OP_2SWAP : return "OP_2SWAP";
160 case OP_IFDUP : return "OP_IFDUP";
161 case OP_DEPTH : return "OP_DEPTH";
162 case OP_DROP : return "OP_DROP";
163 case OP_DUP : return "OP_DUP";
164 case OP_NIP : return "OP_NIP";
165 case OP_OVER : return "OP_OVER";
166 case OP_PICK : return "OP_PICK";
167 case OP_ROLL : return "OP_ROLL";
168 case OP_ROT : return "OP_ROT";
169 case OP_SWAP : return "OP_SWAP";
170 case OP_TUCK : return "OP_TUCK";
173 case OP_CAT : return "OP_CAT";
174 case OP_SUBSTR : return "OP_SUBSTR";
175 case OP_LEFT : return "OP_LEFT";
176 case OP_RIGHT : return "OP_RIGHT";
177 case OP_SIZE : return "OP_SIZE";
180 case OP_INVERT : return "OP_INVERT";
181 case OP_AND : return "OP_AND";
182 case OP_OR : return "OP_OR";
183 case OP_XOR : return "OP_XOR";
184 case OP_EQUAL : return "OP_EQUAL";
185 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
186 case OP_RESERVED1 : return "OP_RESERVED1";
187 case OP_RESERVED2 : return "OP_RESERVED2";
190 case OP_1ADD : return "OP_1ADD";
191 case OP_1SUB : return "OP_1SUB";
192 case OP_2MUL : return "OP_2MUL";
193 case OP_2DIV : return "OP_2DIV";
194 case OP_NEGATE : return "OP_NEGATE";
195 case OP_ABS : return "OP_ABS";
196 case OP_NOT : return "OP_NOT";
197 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
198 case OP_ADD : return "OP_ADD";
199 case OP_SUB : return "OP_SUB";
200 case OP_MUL : return "OP_MUL";
201 case OP_DIV : return "OP_DIV";
202 case OP_MOD : return "OP_MOD";
203 case OP_LSHIFT : return "OP_LSHIFT";
204 case OP_RSHIFT : return "OP_RSHIFT";
205 case OP_BOOLAND : return "OP_BOOLAND";
206 case OP_BOOLOR : return "OP_BOOLOR";
207 case OP_NUMEQUAL : return "OP_NUMEQUAL";
208 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
209 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
210 case OP_LESSTHAN : return "OP_LESSTHAN";
211 case OP_GREATERTHAN : return "OP_GREATERTHAN";
212 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
213 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
214 case OP_MIN : return "OP_MIN";
215 case OP_MAX : return "OP_MAX";
216 case OP_WITHIN : return "OP_WITHIN";
219 case OP_RIPEMD160 : return "OP_RIPEMD160";
220 case OP_SHA1 : return "OP_SHA1";
221 case OP_SHA256 : return "OP_SHA256";
222 case OP_HASH160 : return "OP_HASH160";
223 case OP_HASH256 : return "OP_HASH256";
224 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
225 case OP_CHECKSIG : return "OP_CHECKSIG";
226 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
227 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
228 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
231 case OP_NOP1 : return "OP_NOP1";
232 case OP_NOP4 : return "OP_NOP4";
233 case OP_NOP5 : return "OP_NOP5";
234 case OP_NOP6 : return "OP_NOP6";
235 case OP_NOP7 : return "OP_NOP7";
236 case OP_NOP8 : return "OP_NOP8";
237 case OP_NOP9 : return "OP_NOP9";
238 case OP_NOP10 : return "OP_NOP10";
242 // template matching params
243 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
244 case OP_PUBKEY : return "OP_PUBKEY";
245 case OP_SMALLDATA : return "OP_SMALLDATA";
247 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
253 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
254 if (!(flags & SCRIPT_VERIFY_STRICTENC))
257 if (vchPubKey.size() < 33)
258 return error("Non-canonical public key: too short");
259 if (vchPubKey[0] == 0x04) {
260 if (vchPubKey.size() != 65)
261 return error("Non-canonical public key: invalid length for uncompressed key");
262 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
263 if (vchPubKey.size() != 33)
264 return error("Non-canonical public key: invalid length for compressed key");
266 return error("Non-canonical public key: compressed nor uncompressed");
271 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
272 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
273 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
274 // Where R and S are not negative (their first byte has its highest bit not set), and not
275 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
276 // in which case a single 0 byte is necessary and even required).
277 if (vchSig.size() < 9)
278 return error("Non-canonical signature: too short");
279 if (vchSig.size() > 73)
280 return error("Non-canonical signature: too long");
281 if (vchSig[0] != 0x30)
282 return error("Non-canonical signature: wrong type");
283 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
284 return error("Non-canonical signature: wrong length marker");
286 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
287 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
288 return error("Non-canonical signature: unknown hashtype byte");
290 unsigned int nLenR = vchSig[3];
291 if (5 + nLenR >= vchSig.size())
292 return error("Non-canonical signature: S length misplaced");
293 unsigned int nLenS = vchSig[5+nLenR];
294 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
295 return error("Non-canonical signature: R+S length mismatch");
297 const unsigned char *R = &vchSig[4];
299 return error("Non-canonical signature: R value type mismatch");
301 return error("Non-canonical signature: R length is zero");
303 return error("Non-canonical signature: R value negative");
304 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
305 return error("Non-canonical signature: R value excessively padded");
307 const unsigned char *S = &vchSig[6+nLenR];
309 return error("Non-canonical signature: S value type mismatch");
311 return error("Non-canonical signature: S length is zero");
313 return error("Non-canonical signature: S value negative");
314 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
315 return error("Non-canonical signature: S value excessively padded");
318 unsigned int nLenR = vchSig[3];
319 unsigned int nLenS = vchSig[5+nLenR];
320 const unsigned char *S = &vchSig[6+nLenR];
321 // If the S value is above the order of the curve divided by two, its
322 // complement modulo the order could have been used instead, which is
323 // one byte shorter when encoded correctly.
324 if (!CKey::CheckSignatureElement(S, nLenS, true))
325 return error("Non-canonical signature: S value is unnecessarily high");
331 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
332 if (!(flags & SCRIPT_VERIFY_STRICTENC))
335 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
338 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
340 // There are two kinds of nLockTime: lock-by-blockheight
341 // and lock-by-blocktime, distinguished by whether
342 // nLockTime < LOCKTIME_THRESHOLD.
344 // We want to compare apples to apples, so fail the script
345 // unless the type of nLockTime being tested is the same as
346 // the nLockTime in the transaction.
348 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
349 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
353 // Now that we know we're comparing apples-to-apples, the
354 // comparison is a simple numeric one.
355 if (nLockTime > (int64_t)txTo.nLockTime)
358 // Finally the nLockTime feature can be disabled and thus
359 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
360 // finalized by setting nSequence to maxint. The
361 // transaction would be allowed into the blockchain, making
362 // the opcode ineffective.
364 // Testing if this vin is not final is sufficient to
365 // prevent this condition. Alternatively we could test all
366 // inputs, but testing just this input minimizes the data
367 // required to prove correct CHECKLOCKTIMEVERIFY execution.
368 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
374 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
376 // Relative lock times are supported by comparing the passed
377 // in operand to the sequence number of the input.
378 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
380 // Sequence numbers with their most significant bit set are not
381 // consensus constrained. Testing that the transaction's sequence
382 // number do not have this bit set prevents using this property
383 // to get around a CHECKSEQUENCEVERIFY check.
384 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
387 // Mask off any bits that do not have consensus-enforced meaning
388 // before doing the integer comparisons
389 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
390 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
391 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
393 // There are two kinds of nSequence: lock-by-blockheight
394 // and lock-by-blocktime, distinguished by whether
395 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
397 // We want to compare apples to apples, so fail the script
398 // unless the type of nSequenceMasked being tested is the same as
399 // the nSequenceMasked in the transaction.
401 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
402 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
407 // Now that we know we're comparing apples-to-apples, the
408 // comparison is a simple numeric one.
409 if (nSequenceMasked > txToSequenceMasked)
415 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
418 auto pc = script.begin();
419 auto pend = script.end();
420 auto pbegincodehash = script.begin();
422 valtype vchPushValue;
424 vector<valtype> altstack;
425 if (script.size() > 10000)
433 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
438 if (!script.GetOp(pc, opcode, vchPushValue))
440 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
442 if (opcode > OP_16 && ++nOpCount > 201)
445 if (opcode == OP_CAT ||
446 opcode == OP_SUBSTR ||
448 opcode == OP_RIGHT ||
449 opcode == OP_INVERT ||
458 opcode == OP_LSHIFT ||
460 return false; // Disabled opcodes.
462 if (fExec && opcode <= OP_PUSHDATA4)
463 stack.push_back(vchPushValue);
464 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
489 CBigNum bn(opcode - (OP_1 - 1));
490 stack.push_back(bn.getvch());
499 case OP_NOP1: case OP_NOP4: case OP_NOP5:
500 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
506 // <expression> if [statements] [else [statements]] endif
510 if (stack.size() < 1)
512 auto& vch = stacktop(-1);
513 fValue = CastToBool(vch);
514 if (opcode == OP_NOTIF)
518 vfExec.push_back(fValue);
526 vfExec.back() = !vfExec.back();
541 // (false -- false) and return
542 if (stack.size() < 1)
544 bool fValue = CastToBool(stacktop(-1));
558 case OP_CHECKLOCKTIMEVERIFY:
560 // CHECKLOCKTIMEVERIFY
562 // (nLockTime -- nLockTime)
563 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
564 // treat as a NOP2 if not enabled
568 if (stack.size() < 1)
571 auto nLockTime = CastToBigNum(stacktop(-1));
573 // In the rare event that the argument may be < 0 due to
574 // some arithmetic being done first, you can always use
575 // 0 MAX CHECKLOCKTIMEVERIFY.
579 // Actually compare the specified lock time with the transaction.
580 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
586 case OP_CHECKSEQUENCEVERIFY:
588 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
589 // treat as a NOP3 not enabled
593 if (stack.size() < 1)
596 // nSequence, like nLockTime, is a 32-bit unsigned integer
597 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
598 // 5-byte numeric operands.
599 auto nSequence = CastToBigNum(stacktop(-1));
601 // In the rare event that the argument may be < 0 due to
602 // some arithmetic being done first, you can always use
603 // 0 MAX CHECKSEQUENCEVERIFY.
607 // To provide for future soft-fork extensibility, if the
608 // operand has the disabled lock-time flag set,
609 // CHECKSEQUENCEVERIFY behaves as a NOP.
610 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
613 // Compare the specified sequence number with the input.
614 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
625 if (stack.size() < 1)
627 altstack.push_back(stacktop(-1));
632 case OP_FROMALTSTACK:
634 if (altstack.size() < 1)
636 stack.push_back(altstacktop(-1));
644 if (stack.size() < 2)
653 // (x1 x2 -- x1 x2 x1 x2)
654 if (stack.size() < 2)
656 auto vch1 = stacktop(-2);
657 auto vch2 = stacktop(-1);
658 stack.push_back(vch1);
659 stack.push_back(vch2);
665 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
666 if (stack.size() < 3)
668 auto vch1 = stacktop(-3);
669 auto vch2 = stacktop(-2);
670 auto vch3 = stacktop(-1);
671 stack.push_back(vch1);
672 stack.push_back(vch2);
673 stack.push_back(vch3);
679 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
680 if (stack.size() < 4)
682 auto vch1 = stacktop(-4);
683 auto vch2 = stacktop(-3);
684 stack.push_back(vch1);
685 stack.push_back(vch2);
691 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
692 if (stack.size() < 6)
694 auto vch1 = stacktop(-6);
695 auto vch2 = stacktop(-5);
696 stack.erase(stack.end()-6, stack.end()-4);
697 stack.push_back(vch1);
698 stack.push_back(vch2);
704 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
705 if (stack.size() < 4)
707 swap(stacktop(-4), stacktop(-2));
708 swap(stacktop(-3), stacktop(-1));
715 if (stack.size() < 1)
717 auto vch = stacktop(-1);
719 stack.push_back(vch);
726 CBigNum bn((uint16_t) stack.size());
727 stack.push_back(bn.getvch());
734 if (stack.size() < 1)
743 if (stack.size() < 1)
745 auto vch = stacktop(-1);
746 stack.push_back(vch);
753 if (stack.size() < 2)
755 stack.erase(stack.end() - 2);
761 // (x1 x2 -- x1 x2 x1)
762 if (stack.size() < 2)
764 auto vch = stacktop(-2);
765 stack.push_back(vch);
772 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
773 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
774 if (stack.size() < 2)
776 int n = CastToBigNum(stacktop(-1)).getint32();
778 if (n < 0 || n >= (int)stack.size())
780 auto vch = stacktop(-n-1);
781 if (opcode == OP_ROLL)
782 stack.erase(stack.end()-n-1);
783 stack.push_back(vch);
789 // (x1 x2 x3 -- x2 x3 x1)
790 // x2 x1 x3 after first swap
791 // x2 x3 x1 after second swap
792 if (stack.size() < 3)
794 swap(stacktop(-3), stacktop(-2));
795 swap(stacktop(-2), stacktop(-1));
802 if (stack.size() < 2)
804 swap(stacktop(-2), stacktop(-1));
810 // (x1 x2 -- x2 x1 x2)
811 if (stack.size() < 2)
813 auto vch = stacktop(-1);
814 stack.insert(stack.end()-2, vch);
822 if (stack.size() < 1)
824 CBigNum bn((uint16_t) stacktop(-1).size());
825 stack.push_back(bn.getvch());
835 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
838 if (stack.size() < 2)
840 auto& vch1 = stacktop(-2);
841 auto& vch2 = stacktop(-1);
842 bool fEqual = (vch1 == vch2);
843 // OP_NOTEQUAL is disabled because it would be too easy to say
844 // something like n != 1 and have some wiseguy pass in 1 with extra
845 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
846 //if (opcode == OP_NOTEQUAL)
850 stack.push_back(fEqual ? vchTrue : vchFalse);
851 if (opcode == OP_EQUALVERIFY)
873 if (stack.size() < 1)
875 auto bn = CastToBigNum(stacktop(-1));
878 case OP_1ADD: bn += bnOne; break;
879 case OP_1SUB: bn -= bnOne; break;
880 case OP_NEGATE: bn = -bn; break;
881 case OP_ABS: if (bn < bnZero) bn = -bn; break;
882 case OP_NOT: bn = (bn == bnZero); break;
883 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
884 default: assert(!"invalid opcode"); break;
887 stack.push_back(bn.getvch());
896 case OP_NUMEQUALVERIFY:
900 case OP_LESSTHANOREQUAL:
901 case OP_GREATERTHANOREQUAL:
906 if (stack.size() < 2)
908 auto bn1 = CastToBigNum(stacktop(-2));
909 auto bn2 = CastToBigNum(stacktop(-1));
921 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
922 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
923 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
924 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
925 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
926 case OP_LESSTHAN: bn = (bn1 < bn2); break;
927 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
928 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
929 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
930 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
931 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
932 default: assert(!"invalid opcode"); break;
936 stack.push_back(bn.getvch());
938 if (opcode == OP_NUMEQUALVERIFY)
940 if (CastToBool(stacktop(-1)))
950 // (x min max -- out)
951 if (stack.size() < 3)
953 auto bn1 = CastToBigNum(stacktop(-3));
954 auto bn2 = CastToBigNum(stacktop(-2));
955 auto bn3 = CastToBigNum(stacktop(-1));
956 bool fValue = (bn2 <= bn1 && bn1 < bn3);
960 stack.push_back(fValue ? vchTrue : vchFalse);
975 if (stack.size() < 1)
977 auto& vch = stacktop(-1);
978 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
979 if (opcode == OP_RIPEMD160)
980 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
981 else if (opcode == OP_SHA1)
982 SHA1(&vch[0], vch.size(), &vchHash[0]);
983 else if (opcode == OP_SHA256)
984 SHA256(&vch[0], vch.size(), &vchHash[0]);
985 else if (opcode == OP_HASH160)
987 auto hash160 = Hash160(vch);
988 memcpy(&vchHash[0], &hash160, sizeof(hash160));
990 else if (opcode == OP_HASH256)
992 auto hash = Hash(vch.begin(), vch.end());
993 memcpy(&vchHash[0], &hash, sizeof(hash));
996 stack.push_back(vchHash);
1000 case OP_CODESEPARATOR:
1002 // Hash starts after the code separator
1003 pbegincodehash = pc;
1008 case OP_CHECKSIGVERIFY:
1010 // (sig pubkey -- bool)
1011 if (stack.size() < 2)
1014 auto& vchSig = stacktop(-2);
1015 auto& vchPubKey = stacktop(-1);
1018 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1019 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1021 // Subset of script starting at the most recent codeseparator
1022 CScript scriptCode(pbegincodehash, pend);
1024 // Drop the signature, since there's no way for a signature to sign itself
1025 scriptCode.FindAndDelete(CScript(vchSig));
1027 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1028 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1032 stack.push_back(fSuccess ? vchTrue : vchFalse);
1033 if (opcode == OP_CHECKSIGVERIFY)
1043 case OP_CHECKMULTISIG:
1044 case OP_CHECKMULTISIGVERIFY:
1046 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1049 if ((int)stack.size() < i)
1052 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1053 if (nKeysCount < 0 || nKeysCount > 20)
1055 nOpCount += nKeysCount;
1060 if ((int)stack.size() < i)
1063 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1064 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1068 if ((int)stack.size() < i)
1071 // Subset of script starting at the most recent codeseparator
1072 CScript scriptCode(pbegincodehash, pend);
1074 // Drop the signatures, since there's no way for a signature to sign itself
1075 for (int k = 0; k < nSigsCount; k++)
1077 auto& vchSig = stacktop(-isig-k);
1078 scriptCode.FindAndDelete(CScript(vchSig));
1081 bool fSuccess = true;
1082 while (fSuccess && nSigsCount > 0)
1084 auto& vchSig = stacktop(-isig);
1085 auto& vchPubKey = stacktop(-ikey);
1088 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1089 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1098 // If there are more signatures left than keys left,
1099 // then too many signatures have failed
1100 if (nSigsCount > nKeysCount)
1107 // A bug causes CHECKMULTISIG to consume one extra argument
1108 // whose contents were not checked in any way.
1110 // Unfortunately this is a potential source of mutability,
1111 // so optionally verify it is exactly equal to zero prior
1112 // to removing it from the stack.
1113 if (stack.size() < 1)
1115 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1116 return error("CHECKMULTISIG dummy argument not null");
1119 stack.push_back(fSuccess ? vchTrue : vchFalse);
1121 if (opcode == OP_CHECKMULTISIGVERIFY)
1136 if (stack.size() + altstack.size() > 1000)
1146 if (!vfExec.empty())
1160 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, uint32_t nIn, int nHashType)
1162 if (nIn >= txTo.vin.size())
1164 printf("ERROR: SignatureHash() : nIn=%" PRIu32 " out of range\n", nIn);
1167 CTransaction txTmp(txTo);
1169 // In case concatenating two scripts ends up with two codeseparators,
1170 // or an extra one at the end, this prevents all those possible incompatibilities.
1171 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1173 // Blank out other inputs' signatures
1174 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1175 txTmp.vin[i].scriptSig = CScript();
1176 txTmp.vin[nIn].scriptSig = scriptCode;
1178 // Blank out some of the outputs
1179 if ((nHashType & 0x1f) == SIGHASH_NONE)
1184 // Let the others update at will
1185 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1187 txTmp.vin[i].nSequence = 0;
1189 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1191 // Only lock-in the txout payee at same index as txin
1192 uint32_t nOut = nIn;
1193 if (nOut >= txTmp.vout.size())
1195 printf("ERROR: SignatureHash() : nOut=%" PRIu32 " out of range\n", nOut);
1198 txTmp.vout.resize(nOut+1);
1199 for (unsigned int i = 0; i < nOut; i++)
1200 txTmp.vout[i].SetNull();
1202 // Let the others update at will
1203 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1205 txTmp.vin[i].nSequence = 0;
1208 // Blank out other inputs completely, not recommended for open transactions
1209 if (nHashType & SIGHASH_ANYONECANPAY)
1211 txTmp.vin[0] = txTmp.vin[nIn];
1212 txTmp.vin.resize(1);
1215 // Serialize and hash
1216 CDataStream ss(SER_GETHASH, 0);
1218 ss << txTmp << nHashType;
1219 return Hash(ss.begin(), ss.end());
1223 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1224 // twice for every transaction (once when accepted into memory pool, and
1225 // again when accepted into the block chain)
1227 class CSignatureCache
1230 // sigdata_type is (signature hash, signature, public key):
1231 typedef tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1232 set< sigdata_type> setValid;
1233 boost::shared_mutex cs_sigcache;
1237 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1239 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1241 sigdata_type k(hash, vchSig, pubKey);
1242 auto mi = setValid.find(k);
1243 if (mi != setValid.end())
1248 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1250 // DoS prevention: limit cache size to less than 10MB
1251 // (~200 bytes per cache entry times 50,000 entries)
1252 // Since there are a maximum of 20,000 signature operations per block
1253 // 50,000 is a reasonable default.
1254 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1255 if (nMaxCacheSize <= 0) return;
1257 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1259 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1261 // Evict a random entry. Random because that helps
1262 // foil would-be DoS attackers who might try to pre-generate
1263 // and re-use a set of valid signatures just-slightly-greater
1264 // than our cache size.
1265 auto randomHash = GetRandHash();
1266 std::vector<unsigned char> unused;
1267 auto it = setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1268 if (it == setValid.end())
1269 it = setValid.begin();
1270 setValid.erase(*it);
1273 sigdata_type k(hash, vchSig, pubKey);
1278 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1279 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1281 static CSignatureCache signatureCache;
1283 CPubKey pubkey(vchPubKey);
1284 if (!pubkey.IsValid())
1287 // Hash type is one byte tacked on to the end of the signature
1291 nHashType = vchSig.back();
1292 else if (nHashType != vchSig.back())
1296 auto sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1298 if (signatureCache.Get(sighash, vchSig, pubkey))
1301 if (!pubkey.Verify(sighash, vchSig))
1304 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1305 signatureCache.Set(sighash, vchSig, pubkey);
1312 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1314 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1317 static map<txnouttype, CScript> mTemplates;
1318 if (mTemplates.empty())
1320 // Standard tx, sender provides pubkey, receiver adds signature
1321 mTemplates.insert({ TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG });
1323 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1324 mTemplates.insert({ TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG });
1326 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1327 mTemplates.insert({ TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG });
1329 // Sender provides N pubkeys, receivers provides M signatures
1330 mTemplates.insert({ TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG });
1332 // Empty, provably prunable, data-carrying output
1333 mTemplates.insert({ TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA });
1336 vSolutionsRet.clear();
1338 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1339 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1340 if (scriptPubKey.IsPayToScriptHash())
1342 typeRet = TX_SCRIPTHASH;
1343 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1344 vSolutionsRet.push_back(hashBytes);
1348 // Provably prunable, data-carrying output
1350 // So long as script passes the IsUnspendable() test and all but the first
1351 // byte passes the IsPushOnly() test we don't care what exactly is in the
1353 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1354 typeRet = TX_NULL_DATA;
1359 const auto& script1 = scriptPubKey;
1360 for(const auto& tplate : mTemplates)
1362 const auto& script2 = tplate.second;
1363 vSolutionsRet.clear();
1365 opcodetype opcode1, opcode2;
1366 vector<unsigned char> vch1, vch2;
1369 auto pc1 = script1.begin();
1370 auto pc2 = script2.begin();
1373 if (pc1 == script1.end() && pc2 == script2.end())
1376 typeRet = tplate.first;
1377 if (typeRet == TX_MULTISIG)
1379 // Additional checks for TX_MULTISIG:
1380 auto m = vSolutionsRet.front()[0];
1381 auto n = vSolutionsRet.back()[0];
1382 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1387 if (!script1.GetOp(pc1, opcode1, vch1))
1389 if (!script2.GetOp(pc2, opcode2, vch2))
1392 // Template matching opcodes:
1393 if (opcode2 == OP_PUBKEYS)
1395 while (vch1.size() >= 33 && vch1.size() <= 120)
1397 vSolutionsRet.push_back(vch1);
1398 if (!script1.GetOp(pc1, opcode1, vch1))
1401 if (!script2.GetOp(pc2, opcode2, vch2))
1403 // Normal situation is to fall through
1404 // to other if/else statements
1407 if (opcode2 == OP_PUBKEY)
1409 if (vch1.size() < 33 || vch1.size() > 120)
1411 vSolutionsRet.push_back(vch1);
1413 else if (opcode2 == OP_PUBKEYHASH)
1415 if (vch1.size() != sizeof(uint160))
1417 vSolutionsRet.push_back(vch1);
1419 else if (opcode2 == OP_SMALLINTEGER)
1420 { // Single-byte small integer pushed onto vSolutions
1421 if (opcode1 == OP_0 ||
1422 (opcode1 >= OP_1 && opcode1 <= OP_16))
1424 char n = (char)CScript::DecodeOP_N(opcode1);
1425 vSolutionsRet.push_back(valtype(1, n));
1430 else if (opcode2 == OP_INTEGER)
1431 { // Up to four-byte integer pushed onto vSolutions
1434 auto bnVal = CastToBigNum(vch1);
1436 break; // It's better to use OP_0 ... OP_16 for small integers.
1437 vSolutionsRet.push_back(vch1);
1444 else if (opcode2 == OP_SMALLDATA)
1446 // small pushdata, <= 1024 bytes
1447 if (vch1.size() > 1024)
1450 else if (opcode1 != opcode2 || vch1 != vch2)
1452 // Others must match exactly
1458 vSolutionsRet.clear();
1459 typeRet = TX_NONSTANDARD;
1464 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1467 if (!keystore.GetKey(address, key))
1470 vector<unsigned char> vchSig;
1471 if (!key.Sign(hash, vchSig))
1473 vchSig.push_back((unsigned char)nHashType);
1474 scriptSigRet << vchSig;
1479 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1482 if (!keystore.CreatePrivKey(pubKey, R, key))
1485 vector<unsigned char> vchSig;
1486 if (!key.Sign(hash, vchSig))
1488 vchSig.push_back((unsigned char)nHashType);
1489 scriptSigRet << vchSig;
1494 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1497 int nRequired = multisigdata.front()[0];
1498 for (uint32_t i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1500 const auto& pubkey = multisigdata[i];
1501 auto keyID = CPubKey(pubkey).GetID();
1502 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1505 return nSigned==nRequired;
1509 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1510 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1511 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1512 // Returns false if scriptPubKey could not be completely satisfied.
1514 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1515 CScript& scriptSigRet, txnouttype& whichTypeRet)
1517 scriptSigRet.clear();
1519 vector<valtype> vSolutions;
1520 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1524 switch (whichTypeRet)
1526 case TX_NONSTANDARD:
1530 keyID = CPubKey(vSolutions[0]).GetID();
1531 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1532 case TX_PUBKEY_DROP:
1534 auto key = CPubKey(vSolutions[0]);
1535 auto R = CPubKey(vSolutions[1]);
1536 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1539 keyID = CKeyID(uint160(vSolutions[0]));
1540 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1545 keystore.GetPubKey(keyID, vch);
1546 scriptSigRet << vch;
1550 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1553 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1554 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1559 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1563 case TX_NONSTANDARD:
1568 case TX_PUBKEY_DROP:
1573 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1575 return vSolutions[0][0] + 1;
1577 return 1; // doesn't include args needed by the script
1582 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1584 vector<valtype> vSolutions;
1585 if (!Solver(scriptPubKey, whichType, vSolutions))
1588 if (whichType == TX_MULTISIG)
1590 unsigned char m = vSolutions.front()[0];
1591 unsigned char n = vSolutions.back()[0];
1592 // Support up to x-of-3 multisig txns as standard
1599 return whichType != TX_NONSTANDARD;
1603 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1605 uint32_t nResult = 0;
1606 for(const auto& pubkey : pubkeys)
1608 auto keyID = CPubKey(pubkey).GetID();
1609 if (keystore.HaveKey(keyID))
1616 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1619 const CKeyStore *keystore;
1621 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1622 bool operator()(const CNoDestination &dest) const { return false; }
1623 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1624 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1627 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1630 script.SetAddress(dest);
1631 return IsMine(keystore, script);
1634 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1636 vector<valtype> vSolutions;
1637 txnouttype whichType;
1638 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1639 if (keystore.HaveWatchOnly(scriptPubKey))
1640 return MINE_WATCH_ONLY;
1647 case TX_NONSTANDARD:
1651 keyID = CPubKey(vSolutions[0]).GetID();
1652 if (keystore.HaveKey(keyID))
1653 return MINE_SPENDABLE;
1655 case TX_PUBKEY_DROP:
1657 auto key = CPubKey(vSolutions[0]);
1658 auto R = CPubKey(vSolutions[1]);
1659 if (keystore.CheckOwnership(key, R))
1660 return MINE_SPENDABLE;
1664 keyID = CKeyID(uint160(vSolutions[0]));
1665 if (keystore.HaveKey(keyID))
1666 return MINE_SPENDABLE;
1670 auto scriptID = CScriptID(uint160(vSolutions[0]));
1672 if (keystore.GetCScript(scriptID, subscript)) {
1673 auto ret = IsMine(keystore, subscript);
1674 if (ret == MINE_SPENDABLE)
1681 // Only consider transactions "mine" if we own ALL the
1682 // keys involved. multi-signature transactions that are
1683 // partially owned (somebody else has a key that can spend
1684 // them) enable spend-out-from-under-you attacks, especially
1685 // in shared-wallet situations.
1686 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1687 if (HaveKeys(keys, keystore) == keys.size())
1688 return MINE_SPENDABLE;
1693 if (keystore.HaveWatchOnly(scriptPubKey))
1694 return MINE_WATCH_ONLY;
1698 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1700 vector<valtype> vSolutions;
1701 txnouttype whichType;
1702 if (!Solver(scriptPubKey, whichType, vSolutions))
1705 if (whichType == TX_PUBKEY)
1707 addressRet = CPubKey(vSolutions[0]).GetID();
1710 else if (whichType == TX_PUBKEYHASH)
1712 addressRet = CKeyID(uint160(vSolutions[0]));
1715 else if (whichType == TX_SCRIPTHASH)
1717 addressRet = CScriptID(uint160(vSolutions[0]));
1720 // Multisig txns have more than one address...
1724 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1726 vector<valtype> vSolutions;
1727 txnouttype whichType;
1728 if (!Solver(scriptPubKey, whichType, vSolutions))
1731 if (whichType == TX_PUBKEY)
1733 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1736 if (whichType == TX_PUBKEY_DROP)
1739 CMalleableKeyView view;
1740 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1743 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1746 else if (whichType == TX_PUBKEYHASH)
1748 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1751 else if (whichType == TX_SCRIPTHASH)
1753 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1756 // Multisig txns have more than one address...
1760 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1762 const CKeyStore &keystore;
1763 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1764 std::vector<CKeyID> &vKeys;
1767 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1769 void Process(const CScript &script) {
1771 std::vector<CTxDestination> vDest;
1773 if (ExtractDestinations(script, type, vDest, nRequired)) {
1774 for(const CTxDestination &dest : vDest)
1775 boost::apply_visitor(*this, dest);
1779 void operator()(const CKeyID &keyId) {
1780 if (keystore.HaveKey(keyId))
1781 vKeys.push_back(keyId);
1784 void operator()(const CScriptID &scriptId) {
1786 if (keystore.GetCScript(scriptId, script))
1790 void operator()(const CNoDestination &none) {}
1794 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1795 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1798 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1801 typeRet = TX_NONSTANDARD;
1802 vector<valtype> vSolutions;
1803 if (!Solver(scriptPubKey, typeRet, vSolutions))
1805 if (typeRet == TX_NULL_DATA)
1811 if (typeRet == TX_MULTISIG)
1813 nRequiredRet = vSolutions.front()[0];
1814 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1816 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1817 addressRet.push_back(address);
1823 if (typeRet == TX_PUBKEY_DROP)
1825 CTxDestination address;
1826 if (!ExtractDestination(scriptPubKey, address))
1828 addressRet.push_back(address);
1834 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
1836 vector<vector<unsigned char> > stack, stackCopy;
1837 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1839 if (flags & SCRIPT_VERIFY_P2SH)
1841 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1846 if (CastToBool(stack.back()) == false)
1849 // Additional validation for spend-to-script-hash transactions:
1850 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1852 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1853 return false; // or validation fails
1855 // stackCopy cannot be empty here, because if it was the
1856 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1857 // an empty stack and the EvalScript above would return false.
1858 assert(!stackCopy.empty());
1860 const auto& pubKeySerialized = stackCopy.back();
1861 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1862 popstack(stackCopy);
1864 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1866 if (stackCopy.empty())
1868 return CastToBool(stackCopy.back());
1874 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, uint32_t nIn, int nHashType)
1876 assert(nIn < txTo.vin.size());
1877 auto& txin = txTo.vin[nIn];
1879 // Leave out the signature from the hash, since a signature can't sign itself.
1880 // The checksig op will also drop the signatures from its hash.
1881 auto hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1883 txnouttype whichType;
1884 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1887 if (whichType == TX_SCRIPTHASH)
1889 // Solver returns the subscript that need to be evaluated;
1890 // the final scriptSig is the signatures from that
1891 // and then the serialized subscript:
1892 auto subscript = txin.scriptSig;
1894 // Recompute txn hash using subscript in place of scriptPubKey:
1895 auto hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1898 bool fSolved = Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1899 // Append serialized subscript whether or not it is completely signed:
1900 txin.scriptSig << static_cast<valtype>(subscript);
1901 if (!fSolved) return false;
1905 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1908 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, uint32_t nIn, int nHashType)
1910 assert(nIn < txTo.vin.size());
1911 auto& txin = txTo.vin[nIn];
1912 assert(txin.prevout.n < txFrom.vout.size());
1913 assert(txin.prevout.hash == txFrom.GetHash());
1914 const auto& txout = txFrom.vout[txin.prevout.n];
1916 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1919 static CScript PushAll(const vector<valtype>& values)
1922 for(const auto& v : values)
1927 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1928 const vector<valtype>& vSolutions,
1929 vector<valtype>& sigs1, vector<valtype>& sigs2)
1931 // Combine all the signatures we've got:
1932 set<valtype> allsigs;
1933 for(const auto& v : sigs1)
1938 for(const auto& v : sigs2)
1944 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1945 assert(vSolutions.size() > 1);
1946 auto nSigsRequired = (uint32_t)vSolutions.front()[0];
1947 auto nPubKeys = (uint32_t)(vSolutions.size()-2);
1949 map<valtype, valtype> sigs;
1950 for(const auto& sig : allsigs)
1952 for (unsigned int i = 0; i < nPubKeys; i++)
1954 const auto& pubkey = vSolutions[i+1];
1955 if (sigs.count(pubkey))
1956 continue; // Already got a sig for this pubkey
1958 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1965 // Now build a merged CScript:
1966 uint32_t nSigsHave = 0;
1967 CScript result; result << OP_0; // pop-one-too-many workaround
1968 for (uint32_t i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1970 if (sigs.count(vSolutions[i+1]))
1972 result << sigs[vSolutions[i+1]];
1976 // Fill any missing with OP_0:
1977 for (auto i = nSigsHave; i < nSigsRequired; i++)
1983 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1984 const txnouttype txType, const vector<valtype>& vSolutions,
1985 vector<valtype>& sigs1, vector<valtype>& sigs2)
1989 case TX_NONSTANDARD:
1991 // Don't know anything about this, assume bigger one is correct:
1992 if (sigs1.size() >= sigs2.size())
1993 return PushAll(sigs1);
1994 return PushAll(sigs2);
1996 case TX_PUBKEY_DROP:
1998 // Signatures are bigger than placeholders or empty scripts:
1999 if (sigs1.empty() || sigs1[0].empty())
2000 return PushAll(sigs2);
2001 return PushAll(sigs1);
2003 if (sigs1.empty() || sigs1.back().empty())
2004 return PushAll(sigs2);
2005 else if (sigs2.empty() || sigs2.back().empty())
2006 return PushAll(sigs1);
2009 // Recur to combine:
2010 auto spk = sigs1.back();
2011 CScript pubKey2(spk.begin(), spk.end());
2014 vector<vector<unsigned char> > vSolutions2;
2015 Solver(pubKey2, txType2, vSolutions2);
2018 auto result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2023 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2029 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn,
2030 const CScript& scriptSig1, const CScript& scriptSig2)
2033 vector<vector<unsigned char> > vSolutions;
2034 Solver(scriptPubKey, txType, vSolutions);
2036 vector<valtype> stack1;
2037 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2038 vector<valtype> stack2;
2039 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2041 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2048 CScript& CScript::push_int64(int64_t n)
2050 if (n == -1 || (n >= 1 && n <= 16))
2052 push_back((uint8_t)n + (OP_1 - 1));
2057 *this << bn.getvch();
2062 CScript& CScript::push_uint64(uint64_t n)
2064 if (n >= 1 && n <= 16)
2066 push_back((uint8_t)n + (OP_1 - 1));
2071 *this << bn.getvch();
2076 CScript& CScript::operator+=(const CScript& b)
2078 insert(end(), b.begin(), b.end());
2082 CScript& CScript::operator<<(opcodetype opcode)
2084 insert(end(), opcode);
2088 CScript& CScript::operator<<(const uint160& b)
2090 insert(end(), sizeof(b));
2091 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2095 CScript& CScript::operator<<(const uint256& b)
2097 insert(end(), sizeof(b));
2098 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2102 CScript& CScript::operator<<(const CPubKey& key)
2104 std::vector<uint8_t> vchKey(key.begin(), key.end());
2105 return (*this) << vchKey;
2108 CScript& CScript::operator<<(const CBigNum& b)
2110 *this << b.getvch();
2114 CScript& CScript::operator<<(const std::vector<uint8_t>& b)
2116 if (b.size() < OP_PUSHDATA1)
2118 insert(end(), (uint8_t)b.size());
2120 else if (b.size() <= 0xff)
2122 insert(end(), OP_PUSHDATA1);
2123 insert(end(), (uint8_t)b.size());
2125 else if (b.size() <= 0xffff)
2127 insert(end(), OP_PUSHDATA2);
2128 uint16_t nSize = (uint16_t) b.size();
2129 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2133 insert(end(), OP_PUSHDATA4);
2134 uint32_t nSize = (uint32_t) b.size();
2135 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2137 insert(end(), b.begin(), b.end());
2141 CScript& CScript::operator<<(const CScript& b)
2143 // I'm not sure if this should push the script or concatenate scripts.
2144 // If there's ever a use for pushing a script onto a script, delete this member fn
2145 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
2149 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
2151 // Wrapper so it can be called with either iterator or const_iterator
2152 const_iterator pc2 = pc;
2153 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
2154 pc = begin() + (pc2 - begin());
2158 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet)
2160 const_iterator pc2 = pc;
2161 bool fRet = GetOp2(pc2, opcodeRet, NULL);
2162 pc = begin() + (pc2 - begin());
2166 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
2168 return GetOp2(pc, opcodeRet, &vchRet);
2171 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet) const
2173 return GetOp2(pc, opcodeRet, NULL);
2176 bool CScript::GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
2178 opcodeRet = OP_INVALIDOPCODE;
2187 uint32_t opcode = *pc++;
2189 // Immediate operand
2190 if (opcode <= OP_PUSHDATA4)
2192 uint32_t nSize = OP_0;
2193 if (opcode < OP_PUSHDATA1)
2197 else if (opcode == OP_PUSHDATA1)
2203 else if (opcode == OP_PUSHDATA2)
2207 memcpy(&nSize, &pc[0], 2);
2210 else if (opcode == OP_PUSHDATA4)
2214 memcpy(&nSize, &pc[0], 4);
2217 if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
2220 pvchRet->assign(pc, pc + nSize);
2224 opcodeRet = (opcodetype)opcode;
2228 int CScript::DecodeOP_N(opcodetype opcode)
2232 assert(opcode >= OP_1 && opcode <= OP_16);
2233 return (opcode - (OP_1 - 1));
2236 opcodetype CScript::EncodeOP_N(int n)
2238 assert(n >= 0 && n <= 16);
2241 return (opcodetype)(OP_1+n-1);
2244 int CScript::FindAndDelete(const CScript& b)
2249 iterator pc = begin();
2253 while (end() - pc >= (long)b.size() && memcmp(&pc[0], &b[0], b.size()) == 0)
2255 erase(pc, pc + b.size());
2259 while (GetOp(pc, opcode));
2263 int CScript::Find(opcodetype op) const
2267 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
2273 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2277 auto lastOpcode = OP_INVALIDOPCODE;
2281 if (!GetOp(pc, opcode))
2283 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2285 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2287 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2288 n += DecodeOP_N(lastOpcode);
2292 lastOpcode = opcode;
2297 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2299 if (!IsPayToScriptHash())
2300 return GetSigOpCount(true);
2302 // This is a pay-to-script-hash scriptPubKey;
2303 // get the last item that the scriptSig
2304 // pushes onto the stack:
2305 auto pc = scriptSig.begin();
2306 vector<unsigned char> data;
2307 while (pc < scriptSig.end())
2310 if (!scriptSig.GetOp(pc, opcode, data))
2316 /// ... and return its opcount:
2317 CScript subscript(data.begin(), data.end());
2318 return subscript.GetSigOpCount(true);
2321 bool CScript::IsPayToScriptHash() const
2323 // Extra-fast test for pay-to-script-hash CScripts:
2324 return (this->size() == 23 &&
2325 this->at(0) == OP_HASH160 &&
2326 this->at(1) == 0x14 &&
2327 this->at(22) == OP_EQUAL);
2330 bool CScript::IsPushOnly(const_iterator pc) const
2335 if (!GetOp(pc, opcode))
2343 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
2344 bool CScript::IsPushOnly() const
2346 return this->IsPushOnly(begin());
2349 bool CScript::HasCanonicalPushes() const
2355 std::vector<unsigned char> data;
2356 if (!GetOp(pc, opcode, data))
2360 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2361 // Could have used an OP_n code, rather than a 1-byte push.
2363 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2364 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2366 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2367 // Could have used an OP_PUSHDATA1.
2369 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2370 // Could have used an OP_PUSHDATA2.
2376 class CScriptVisitor : public boost::static_visitor<bool>
2381 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2383 bool operator()(const CNoDestination &dest) const {
2388 bool operator()(const CKeyID &keyID) const {
2390 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2394 bool operator()(const CScriptID &scriptID) const {
2396 *script << OP_HASH160 << scriptID << OP_EQUAL;
2401 void CScript::SetDestination(const CTxDestination& dest)
2403 boost::apply_visitor(CScriptVisitor(this), dest);
2406 void CScript::SetAddress(const CBitcoinAddress& dest)
2409 if (dest.IsScript())
2410 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2411 else if (dest.IsPubKey())
2412 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2413 else if (dest.IsPair()) {
2414 // Pubkey pair address, going to generate
2415 // new one-time public key.
2416 CMalleablePubKey mpk;
2417 if (!mpk.setvch(dest.GetData()))
2419 CPubKey R, pubKeyVariant;
2420 mpk.GetVariant(R, pubKeyVariant);
2421 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2425 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2429 *this << EncodeOP_N(nRequired);
2430 for(const auto& key : keys)
2432 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2435 void CScript::PrintHex() const
2437 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
2440 std::string CScript::ToString(bool fShort) const
2444 std::vector<uint8_t> vch;
2445 const_iterator pc = begin();
2450 if (!GetOp(pc, opcode, vch))
2455 if (opcode <= OP_PUSHDATA4)
2456 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
2458 str += GetOpName(opcode);
2463 void CScript::print() const
2465 printf("%s\n", ToString().c_str());
2468 CScriptID CScript::GetID() const
2470 return CScriptID(Hash160(*this));