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.
14 #include <shared_mutex>
16 bool CheckSig(std::vector<unsigned char> vchSig, const std::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 std::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(std::vector<valtype>& stack)
88 throw std::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(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
418 CScript::const_iterator pc = script.begin();
419 CScript::const_iterator pend = script.end();
420 CScript::const_iterator pbegincodehash = script.begin();
422 valtype vchPushValue;
423 std::vector<bool> vfExec;
424 std::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 && 0 <= opcode && opcode <= OP_PUSHDATA4)
463 stack.push_back(vchPushValue);
464 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
489 CBigNum bn((int)opcode - (int)(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 valtype& 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 CBigNum 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 CBigNum 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 valtype vch1 = stacktop(-2);
657 valtype 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 valtype vch1 = stacktop(-3);
669 valtype vch2 = stacktop(-2);
670 valtype 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 valtype vch1 = stacktop(-4);
683 valtype 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 valtype vch1 = stacktop(-6);
695 valtype 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 valtype 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 valtype 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 valtype 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 valtype 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 valtype 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 valtype& vch1 = stacktop(-2);
841 valtype& 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 CBigNum 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 CBigNum bn1 = CastToBigNum(stacktop(-2));
909 CBigNum 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 CBigNum bn1 = CastToBigNum(stacktop(-3));
954 CBigNum bn2 = CastToBigNum(stacktop(-2));
955 CBigNum bn3 = CastToBigNum(stacktop(-1));
956 bool fValue = (bn2 <= bn1 && bn1 < bn3);
960 stack.push_back(fValue ? vchTrue : vchFalse);
975 if (stack.size() < 1)
977 valtype& 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 uint160 hash160 = Hash160(vch);
988 memcpy(&vchHash[0], &hash160, sizeof(hash160));
990 else if (opcode == OP_HASH256)
992 uint256 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 valtype& vchSig = stacktop(-2);
1015 valtype& 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 valtype& vchSig = stacktop(-isig-k);
1078 scriptCode.FindAndDelete(CScript(vchSig));
1081 bool fSuccess = true;
1082 while (fSuccess && nSigsCount > 0)
1084 valtype& vchSig = stacktop(-isig);
1085 valtype& 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, unsigned int nIn, int nHashType)
1162 if (nIn >= txTo.vin.size())
1164 printf("ERROR: SignatureHash() : nIn=%d 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 unsigned int nOut = nIn;
1193 if (nOut >= txTmp.vout.size())
1195 printf("ERROR: SignatureHash() : nOut=%d 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 using sigdata_type = std::tuple<uint256, std::vector<unsigned char>, CPubKey>;
1232 std::set<sigdata_type> setValid;
1233 std::shared_mutex cs_sigcache;
1237 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1239 std::shared_lock<std::shared_mutex> lock(cs_sigcache);
1241 sigdata_type k(hash, vchSig, pubKey);
1242 std::set<sigdata_type>::iterator 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 std::shared_lock<std::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 uint256 randomHash = GetRandHash();
1266 std::vector<unsigned char> unused;
1267 std::set<sigdata_type>::iterator it =
1268 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1269 if (it == setValid.end())
1270 it = setValid.begin();
1271 setValid.erase(*it);
1274 sigdata_type k(hash, vchSig, pubKey);
1279 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1280 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1282 static CSignatureCache signatureCache;
1284 CPubKey pubkey(vchPubKey);
1285 if (!pubkey.IsValid())
1288 // Hash type is one byte tacked on to the end of the signature
1292 nHashType = vchSig.back();
1293 else if (nHashType != vchSig.back())
1297 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1299 if (signatureCache.Get(sighash, vchSig, pubkey))
1302 if (!pubkey.Verify(sighash, vchSig))
1305 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1306 signatureCache.Set(sighash, vchSig, pubkey);
1313 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1315 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
1318 static std::map<txnouttype, CScript> mTemplates;
1319 if (mTemplates.empty())
1321 // Standard tx, sender provides pubkey, receiver adds signature
1322 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1324 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1325 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1327 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1328 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1330 // Sender provides N pubkeys, receivers provides M signatures
1331 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1333 // Empty, provably prunable, data-carrying output
1334 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1337 vSolutionsRet.clear();
1339 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1340 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1341 if (scriptPubKey.IsPayToScriptHash())
1343 typeRet = TX_SCRIPTHASH;
1344 std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1345 vSolutionsRet.push_back(hashBytes);
1349 // Provably prunable, data-carrying output
1351 // So long as script passes the IsUnspendable() test and all but the first
1352 // byte passes the IsPushOnly() test we don't care what exactly is in the
1354 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1355 typeRet = TX_NULL_DATA;
1360 const CScript& script1 = scriptPubKey;
1361 for (const auto& tplate : mTemplates)
1363 const CScript& script2 = tplate.second;
1364 vSolutionsRet.clear();
1366 opcodetype opcode1, opcode2;
1367 std::vector<unsigned char> vch1, vch2;
1370 CScript::const_iterator pc1 = script1.begin();
1371 CScript::const_iterator pc2 = script2.begin();
1374 if (pc1 == script1.end() && pc2 == script2.end())
1377 typeRet = tplate.first;
1378 if (typeRet == TX_MULTISIG)
1380 // Additional checks for TX_MULTISIG:
1381 unsigned char m = vSolutionsRet.front()[0];
1382 unsigned char n = vSolutionsRet.back()[0];
1383 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1388 if (!script1.GetOp(pc1, opcode1, vch1))
1390 if (!script2.GetOp(pc2, opcode2, vch2))
1393 // Template matching opcodes:
1394 if (opcode2 == OP_PUBKEYS)
1396 while (vch1.size() >= 33 && vch1.size() <= 120)
1398 vSolutionsRet.push_back(vch1);
1399 if (!script1.GetOp(pc1, opcode1, vch1))
1402 if (!script2.GetOp(pc2, opcode2, vch2))
1404 // Normal situation is to fall through
1405 // to other if/else statements
1408 if (opcode2 == OP_PUBKEY)
1410 if (vch1.size() < 33 || vch1.size() > 120)
1412 vSolutionsRet.push_back(vch1);
1414 else if (opcode2 == OP_PUBKEYHASH)
1416 if (vch1.size() != sizeof(uint160))
1418 vSolutionsRet.push_back(vch1);
1420 else if (opcode2 == OP_SMALLINTEGER)
1421 { // Single-byte small integer pushed onto vSolutions
1422 if (opcode1 == OP_0 ||
1423 (opcode1 >= OP_1 && opcode1 <= OP_16))
1425 char n = (char)CScript::DecodeOP_N(opcode1);
1426 vSolutionsRet.push_back(valtype(1, n));
1431 else if (opcode2 == OP_INTEGER)
1432 { // Up to four-byte integer pushed onto vSolutions
1435 CBigNum bnVal = CastToBigNum(vch1);
1437 break; // It's better to use OP_0 ... OP_16 for small integers.
1438 vSolutionsRet.push_back(vch1);
1445 else if (opcode2 == OP_SMALLDATA)
1447 // small pushdata, <= 1024 bytes
1448 if (vch1.size() > 1024)
1451 else if (opcode1 != opcode2 || vch1 != vch2)
1453 // Others must match exactly
1459 vSolutionsRet.clear();
1460 typeRet = TX_NONSTANDARD;
1465 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1468 if (!keystore.GetKey(address, key))
1471 std::vector<unsigned char> vchSig;
1472 if (!key.Sign(hash, vchSig))
1474 vchSig.push_back((unsigned char)nHashType);
1475 scriptSigRet << vchSig;
1480 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1483 if (!keystore.CreatePrivKey(pubKey, R, key))
1486 std::vector<unsigned char> vchSig;
1487 if (!key.Sign(hash, vchSig))
1489 vchSig.push_back((unsigned char)nHashType);
1490 scriptSigRet << vchSig;
1495 bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1498 int nRequired = multisigdata.front()[0];
1499 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1501 const valtype& pubkey = multisigdata[i];
1502 CKeyID keyID = CPubKey(pubkey).GetID();
1503 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1506 return nSigned==nRequired;
1510 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1511 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1512 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1513 // Returns false if scriptPubKey could not be completely satisfied.
1515 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1516 CScript& scriptSigRet, txnouttype& whichTypeRet)
1518 scriptSigRet.clear();
1520 std::vector<valtype> vSolutions;
1521 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1525 switch (whichTypeRet)
1527 case TX_NONSTANDARD:
1531 keyID = CPubKey(vSolutions[0]).GetID();
1532 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1533 case TX_PUBKEY_DROP:
1535 CPubKey key = CPubKey(vSolutions[0]);
1536 CPubKey R = CPubKey(vSolutions[1]);
1537 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1540 keyID = CKeyID(uint160(vSolutions[0]));
1541 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1546 keystore.GetPubKey(keyID, vch);
1547 scriptSigRet << vch;
1551 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1554 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1555 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1560 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1564 case TX_NONSTANDARD:
1569 case TX_PUBKEY_DROP:
1574 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1576 return vSolutions[0][0] + 1;
1578 return 1; // doesn't include args needed by the script
1583 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1585 std::vector<valtype> vSolutions;
1586 if (!Solver(scriptPubKey, whichType, vSolutions))
1589 if (whichType == TX_MULTISIG)
1591 unsigned char m = vSolutions.front()[0];
1592 unsigned char n = vSolutions.back()[0];
1593 // Support up to x-of-3 multisig txns as standard
1600 return whichType != TX_NONSTANDARD;
1604 unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
1606 unsigned int nResult = 0;
1607 for (const valtype& pubkey : pubkeys)
1609 CKeyID keyID = CPubKey(pubkey).GetID();
1610 if (keystore.HaveKey(keyID))
1617 class CKeyStoreIsMineVisitor
1620 const CKeyStore *keystore;
1622 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1623 bool operator()(const CNoDestination &dest) const { return false; }
1624 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1625 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1629 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1632 script.SetDestination(dest);
1633 return IsMine(keystore, script);
1636 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1639 script.SetAddress(dest);
1640 return IsMine(keystore, script);
1643 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1645 std::vector<valtype> vSolutions;
1646 txnouttype whichType;
1647 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1648 if (keystore.HaveWatchOnly(scriptPubKey))
1649 return MINE_WATCH_ONLY;
1656 case TX_NONSTANDARD:
1660 keyID = CPubKey(vSolutions[0]).GetID();
1661 if (keystore.HaveKey(keyID))
1662 return MINE_SPENDABLE;
1664 case TX_PUBKEY_DROP:
1666 CPubKey key = CPubKey(vSolutions[0]);
1667 CPubKey R = CPubKey(vSolutions[1]);
1668 if (keystore.CheckOwnership(key, R))
1669 return MINE_SPENDABLE;
1673 keyID = CKeyID(uint160(vSolutions[0]));
1674 if (keystore.HaveKey(keyID))
1675 return MINE_SPENDABLE;
1679 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1681 if (keystore.GetCScript(scriptID, subscript)) {
1682 isminetype ret = IsMine(keystore, subscript);
1683 if (ret == MINE_SPENDABLE)
1690 // Only consider transactions "mine" if we own ALL the
1691 // keys involved. multi-signature transactions that are
1692 // partially owned (somebody else has a key that can spend
1693 // them) enable spend-out-from-under-you attacks, especially
1694 // in shared-wallet situations.
1695 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1696 if (HaveKeys(keys, keystore) == keys.size())
1697 return MINE_SPENDABLE;
1702 if (keystore.HaveWatchOnly(scriptPubKey))
1703 return MINE_WATCH_ONLY;
1707 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1709 std::vector<valtype> vSolutions;
1710 txnouttype whichType;
1711 if (!Solver(scriptPubKey, whichType, vSolutions))
1714 if (whichType == TX_PUBKEY)
1716 addressRet = CPubKey(vSolutions[0]).GetID();
1719 else if (whichType == TX_PUBKEYHASH)
1721 addressRet = CKeyID(uint160(vSolutions[0]));
1724 else if (whichType == TX_SCRIPTHASH)
1726 addressRet = CScriptID(uint160(vSolutions[0]));
1729 // Multisig txns have more than one address...
1733 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1735 std::vector<valtype> vSolutions;
1736 txnouttype whichType;
1737 if (!Solver(scriptPubKey, whichType, vSolutions))
1740 if (whichType == TX_PUBKEY)
1742 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1745 if (whichType == TX_PUBKEY_DROP)
1748 CMalleableKeyView view;
1749 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1752 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1755 else if (whichType == TX_PUBKEYHASH)
1757 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1760 else if (whichType == TX_SCRIPTHASH)
1762 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1765 // Multisig txns have more than one address...
1769 class CAffectedKeysVisitor {
1771 const CKeyStore &keystore;
1772 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1773 std::vector<CKeyID> &vKeys;
1776 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1778 void Process(const CScript &script) {
1780 std::vector<CTxDestination> vDest;
1782 if (ExtractDestinations(script, type, vDest, nRequired)) {
1783 for (const CTxDestination &dest : vDest)
1784 std::visit(*this, dest);
1788 void operator()(const CKeyID &keyId) {
1789 if (keystore.HaveKey(keyId))
1790 vKeys.push_back(keyId);
1793 void operator()(const CScriptID &scriptId) {
1795 if (keystore.GetCScript(scriptId, script))
1799 void operator()(const CNoDestination &none) {}
1803 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1804 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1807 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
1810 typeRet = TX_NONSTANDARD;
1811 std::vector<valtype> vSolutions;
1812 if (!Solver(scriptPubKey, typeRet, vSolutions))
1814 if (typeRet == TX_NULL_DATA)
1820 if (typeRet == TX_MULTISIG)
1822 nRequiredRet = vSolutions.front()[0];
1823 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1825 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1826 addressRet.push_back(address);
1832 if (typeRet == TX_PUBKEY_DROP)
1834 CTxDestination address;
1835 if (!ExtractDestination(scriptPubKey, address))
1837 addressRet.push_back(address);
1843 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1844 unsigned int flags, int nHashType)
1846 std::vector<std::vector<unsigned char> > stack, stackCopy;
1847 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1849 if (flags & SCRIPT_VERIFY_P2SH)
1851 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1856 if (CastToBool(stack.back()) == false)
1859 // Additional validation for spend-to-script-hash transactions:
1860 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1862 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1863 return false; // or validation fails
1865 // stackCopy cannot be empty here, because if it was the
1866 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1867 // an empty stack and the EvalScript above would return false.
1868 assert(!stackCopy.empty());
1870 const valtype& pubKeySerialized = stackCopy.back();
1871 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1872 popstack(stackCopy);
1874 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1876 if (stackCopy.empty())
1878 return CastToBool(stackCopy.back());
1884 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1886 assert(nIn < txTo.vin.size());
1887 CTxIn& txin = txTo.vin[nIn];
1889 // Leave out the signature from the hash, since a signature can't sign itself.
1890 // The checksig op will also drop the signatures from its hash.
1891 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1893 txnouttype whichType;
1894 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1897 if (whichType == TX_SCRIPTHASH)
1899 // Solver returns the subscript that need to be evaluated;
1900 // the final scriptSig is the signatures from that
1901 // and then the serialized subscript:
1902 CScript subscript = txin.scriptSig;
1904 // Recompute txn hash using subscript in place of scriptPubKey:
1905 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1909 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1910 // Append serialized subscript whether or not it is completely signed:
1911 txin.scriptSig << static_cast<valtype>(subscript);
1912 if (!fSolved) return false;
1916 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1919 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1921 assert(nIn < txTo.vin.size());
1922 CTxIn& txin = txTo.vin[nIn];
1923 assert(txin.prevout.n < txFrom.vout.size());
1924 assert(txin.prevout.hash == txFrom.GetHash());
1925 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1927 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1930 static CScript PushAll(const std::vector<valtype>& values)
1933 for (const valtype& v : values)
1938 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1939 const std::vector<valtype>& vSolutions,
1940 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1942 // Combine all the signatures we've got:
1943 std::set<valtype> allsigs;
1944 for (const valtype& v : sigs1)
1949 for (const valtype& v : sigs2)
1955 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1956 assert(vSolutions.size() > 1);
1957 unsigned int nSigsRequired = vSolutions.front()[0];
1958 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1959 std::map<valtype, valtype> sigs;
1960 for (const valtype& sig : allsigs)
1962 for (unsigned int i = 0; i < nPubKeys; i++)
1964 const valtype& pubkey = vSolutions[i+1];
1965 if (sigs.count(pubkey))
1966 continue; // Already got a sig for this pubkey
1968 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1975 // Now build a merged CScript:
1976 unsigned int nSigsHave = 0;
1977 CScript result; result << OP_0; // pop-one-too-many workaround
1978 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1980 if (sigs.count(vSolutions[i+1]))
1982 result << sigs[vSolutions[i+1]];
1986 // Fill any missing with OP_0:
1987 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1993 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1994 const txnouttype txType, const std::vector<valtype>& vSolutions,
1995 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1999 case TX_NONSTANDARD:
2001 // Don't know anything about this, assume bigger one is correct:
2002 if (sigs1.size() >= sigs2.size())
2003 return PushAll(sigs1);
2004 return PushAll(sigs2);
2006 case TX_PUBKEY_DROP:
2008 // Signatures are bigger than placeholders or empty scripts:
2009 if (sigs1.empty() || sigs1[0].empty())
2010 return PushAll(sigs2);
2011 return PushAll(sigs1);
2013 if (sigs1.empty() || sigs1.back().empty())
2014 return PushAll(sigs2);
2015 else if (sigs2.empty() || sigs2.back().empty())
2016 return PushAll(sigs1);
2019 // Recur to combine:
2020 valtype spk = sigs1.back();
2021 CScript pubKey2(spk.begin(), spk.end());
2024 std::vector<std::vector<unsigned char> > vSolutions2;
2025 Solver(pubKey2, txType2, vSolutions2);
2028 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2033 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2039 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2040 const CScript& scriptSig1, const CScript& scriptSig2)
2043 std::vector<std::vector<unsigned char> > vSolutions;
2044 Solver(scriptPubKey, txType, vSolutions);
2046 std::vector<valtype> stack1;
2047 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2048 std::vector<valtype> stack2;
2049 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2051 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2054 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2057 const_iterator pc = begin();
2058 opcodetype lastOpcode = OP_INVALIDOPCODE;
2062 if (!GetOp(pc, opcode))
2064 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2066 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2068 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2069 n += DecodeOP_N(lastOpcode);
2073 lastOpcode = opcode;
2078 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2080 if (!IsPayToScriptHash())
2081 return GetSigOpCount(true);
2083 // This is a pay-to-script-hash scriptPubKey;
2084 // get the last item that the scriptSig
2085 // pushes onto the stack:
2086 const_iterator pc = scriptSig.begin();
2087 vector<unsigned char> data;
2088 while (pc < scriptSig.end())
2091 if (!scriptSig.GetOp(pc, opcode, data))
2097 /// ... and return its opcount:
2098 CScript subscript(data.begin(), data.end());
2099 return subscript.GetSigOpCount(true);
2102 bool CScript::IsPayToScriptHash() const
2104 // Extra-fast test for pay-to-script-hash CScripts:
2105 return (this->size() == 23 &&
2106 this->at(0) == OP_HASH160 &&
2107 this->at(1) == 0x14 &&
2108 this->at(22) == OP_EQUAL);
2111 bool CScript::HasCanonicalPushes() const
2113 const_iterator pc = begin();
2117 std::vector<unsigned char> data;
2118 if (!GetOp(pc, opcode, data))
2122 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2123 // Could have used an OP_n code, rather than a 1-byte push.
2125 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2126 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2128 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2129 // Could have used an OP_PUSHDATA1.
2131 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2132 // Could have used an OP_PUSHDATA2.
2138 class CScriptVisitor
2143 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2145 bool operator()(const CNoDestination &dest) const {
2150 bool operator()(const CKeyID &keyID) const {
2152 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2156 bool operator()(const CScriptID &scriptID) const {
2158 *script << OP_HASH160 << scriptID << OP_EQUAL;
2163 void CScript::SetDestination(const CTxDestination& dest)
2165 std::visit(CScriptVisitor(this), dest);
2168 void CScript::SetAddress(const CBitcoinAddress& dest)
2171 if (dest.IsScript())
2172 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2173 else if (dest.IsPubKey())
2174 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2175 else if (dest.IsPair()) {
2176 // Pubkey pair address, going to generate
2177 // new one-time public key.
2178 CMalleablePubKey mpk;
2179 if (!mpk.setvch(dest.GetData()))
2181 CPubKey R, pubKeyVariant;
2182 mpk.GetVariant(R, pubKeyVariant);
2183 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2187 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2191 *this << EncodeOP_N(nRequired);
2192 for (const CPubKey& key : keys)
2194 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2197 CScriptID CScript::GetID() const
2199 return CScriptID(Hash160(*this));