1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
16 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
18 static const valtype vchFalse(0);
19 static const valtype vchZero(0);
20 static const valtype vchTrue(1, 1);
21 static const CBigNum bnZero(0);
22 static const CBigNum bnOne(1);
23 static const CBigNum bnFalse(0);
24 static const CBigNum bnTrue(1);
25 static const size_t nMaxNumSize = 4;
28 CBigNum CastToBigNum(const valtype& vch)
30 if (vch.size() > nMaxNumSize)
31 throw runtime_error("CastToBigNum() : overflow");
32 // Get rid of extra leading zeros
33 return CBigNum(CBigNum(vch).getvch());
36 bool CastToBool(const valtype& vch)
38 for (unsigned int i = 0; i < vch.size(); i++)
42 // Can be negative zero
43 if (i == vch.size()-1 && vch[i] == 0x80)
52 // WARNING: This does not work as expected for signed integers; the sign-bit
53 // is left in place as the integer is zero-extended. The correct behavior
54 // would be to move the most significant bit of the last byte during the
55 // resize process. MakeSameSize() is currently only used by the disabled
56 // opcodes OP_AND, OP_OR, and OP_XOR.
58 void MakeSameSize(valtype& vch1, valtype& vch2)
60 // Lengthen the shorter one
61 if (vch1.size() < vch2.size())
63 // +unsigned char msb = vch1[vch1.size()-1];
64 // +vch1[vch1.size()-1] &= 0x7f;
65 // vch1.resize(vch2.size(), 0);
66 // +vch1[vch1.size()-1] = msb;
67 vch1.resize(vch2.size(), 0);
68 if (vch2.size() < vch1.size())
70 // +unsigned char msb = vch2[vch2.size()-1];
71 // +vch2[vch2.size()-1] &= 0x7f;
72 // vch2.resize(vch1.size(), 0);
73 // +vch2[vch2.size()-1] = msb;
74 vch2.resize(vch1.size(), 0);
79 // Script is a stack machine (like Forth) that evaluates a predicate
80 // returning a bool indicating valid or not. There are no loops.
82 #define stacktop(i) (stack.at(stack.size()+(i)))
84 //static inline valtype stacktop(vector<valtype>& st, int nDepth)
86 // return st.at(st.size()+nDepth);
89 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
91 static inline void popstack(vector<valtype>& stack)
94 throw runtime_error("popstack() : stack empty");
99 const char* GetTxnOutputType(txnouttype t)
103 case TX_NONSTANDARD: return "nonstandard";
104 case TX_PUBKEY: return "pubkey";
105 case TX_PUBKEY_DROP: return "pubkeydrop";
106 case TX_PUBKEYHASH: return "pubkeyhash";
107 case TX_SCRIPTHASH: return "scripthash";
108 case TX_MULTISIG: return "multisig";
109 case TX_NULL_DATA: return "nulldata";
115 const char* GetOpName(opcodetype opcode)
120 case OP_0 : return "0";
121 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
122 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
123 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
124 case OP_1NEGATE : return "-1";
125 case OP_RESERVED : return "OP_RESERVED";
126 case OP_1 : return "1";
127 case OP_2 : return "2";
128 case OP_3 : return "3";
129 case OP_4 : return "4";
130 case OP_5 : return "5";
131 case OP_6 : return "6";
132 case OP_7 : return "7";
133 case OP_8 : return "8";
134 case OP_9 : return "9";
135 case OP_10 : return "10";
136 case OP_11 : return "11";
137 case OP_12 : return "12";
138 case OP_13 : return "13";
139 case OP_14 : return "14";
140 case OP_15 : return "15";
141 case OP_16 : return "16";
144 case OP_NOP : return "OP_NOP";
145 case OP_VER : return "OP_VER";
146 case OP_IF : return "OP_IF";
147 case OP_NOTIF : return "OP_NOTIF";
148 case OP_VERIF : return "OP_VERIF";
149 case OP_VERNOTIF : return "OP_VERNOTIF";
150 case OP_ELSE : return "OP_ELSE";
151 case OP_ENDIF : return "OP_ENDIF";
152 case OP_VERIFY : return "OP_VERIFY";
153 case OP_RETURN : return "OP_RETURN";
154 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
155 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
158 case OP_TOALTSTACK : return "OP_TOALTSTACK";
159 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
160 case OP_2DROP : return "OP_2DROP";
161 case OP_2DUP : return "OP_2DUP";
162 case OP_3DUP : return "OP_3DUP";
163 case OP_2OVER : return "OP_2OVER";
164 case OP_2ROT : return "OP_2ROT";
165 case OP_2SWAP : return "OP_2SWAP";
166 case OP_IFDUP : return "OP_IFDUP";
167 case OP_DEPTH : return "OP_DEPTH";
168 case OP_DROP : return "OP_DROP";
169 case OP_DUP : return "OP_DUP";
170 case OP_NIP : return "OP_NIP";
171 case OP_OVER : return "OP_OVER";
172 case OP_PICK : return "OP_PICK";
173 case OP_ROLL : return "OP_ROLL";
174 case OP_ROT : return "OP_ROT";
175 case OP_SWAP : return "OP_SWAP";
176 case OP_TUCK : return "OP_TUCK";
179 case OP_CAT : return "OP_CAT";
180 case OP_SUBSTR : return "OP_SUBSTR";
181 case OP_LEFT : return "OP_LEFT";
182 case OP_RIGHT : return "OP_RIGHT";
183 case OP_SIZE : return "OP_SIZE";
186 case OP_INVERT : return "OP_INVERT";
187 case OP_AND : return "OP_AND";
188 case OP_OR : return "OP_OR";
189 case OP_XOR : return "OP_XOR";
190 case OP_EQUAL : return "OP_EQUAL";
191 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
192 case OP_RESERVED1 : return "OP_RESERVED1";
193 case OP_RESERVED2 : return "OP_RESERVED2";
196 case OP_1ADD : return "OP_1ADD";
197 case OP_1SUB : return "OP_1SUB";
198 case OP_2MUL : return "OP_2MUL";
199 case OP_2DIV : return "OP_2DIV";
200 case OP_NEGATE : return "OP_NEGATE";
201 case OP_ABS : return "OP_ABS";
202 case OP_NOT : return "OP_NOT";
203 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
204 case OP_ADD : return "OP_ADD";
205 case OP_SUB : return "OP_SUB";
206 case OP_MUL : return "OP_MUL";
207 case OP_DIV : return "OP_DIV";
208 case OP_MOD : return "OP_MOD";
209 case OP_LSHIFT : return "OP_LSHIFT";
210 case OP_RSHIFT : return "OP_RSHIFT";
211 case OP_BOOLAND : return "OP_BOOLAND";
212 case OP_BOOLOR : return "OP_BOOLOR";
213 case OP_NUMEQUAL : return "OP_NUMEQUAL";
214 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
215 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
216 case OP_LESSTHAN : return "OP_LESSTHAN";
217 case OP_GREATERTHAN : return "OP_GREATERTHAN";
218 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
219 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
220 case OP_MIN : return "OP_MIN";
221 case OP_MAX : return "OP_MAX";
222 case OP_WITHIN : return "OP_WITHIN";
225 case OP_RIPEMD160 : return "OP_RIPEMD160";
226 case OP_SHA1 : return "OP_SHA1";
227 case OP_SHA256 : return "OP_SHA256";
228 case OP_HASH160 : return "OP_HASH160";
229 case OP_HASH256 : return "OP_HASH256";
230 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
231 case OP_CHECKSIG : return "OP_CHECKSIG";
232 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
233 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
234 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
237 case OP_NOP1 : return "OP_NOP1";
238 case OP_NOP4 : return "OP_NOP4";
239 case OP_NOP5 : return "OP_NOP5";
240 case OP_NOP6 : return "OP_NOP6";
241 case OP_NOP7 : return "OP_NOP7";
242 case OP_NOP8 : return "OP_NOP8";
243 case OP_NOP9 : return "OP_NOP9";
244 case OP_NOP10 : return "OP_NOP10";
248 // template matching params
249 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
250 case OP_PUBKEY : return "OP_PUBKEY";
251 case OP_SMALLDATA : return "OP_SMALLDATA";
253 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
259 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
260 if (!(flags & SCRIPT_VERIFY_STRICTENC))
263 if (vchPubKey.size() < 33)
264 return error("Non-canonical public key: too short");
265 if (vchPubKey[0] == 0x04) {
266 if (vchPubKey.size() != 65)
267 return error("Non-canonical public key: invalid length for uncompressed key");
268 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
269 if (vchPubKey.size() != 33)
270 return error("Non-canonical public key: invalid length for compressed key");
272 return error("Non-canonical public key: compressed nor uncompressed");
277 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
278 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
279 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
280 // Where R and S are not negative (their first byte has its highest bit not set), and not
281 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
282 // in which case a single 0 byte is necessary and even required).
283 if (vchSig.size() < 9)
284 return error("Non-canonical signature: too short");
285 if (vchSig.size() > 73)
286 return error("Non-canonical signature: too long");
287 if (vchSig[0] != 0x30)
288 return error("Non-canonical signature: wrong type");
289 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
290 return error("Non-canonical signature: wrong length marker");
292 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
293 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
294 return error("Non-canonical signature: unknown hashtype byte");
296 unsigned int nLenR = vchSig[3];
297 if (5 + nLenR >= vchSig.size())
298 return error("Non-canonical signature: S length misplaced");
299 unsigned int nLenS = vchSig[5+nLenR];
300 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
301 return error("Non-canonical signature: R+S length mismatch");
303 const unsigned char *R = &vchSig[4];
305 return error("Non-canonical signature: R value type mismatch");
307 return error("Non-canonical signature: R length is zero");
309 return error("Non-canonical signature: R value negative");
310 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
311 return error("Non-canonical signature: R value excessively padded");
313 const unsigned char *S = &vchSig[6+nLenR];
315 return error("Non-canonical signature: S value type mismatch");
317 return error("Non-canonical signature: S length is zero");
319 return error("Non-canonical signature: S value negative");
320 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
321 return error("Non-canonical signature: S value excessively padded");
324 unsigned int nLenR = vchSig[3];
325 unsigned int nLenS = vchSig[5+nLenR];
326 const unsigned char *S = &vchSig[6+nLenR];
327 // If the S value is above the order of the curve divided by two, its
328 // complement modulo the order could have been used instead, which is
329 // one byte shorter when encoded correctly.
330 if (!CKey::CheckSignatureElement(S, nLenS, true))
331 return error("Non-canonical signature: S value is unnecessarily high");
337 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
338 if (!(flags & SCRIPT_VERIFY_STRICTENC))
341 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
344 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
346 // There are two kinds of nLockTime: lock-by-blockheight
347 // and lock-by-blocktime, distinguished by whether
348 // nLockTime < LOCKTIME_THRESHOLD.
350 // We want to compare apples to apples, so fail the script
351 // unless the type of nLockTime being tested is the same as
352 // the nLockTime in the transaction.
354 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
355 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
359 // Now that we know we're comparing apples-to-apples, the
360 // comparison is a simple numeric one.
361 if (nLockTime > (int64_t)txTo.nLockTime)
364 // Finally the nLockTime feature can be disabled and thus
365 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
366 // finalized by setting nSequence to maxint. The
367 // transaction would be allowed into the blockchain, making
368 // the opcode ineffective.
370 // Testing if this vin is not final is sufficient to
371 // prevent this condition. Alternatively we could test all
372 // inputs, but testing just this input minimizes the data
373 // required to prove correct CHECKLOCKTIMEVERIFY execution.
374 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
380 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
382 // Relative lock times are supported by comparing the passed
383 // in operand to the sequence number of the input.
384 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
386 // Sequence numbers with their most significant bit set are not
387 // consensus constrained. Testing that the transaction's sequence
388 // number do not have this bit set prevents using this property
389 // to get around a CHECKSEQUENCEVERIFY check.
390 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
393 // Mask off any bits that do not have consensus-enforced meaning
394 // before doing the integer comparisons
395 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
396 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
397 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
399 // There are two kinds of nSequence: lock-by-blockheight
400 // and lock-by-blocktime, distinguished by whether
401 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
403 // We want to compare apples to apples, so fail the script
404 // unless the type of nSequenceMasked being tested is the same as
405 // the nSequenceMasked in the transaction.
407 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
408 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
413 // Now that we know we're comparing apples-to-apples, the
414 // comparison is a simple numeric one.
415 if (nSequenceMasked > txToSequenceMasked)
421 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
424 auto pc = script.begin();
425 auto pend = script.end();
426 auto pbegincodehash = script.begin();
428 valtype vchPushValue;
430 vector<valtype> altstack;
431 if (script.size() > 10000)
439 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
444 if (!script.GetOp(pc, opcode, vchPushValue))
446 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
448 if (opcode > OP_16 && ++nOpCount > 201)
451 if (opcode == OP_CAT ||
452 opcode == OP_SUBSTR ||
454 opcode == OP_RIGHT ||
455 opcode == OP_INVERT ||
464 opcode == OP_LSHIFT ||
466 return false; // Disabled opcodes.
468 if (fExec && opcode <= OP_PUSHDATA4)
469 stack.push_back(vchPushValue);
470 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
495 CBigNum bn(opcode - (OP_1 - 1));
496 stack.push_back(bn.getvch());
505 case OP_NOP1: case OP_NOP4: case OP_NOP5:
506 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
512 // <expression> if [statements] [else [statements]] endif
516 if (stack.size() < 1)
518 auto& vch = stacktop(-1);
519 fValue = CastToBool(vch);
520 if (opcode == OP_NOTIF)
524 vfExec.push_back(fValue);
532 vfExec.back() = !vfExec.back();
547 // (false -- false) and return
548 if (stack.size() < 1)
550 bool fValue = CastToBool(stacktop(-1));
564 case OP_CHECKLOCKTIMEVERIFY:
566 // CHECKLOCKTIMEVERIFY
568 // (nLockTime -- nLockTime)
569 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
570 // treat as a NOP2 if not enabled
574 if (stack.size() < 1)
577 auto nLockTime = CastToBigNum(stacktop(-1));
579 // In the rare event that the argument may be < 0 due to
580 // some arithmetic being done first, you can always use
581 // 0 MAX CHECKLOCKTIMEVERIFY.
585 // Actually compare the specified lock time with the transaction.
586 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
592 case OP_CHECKSEQUENCEVERIFY:
594 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
595 // treat as a NOP3 not enabled
599 if (stack.size() < 1)
602 // nSequence, like nLockTime, is a 32-bit unsigned integer
603 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
604 // 5-byte numeric operands.
605 auto nSequence = CastToBigNum(stacktop(-1));
607 // In the rare event that the argument may be < 0 due to
608 // some arithmetic being done first, you can always use
609 // 0 MAX CHECKSEQUENCEVERIFY.
613 // To provide for future soft-fork extensibility, if the
614 // operand has the disabled lock-time flag set,
615 // CHECKSEQUENCEVERIFY behaves as a NOP.
616 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
619 // Compare the specified sequence number with the input.
620 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
631 if (stack.size() < 1)
633 altstack.push_back(stacktop(-1));
638 case OP_FROMALTSTACK:
640 if (altstack.size() < 1)
642 stack.push_back(altstacktop(-1));
650 if (stack.size() < 2)
659 // (x1 x2 -- x1 x2 x1 x2)
660 if (stack.size() < 2)
662 auto vch1 = stacktop(-2);
663 auto vch2 = stacktop(-1);
664 stack.push_back(vch1);
665 stack.push_back(vch2);
671 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
672 if (stack.size() < 3)
674 auto vch1 = stacktop(-3);
675 auto vch2 = stacktop(-2);
676 auto vch3 = stacktop(-1);
677 stack.push_back(vch1);
678 stack.push_back(vch2);
679 stack.push_back(vch3);
685 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
686 if (stack.size() < 4)
688 auto vch1 = stacktop(-4);
689 auto vch2 = stacktop(-3);
690 stack.push_back(vch1);
691 stack.push_back(vch2);
697 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
698 if (stack.size() < 6)
700 auto vch1 = stacktop(-6);
701 auto vch2 = stacktop(-5);
702 stack.erase(stack.end()-6, stack.end()-4);
703 stack.push_back(vch1);
704 stack.push_back(vch2);
710 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
711 if (stack.size() < 4)
713 swap(*(stack.end()-4),*(stack.end()-2));
714 swap(*(stack.end()-3),*(stack.end()-1));
721 if (stack.size() < 1)
723 auto vch = stacktop(-1);
725 stack.push_back(vch);
732 CBigNum bn((uint16_t) stack.size());
733 stack.push_back(bn.getvch());
740 if (stack.size() < 1)
749 if (stack.size() < 1)
751 auto vch = stacktop(-1);
752 stack.push_back(vch);
759 if (stack.size() < 2)
761 stack.erase(stack.end() - 2);
767 // (x1 x2 -- x1 x2 x1)
768 if (stack.size() < 2)
770 auto vch = stacktop(-2);
771 stack.push_back(vch);
778 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
779 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
780 if (stack.size() < 2)
782 int n = CastToBigNum(stack.back()).getint32();
784 if (n < 0 || n >= (int)stack.size())
786 auto vch = stacktop(-n-1);
787 if (opcode == OP_ROLL)
788 stack.erase(stack.end()-n-1);
789 stack.push_back(vch);
795 // (x1 x2 x3 -- x2 x3 x1)
796 // x2 x1 x3 after first swap
797 // x2 x3 x1 after second swap
798 if (stack.size() < 3)
800 swap(*(stack.end()-3), *(stack.end()-2));
801 swap(*(stack.end()-2), *(stack.end()-1));
808 if (stack.size() < 2)
810 swap(*(stack.end()-2),*(stack.end()-1));
816 // (x1 x2 -- x2 x1 x2)
817 if (stack.size() < 2)
819 auto vch = stacktop(-1);
820 stack.insert(stack.end()-2, vch);
828 if (stack.size() < 1)
830 CBigNum bn((uint16_t) (stack.back()).size());
831 stack.push_back(bn.getvch());
841 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
844 if (stack.size() < 2)
846 auto& vch1 = stacktop(-2);
847 auto& vch2 = stacktop(-1);
848 bool fEqual = (vch1 == vch2);
849 // OP_NOTEQUAL is disabled because it would be too easy to say
850 // something like n != 1 and have some wiseguy pass in 1 with extra
851 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
852 //if (opcode == OP_NOTEQUAL)
856 stack.push_back(fEqual ? vchTrue : vchFalse);
857 if (opcode == OP_EQUALVERIFY)
879 if (stack.size() < 1)
881 auto bn = CastToBigNum(stacktop(-1));
884 case OP_1ADD: bn += bnOne; break;
885 case OP_1SUB: bn -= bnOne; break;
886 case OP_NEGATE: bn = -bn; break;
887 case OP_ABS: if (bn < bnZero) bn = -bn; break;
888 case OP_NOT: bn = (bn == bnZero); break;
889 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
890 default: assert(!"invalid opcode"); break;
893 stack.push_back(bn.getvch());
902 case OP_NUMEQUALVERIFY:
906 case OP_LESSTHANOREQUAL:
907 case OP_GREATERTHANOREQUAL:
912 if (stack.size() < 2)
914 auto bn1 = CastToBigNum(stacktop(-2));
915 auto bn2 = CastToBigNum(stacktop(-1));
927 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
928 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
929 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
930 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
931 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
932 case OP_LESSTHAN: bn = (bn1 < bn2); break;
933 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
934 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
935 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
936 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
937 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
938 default: assert(!"invalid opcode"); break;
942 stack.push_back(bn.getvch());
944 if (opcode == OP_NUMEQUALVERIFY)
946 if (CastToBool(stacktop(-1)))
956 // (x min max -- out)
957 if (stack.size() < 3)
959 auto bn1 = CastToBigNum(stacktop(-3));
960 auto bn2 = CastToBigNum(stacktop(-2));
961 auto bn3 = CastToBigNum(stacktop(-1));
962 bool fValue = (bn2 <= bn1 && bn1 < bn3);
966 stack.push_back(fValue ? vchTrue : vchFalse);
981 if (stack.size() < 1)
983 auto& vch = stacktop(-1);
984 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
985 if (opcode == OP_RIPEMD160)
986 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
987 else if (opcode == OP_SHA1)
988 SHA1(&vch[0], vch.size(), &vchHash[0]);
989 else if (opcode == OP_SHA256)
990 SHA256(&vch[0], vch.size(), &vchHash[0]);
991 else if (opcode == OP_HASH160)
993 auto hash160 = Hash160(vch);
994 memcpy(&vchHash[0], &hash160, sizeof(hash160));
996 else if (opcode == OP_HASH256)
998 auto hash = Hash(vch.begin(), vch.end());
999 memcpy(&vchHash[0], &hash, sizeof(hash));
1002 stack.push_back(vchHash);
1006 case OP_CODESEPARATOR:
1008 // Hash starts after the code separator
1009 pbegincodehash = pc;
1014 case OP_CHECKSIGVERIFY:
1016 // (sig pubkey -- bool)
1017 if (stack.size() < 2)
1020 auto& vchSig = stacktop(-2);
1021 auto& vchPubKey = stacktop(-1);
1024 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1025 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1027 // Subset of script starting at the most recent codeseparator
1028 CScript scriptCode(pbegincodehash, pend);
1030 // Drop the signature, since there's no way for a signature to sign itself
1031 scriptCode.FindAndDelete(CScript(vchSig));
1033 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1034 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1038 stack.push_back(fSuccess ? vchTrue : vchFalse);
1039 if (opcode == OP_CHECKSIGVERIFY)
1049 case OP_CHECKMULTISIG:
1050 case OP_CHECKMULTISIGVERIFY:
1052 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1055 if ((int)stack.size() < i)
1058 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1059 if (nKeysCount < 0 || nKeysCount > 20)
1061 nOpCount += nKeysCount;
1066 if ((int)stack.size() < i)
1069 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1070 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1074 if ((int)stack.size() < i)
1077 // Subset of script starting at the most recent codeseparator
1078 CScript scriptCode(pbegincodehash, pend);
1080 // Drop the signatures, since there's no way for a signature to sign itself
1081 for (int k = 0; k < nSigsCount; k++)
1083 auto& vchSig = stacktop(-isig-k);
1084 scriptCode.FindAndDelete(CScript(vchSig));
1087 bool fSuccess = true;
1088 while (fSuccess && nSigsCount > 0)
1090 auto& vchSig = stacktop(-isig);
1091 auto& vchPubKey = stacktop(-ikey);
1094 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1095 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1104 // If there are more signatures left than keys left,
1105 // then too many signatures have failed
1106 if (nSigsCount > nKeysCount)
1113 // A bug causes CHECKMULTISIG to consume one extra argument
1114 // whose contents were not checked in any way.
1116 // Unfortunately this is a potential source of mutability,
1117 // so optionally verify it is exactly equal to zero prior
1118 // to removing it from the stack.
1119 if (stack.size() < 1)
1121 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1122 return error("CHECKMULTISIG dummy argument not null");
1125 stack.push_back(fSuccess ? vchTrue : vchFalse);
1127 if (opcode == OP_CHECKMULTISIGVERIFY)
1142 if (stack.size() + altstack.size() > 1000)
1152 if (!vfExec.empty())
1166 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, uint32_t nIn, int nHashType)
1168 if (nIn >= txTo.vin.size())
1170 printf("ERROR: SignatureHash() : nIn=%" PRIu32 " out of range\n", nIn);
1173 CTransaction txTmp(txTo);
1175 // In case concatenating two scripts ends up with two codeseparators,
1176 // or an extra one at the end, this prevents all those possible incompatibilities.
1177 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1179 // Blank out other inputs' signatures
1180 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1181 txTmp.vin[i].scriptSig = CScript();
1182 txTmp.vin[nIn].scriptSig = scriptCode;
1184 // Blank out some of the outputs
1185 if ((nHashType & 0x1f) == SIGHASH_NONE)
1190 // Let the others update at will
1191 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1193 txTmp.vin[i].nSequence = 0;
1195 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1197 // Only lock-in the txout payee at same index as txin
1198 uint32_t nOut = nIn;
1199 if (nOut >= txTmp.vout.size())
1201 printf("ERROR: SignatureHash() : nOut=%" PRIu32 " out of range\n", nOut);
1204 txTmp.vout.resize(nOut+1);
1205 for (unsigned int i = 0; i < nOut; i++)
1206 txTmp.vout[i].SetNull();
1208 // Let the others update at will
1209 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1211 txTmp.vin[i].nSequence = 0;
1214 // Blank out other inputs completely, not recommended for open transactions
1215 if (nHashType & SIGHASH_ANYONECANPAY)
1217 txTmp.vin[0] = txTmp.vin[nIn];
1218 txTmp.vin.resize(1);
1221 // Serialize and hash
1222 CDataStream ss(SER_GETHASH, 0);
1224 ss << txTmp << nHashType;
1225 return Hash(ss.begin(), ss.end());
1229 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1230 // twice for every transaction (once when accepted into memory pool, and
1231 // again when accepted into the block chain)
1233 class CSignatureCache
1236 // sigdata_type is (signature hash, signature, public key):
1237 typedef tuple<uint256, vector<unsigned char>, CPubKey > sigdata_type;
1238 set< sigdata_type> setValid;
1239 boost::shared_mutex cs_sigcache;
1243 Get(const uint256 &hash, const vector<unsigned char>& vchSig, const CPubKey& pubKey)
1245 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1247 sigdata_type k(hash, vchSig, pubKey);
1248 auto mi = setValid.find(k);
1249 if (mi != setValid.end())
1254 void Set(const uint256 &hash, const vector<unsigned char>& vchSig, const CPubKey& pubKey)
1256 // DoS prevention: limit cache size to less than 10MB
1257 // (~200 bytes per cache entry times 50,000 entries)
1258 // Since there are a maximum of 20,000 signature operations per block
1259 // 50,000 is a reasonable default.
1260 size_t nMaxCacheSize = GetArgUInt("-maxsigcachesize", 50000u);
1261 if (nMaxCacheSize <= 0) return;
1263 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1265 while (setValid.size() > nMaxCacheSize)
1267 // Evict a random entry. Random because that helps
1268 // foil would-be DoS attackers who might try to pre-generate
1269 // and re-use a set of valid signatures just-slightly-greater
1270 // than our cache size.
1271 auto randomHash = GetRandHash();
1272 vector<unsigned char> unused;
1273 auto it = setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1274 if (it == setValid.end())
1275 it = setValid.begin();
1276 setValid.erase(*it);
1279 sigdata_type k(hash, vchSig, pubKey);
1284 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1285 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1287 static CSignatureCache signatureCache;
1289 CPubKey pubkey(vchPubKey);
1290 if (!pubkey.IsValid())
1293 // Hash type is one byte tacked on to the end of the signature
1297 nHashType = vchSig.back();
1298 else if (nHashType != vchSig.back())
1302 auto sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1304 if (signatureCache.Get(sighash, vchSig, pubkey))
1307 if (!pubkey.Verify(sighash, vchSig))
1310 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1311 signatureCache.Set(sighash, vchSig, pubkey);
1318 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1320 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1323 static map<txnouttype, CScript> mTemplates;
1324 if (mTemplates.empty())
1326 // Standard tx, sender provides pubkey, receiver adds signature
1327 mTemplates.insert({ TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG });
1329 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1330 mTemplates.insert({ TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG });
1332 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1333 mTemplates.insert({ TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG });
1335 // Sender provides N pubkeys, receivers provides M signatures
1336 mTemplates.insert({ TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG });
1338 // Empty, provably prunable, data-carrying output
1339 mTemplates.insert({ TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA });
1342 vSolutionsRet.clear();
1344 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1345 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1346 if (scriptPubKey.IsPayToScriptHash())
1348 typeRet = TX_SCRIPTHASH;
1349 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1350 vSolutionsRet.push_back(hashBytes);
1354 // Provably prunable, data-carrying output
1356 // So long as script passes the IsUnspendable() test and all but the first
1357 // byte passes the IsPushOnly() test we don't care what exactly is in the
1359 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1360 typeRet = TX_NULL_DATA;
1365 const auto& script1 = scriptPubKey;
1366 for(const auto& tplate : mTemplates)
1368 const auto& script2 = tplate.second;
1369 vSolutionsRet.clear();
1371 opcodetype opcode1, opcode2;
1372 vector<unsigned char> vch1, vch2;
1375 auto pc1 = script1.begin();
1376 auto pc2 = script2.begin();
1379 if (pc1 == script1.end() && pc2 == script2.end())
1382 typeRet = tplate.first;
1383 if (typeRet == TX_MULTISIG)
1385 // Additional checks for TX_MULTISIG:
1386 auto m = vSolutionsRet.front()[0];
1387 auto n = vSolutionsRet.back()[0];
1388 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1393 if (!script1.GetOp(pc1, opcode1, vch1))
1395 if (!script2.GetOp(pc2, opcode2, vch2))
1398 // Template matching opcodes:
1399 if (opcode2 == OP_PUBKEYS)
1401 while (vch1.size() >= 33 && vch1.size() <= 120)
1403 vSolutionsRet.push_back(vch1);
1404 if (!script1.GetOp(pc1, opcode1, vch1))
1407 if (!script2.GetOp(pc2, opcode2, vch2))
1409 // Normal situation is to fall through
1410 // to other if/else statements
1413 if (opcode2 == OP_PUBKEY)
1415 if (vch1.size() < 33 || vch1.size() > 120)
1417 vSolutionsRet.push_back(vch1);
1419 else if (opcode2 == OP_PUBKEYHASH)
1421 if (vch1.size() != sizeof(uint160))
1423 vSolutionsRet.push_back(vch1);
1425 else if (opcode2 == OP_SMALLINTEGER)
1426 { // Single-byte small integer pushed onto vSolutions
1427 if (opcode1 == OP_0 ||
1428 (opcode1 >= OP_1 && opcode1 <= OP_16))
1430 char n = (char)CScript::DecodeOP_N(opcode1);
1431 vSolutionsRet.push_back(valtype(1, n));
1436 else if (opcode2 == OP_INTEGER)
1437 { // Up to four-byte integer pushed onto vSolutions
1440 auto bnVal = CastToBigNum(vch1);
1442 break; // It's better to use OP_0 ... OP_16 for small integers.
1443 vSolutionsRet.push_back(vch1);
1450 else if (opcode2 == OP_SMALLDATA)
1452 // small pushdata, <= 1024 bytes
1453 if (vch1.size() > 1024)
1456 else if (opcode1 != opcode2 || vch1 != vch2)
1458 // Others must match exactly
1464 vSolutionsRet.clear();
1465 typeRet = TX_NONSTANDARD;
1470 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1473 if (!keystore.GetKey(address, key))
1476 vector<unsigned char> vchSig;
1477 if (!key.Sign(hash, vchSig))
1479 vchSig.push_back((unsigned char)nHashType);
1480 scriptSigRet << vchSig;
1485 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1488 if (!keystore.CreatePrivKey(pubKey, R, key))
1491 vector<unsigned char> vchSig;
1492 if (!key.Sign(hash, vchSig))
1494 vchSig.push_back((unsigned char)nHashType);
1495 scriptSigRet << vchSig;
1500 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1503 int nRequired = multisigdata.front()[0];
1504 for (uint32_t i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1506 const auto& pubkey = multisigdata[i];
1507 auto keyID = CPubKey(pubkey).GetID();
1508 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1511 return nSigned==nRequired;
1515 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1516 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1517 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1518 // Returns false if scriptPubKey could not be completely satisfied.
1520 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1521 CScript& scriptSigRet, txnouttype& whichTypeRet)
1523 scriptSigRet.clear();
1525 vector<valtype> vSolutions;
1526 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1530 switch (whichTypeRet)
1532 case TX_NONSTANDARD:
1536 keyID = CPubKey(vSolutions[0]).GetID();
1537 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1538 case TX_PUBKEY_DROP:
1540 auto key = CPubKey(vSolutions[0]);
1541 auto R = CPubKey(vSolutions[1]);
1542 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1545 keyID = CKeyID(uint160(vSolutions[0]));
1546 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1551 keystore.GetPubKey(keyID, vch);
1552 scriptSigRet << vch;
1556 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1559 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1560 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1565 int ScriptSigArgsExpected(txnouttype t, const vector<vector<unsigned char> >& vSolutions)
1569 case TX_NONSTANDARD:
1574 case TX_PUBKEY_DROP:
1579 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1581 return vSolutions[0][0] + 1;
1583 return 1; // doesn't include args needed by the script
1588 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1590 vector<valtype> vSolutions;
1591 if (!Solver(scriptPubKey, whichType, vSolutions))
1594 if (whichType == TX_MULTISIG)
1596 unsigned char m = vSolutions.front()[0];
1597 unsigned char n = vSolutions.back()[0];
1598 // Support up to x-of-3 multisig txns as standard
1605 return whichType != TX_NONSTANDARD;
1609 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1611 uint32_t nResult = 0;
1612 for(const auto& pubkey : pubkeys)
1614 auto keyID = CPubKey(pubkey).GetID();
1615 if (keystore.HaveKey(keyID))
1622 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1625 const CKeyStore *keystore;
1627 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1628 bool operator()(const CNoDestination &dest) const { return false; }
1629 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1630 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1633 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1636 script.SetAddress(dest);
1637 return IsMine(keystore, script);
1640 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1642 vector<valtype> vSolutions;
1643 txnouttype whichType;
1644 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1645 if (keystore.HaveWatchOnly(scriptPubKey))
1646 return MINE_WATCH_ONLY;
1653 case TX_NONSTANDARD:
1657 keyID = CPubKey(vSolutions[0]).GetID();
1658 if (keystore.HaveKey(keyID))
1659 return MINE_SPENDABLE;
1661 case TX_PUBKEY_DROP:
1663 auto key = CPubKey(vSolutions[0]);
1664 auto R = CPubKey(vSolutions[1]);
1665 if (keystore.CheckOwnership(key, R))
1666 return MINE_SPENDABLE;
1670 keyID = CKeyID(uint160(vSolutions[0]));
1671 if (keystore.HaveKey(keyID))
1672 return MINE_SPENDABLE;
1676 auto scriptID = CScriptID(uint160(vSolutions[0]));
1678 if (keystore.GetCScript(scriptID, subscript)) {
1679 auto ret = IsMine(keystore, subscript);
1680 if (ret == MINE_SPENDABLE)
1687 // Only consider transactions "mine" if we own ALL the
1688 // keys involved. multi-signature transactions that are
1689 // partially owned (somebody else has a key that can spend
1690 // them) enable spend-out-from-under-you attacks, especially
1691 // in shared-wallet situations.
1692 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1693 if (HaveKeys(keys, keystore) == keys.size())
1694 return MINE_SPENDABLE;
1699 if (keystore.HaveWatchOnly(scriptPubKey))
1700 return MINE_WATCH_ONLY;
1704 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1706 vector<valtype> vSolutions;
1707 txnouttype whichType;
1708 if (!Solver(scriptPubKey, whichType, vSolutions))
1711 if (whichType == TX_PUBKEY)
1713 addressRet = CPubKey(vSolutions[0]).GetID();
1716 else if (whichType == TX_PUBKEYHASH)
1718 addressRet = CKeyID(uint160(vSolutions[0]));
1721 else if (whichType == TX_SCRIPTHASH)
1723 addressRet = CScriptID(uint160(vSolutions[0]));
1726 // Multisig txns have more than one address...
1730 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1732 vector<valtype> vSolutions;
1733 txnouttype whichType;
1734 if (!Solver(scriptPubKey, whichType, vSolutions))
1737 if (whichType == TX_PUBKEY)
1739 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1742 if (whichType == TX_PUBKEY_DROP)
1745 CMalleableKeyView view;
1746 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1749 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1752 else if (whichType == TX_PUBKEYHASH)
1754 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1757 else if (whichType == TX_SCRIPTHASH)
1759 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1762 // Multisig txns have more than one address...
1766 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1768 const CKeyStore &keystore;
1769 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1770 vector<CKeyID> &vKeys;
1773 CAffectedKeysVisitor(const CKeyStore &keystoreIn, vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1775 void Process(const CScript &script) {
1777 vector<CTxDestination> vDest;
1779 if (ExtractDestinations(script, type, vDest, nRequired)) {
1780 for(const CTxDestination &dest : vDest)
1781 boost::apply_visitor(*this, dest);
1785 void operator()(const CKeyID &keyId) {
1786 if (keystore.HaveKey(keyId))
1787 vKeys.push_back(keyId);
1790 void operator()(const CScriptID &scriptId) {
1792 if (keystore.GetCScript(scriptId, script))
1796 void operator()(const CNoDestination &none) {}
1800 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, vector<CKeyID> &vKeys) {
1801 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1804 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1807 typeRet = TX_NONSTANDARD;
1808 vector<valtype> vSolutions;
1809 if (!Solver(scriptPubKey, typeRet, vSolutions))
1811 if (typeRet == TX_NULL_DATA)
1817 if (typeRet == TX_MULTISIG)
1819 nRequiredRet = vSolutions.front()[0];
1820 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1822 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1823 addressRet.push_back(address);
1829 if (typeRet == TX_PUBKEY_DROP)
1831 CTxDestination address;
1832 if (!ExtractDestination(scriptPubKey, address))
1834 addressRet.push_back(address);
1840 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
1842 vector<vector<unsigned char> > stack, stackCopy;
1843 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1845 if (flags & SCRIPT_VERIFY_P2SH)
1847 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1852 if (CastToBool(stack.back()) == false)
1855 // Additional validation for spend-to-script-hash transactions:
1856 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1858 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1859 return false; // or validation fails
1861 // stackCopy cannot be empty here, because if it was the
1862 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1863 // an empty stack and the EvalScript above would return false.
1864 assert(!stackCopy.empty());
1866 const auto& pubKeySerialized = stackCopy.back();
1867 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1868 popstack(stackCopy);
1870 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1872 if (stackCopy.empty())
1874 return CastToBool(stackCopy.back());
1880 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, uint32_t nIn, int nHashType)
1882 assert(nIn < txTo.vin.size());
1883 auto& txin = txTo.vin[nIn];
1885 // Leave out the signature from the hash, since a signature can't sign itself.
1886 // The checksig op will also drop the signatures from its hash.
1887 auto hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1889 txnouttype whichType;
1890 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1893 if (whichType == TX_SCRIPTHASH)
1895 // Solver returns the subscript that need to be evaluated;
1896 // the final scriptSig is the signatures from that
1897 // and then the serialized subscript:
1898 auto subscript = txin.scriptSig;
1900 // Recompute txn hash using subscript in place of scriptPubKey:
1901 auto hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1904 bool fSolved = Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1905 // Append serialized subscript whether or not it is completely signed:
1906 txin.scriptSig << static_cast<valtype>(subscript);
1907 if (!fSolved) return false;
1911 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1914 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, uint32_t nIn, int nHashType)
1916 assert(nIn < txTo.vin.size());
1917 auto& txin = txTo.vin[nIn];
1918 assert(txin.prevout.n < txFrom.vout.size());
1919 assert(txin.prevout.hash == txFrom.GetHash());
1920 const auto& txout = txFrom.vout[txin.prevout.n];
1922 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1925 static CScript PushAll(const vector<valtype>& values)
1928 for(const auto& v : values)
1933 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1934 const vector<valtype>& vSolutions,
1935 vector<valtype>& sigs1, vector<valtype>& sigs2)
1937 // Combine all the signatures we've got:
1938 set<valtype> allsigs;
1939 for(const auto& v : sigs1)
1944 for(const auto& v : sigs2)
1950 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1951 assert(vSolutions.size() > 1);
1952 auto nSigsRequired = (uint32_t)vSolutions.front()[0];
1953 auto nPubKeys = (uint32_t)(vSolutions.size()-2);
1955 map<valtype, valtype> sigs;
1956 for(const auto& sig : allsigs)
1958 for (unsigned int i = 0; i < nPubKeys; i++)
1960 const auto& pubkey = vSolutions[i+1];
1961 if (sigs.count(pubkey))
1962 continue; // Already got a sig for this pubkey
1964 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1971 // Now build a merged CScript:
1972 uint32_t nSigsHave = 0;
1973 CScript result; result << OP_0; // pop-one-too-many workaround
1974 for (uint32_t i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1976 if (sigs.count(vSolutions[i+1]))
1978 result << sigs[vSolutions[i+1]];
1982 // Fill any missing with OP_0:
1983 for (auto i = nSigsHave; i < nSigsRequired; i++)
1989 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1990 const txnouttype txType, const vector<valtype>& vSolutions,
1991 vector<valtype>& sigs1, vector<valtype>& sigs2)
1995 case TX_NONSTANDARD:
1997 // Don't know anything about this, assume bigger one is correct:
1998 if (sigs1.size() >= sigs2.size())
1999 return PushAll(sigs1);
2000 return PushAll(sigs2);
2002 case TX_PUBKEY_DROP:
2004 // Signatures are bigger than placeholders or empty scripts:
2005 if (sigs1.empty() || sigs1[0].empty())
2006 return PushAll(sigs2);
2007 return PushAll(sigs1);
2009 if (sigs1.empty() || sigs1.back().empty())
2010 return PushAll(sigs2);
2011 else if (sigs2.empty() || sigs2.back().empty())
2012 return PushAll(sigs1);
2015 // Recur to combine:
2016 auto spk = sigs1.back();
2017 CScript pubKey2(spk.begin(), spk.end());
2020 vector<vector<unsigned char> > vSolutions2;
2021 Solver(pubKey2, txType2, vSolutions2);
2024 auto result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2029 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2035 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn,
2036 const CScript& scriptSig1, const CScript& scriptSig2)
2039 vector<vector<unsigned char> > vSolutions;
2040 Solver(scriptPubKey, txType, vSolutions);
2042 vector<valtype> stack1;
2043 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2044 vector<valtype> stack2;
2045 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2047 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2054 CScript& CScript::push_int64(int64_t n)
2056 if (n == -1 || (n >= 1 && n <= 16))
2058 push_back((uint8_t)n + (OP_1 - 1));
2063 *this << bn.getvch();
2068 CScript& CScript::push_uint64(uint64_t n)
2070 if (n >= 1 && n <= 16)
2072 push_back((uint8_t)n + (OP_1 - 1));
2077 *this << bn.getvch();
2082 CScript& CScript::operator+=(const CScript& b)
2084 insert(end(), b.begin(), b.end());
2088 CScript& CScript::operator<<(opcodetype opcode)
2090 insert(end(), opcode);
2094 CScript& CScript::operator<<(const uint160& b)
2096 insert(end(), sizeof(b));
2097 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2101 CScript& CScript::operator<<(const uint256& b)
2103 insert(end(), sizeof(b));
2104 insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2108 CScript& CScript::operator<<(const CPubKey& key)
2110 vector<uint8_t> vchKey(key.begin(), key.end());
2111 return (*this) << vchKey;
2114 CScript& CScript::operator<<(const CBigNum& b)
2116 *this << b.getvch();
2120 CScript& CScript::operator<<(const vector<uint8_t>& b)
2122 if (b.size() < OP_PUSHDATA1)
2124 insert(end(), (uint8_t)b.size());
2126 else if (b.size() <= 0xff)
2128 insert(end(), OP_PUSHDATA1);
2129 insert(end(), (uint8_t)b.size());
2131 else if (b.size() <= 0xffff)
2133 insert(end(), OP_PUSHDATA2);
2134 uint16_t nSize = (uint16_t) b.size();
2135 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2139 insert(end(), OP_PUSHDATA4);
2140 uint32_t nSize = (uint32_t) b.size();
2141 insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2143 insert(end(), b.begin(), b.end());
2147 CScript& CScript::operator<<(const CScript& b)
2149 // I'm not sure if this should push the script or concatenate scripts.
2150 // If there's ever a use for pushing a script onto a script, delete this member fn
2151 assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
2155 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet, vector<uint8_t>& vchRet)
2157 // Wrapper so it can be called with either iterator or const_iterator
2158 const_iterator pc2 = pc;
2159 bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
2160 pc = begin() + (pc2 - begin());
2164 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet)
2166 const_iterator pc2 = pc;
2167 bool fRet = GetOp2(pc2, opcodeRet, NULL);
2168 pc = begin() + (pc2 - begin());
2172 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet, vector<uint8_t>& vchRet) const
2174 return GetOp2(pc, opcodeRet, &vchRet);
2177 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet) const
2179 return GetOp2(pc, opcodeRet, NULL);
2182 bool CScript::GetOp2(const_iterator& pc, opcodetype& opcodeRet, vector<uint8_t>* pvchRet) const
2184 opcodeRet = OP_INVALIDOPCODE;
2193 uint32_t opcode = *pc++;
2195 // Immediate operand
2196 if (opcode <= OP_PUSHDATA4)
2198 uint32_t nSize = OP_0;
2199 if (opcode < OP_PUSHDATA1)
2203 else if (opcode == OP_PUSHDATA1)
2209 else if (opcode == OP_PUSHDATA2)
2213 memcpy(&nSize, &pc[0], 2);
2216 else if (opcode == OP_PUSHDATA4)
2220 memcpy(&nSize, &pc[0], 4);
2223 if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
2226 pvchRet->assign(pc, pc + nSize);
2230 opcodeRet = (opcodetype)opcode;
2234 int CScript::DecodeOP_N(opcodetype opcode)
2238 assert(opcode >= OP_1 && opcode <= OP_16);
2239 return (opcode - (OP_1 - 1));
2242 opcodetype CScript::EncodeOP_N(int n)
2244 assert(n >= 0 && n <= 16);
2247 return (opcodetype)(OP_1+n-1);
2250 int CScript::FindAndDelete(const CScript& b)
2256 iterator pc = begin(), pc2 = begin();
2260 result.insert(result.end(), pc2, pc);
2261 while (static_cast<size_t>(end() - pc) >= b.size() && equal(b.begin(), b.end(), pc))
2268 while (GetOp(pc, opcode));
2271 result.insert(result.end(), pc2, end());
2277 int CScript::Find(opcodetype op) const
2281 for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
2287 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2291 auto lastOpcode = OP_INVALIDOPCODE;
2295 if (!GetOp(pc, opcode))
2297 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2299 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2301 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2302 n += DecodeOP_N(lastOpcode);
2306 lastOpcode = opcode;
2311 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2313 if (!IsPayToScriptHash())
2314 return GetSigOpCount(true);
2316 // This is a pay-to-script-hash scriptPubKey;
2317 // get the last item that the scriptSig
2318 // pushes onto the stack:
2319 auto pc = scriptSig.begin();
2320 vector<unsigned char> data;
2321 while (pc < scriptSig.end())
2324 if (!scriptSig.GetOp(pc, opcode, data))
2330 /// ... and return its opcount:
2331 CScript subscript(data.begin(), data.end());
2332 return subscript.GetSigOpCount(true);
2335 bool CScript::IsPayToScriptHash() const
2337 // Extra-fast test for pay-to-script-hash CScripts:
2338 return (this->size() == 23 &&
2339 this->at(0) == OP_HASH160 &&
2340 this->at(1) == 0x14 &&
2341 this->at(22) == OP_EQUAL);
2344 bool CScript::IsPushOnly(const_iterator pc) const
2349 if (!GetOp(pc, opcode))
2357 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
2358 bool CScript::IsPushOnly() const
2360 return this->IsPushOnly(begin());
2363 bool CScript::HasCanonicalPushes() const
2369 vector<unsigned char> data;
2370 if (!GetOp(pc, opcode, data))
2374 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2375 // Could have used an OP_n code, rather than a 1-byte push.
2377 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2378 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2380 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2381 // Could have used an OP_PUSHDATA1.
2383 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2384 // Could have used an OP_PUSHDATA2.
2390 class CScriptVisitor : public boost::static_visitor<bool>
2395 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2397 bool operator()(const CNoDestination &dest) const {
2402 bool operator()(const CKeyID &keyID) const {
2404 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2408 bool operator()(const CScriptID &scriptID) const {
2410 *script << OP_HASH160 << scriptID << OP_EQUAL;
2415 void CScript::SetDestination(const CTxDestination& dest)
2417 boost::apply_visitor(CScriptVisitor(this), dest);
2420 void CScript::SetAddress(const CBitcoinAddress& dest)
2423 if (dest.IsScript())
2424 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2425 else if (dest.IsPubKey())
2426 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2427 else if (dest.IsPair()) {
2428 // Pubkey pair address, going to generate
2429 // new one-time public key.
2430 CMalleablePubKey mpk;
2431 if (!mpk.setvch(dest.GetData()))
2433 CPubKey R, pubKeyVariant;
2434 mpk.GetVariant(R, pubKeyVariant);
2435 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2439 void CScript::SetMultisig(int nRequired, const vector<CPubKey>& keys)
2443 *this << EncodeOP_N(nRequired);
2444 for(const auto& key : keys)
2446 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2449 void CScript::PrintHex() const
2451 printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
2454 string CScript::ToString(bool fShort) const
2458 vector<uint8_t> vch;
2459 const_iterator pc = begin();
2464 if (!GetOp(pc, opcode, vch))
2469 if (opcode <= OP_PUSHDATA4)
2470 str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
2472 str += GetOpName(opcode);
2477 void CScript::print() const
2479 printf("%s\n", ToString().c_str());
2482 CScriptID CScript::GetID() const
2484 return CScriptID(Hash160(*this));