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.
15 #include <shared_mutex>
17 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);
19 static const valtype vchFalse(0);
20 static const valtype vchZero(0);
21 static const valtype vchTrue(1, 1);
22 static const CBigNum bnZero(0);
23 static const CBigNum bnOne(1);
24 static const CBigNum bnFalse(0);
25 static const CBigNum bnTrue(1);
26 static const size_t nMaxNumSize = 4;
29 CBigNum CastToBigNum(const valtype& vch)
31 if (vch.size() > nMaxNumSize)
32 throw std::runtime_error("CastToBigNum() : overflow");
33 // Get rid of extra leading zeros
34 return CBigNum(CBigNum(vch).getvch());
37 bool CastToBool(const valtype& vch)
39 for (unsigned int i = 0; i < vch.size(); i++)
43 // Can be negative zero
44 if (i == vch.size()-1 && vch[i] == 0x80)
53 // WARNING: This does not work as expected for signed integers; the sign-bit
54 // is left in place as the integer is zero-extended. The correct behavior
55 // would be to move the most significant bit of the last byte during the
56 // resize process. MakeSameSize() is currently only used by the disabled
57 // opcodes OP_AND, OP_OR, and OP_XOR.
59 void MakeSameSize(valtype& vch1, valtype& vch2)
61 // Lengthen the shorter one
62 if (vch1.size() < vch2.size())
64 // +unsigned char msb = vch1[vch1.size()-1];
65 // +vch1[vch1.size()-1] &= 0x7f;
66 // vch1.resize(vch2.size(), 0);
67 // +vch1[vch1.size()-1] = msb;
68 vch1.resize(vch2.size(), 0);
69 if (vch2.size() < vch1.size())
71 // +unsigned char msb = vch2[vch2.size()-1];
72 // +vch2[vch2.size()-1] &= 0x7f;
73 // vch2.resize(vch1.size(), 0);
74 // +vch2[vch2.size()-1] = msb;
75 vch2.resize(vch1.size(), 0);
81 // Script is a stack machine (like Forth) that evaluates a predicate
82 // returning a bool indicating valid or not. There are no loops.
84 #define stacktop(i) (stack.at(stack.size()+(i)))
85 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
86 static inline void popstack(std::vector<valtype>& stack)
89 throw std::runtime_error("popstack() : stack empty");
94 const char* GetTxnOutputType(txnouttype t)
98 case TX_NONSTANDARD: return "nonstandard";
99 case TX_PUBKEY: return "pubkey";
100 case TX_PUBKEY_DROP: return "pubkeydrop";
101 case TX_PUBKEYHASH: return "pubkeyhash";
102 case TX_SCRIPTHASH: return "scripthash";
103 case TX_MULTISIG: return "multisig";
104 case TX_NULL_DATA: return "nulldata";
110 const char* GetOpName(opcodetype opcode)
115 case OP_0 : return "0";
116 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
117 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
118 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
119 case OP_1NEGATE : return "-1";
120 case OP_RESERVED : return "OP_RESERVED";
121 case OP_1 : return "1";
122 case OP_2 : return "2";
123 case OP_3 : return "3";
124 case OP_4 : return "4";
125 case OP_5 : return "5";
126 case OP_6 : return "6";
127 case OP_7 : return "7";
128 case OP_8 : return "8";
129 case OP_9 : return "9";
130 case OP_10 : return "10";
131 case OP_11 : return "11";
132 case OP_12 : return "12";
133 case OP_13 : return "13";
134 case OP_14 : return "14";
135 case OP_15 : return "15";
136 case OP_16 : return "16";
139 case OP_NOP : return "OP_NOP";
140 case OP_VER : return "OP_VER";
141 case OP_IF : return "OP_IF";
142 case OP_NOTIF : return "OP_NOTIF";
143 case OP_VERIF : return "OP_VERIF";
144 case OP_VERNOTIF : return "OP_VERNOTIF";
145 case OP_ELSE : return "OP_ELSE";
146 case OP_ENDIF : return "OP_ENDIF";
147 case OP_VERIFY : return "OP_VERIFY";
148 case OP_RETURN : return "OP_RETURN";
149 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
150 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
153 case OP_TOALTSTACK : return "OP_TOALTSTACK";
154 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
155 case OP_2DROP : return "OP_2DROP";
156 case OP_2DUP : return "OP_2DUP";
157 case OP_3DUP : return "OP_3DUP";
158 case OP_2OVER : return "OP_2OVER";
159 case OP_2ROT : return "OP_2ROT";
160 case OP_2SWAP : return "OP_2SWAP";
161 case OP_IFDUP : return "OP_IFDUP";
162 case OP_DEPTH : return "OP_DEPTH";
163 case OP_DROP : return "OP_DROP";
164 case OP_DUP : return "OP_DUP";
165 case OP_NIP : return "OP_NIP";
166 case OP_OVER : return "OP_OVER";
167 case OP_PICK : return "OP_PICK";
168 case OP_ROLL : return "OP_ROLL";
169 case OP_ROT : return "OP_ROT";
170 case OP_SWAP : return "OP_SWAP";
171 case OP_TUCK : return "OP_TUCK";
174 case OP_CAT : return "OP_CAT";
175 case OP_SUBSTR : return "OP_SUBSTR";
176 case OP_LEFT : return "OP_LEFT";
177 case OP_RIGHT : return "OP_RIGHT";
178 case OP_SIZE : return "OP_SIZE";
181 case OP_INVERT : return "OP_INVERT";
182 case OP_AND : return "OP_AND";
183 case OP_OR : return "OP_OR";
184 case OP_XOR : return "OP_XOR";
185 case OP_EQUAL : return "OP_EQUAL";
186 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
187 case OP_RESERVED1 : return "OP_RESERVED1";
188 case OP_RESERVED2 : return "OP_RESERVED2";
191 case OP_1ADD : return "OP_1ADD";
192 case OP_1SUB : return "OP_1SUB";
193 case OP_2MUL : return "OP_2MUL";
194 case OP_2DIV : return "OP_2DIV";
195 case OP_NEGATE : return "OP_NEGATE";
196 case OP_ABS : return "OP_ABS";
197 case OP_NOT : return "OP_NOT";
198 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
199 case OP_ADD : return "OP_ADD";
200 case OP_SUB : return "OP_SUB";
201 case OP_MUL : return "OP_MUL";
202 case OP_DIV : return "OP_DIV";
203 case OP_MOD : return "OP_MOD";
204 case OP_LSHIFT : return "OP_LSHIFT";
205 case OP_RSHIFT : return "OP_RSHIFT";
206 case OP_BOOLAND : return "OP_BOOLAND";
207 case OP_BOOLOR : return "OP_BOOLOR";
208 case OP_NUMEQUAL : return "OP_NUMEQUAL";
209 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
210 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
211 case OP_LESSTHAN : return "OP_LESSTHAN";
212 case OP_GREATERTHAN : return "OP_GREATERTHAN";
213 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
214 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
215 case OP_MIN : return "OP_MIN";
216 case OP_MAX : return "OP_MAX";
217 case OP_WITHIN : return "OP_WITHIN";
220 case OP_RIPEMD160 : return "OP_RIPEMD160";
221 case OP_SHA1 : return "OP_SHA1";
222 case OP_SHA256 : return "OP_SHA256";
223 case OP_HASH160 : return "OP_HASH160";
224 case OP_HASH256 : return "OP_HASH256";
225 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
226 case OP_CHECKSIG : return "OP_CHECKSIG";
227 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
228 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
229 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
232 case OP_NOP1 : return "OP_NOP1";
233 case OP_NOP4 : return "OP_NOP4";
234 case OP_NOP5 : return "OP_NOP5";
235 case OP_NOP6 : return "OP_NOP6";
236 case OP_NOP7 : return "OP_NOP7";
237 case OP_NOP8 : return "OP_NOP8";
238 case OP_NOP9 : return "OP_NOP9";
239 case OP_NOP10 : return "OP_NOP10";
243 // template matching params
244 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
245 case OP_PUBKEY : return "OP_PUBKEY";
246 case OP_SMALLDATA : return "OP_SMALLDATA";
248 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
254 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
255 if (!(flags & SCRIPT_VERIFY_STRICTENC))
258 if (vchPubKey.size() < 33)
259 return error("Non-canonical public key: too short");
260 if (vchPubKey[0] == 0x04) {
261 if (vchPubKey.size() != 65)
262 return error("Non-canonical public key: invalid length for uncompressed key");
263 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
264 if (vchPubKey.size() != 33)
265 return error("Non-canonical public key: invalid length for compressed key");
267 return error("Non-canonical public key: compressed nor uncompressed");
272 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
273 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
274 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
275 // Where R and S are not negative (their first byte has its highest bit not set), and not
276 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
277 // in which case a single 0 byte is necessary and even required).
278 if (vchSig.size() < 9)
279 return error("Non-canonical signature: too short");
280 if (vchSig.size() > 73)
281 return error("Non-canonical signature: too long");
282 if (vchSig[0] != 0x30)
283 return error("Non-canonical signature: wrong type");
284 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
285 return error("Non-canonical signature: wrong length marker");
287 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
288 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
289 return error("Non-canonical signature: unknown hashtype byte");
291 unsigned int nLenR = vchSig[3];
292 if (5 + nLenR >= vchSig.size())
293 return error("Non-canonical signature: S length misplaced");
294 unsigned int nLenS = vchSig[5+nLenR];
295 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
296 return error("Non-canonical signature: R+S length mismatch");
298 const unsigned char *R = &vchSig[4];
300 return error("Non-canonical signature: R value type mismatch");
302 return error("Non-canonical signature: R length is zero");
304 return error("Non-canonical signature: R value negative");
305 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
306 return error("Non-canonical signature: R value excessively padded");
308 const unsigned char *S = &vchSig[6+nLenR];
310 return error("Non-canonical signature: S value type mismatch");
312 return error("Non-canonical signature: S length is zero");
314 return error("Non-canonical signature: S value negative");
315 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
316 return error("Non-canonical signature: S value excessively padded");
319 unsigned int nLenR = vchSig[3];
320 unsigned int nLenS = vchSig[5+nLenR];
321 const unsigned char *S = &vchSig[6+nLenR];
322 // If the S value is above the order of the curve divided by two, its
323 // complement modulo the order could have been used instead, which is
324 // one byte shorter when encoded correctly.
325 if (!CKey::CheckSignatureElement(S, nLenS, true))
326 return error("Non-canonical signature: S value is unnecessarily high");
332 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
333 if (!(flags & SCRIPT_VERIFY_STRICTENC))
336 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
339 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
341 // There are two kinds of nLockTime: lock-by-blockheight
342 // and lock-by-blocktime, distinguished by whether
343 // nLockTime < LOCKTIME_THRESHOLD.
345 // We want to compare apples to apples, so fail the script
346 // unless the type of nLockTime being tested is the same as
347 // the nLockTime in the transaction.
349 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
350 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
354 // Now that we know we're comparing apples-to-apples, the
355 // comparison is a simple numeric one.
356 if (nLockTime > (int64_t)txTo.nLockTime)
359 // Finally the nLockTime feature can be disabled and thus
360 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
361 // finalized by setting nSequence to maxint. The
362 // transaction would be allowed into the blockchain, making
363 // the opcode ineffective.
365 // Testing if this vin is not final is sufficient to
366 // prevent this condition. Alternatively we could test all
367 // inputs, but testing just this input minimizes the data
368 // required to prove correct CHECKLOCKTIMEVERIFY execution.
369 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
375 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
377 // Relative lock times are supported by comparing the passed
378 // in operand to the sequence number of the input.
379 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
381 // Sequence numbers with their most significant bit set are not
382 // consensus constrained. Testing that the transaction's sequence
383 // number do not have this bit set prevents using this property
384 // to get around a CHECKSEQUENCEVERIFY check.
385 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
388 // Mask off any bits that do not have consensus-enforced meaning
389 // before doing the integer comparisons
390 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
391 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
392 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
394 // There are two kinds of nSequence: lock-by-blockheight
395 // and lock-by-blocktime, distinguished by whether
396 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
398 // We want to compare apples to apples, so fail the script
399 // unless the type of nSequenceMasked being tested is the same as
400 // the nSequenceMasked in the transaction.
402 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
403 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
408 // Now that we know we're comparing apples-to-apples, the
409 // comparison is a simple numeric one.
410 if (nSequenceMasked > txToSequenceMasked)
416 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
419 CScript::const_iterator pc = script.begin();
420 CScript::const_iterator pend = script.end();
421 CScript::const_iterator pbegincodehash = script.begin();
423 valtype vchPushValue;
424 std::vector<bool> vfExec;
425 std::vector<valtype> altstack;
426 if (script.size() > 10000)
434 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
439 if (!script.GetOp(pc, opcode, vchPushValue))
441 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
443 if (opcode > OP_16 && ++nOpCount > 201)
446 if (opcode == OP_CAT ||
447 opcode == OP_SUBSTR ||
449 opcode == OP_RIGHT ||
450 opcode == OP_INVERT ||
459 opcode == OP_LSHIFT ||
461 return false; // Disabled opcodes.
463 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
464 stack.push_back(vchPushValue);
465 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
490 CBigNum bn((int)opcode - (int)(OP_1 - 1));
491 stack.push_back(bn.getvch());
500 case OP_NOP1: case OP_NOP4: case OP_NOP5:
501 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
507 // <expression> if [statements] [else [statements]] endif
511 if (stack.size() < 1)
513 valtype& vch = stacktop(-1);
514 fValue = CastToBool(vch);
515 if (opcode == OP_NOTIF)
519 vfExec.push_back(fValue);
527 vfExec.back() = !vfExec.back();
542 // (false -- false) and return
543 if (stack.size() < 1)
545 bool fValue = CastToBool(stacktop(-1));
559 case OP_CHECKLOCKTIMEVERIFY:
561 // CHECKLOCKTIMEVERIFY
563 // (nLockTime -- nLockTime)
564 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
565 // treat as a NOP2 if not enabled
569 if (stack.size() < 1)
572 CBigNum nLockTime = CastToBigNum(stacktop(-1));
574 // In the rare event that the argument may be < 0 due to
575 // some arithmetic being done first, you can always use
576 // 0 MAX CHECKLOCKTIMEVERIFY.
580 // Actually compare the specified lock time with the transaction.
581 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
587 case OP_CHECKSEQUENCEVERIFY:
589 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
590 // treat as a NOP3 not enabled
594 if (stack.size() < 1)
597 // nSequence, like nLockTime, is a 32-bit unsigned integer
598 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
599 // 5-byte numeric operands.
600 CBigNum nSequence = CastToBigNum(stacktop(-1));
602 // In the rare event that the argument may be < 0 due to
603 // some arithmetic being done first, you can always use
604 // 0 MAX CHECKSEQUENCEVERIFY.
608 // To provide for future soft-fork extensibility, if the
609 // operand has the disabled lock-time flag set,
610 // CHECKSEQUENCEVERIFY behaves as a NOP.
611 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
614 // Compare the specified sequence number with the input.
615 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
626 if (stack.size() < 1)
628 altstack.push_back(stacktop(-1));
633 case OP_FROMALTSTACK:
635 if (altstack.size() < 1)
637 stack.push_back(altstacktop(-1));
645 if (stack.size() < 2)
654 // (x1 x2 -- x1 x2 x1 x2)
655 if (stack.size() < 2)
657 valtype vch1 = stacktop(-2);
658 valtype vch2 = stacktop(-1);
659 stack.push_back(vch1);
660 stack.push_back(vch2);
666 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
667 if (stack.size() < 3)
669 valtype vch1 = stacktop(-3);
670 valtype vch2 = stacktop(-2);
671 valtype vch3 = stacktop(-1);
672 stack.push_back(vch1);
673 stack.push_back(vch2);
674 stack.push_back(vch3);
680 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
681 if (stack.size() < 4)
683 valtype vch1 = stacktop(-4);
684 valtype vch2 = stacktop(-3);
685 stack.push_back(vch1);
686 stack.push_back(vch2);
692 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
693 if (stack.size() < 6)
695 valtype vch1 = stacktop(-6);
696 valtype vch2 = stacktop(-5);
697 stack.erase(stack.end()-6, stack.end()-4);
698 stack.push_back(vch1);
699 stack.push_back(vch2);
705 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
706 if (stack.size() < 4)
708 swap(stacktop(-4), stacktop(-2));
709 swap(stacktop(-3), stacktop(-1));
716 if (stack.size() < 1)
718 valtype vch = stacktop(-1);
720 stack.push_back(vch);
727 CBigNum bn((uint16_t) stack.size());
728 stack.push_back(bn.getvch());
735 if (stack.size() < 1)
744 if (stack.size() < 1)
746 valtype vch = stacktop(-1);
747 stack.push_back(vch);
754 if (stack.size() < 2)
756 stack.erase(stack.end() - 2);
762 // (x1 x2 -- x1 x2 x1)
763 if (stack.size() < 2)
765 valtype vch = stacktop(-2);
766 stack.push_back(vch);
773 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
774 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
775 if (stack.size() < 2)
777 int n = CastToBigNum(stacktop(-1)).getint32();
779 if (n < 0 || n >= (int)stack.size())
781 valtype vch = stacktop(-n-1);
782 if (opcode == OP_ROLL)
783 stack.erase(stack.end()-n-1);
784 stack.push_back(vch);
790 // (x1 x2 x3 -- x2 x3 x1)
791 // x2 x1 x3 after first swap
792 // x2 x3 x1 after second swap
793 if (stack.size() < 3)
795 swap(stacktop(-3), stacktop(-2));
796 swap(stacktop(-2), stacktop(-1));
803 if (stack.size() < 2)
805 swap(stacktop(-2), stacktop(-1));
811 // (x1 x2 -- x2 x1 x2)
812 if (stack.size() < 2)
814 valtype vch = stacktop(-1);
815 stack.insert(stack.end()-2, vch);
823 if (stack.size() < 1)
825 CBigNum bn((uint16_t) stacktop(-1).size());
826 stack.push_back(bn.getvch());
836 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
839 if (stack.size() < 2)
841 valtype& vch1 = stacktop(-2);
842 valtype& vch2 = stacktop(-1);
843 bool fEqual = (vch1 == vch2);
844 // OP_NOTEQUAL is disabled because it would be too easy to say
845 // something like n != 1 and have some wiseguy pass in 1 with extra
846 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
847 //if (opcode == OP_NOTEQUAL)
851 stack.push_back(fEqual ? vchTrue : vchFalse);
852 if (opcode == OP_EQUALVERIFY)
874 if (stack.size() < 1)
876 CBigNum bn = CastToBigNum(stacktop(-1));
879 case OP_1ADD: bn += bnOne; break;
880 case OP_1SUB: bn -= bnOne; break;
881 case OP_NEGATE: bn = -bn; break;
882 case OP_ABS: if (bn < bnZero) bn = -bn; break;
883 case OP_NOT: bn = (bn == bnZero); break;
884 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
885 default: assert(!"invalid opcode"); break;
888 stack.push_back(bn.getvch());
897 case OP_NUMEQUALVERIFY:
901 case OP_LESSTHANOREQUAL:
902 case OP_GREATERTHANOREQUAL:
907 if (stack.size() < 2)
909 CBigNum bn1 = CastToBigNum(stacktop(-2));
910 CBigNum bn2 = CastToBigNum(stacktop(-1));
922 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
923 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
924 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
925 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
926 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
927 case OP_LESSTHAN: bn = (bn1 < bn2); break;
928 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
929 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
930 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
931 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
932 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
933 default: assert(!"invalid opcode"); break;
937 stack.push_back(bn.getvch());
939 if (opcode == OP_NUMEQUALVERIFY)
941 if (CastToBool(stacktop(-1)))
951 // (x min max -- out)
952 if (stack.size() < 3)
954 CBigNum bn1 = CastToBigNum(stacktop(-3));
955 CBigNum bn2 = CastToBigNum(stacktop(-2));
956 CBigNum bn3 = CastToBigNum(stacktop(-1));
957 bool fValue = (bn2 <= bn1 && bn1 < bn3);
961 stack.push_back(fValue ? vchTrue : vchFalse);
976 if (stack.size() < 1)
978 valtype& vch = stacktop(-1);
979 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
980 if (opcode == OP_RIPEMD160)
981 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
982 else if (opcode == OP_SHA1)
983 SHA1(&vch[0], vch.size(), &vchHash[0]);
984 else if (opcode == OP_SHA256)
985 SHA256(&vch[0], vch.size(), &vchHash[0]);
986 else if (opcode == OP_HASH160)
988 uint160 hash160 = Hash160(vch);
989 memcpy(&vchHash[0], &hash160, sizeof(hash160));
991 else if (opcode == OP_HASH256)
993 uint256 hash = Hash(vch.begin(), vch.end());
994 memcpy(&vchHash[0], &hash, sizeof(hash));
997 stack.push_back(vchHash);
1001 case OP_CODESEPARATOR:
1003 // Hash starts after the code separator
1004 pbegincodehash = pc;
1009 case OP_CHECKSIGVERIFY:
1011 // (sig pubkey -- bool)
1012 if (stack.size() < 2)
1015 valtype& vchSig = stacktop(-2);
1016 valtype& vchPubKey = stacktop(-1);
1019 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1020 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1022 // Subset of script starting at the most recent codeseparator
1023 CScript scriptCode(pbegincodehash, pend);
1025 // Drop the signature, since there's no way for a signature to sign itself
1026 scriptCode.FindAndDelete(CScript(vchSig));
1028 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1029 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1033 stack.push_back(fSuccess ? vchTrue : vchFalse);
1034 if (opcode == OP_CHECKSIGVERIFY)
1044 case OP_CHECKMULTISIG:
1045 case OP_CHECKMULTISIGVERIFY:
1047 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1050 if ((int)stack.size() < i)
1053 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1054 if (nKeysCount < 0 || nKeysCount > 20)
1056 nOpCount += nKeysCount;
1061 if ((int)stack.size() < i)
1064 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1065 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1069 if ((int)stack.size() < i)
1072 // Subset of script starting at the most recent codeseparator
1073 CScript scriptCode(pbegincodehash, pend);
1075 // Drop the signatures, since there's no way for a signature to sign itself
1076 for (int k = 0; k < nSigsCount; k++)
1078 valtype& vchSig = stacktop(-isig-k);
1079 scriptCode.FindAndDelete(CScript(vchSig));
1082 bool fSuccess = true;
1083 while (fSuccess && nSigsCount > 0)
1085 valtype& vchSig = stacktop(-isig);
1086 valtype& vchPubKey = stacktop(-ikey);
1089 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1090 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1099 // If there are more signatures left than keys left,
1100 // then too many signatures have failed
1101 if (nSigsCount > nKeysCount)
1108 // A bug causes CHECKMULTISIG to consume one extra argument
1109 // whose contents were not checked in any way.
1111 // Unfortunately this is a potential source of mutability,
1112 // so optionally verify it is exactly equal to zero prior
1113 // to removing it from the stack.
1114 if (stack.size() < 1)
1116 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1117 return error("CHECKMULTISIG dummy argument not null");
1120 stack.push_back(fSuccess ? vchTrue : vchFalse);
1122 if (opcode == OP_CHECKMULTISIGVERIFY)
1137 if (stack.size() + altstack.size() > 1000)
1147 if (!vfExec.empty())
1161 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1163 if (nIn >= txTo.vin.size())
1165 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1168 CTransaction txTmp(txTo);
1170 // In case concatenating two scripts ends up with two codeseparators,
1171 // or an extra one at the end, this prevents all those possible incompatibilities.
1172 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1174 // Blank out other inputs' signatures
1175 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1176 txTmp.vin[i].scriptSig = CScript();
1177 txTmp.vin[nIn].scriptSig = scriptCode;
1179 // Blank out some of the outputs
1180 if ((nHashType & 0x1f) == SIGHASH_NONE)
1185 // Let the others update at will
1186 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1188 txTmp.vin[i].nSequence = 0;
1190 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1192 // Only lock-in the txout payee at same index as txin
1193 unsigned int nOut = nIn;
1194 if (nOut >= txTmp.vout.size())
1196 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1199 txTmp.vout.resize(nOut+1);
1200 for (unsigned int i = 0; i < nOut; i++)
1201 txTmp.vout[i].SetNull();
1203 // Let the others update at will
1204 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1206 txTmp.vin[i].nSequence = 0;
1209 // Blank out other inputs completely, not recommended for open transactions
1210 if (nHashType & SIGHASH_ANYONECANPAY)
1212 txTmp.vin[0] = txTmp.vin[nIn];
1213 txTmp.vin.resize(1);
1216 // Serialize and hash
1217 CDataStream ss(SER_GETHASH, 0);
1219 ss << txTmp << nHashType;
1220 return Hash(ss.begin(), ss.end());
1224 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1225 // twice for every transaction (once when accepted into memory pool, and
1226 // again when accepted into the block chain)
1228 class CSignatureCache
1231 // sigdata_type is (signature hash, signature, public key):
1232 using sigdata_type = std::tuple<uint256, std::vector<unsigned char>, CPubKey>;
1233 std::set<sigdata_type> setValid;
1234 std::shared_mutex cs_sigcache;
1238 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1240 std::shared_lock<std::shared_mutex> lock(cs_sigcache);
1242 sigdata_type k(hash, vchSig, pubKey);
1243 std::set<sigdata_type>::iterator mi = setValid.find(k);
1244 if (mi != setValid.end())
1249 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1251 // DoS prevention: limit cache size to less than 10MB
1252 // (~200 bytes per cache entry times 50,000 entries)
1253 // Since there are a maximum of 20,000 signature operations per block
1254 // 50,000 is a reasonable default.
1255 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1256 if (nMaxCacheSize <= 0) return;
1258 std::shared_lock<std::shared_mutex> lock(cs_sigcache);
1260 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1262 // Evict a random entry. Random because that helps
1263 // foil would-be DoS attackers who might try to pre-generate
1264 // and re-use a set of valid signatures just-slightly-greater
1265 // than our cache size.
1266 uint256 randomHash = GetRandHash();
1267 std::vector<unsigned char> unused;
1268 std::set<sigdata_type>::iterator it =
1269 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1270 if (it == setValid.end())
1271 it = setValid.begin();
1272 setValid.erase(*it);
1275 sigdata_type k(hash, vchSig, pubKey);
1280 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1281 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1283 static CSignatureCache signatureCache;
1285 CPubKey pubkey(vchPubKey);
1286 if (!pubkey.IsValid())
1289 // Hash type is one byte tacked on to the end of the signature
1293 nHashType = vchSig.back();
1294 else if (nHashType != vchSig.back())
1298 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1300 if (signatureCache.Get(sighash, vchSig, pubkey))
1303 if (!pubkey.Verify(sighash, vchSig))
1306 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1307 signatureCache.Set(sighash, vchSig, pubkey);
1314 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1316 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
1319 static std::map<txnouttype, CScript> mTemplates;
1320 if (mTemplates.empty())
1322 // Standard tx, sender provides pubkey, receiver adds signature
1323 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1325 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1326 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1328 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1329 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1331 // Sender provides N pubkeys, receivers provides M signatures
1332 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1334 // Empty, provably prunable, data-carrying output
1335 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1338 vSolutionsRet.clear();
1340 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1341 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1342 if (scriptPubKey.IsPayToScriptHash())
1344 typeRet = TX_SCRIPTHASH;
1345 std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1346 vSolutionsRet.push_back(hashBytes);
1350 // Provably prunable, data-carrying output
1352 // So long as script passes the IsUnspendable() test and all but the first
1353 // byte passes the IsPushOnly() test we don't care what exactly is in the
1355 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1356 typeRet = TX_NULL_DATA;
1361 const CScript& script1 = scriptPubKey;
1362 for (const auto& tplate : mTemplates)
1364 const CScript& script2 = tplate.second;
1365 vSolutionsRet.clear();
1367 opcodetype opcode1, opcode2;
1368 std::vector<unsigned char> vch1, vch2;
1371 CScript::const_iterator pc1 = script1.begin();
1372 CScript::const_iterator pc2 = script2.begin();
1375 if (pc1 == script1.end() && pc2 == script2.end())
1378 typeRet = tplate.first;
1379 if (typeRet == TX_MULTISIG)
1381 // Additional checks for TX_MULTISIG:
1382 unsigned char m = vSolutionsRet.front()[0];
1383 unsigned char n = vSolutionsRet.back()[0];
1384 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1389 if (!script1.GetOp(pc1, opcode1, vch1))
1391 if (!script2.GetOp(pc2, opcode2, vch2))
1394 // Template matching opcodes:
1395 if (opcode2 == OP_PUBKEYS)
1397 while (vch1.size() >= 33 && vch1.size() <= 120)
1399 vSolutionsRet.push_back(vch1);
1400 if (!script1.GetOp(pc1, opcode1, vch1))
1403 if (!script2.GetOp(pc2, opcode2, vch2))
1405 // Normal situation is to fall through
1406 // to other if/else statements
1409 if (opcode2 == OP_PUBKEY)
1411 if (vch1.size() < 33 || vch1.size() > 120)
1413 vSolutionsRet.push_back(vch1);
1415 else if (opcode2 == OP_PUBKEYHASH)
1417 if (vch1.size() != sizeof(uint160))
1419 vSolutionsRet.push_back(vch1);
1421 else if (opcode2 == OP_SMALLINTEGER)
1422 { // Single-byte small integer pushed onto vSolutions
1423 if (opcode1 == OP_0 ||
1424 (opcode1 >= OP_1 && opcode1 <= OP_16))
1426 char n = (char)CScript::DecodeOP_N(opcode1);
1427 vSolutionsRet.push_back(valtype(1, n));
1432 else if (opcode2 == OP_INTEGER)
1433 { // Up to four-byte integer pushed onto vSolutions
1436 CBigNum bnVal = CastToBigNum(vch1);
1438 break; // It's better to use OP_0 ... OP_16 for small integers.
1439 vSolutionsRet.push_back(vch1);
1446 else if (opcode2 == OP_SMALLDATA)
1448 // small pushdata, <= 1024 bytes
1449 if (vch1.size() > 1024)
1452 else if (opcode1 != opcode2 || vch1 != vch2)
1454 // Others must match exactly
1460 vSolutionsRet.clear();
1461 typeRet = TX_NONSTANDARD;
1466 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1469 if (!keystore.GetKey(address, key))
1472 std::vector<unsigned char> vchSig;
1473 if (!key.Sign(hash, vchSig))
1475 vchSig.push_back((unsigned char)nHashType);
1476 scriptSigRet << vchSig;
1481 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1484 if (!keystore.CreatePrivKey(pubKey, R, key))
1487 std::vector<unsigned char> vchSig;
1488 if (!key.Sign(hash, vchSig))
1490 vchSig.push_back((unsigned char)nHashType);
1491 scriptSigRet << vchSig;
1496 bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1499 int nRequired = multisigdata.front()[0];
1500 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1502 const valtype& pubkey = multisigdata[i];
1503 CKeyID keyID = CPubKey(pubkey).GetID();
1504 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1507 return nSigned==nRequired;
1511 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1512 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1513 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1514 // Returns false if scriptPubKey could not be completely satisfied.
1516 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1517 CScript& scriptSigRet, txnouttype& whichTypeRet)
1519 scriptSigRet.clear();
1521 std::vector<valtype> vSolutions;
1522 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1526 switch (whichTypeRet)
1528 case TX_NONSTANDARD:
1532 keyID = CPubKey(vSolutions[0]).GetID();
1533 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1534 case TX_PUBKEY_DROP:
1536 CPubKey key = CPubKey(vSolutions[0]);
1537 CPubKey R = CPubKey(vSolutions[1]);
1538 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1541 keyID = CKeyID(uint160(vSolutions[0]));
1542 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1547 keystore.GetPubKey(keyID, vch);
1548 scriptSigRet << vch;
1552 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1555 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1556 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1561 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1565 case TX_NONSTANDARD:
1570 case TX_PUBKEY_DROP:
1575 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1577 return vSolutions[0][0] + 1;
1579 return 1; // doesn't include args needed by the script
1584 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1586 std::vector<valtype> vSolutions;
1587 if (!Solver(scriptPubKey, whichType, vSolutions))
1590 if (whichType == TX_MULTISIG)
1592 unsigned char m = vSolutions.front()[0];
1593 unsigned char n = vSolutions.back()[0];
1594 // Support up to x-of-3 multisig txns as standard
1601 return whichType != TX_NONSTANDARD;
1605 unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
1607 unsigned int nResult = 0;
1608 for (const valtype& pubkey : pubkeys)
1610 CKeyID keyID = CPubKey(pubkey).GetID();
1611 if (keystore.HaveKey(keyID))
1618 class CKeyStoreIsMineVisitor
1621 const CKeyStore *keystore;
1623 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1624 bool operator()(const CNoDestination &dest) const { return false; }
1625 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1626 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1630 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1633 script.SetDestination(dest);
1634 return IsMine(keystore, script);
1637 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1640 script.SetAddress(dest);
1641 return IsMine(keystore, script);
1644 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1646 std::vector<valtype> vSolutions;
1647 txnouttype whichType;
1648 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1649 if (keystore.HaveWatchOnly(scriptPubKey))
1650 return MINE_WATCH_ONLY;
1657 case TX_NONSTANDARD:
1661 keyID = CPubKey(vSolutions[0]).GetID();
1662 if (keystore.HaveKey(keyID))
1663 return MINE_SPENDABLE;
1665 case TX_PUBKEY_DROP:
1667 CPubKey key = CPubKey(vSolutions[0]);
1668 CPubKey R = CPubKey(vSolutions[1]);
1669 if (keystore.CheckOwnership(key, R))
1670 return MINE_SPENDABLE;
1674 keyID = CKeyID(uint160(vSolutions[0]));
1675 if (keystore.HaveKey(keyID))
1676 return MINE_SPENDABLE;
1680 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1682 if (keystore.GetCScript(scriptID, subscript)) {
1683 isminetype ret = IsMine(keystore, subscript);
1684 if (ret == MINE_SPENDABLE)
1691 // Only consider transactions "mine" if we own ALL the
1692 // keys involved. multi-signature transactions that are
1693 // partially owned (somebody else has a key that can spend
1694 // them) enable spend-out-from-under-you attacks, especially
1695 // in shared-wallet situations.
1696 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1697 if (HaveKeys(keys, keystore) == keys.size())
1698 return MINE_SPENDABLE;
1703 if (keystore.HaveWatchOnly(scriptPubKey))
1704 return MINE_WATCH_ONLY;
1708 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1710 std::vector<valtype> vSolutions;
1711 txnouttype whichType;
1712 if (!Solver(scriptPubKey, whichType, vSolutions))
1715 if (whichType == TX_PUBKEY)
1717 addressRet = CPubKey(vSolutions[0]).GetID();
1720 else if (whichType == TX_PUBKEYHASH)
1722 addressRet = CKeyID(uint160(vSolutions[0]));
1725 else if (whichType == TX_SCRIPTHASH)
1727 addressRet = CScriptID(uint160(vSolutions[0]));
1730 // Multisig txns have more than one address...
1734 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1736 std::vector<valtype> vSolutions;
1737 txnouttype whichType;
1738 if (!Solver(scriptPubKey, whichType, vSolutions))
1741 if (whichType == TX_PUBKEY)
1743 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1746 if (whichType == TX_PUBKEY_DROP)
1749 CMalleableKeyView view;
1750 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1753 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1756 else if (whichType == TX_PUBKEYHASH)
1758 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1761 else if (whichType == TX_SCRIPTHASH)
1763 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1766 // Multisig txns have more than one address...
1770 class CAffectedKeysVisitor {
1772 const CKeyStore &keystore;
1773 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1774 std::vector<CKeyID> &vKeys;
1777 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1779 void Process(const CScript &script) {
1781 std::vector<CTxDestination> vDest;
1783 if (ExtractDestinations(script, type, vDest, nRequired)) {
1784 for (const CTxDestination &dest : vDest)
1785 std::visit(*this, dest);
1789 void operator()(const CKeyID &keyId) {
1790 if (keystore.HaveKey(keyId))
1791 vKeys.push_back(keyId);
1794 void operator()(const CScriptID &scriptId) {
1796 if (keystore.GetCScript(scriptId, script))
1800 void operator()(const CNoDestination &none) {}
1804 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1805 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1808 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
1811 typeRet = TX_NONSTANDARD;
1812 std::vector<valtype> vSolutions;
1813 if (!Solver(scriptPubKey, typeRet, vSolutions))
1815 if (typeRet == TX_NULL_DATA)
1821 if (typeRet == TX_MULTISIG)
1823 nRequiredRet = vSolutions.front()[0];
1824 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1826 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1827 addressRet.push_back(address);
1833 if (typeRet == TX_PUBKEY_DROP)
1835 CTxDestination address;
1836 if (!ExtractDestination(scriptPubKey, address))
1838 addressRet.push_back(address);
1844 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1845 unsigned int flags, int nHashType)
1847 std::vector<std::vector<unsigned char> > stack, stackCopy;
1848 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1850 if (flags & SCRIPT_VERIFY_P2SH)
1852 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1857 if (CastToBool(stack.back()) == false)
1860 // Additional validation for spend-to-script-hash transactions:
1861 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1863 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1864 return false; // or validation fails
1866 // stackCopy cannot be empty here, because if it was the
1867 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1868 // an empty stack and the EvalScript above would return false.
1869 assert(!stackCopy.empty());
1871 const valtype& pubKeySerialized = stackCopy.back();
1872 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1873 popstack(stackCopy);
1875 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1877 if (stackCopy.empty())
1879 return CastToBool(stackCopy.back());
1885 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1887 assert(nIn < txTo.vin.size());
1888 CTxIn& txin = txTo.vin[nIn];
1890 // Leave out the signature from the hash, since a signature can't sign itself.
1891 // The checksig op will also drop the signatures from its hash.
1892 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1894 txnouttype whichType;
1895 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1898 if (whichType == TX_SCRIPTHASH)
1900 // Solver returns the subscript that need to be evaluated;
1901 // the final scriptSig is the signatures from that
1902 // and then the serialized subscript:
1903 CScript subscript = txin.scriptSig;
1905 // Recompute txn hash using subscript in place of scriptPubKey:
1906 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1910 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1911 // Append serialized subscript whether or not it is completely signed:
1912 txin.scriptSig << static_cast<valtype>(subscript);
1913 if (!fSolved) return false;
1917 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1920 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1922 assert(nIn < txTo.vin.size());
1923 CTxIn& txin = txTo.vin[nIn];
1924 assert(txin.prevout.n < txFrom.vout.size());
1925 assert(txin.prevout.hash == txFrom.GetHash());
1926 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1928 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1931 static CScript PushAll(const std::vector<valtype>& values)
1934 for (const valtype& v : values)
1939 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1940 const std::vector<valtype>& vSolutions,
1941 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1943 // Combine all the signatures we've got:
1944 std::set<valtype> allsigs;
1945 for (const valtype& v : sigs1)
1950 for (const valtype& v : sigs2)
1956 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1957 assert(vSolutions.size() > 1);
1958 unsigned int nSigsRequired = vSolutions.front()[0];
1959 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1960 std::map<valtype, valtype> sigs;
1961 for (const valtype& sig : allsigs)
1963 for (unsigned int i = 0; i < nPubKeys; i++)
1965 const valtype& pubkey = vSolutions[i+1];
1966 if (sigs.count(pubkey))
1967 continue; // Already got a sig for this pubkey
1969 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1976 // Now build a merged CScript:
1977 unsigned int nSigsHave = 0;
1978 CScript result; result << OP_0; // pop-one-too-many workaround
1979 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1981 if (sigs.count(vSolutions[i+1]))
1983 result << sigs[vSolutions[i+1]];
1987 // Fill any missing with OP_0:
1988 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1994 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1995 const txnouttype txType, const std::vector<valtype>& vSolutions,
1996 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
2000 case TX_NONSTANDARD:
2002 // Don't know anything about this, assume bigger one is correct:
2003 if (sigs1.size() >= sigs2.size())
2004 return PushAll(sigs1);
2005 return PushAll(sigs2);
2007 case TX_PUBKEY_DROP:
2009 // Signatures are bigger than placeholders or empty scripts:
2010 if (sigs1.empty() || sigs1[0].empty())
2011 return PushAll(sigs2);
2012 return PushAll(sigs1);
2014 if (sigs1.empty() || sigs1.back().empty())
2015 return PushAll(sigs2);
2016 else if (sigs2.empty() || sigs2.back().empty())
2017 return PushAll(sigs1);
2020 // Recur to combine:
2021 valtype spk = sigs1.back();
2022 CScript pubKey2(spk.begin(), spk.end());
2025 std::vector<std::vector<unsigned char> > vSolutions2;
2026 Solver(pubKey2, txType2, vSolutions2);
2029 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2034 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2040 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2041 const CScript& scriptSig1, const CScript& scriptSig2)
2044 std::vector<std::vector<unsigned char> > vSolutions;
2045 Solver(scriptPubKey, txType, vSolutions);
2047 std::vector<valtype> stack1;
2048 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2049 std::vector<valtype> stack2;
2050 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2052 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2055 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2058 const_iterator pc = begin();
2059 opcodetype lastOpcode = OP_INVALIDOPCODE;
2063 if (!GetOp(pc, opcode))
2065 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2067 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2069 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2070 n += DecodeOP_N(lastOpcode);
2074 lastOpcode = opcode;
2079 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2081 if (!IsPayToScriptHash())
2082 return GetSigOpCount(true);
2084 // This is a pay-to-script-hash scriptPubKey;
2085 // get the last item that the scriptSig
2086 // pushes onto the stack:
2087 const_iterator pc = scriptSig.begin();
2088 vector<unsigned char> data;
2089 while (pc < scriptSig.end())
2092 if (!scriptSig.GetOp(pc, opcode, data))
2098 /// ... and return its opcount:
2099 CScript subscript(data.begin(), data.end());
2100 return subscript.GetSigOpCount(true);
2103 bool CScript::IsPayToScriptHash() const
2105 // Extra-fast test for pay-to-script-hash CScripts:
2106 return (this->size() == 23 &&
2107 this->at(0) == OP_HASH160 &&
2108 this->at(1) == 0x14 &&
2109 this->at(22) == OP_EQUAL);
2112 bool CScript::HasCanonicalPushes() const
2114 const_iterator pc = begin();
2118 std::vector<unsigned char> data;
2119 if (!GetOp(pc, opcode, data))
2123 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2124 // Could have used an OP_n code, rather than a 1-byte push.
2126 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2127 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2129 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2130 // Could have used an OP_PUSHDATA1.
2132 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2133 // Could have used an OP_PUSHDATA2.
2139 class CScriptVisitor
2144 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2146 bool operator()(const CNoDestination &dest) const {
2151 bool operator()(const CKeyID &keyID) const {
2153 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2157 bool operator()(const CScriptID &scriptID) const {
2159 *script << OP_HASH160 << scriptID << OP_EQUAL;
2164 void CScript::SetDestination(const CTxDestination& dest)
2166 std::visit(CScriptVisitor(this), dest);
2169 void CScript::SetAddress(const CBitcoinAddress& dest)
2172 if (dest.IsScript())
2173 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2174 else if (dest.IsPubKey())
2175 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2176 else if (dest.IsPair()) {
2177 // Pubkey pair address, going to generate
2178 // new one-time public key.
2179 CMalleablePubKey mpk;
2180 if (!mpk.setvch(dest.GetData()))
2182 CPubKey R, pubKeyVariant;
2183 mpk.GetVariant(R, pubKeyVariant);
2184 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2188 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2192 *this << EncodeOP_N(nRequired);
2193 for (const CPubKey& key : keys)
2195 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;