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 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);
17 static const valtype vchFalse(0);
18 static const valtype vchZero(0);
19 static const valtype vchTrue(1, 1);
20 static const CBigNum bnZero(0);
21 static const CBigNum bnOne(1);
22 static const CBigNum bnFalse(0);
23 static const CBigNum bnTrue(1);
24 static const size_t nMaxNumSize = 4;
27 CBigNum CastToBigNum(const valtype& vch)
29 if (vch.size() > nMaxNumSize)
30 throw std::runtime_error("CastToBigNum() : overflow");
31 // Get rid of extra leading zeros
32 return CBigNum(CBigNum(vch).getvch());
35 bool CastToBool(const valtype& vch)
37 for (unsigned int i = 0; i < vch.size(); i++)
41 // Can be negative zero
42 if (i == vch.size()-1 && vch[i] == 0x80)
51 // WARNING: This does not work as expected for signed integers; the sign-bit
52 // is left in place as the integer is zero-extended. The correct behavior
53 // would be to move the most significant bit of the last byte during the
54 // resize process. MakeSameSize() is currently only used by the disabled
55 // opcodes OP_AND, OP_OR, and OP_XOR.
57 void MakeSameSize(valtype& vch1, valtype& vch2)
59 // Lengthen the shorter one
60 if (vch1.size() < vch2.size())
62 // +unsigned char msb = vch1[vch1.size()-1];
63 // +vch1[vch1.size()-1] &= 0x7f;
64 // vch1.resize(vch2.size(), 0);
65 // +vch1[vch1.size()-1] = msb;
66 vch1.resize(vch2.size(), 0);
67 if (vch2.size() < vch1.size())
69 // +unsigned char msb = vch2[vch2.size()-1];
70 // +vch2[vch2.size()-1] &= 0x7f;
71 // vch2.resize(vch1.size(), 0);
72 // +vch2[vch2.size()-1] = msb;
73 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)))
83 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
84 static inline void popstack(std::vector<valtype>& stack)
87 throw std::runtime_error("popstack() : stack empty");
92 const char* GetTxnOutputType(txnouttype t)
96 case TX_NONSTANDARD: return "nonstandard";
97 case TX_PUBKEY: return "pubkey";
98 case TX_PUBKEY_DROP: return "pubkeydrop";
99 case TX_PUBKEYHASH: return "pubkeyhash";
100 case TX_SCRIPTHASH: return "scripthash";
101 case TX_MULTISIG: return "multisig";
102 case TX_NULL_DATA: return "nulldata";
108 const char* GetOpName(opcodetype opcode)
113 case OP_0 : return "0";
114 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
115 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
116 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
117 case OP_1NEGATE : return "-1";
118 case OP_RESERVED : return "OP_RESERVED";
119 case OP_1 : return "1";
120 case OP_2 : return "2";
121 case OP_3 : return "3";
122 case OP_4 : return "4";
123 case OP_5 : return "5";
124 case OP_6 : return "6";
125 case OP_7 : return "7";
126 case OP_8 : return "8";
127 case OP_9 : return "9";
128 case OP_10 : return "10";
129 case OP_11 : return "11";
130 case OP_12 : return "12";
131 case OP_13 : return "13";
132 case OP_14 : return "14";
133 case OP_15 : return "15";
134 case OP_16 : return "16";
137 case OP_NOP : return "OP_NOP";
138 case OP_VER : return "OP_VER";
139 case OP_IF : return "OP_IF";
140 case OP_NOTIF : return "OP_NOTIF";
141 case OP_VERIF : return "OP_VERIF";
142 case OP_VERNOTIF : return "OP_VERNOTIF";
143 case OP_ELSE : return "OP_ELSE";
144 case OP_ENDIF : return "OP_ENDIF";
145 case OP_VERIFY : return "OP_VERIFY";
146 case OP_RETURN : return "OP_RETURN";
147 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
148 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
151 case OP_TOALTSTACK : return "OP_TOALTSTACK";
152 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
153 case OP_2DROP : return "OP_2DROP";
154 case OP_2DUP : return "OP_2DUP";
155 case OP_3DUP : return "OP_3DUP";
156 case OP_2OVER : return "OP_2OVER";
157 case OP_2ROT : return "OP_2ROT";
158 case OP_2SWAP : return "OP_2SWAP";
159 case OP_IFDUP : return "OP_IFDUP";
160 case OP_DEPTH : return "OP_DEPTH";
161 case OP_DROP : return "OP_DROP";
162 case OP_DUP : return "OP_DUP";
163 case OP_NIP : return "OP_NIP";
164 case OP_OVER : return "OP_OVER";
165 case OP_PICK : return "OP_PICK";
166 case OP_ROLL : return "OP_ROLL";
167 case OP_ROT : return "OP_ROT";
168 case OP_SWAP : return "OP_SWAP";
169 case OP_TUCK : return "OP_TUCK";
172 case OP_CAT : return "OP_CAT";
173 case OP_SUBSTR : return "OP_SUBSTR";
174 case OP_LEFT : return "OP_LEFT";
175 case OP_RIGHT : return "OP_RIGHT";
176 case OP_SIZE : return "OP_SIZE";
179 case OP_INVERT : return "OP_INVERT";
180 case OP_AND : return "OP_AND";
181 case OP_OR : return "OP_OR";
182 case OP_XOR : return "OP_XOR";
183 case OP_EQUAL : return "OP_EQUAL";
184 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
185 case OP_RESERVED1 : return "OP_RESERVED1";
186 case OP_RESERVED2 : return "OP_RESERVED2";
189 case OP_1ADD : return "OP_1ADD";
190 case OP_1SUB : return "OP_1SUB";
191 case OP_2MUL : return "OP_2MUL";
192 case OP_2DIV : return "OP_2DIV";
193 case OP_NEGATE : return "OP_NEGATE";
194 case OP_ABS : return "OP_ABS";
195 case OP_NOT : return "OP_NOT";
196 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
197 case OP_ADD : return "OP_ADD";
198 case OP_SUB : return "OP_SUB";
199 case OP_MUL : return "OP_MUL";
200 case OP_DIV : return "OP_DIV";
201 case OP_MOD : return "OP_MOD";
202 case OP_LSHIFT : return "OP_LSHIFT";
203 case OP_RSHIFT : return "OP_RSHIFT";
204 case OP_BOOLAND : return "OP_BOOLAND";
205 case OP_BOOLOR : return "OP_BOOLOR";
206 case OP_NUMEQUAL : return "OP_NUMEQUAL";
207 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
208 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
209 case OP_LESSTHAN : return "OP_LESSTHAN";
210 case OP_GREATERTHAN : return "OP_GREATERTHAN";
211 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
212 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
213 case OP_MIN : return "OP_MIN";
214 case OP_MAX : return "OP_MAX";
215 case OP_WITHIN : return "OP_WITHIN";
218 case OP_RIPEMD160 : return "OP_RIPEMD160";
219 case OP_SHA1 : return "OP_SHA1";
220 case OP_SHA256 : return "OP_SHA256";
221 case OP_HASH160 : return "OP_HASH160";
222 case OP_HASH256 : return "OP_HASH256";
223 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
224 case OP_CHECKSIG : return "OP_CHECKSIG";
225 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
226 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
227 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
230 case OP_NOP1 : return "OP_NOP1";
231 case OP_NOP4 : return "OP_NOP4";
232 case OP_NOP5 : return "OP_NOP5";
233 case OP_NOP6 : return "OP_NOP6";
234 case OP_NOP7 : return "OP_NOP7";
235 case OP_NOP8 : return "OP_NOP8";
236 case OP_NOP9 : return "OP_NOP9";
237 case OP_NOP10 : return "OP_NOP10";
241 // template matching params
242 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
243 case OP_PUBKEY : return "OP_PUBKEY";
244 case OP_SMALLDATA : return "OP_SMALLDATA";
246 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
252 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
253 if (!(flags & SCRIPT_VERIFY_STRICTENC))
256 if (vchPubKey.size() < 33)
257 return error("Non-canonical public key: too short");
258 if (vchPubKey[0] == 0x04) {
259 if (vchPubKey.size() != 65)
260 return error("Non-canonical public key: invalid length for uncompressed key");
261 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
262 if (vchPubKey.size() != 33)
263 return error("Non-canonical public key: invalid length for compressed key");
265 return error("Non-canonical public key: compressed nor uncompressed");
270 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
271 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
272 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
273 // Where R and S are not negative (their first byte has its highest bit not set), and not
274 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
275 // in which case a single 0 byte is necessary and even required).
276 if (vchSig.size() < 9)
277 return error("Non-canonical signature: too short");
278 if (vchSig.size() > 73)
279 return error("Non-canonical signature: too long");
280 if (vchSig[0] != 0x30)
281 return error("Non-canonical signature: wrong type");
282 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
283 return error("Non-canonical signature: wrong length marker");
285 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
286 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
287 return error("Non-canonical signature: unknown hashtype byte");
289 unsigned int nLenR = vchSig[3];
290 if (5 + nLenR >= vchSig.size())
291 return error("Non-canonical signature: S length misplaced");
292 unsigned int nLenS = vchSig[5+nLenR];
293 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
294 return error("Non-canonical signature: R+S length mismatch");
296 const unsigned char *R = &vchSig[4];
298 return error("Non-canonical signature: R value type mismatch");
300 return error("Non-canonical signature: R length is zero");
302 return error("Non-canonical signature: R value negative");
303 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
304 return error("Non-canonical signature: R value excessively padded");
306 const unsigned char *S = &vchSig[6+nLenR];
308 return error("Non-canonical signature: S value type mismatch");
310 return error("Non-canonical signature: S length is zero");
312 return error("Non-canonical signature: S value negative");
313 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
314 return error("Non-canonical signature: S value excessively padded");
317 unsigned int nLenR = vchSig[3];
318 unsigned int nLenS = vchSig[5+nLenR];
319 const unsigned char *S = &vchSig[6+nLenR];
320 // If the S value is above the order of the curve divided by two, its
321 // complement modulo the order could have been used instead, which is
322 // one byte shorter when encoded correctly.
323 if (!CKey::CheckSignatureElement(S, nLenS, true))
324 return error("Non-canonical signature: S value is unnecessarily high");
330 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
331 if (!(flags & SCRIPT_VERIFY_STRICTENC))
334 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
337 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
339 // There are two kinds of nLockTime: lock-by-blockheight
340 // and lock-by-blocktime, distinguished by whether
341 // nLockTime < LOCKTIME_THRESHOLD.
343 // We want to compare apples to apples, so fail the script
344 // unless the type of nLockTime being tested is the same as
345 // the nLockTime in the transaction.
347 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
348 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
352 // Now that we know we're comparing apples-to-apples, the
353 // comparison is a simple numeric one.
354 if (nLockTime > (int64_t)txTo.nLockTime)
357 // Finally the nLockTime feature can be disabled and thus
358 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
359 // finalized by setting nSequence to maxint. The
360 // transaction would be allowed into the blockchain, making
361 // the opcode ineffective.
363 // Testing if this vin is not final is sufficient to
364 // prevent this condition. Alternatively we could test all
365 // inputs, but testing just this input minimizes the data
366 // required to prove correct CHECKLOCKTIMEVERIFY execution.
367 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
373 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
375 // Relative lock times are supported by comparing the passed
376 // in operand to the sequence number of the input.
377 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
379 // Sequence numbers with their most significant bit set are not
380 // consensus constrained. Testing that the transaction's sequence
381 // number do not have this bit set prevents using this property
382 // to get around a CHECKSEQUENCEVERIFY check.
383 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
386 // Mask off any bits that do not have consensus-enforced meaning
387 // before doing the integer comparisons
388 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
389 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
390 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
392 // There are two kinds of nSequence: lock-by-blockheight
393 // and lock-by-blocktime, distinguished by whether
394 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
396 // We want to compare apples to apples, so fail the script
397 // unless the type of nSequenceMasked being tested is the same as
398 // the nSequenceMasked in the transaction.
400 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
401 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
406 // Now that we know we're comparing apples-to-apples, the
407 // comparison is a simple numeric one.
408 if (nSequenceMasked > txToSequenceMasked)
414 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
417 CScript::const_iterator pc = script.begin();
418 CScript::const_iterator pend = script.end();
419 CScript::const_iterator pbegincodehash = script.begin();
421 valtype vchPushValue;
422 std::vector<bool> vfExec;
423 std::vector<valtype> altstack;
424 if (script.size() > 10000)
432 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
437 if (!script.GetOp(pc, opcode, vchPushValue))
439 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
441 if (opcode > OP_16 && ++nOpCount > 201)
444 if (opcode == OP_CAT ||
445 opcode == OP_SUBSTR ||
447 opcode == OP_RIGHT ||
448 opcode == OP_INVERT ||
457 opcode == OP_LSHIFT ||
459 return false; // Disabled opcodes.
461 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
462 stack.push_back(vchPushValue);
463 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
488 CBigNum bn((int)opcode - (int)(OP_1 - 1));
489 stack.push_back(bn.getvch());
498 case OP_NOP1: case OP_NOP4: case OP_NOP5:
499 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
505 // <expression> if [statements] [else [statements]] endif
509 if (stack.size() < 1)
511 valtype& vch = stacktop(-1);
512 fValue = CastToBool(vch);
513 if (opcode == OP_NOTIF)
517 vfExec.push_back(fValue);
525 vfExec.back() = !vfExec.back();
540 // (false -- false) and return
541 if (stack.size() < 1)
543 bool fValue = CastToBool(stacktop(-1));
557 case OP_CHECKLOCKTIMEVERIFY:
559 // CHECKLOCKTIMEVERIFY
561 // (nLockTime -- nLockTime)
562 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
563 // treat as a NOP2 if not enabled
567 if (stack.size() < 1)
570 CBigNum nLockTime = CastToBigNum(stacktop(-1));
572 // In the rare event that the argument may be < 0 due to
573 // some arithmetic being done first, you can always use
574 // 0 MAX CHECKLOCKTIMEVERIFY.
578 // Actually compare the specified lock time with the transaction.
579 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
585 case OP_CHECKSEQUENCEVERIFY:
587 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
588 // treat as a NOP3 not enabled
592 if (stack.size() < 1)
595 // nSequence, like nLockTime, is a 32-bit unsigned integer
596 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
597 // 5-byte numeric operands.
598 CBigNum nSequence = CastToBigNum(stacktop(-1));
600 // In the rare event that the argument may be < 0 due to
601 // some arithmetic being done first, you can always use
602 // 0 MAX CHECKSEQUENCEVERIFY.
606 // To provide for future soft-fork extensibility, if the
607 // operand has the disabled lock-time flag set,
608 // CHECKSEQUENCEVERIFY behaves as a NOP.
609 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
612 // Compare the specified sequence number with the input.
613 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
624 if (stack.size() < 1)
626 altstack.push_back(stacktop(-1));
631 case OP_FROMALTSTACK:
633 if (altstack.size() < 1)
635 stack.push_back(altstacktop(-1));
643 if (stack.size() < 2)
652 // (x1 x2 -- x1 x2 x1 x2)
653 if (stack.size() < 2)
655 valtype vch1 = stacktop(-2);
656 valtype vch2 = stacktop(-1);
657 stack.push_back(vch1);
658 stack.push_back(vch2);
664 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
665 if (stack.size() < 3)
667 valtype vch1 = stacktop(-3);
668 valtype vch2 = stacktop(-2);
669 valtype vch3 = stacktop(-1);
670 stack.push_back(vch1);
671 stack.push_back(vch2);
672 stack.push_back(vch3);
678 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
679 if (stack.size() < 4)
681 valtype vch1 = stacktop(-4);
682 valtype vch2 = stacktop(-3);
683 stack.push_back(vch1);
684 stack.push_back(vch2);
690 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
691 if (stack.size() < 6)
693 valtype vch1 = stacktop(-6);
694 valtype vch2 = stacktop(-5);
695 stack.erase(stack.end()-6, stack.end()-4);
696 stack.push_back(vch1);
697 stack.push_back(vch2);
703 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
704 if (stack.size() < 4)
706 swap(stacktop(-4), stacktop(-2));
707 swap(stacktop(-3), stacktop(-1));
714 if (stack.size() < 1)
716 valtype vch = stacktop(-1);
718 stack.push_back(vch);
725 CBigNum bn((uint16_t) stack.size());
726 stack.push_back(bn.getvch());
733 if (stack.size() < 1)
742 if (stack.size() < 1)
744 valtype vch = stacktop(-1);
745 stack.push_back(vch);
752 if (stack.size() < 2)
754 stack.erase(stack.end() - 2);
760 // (x1 x2 -- x1 x2 x1)
761 if (stack.size() < 2)
763 valtype vch = stacktop(-2);
764 stack.push_back(vch);
771 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
772 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
773 if (stack.size() < 2)
775 int n = CastToBigNum(stacktop(-1)).getint32();
777 if (n < 0 || n >= (int)stack.size())
779 valtype vch = stacktop(-n-1);
780 if (opcode == OP_ROLL)
781 stack.erase(stack.end()-n-1);
782 stack.push_back(vch);
788 // (x1 x2 x3 -- x2 x3 x1)
789 // x2 x1 x3 after first swap
790 // x2 x3 x1 after second swap
791 if (stack.size() < 3)
793 swap(stacktop(-3), stacktop(-2));
794 swap(stacktop(-2), stacktop(-1));
801 if (stack.size() < 2)
803 swap(stacktop(-2), stacktop(-1));
809 // (x1 x2 -- x2 x1 x2)
810 if (stack.size() < 2)
812 valtype vch = stacktop(-1);
813 stack.insert(stack.end()-2, vch);
821 if (stack.size() < 1)
823 CBigNum bn((uint16_t) stacktop(-1).size());
824 stack.push_back(bn.getvch());
834 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
837 if (stack.size() < 2)
839 valtype& vch1 = stacktop(-2);
840 valtype& vch2 = stacktop(-1);
841 bool fEqual = (vch1 == vch2);
842 // OP_NOTEQUAL is disabled because it would be too easy to say
843 // something like n != 1 and have some wiseguy pass in 1 with extra
844 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
845 //if (opcode == OP_NOTEQUAL)
849 stack.push_back(fEqual ? vchTrue : vchFalse);
850 if (opcode == OP_EQUALVERIFY)
872 if (stack.size() < 1)
874 CBigNum bn = CastToBigNum(stacktop(-1));
877 case OP_1ADD: bn += bnOne; break;
878 case OP_1SUB: bn -= bnOne; break;
879 case OP_NEGATE: bn = -bn; break;
880 case OP_ABS: if (bn < bnZero) bn = -bn; break;
881 case OP_NOT: bn = (bn == bnZero); break;
882 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
883 default: assert(!"invalid opcode"); break;
886 stack.push_back(bn.getvch());
895 case OP_NUMEQUALVERIFY:
899 case OP_LESSTHANOREQUAL:
900 case OP_GREATERTHANOREQUAL:
905 if (stack.size() < 2)
907 CBigNum bn1 = CastToBigNum(stacktop(-2));
908 CBigNum bn2 = CastToBigNum(stacktop(-1));
920 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
921 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
922 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
923 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
924 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
925 case OP_LESSTHAN: bn = (bn1 < bn2); break;
926 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
927 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
928 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
929 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
930 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
931 default: assert(!"invalid opcode"); break;
935 stack.push_back(bn.getvch());
937 if (opcode == OP_NUMEQUALVERIFY)
939 if (CastToBool(stacktop(-1)))
949 // (x min max -- out)
950 if (stack.size() < 3)
952 CBigNum bn1 = CastToBigNum(stacktop(-3));
953 CBigNum bn2 = CastToBigNum(stacktop(-2));
954 CBigNum bn3 = CastToBigNum(stacktop(-1));
955 bool fValue = (bn2 <= bn1 && bn1 < bn3);
959 stack.push_back(fValue ? vchTrue : vchFalse);
974 if (stack.size() < 1)
976 valtype& vch = stacktop(-1);
977 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
978 if (opcode == OP_RIPEMD160)
979 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
980 else if (opcode == OP_SHA1)
981 SHA1(&vch[0], vch.size(), &vchHash[0]);
982 else if (opcode == OP_SHA256)
983 SHA256(&vch[0], vch.size(), &vchHash[0]);
984 else if (opcode == OP_HASH160)
986 uint160 hash160 = Hash160(vch);
987 memcpy(&vchHash[0], &hash160, sizeof(hash160));
989 else if (opcode == OP_HASH256)
991 uint256 hash = Hash(vch.begin(), vch.end());
992 memcpy(&vchHash[0], &hash, sizeof(hash));
995 stack.push_back(vchHash);
999 case OP_CODESEPARATOR:
1001 // Hash starts after the code separator
1002 pbegincodehash = pc;
1007 case OP_CHECKSIGVERIFY:
1009 // (sig pubkey -- bool)
1010 if (stack.size() < 2)
1013 valtype& vchSig = stacktop(-2);
1014 valtype& vchPubKey = stacktop(-1);
1017 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1018 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1020 // Subset of script starting at the most recent codeseparator
1021 CScript scriptCode(pbegincodehash, pend);
1023 // Drop the signature, since there's no way for a signature to sign itself
1024 scriptCode.FindAndDelete(CScript(vchSig));
1026 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1027 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1031 stack.push_back(fSuccess ? vchTrue : vchFalse);
1032 if (opcode == OP_CHECKSIGVERIFY)
1042 case OP_CHECKMULTISIG:
1043 case OP_CHECKMULTISIGVERIFY:
1045 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1048 if ((int)stack.size() < i)
1051 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1052 if (nKeysCount < 0 || nKeysCount > 20)
1054 nOpCount += nKeysCount;
1059 if ((int)stack.size() < i)
1062 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1063 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1067 if ((int)stack.size() < i)
1070 // Subset of script starting at the most recent codeseparator
1071 CScript scriptCode(pbegincodehash, pend);
1073 // Drop the signatures, since there's no way for a signature to sign itself
1074 for (int k = 0; k < nSigsCount; k++)
1076 valtype& vchSig = stacktop(-isig-k);
1077 scriptCode.FindAndDelete(CScript(vchSig));
1080 bool fSuccess = true;
1081 while (fSuccess && nSigsCount > 0)
1083 valtype& vchSig = stacktop(-isig);
1084 valtype& vchPubKey = stacktop(-ikey);
1087 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1088 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1097 // If there are more signatures left than keys left,
1098 // then too many signatures have failed
1099 if (nSigsCount > nKeysCount)
1106 // A bug causes CHECKMULTISIG to consume one extra argument
1107 // whose contents were not checked in any way.
1109 // Unfortunately this is a potential source of mutability,
1110 // so optionally verify it is exactly equal to zero prior
1111 // to removing it from the stack.
1112 if (stack.size() < 1)
1114 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1115 return error("CHECKMULTISIG dummy argument not null");
1118 stack.push_back(fSuccess ? vchTrue : vchFalse);
1120 if (opcode == OP_CHECKMULTISIGVERIFY)
1135 if (stack.size() + altstack.size() > 1000)
1145 if (!vfExec.empty())
1159 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1161 if (nIn >= txTo.vin.size())
1163 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1166 CTransaction txTmp(txTo);
1168 // In case concatenating two scripts ends up with two codeseparators,
1169 // or an extra one at the end, this prevents all those possible incompatibilities.
1170 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1172 // Blank out other inputs' signatures
1173 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1174 txTmp.vin[i].scriptSig = CScript();
1175 txTmp.vin[nIn].scriptSig = scriptCode;
1177 // Blank out some of the outputs
1178 if ((nHashType & 0x1f) == SIGHASH_NONE)
1183 // Let the others update at will
1184 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1186 txTmp.vin[i].nSequence = 0;
1188 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1190 // Only lock-in the txout payee at same index as txin
1191 unsigned int nOut = nIn;
1192 if (nOut >= txTmp.vout.size())
1194 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1197 txTmp.vout.resize(nOut+1);
1198 for (unsigned int i = 0; i < nOut; i++)
1199 txTmp.vout[i].SetNull();
1201 // Let the others update at will
1202 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1204 txTmp.vin[i].nSequence = 0;
1207 // Blank out other inputs completely, not recommended for open transactions
1208 if (nHashType & SIGHASH_ANYONECANPAY)
1210 txTmp.vin[0] = txTmp.vin[nIn];
1211 txTmp.vin.resize(1);
1214 // Serialize and hash
1215 CDataStream ss(SER_GETHASH, 0);
1217 ss << txTmp << nHashType;
1218 return Hash(ss.begin(), ss.end());
1222 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1223 // twice for every transaction (once when accepted into memory pool, and
1224 // again when accepted into the block chain)
1226 class CSignatureCache
1229 // sigdata_type is (signature hash, signature, public key):
1230 typedef std::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1231 std::set< sigdata_type> setValid;
1232 boost::shared_mutex cs_sigcache;
1236 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1238 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1240 sigdata_type k(hash, vchSig, pubKey);
1241 std::set<sigdata_type>::iterator mi = setValid.find(k);
1242 if (mi != setValid.end())
1247 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1249 // DoS prevention: limit cache size to less than 10MB
1250 // (~200 bytes per cache entry times 50,000 entries)
1251 // Since there are a maximum of 20,000 signature operations per block
1252 // 50,000 is a reasonable default.
1253 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1254 if (nMaxCacheSize <= 0) return;
1256 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1258 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1260 // Evict a random entry. Random because that helps
1261 // foil would-be DoS attackers who might try to pre-generate
1262 // and re-use a set of valid signatures just-slightly-greater
1263 // than our cache size.
1264 uint256 randomHash = GetRandHash();
1265 std::vector<unsigned char> unused;
1266 std::set<sigdata_type>::iterator it =
1267 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1268 if (it == setValid.end())
1269 it = setValid.begin();
1270 setValid.erase(*it);
1273 sigdata_type k(hash, vchSig, pubKey);
1278 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1279 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1281 static CSignatureCache signatureCache;
1283 CPubKey pubkey(vchPubKey);
1284 if (!pubkey.IsValid())
1287 // Hash type is one byte tacked on to the end of the signature
1291 nHashType = vchSig.back();
1292 else if (nHashType != vchSig.back())
1296 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1298 if (signatureCache.Get(sighash, vchSig, pubkey))
1301 if (!pubkey.Verify(sighash, vchSig))
1304 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1305 signatureCache.Set(sighash, vchSig, pubkey);
1312 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1314 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
1317 static std::map<txnouttype, CScript> mTemplates;
1318 if (mTemplates.empty())
1320 // Standard tx, sender provides pubkey, receiver adds signature
1321 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1323 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1324 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1326 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1327 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1329 // Sender provides N pubkeys, receivers provides M signatures
1330 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1332 // Empty, provably prunable, data-carrying output
1333 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1336 vSolutionsRet.clear();
1338 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1339 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1340 if (scriptPubKey.IsPayToScriptHash())
1342 typeRet = TX_SCRIPTHASH;
1343 std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1344 vSolutionsRet.push_back(hashBytes);
1348 // Provably prunable, data-carrying output
1350 // So long as script passes the IsUnspendable() test and all but the first
1351 // byte passes the IsPushOnly() test we don't care what exactly is in the
1353 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1354 typeRet = TX_NULL_DATA;
1359 const CScript& script1 = scriptPubKey;
1360 for (const auto& tplate : mTemplates)
1362 const CScript& script2 = tplate.second;
1363 vSolutionsRet.clear();
1365 opcodetype opcode1, opcode2;
1366 std::vector<unsigned char> vch1, vch2;
1369 CScript::const_iterator pc1 = script1.begin();
1370 CScript::const_iterator pc2 = script2.begin();
1373 if (pc1 == script1.end() && pc2 == script2.end())
1376 typeRet = tplate.first;
1377 if (typeRet == TX_MULTISIG)
1379 // Additional checks for TX_MULTISIG:
1380 unsigned char m = vSolutionsRet.front()[0];
1381 unsigned char n = vSolutionsRet.back()[0];
1382 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1387 if (!script1.GetOp(pc1, opcode1, vch1))
1389 if (!script2.GetOp(pc2, opcode2, vch2))
1392 // Template matching opcodes:
1393 if (opcode2 == OP_PUBKEYS)
1395 while (vch1.size() >= 33 && vch1.size() <= 120)
1397 vSolutionsRet.push_back(vch1);
1398 if (!script1.GetOp(pc1, opcode1, vch1))
1401 if (!script2.GetOp(pc2, opcode2, vch2))
1403 // Normal situation is to fall through
1404 // to other if/else statements
1407 if (opcode2 == OP_PUBKEY)
1409 if (vch1.size() < 33 || vch1.size() > 120)
1411 vSolutionsRet.push_back(vch1);
1413 else if (opcode2 == OP_PUBKEYHASH)
1415 if (vch1.size() != sizeof(uint160))
1417 vSolutionsRet.push_back(vch1);
1419 else if (opcode2 == OP_SMALLINTEGER)
1420 { // Single-byte small integer pushed onto vSolutions
1421 if (opcode1 == OP_0 ||
1422 (opcode1 >= OP_1 && opcode1 <= OP_16))
1424 char n = (char)CScript::DecodeOP_N(opcode1);
1425 vSolutionsRet.push_back(valtype(1, n));
1430 else if (opcode2 == OP_INTEGER)
1431 { // Up to four-byte integer pushed onto vSolutions
1434 CBigNum bnVal = CastToBigNum(vch1);
1436 break; // It's better to use OP_0 ... OP_16 for small integers.
1437 vSolutionsRet.push_back(vch1);
1444 else if (opcode2 == OP_SMALLDATA)
1446 // small pushdata, <= 1024 bytes
1447 if (vch1.size() > 1024)
1450 else if (opcode1 != opcode2 || vch1 != vch2)
1452 // Others must match exactly
1458 vSolutionsRet.clear();
1459 typeRet = TX_NONSTANDARD;
1464 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1467 if (!keystore.GetKey(address, key))
1470 std::vector<unsigned char> vchSig;
1471 if (!key.Sign(hash, vchSig))
1473 vchSig.push_back((unsigned char)nHashType);
1474 scriptSigRet << vchSig;
1479 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1482 if (!keystore.CreatePrivKey(pubKey, R, key))
1485 std::vector<unsigned char> vchSig;
1486 if (!key.Sign(hash, vchSig))
1488 vchSig.push_back((unsigned char)nHashType);
1489 scriptSigRet << vchSig;
1494 bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1497 int nRequired = multisigdata.front()[0];
1498 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1500 const valtype& pubkey = multisigdata[i];
1501 CKeyID keyID = CPubKey(pubkey).GetID();
1502 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1505 return nSigned==nRequired;
1509 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1510 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1511 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1512 // Returns false if scriptPubKey could not be completely satisfied.
1514 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1515 CScript& scriptSigRet, txnouttype& whichTypeRet)
1517 scriptSigRet.clear();
1519 std::vector<valtype> vSolutions;
1520 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1524 switch (whichTypeRet)
1526 case TX_NONSTANDARD:
1530 keyID = CPubKey(vSolutions[0]).GetID();
1531 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1532 case TX_PUBKEY_DROP:
1534 CPubKey key = CPubKey(vSolutions[0]);
1535 CPubKey R = CPubKey(vSolutions[1]);
1536 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1539 keyID = CKeyID(uint160(vSolutions[0]));
1540 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1545 keystore.GetPubKey(keyID, vch);
1546 scriptSigRet << vch;
1550 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1553 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1554 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1559 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1563 case TX_NONSTANDARD:
1568 case TX_PUBKEY_DROP:
1573 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1575 return vSolutions[0][0] + 1;
1577 return 1; // doesn't include args needed by the script
1582 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1584 std::vector<valtype> vSolutions;
1585 if (!Solver(scriptPubKey, whichType, vSolutions))
1588 if (whichType == TX_MULTISIG)
1590 unsigned char m = vSolutions.front()[0];
1591 unsigned char n = vSolutions.back()[0];
1592 // Support up to x-of-3 multisig txns as standard
1599 return whichType != TX_NONSTANDARD;
1603 unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
1605 unsigned int nResult = 0;
1606 for (const valtype& pubkey : pubkeys)
1608 CKeyID keyID = CPubKey(pubkey).GetID();
1609 if (keystore.HaveKey(keyID))
1616 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1619 const CKeyStore *keystore;
1621 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1622 bool operator()(const CNoDestination &dest) const { return false; }
1623 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1624 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1628 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1631 script.SetDestination(dest);
1632 return IsMine(keystore, script);
1635 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1638 script.SetAddress(dest);
1639 return IsMine(keystore, script);
1642 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1644 std::vector<valtype> vSolutions;
1645 txnouttype whichType;
1646 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1647 if (keystore.HaveWatchOnly(scriptPubKey))
1648 return MINE_WATCH_ONLY;
1655 case TX_NONSTANDARD:
1659 keyID = CPubKey(vSolutions[0]).GetID();
1660 if (keystore.HaveKey(keyID))
1661 return MINE_SPENDABLE;
1663 case TX_PUBKEY_DROP:
1665 CPubKey key = CPubKey(vSolutions[0]);
1666 CPubKey R = CPubKey(vSolutions[1]);
1667 if (keystore.CheckOwnership(key, R))
1668 return MINE_SPENDABLE;
1672 keyID = CKeyID(uint160(vSolutions[0]));
1673 if (keystore.HaveKey(keyID))
1674 return MINE_SPENDABLE;
1678 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1680 if (keystore.GetCScript(scriptID, subscript)) {
1681 isminetype ret = IsMine(keystore, subscript);
1682 if (ret == MINE_SPENDABLE)
1689 // Only consider transactions "mine" if we own ALL the
1690 // keys involved. multi-signature transactions that are
1691 // partially owned (somebody else has a key that can spend
1692 // them) enable spend-out-from-under-you attacks, especially
1693 // in shared-wallet situations.
1694 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1695 if (HaveKeys(keys, keystore) == keys.size())
1696 return MINE_SPENDABLE;
1701 if (keystore.HaveWatchOnly(scriptPubKey))
1702 return MINE_WATCH_ONLY;
1706 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1708 std::vector<valtype> vSolutions;
1709 txnouttype whichType;
1710 if (!Solver(scriptPubKey, whichType, vSolutions))
1713 if (whichType == TX_PUBKEY)
1715 addressRet = CPubKey(vSolutions[0]).GetID();
1718 else if (whichType == TX_PUBKEYHASH)
1720 addressRet = CKeyID(uint160(vSolutions[0]));
1723 else if (whichType == TX_SCRIPTHASH)
1725 addressRet = CScriptID(uint160(vSolutions[0]));
1728 // Multisig txns have more than one address...
1732 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1734 std::vector<valtype> vSolutions;
1735 txnouttype whichType;
1736 if (!Solver(scriptPubKey, whichType, vSolutions))
1739 if (whichType == TX_PUBKEY)
1741 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1744 if (whichType == TX_PUBKEY_DROP)
1747 CMalleableKeyView view;
1748 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1751 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1754 else if (whichType == TX_PUBKEYHASH)
1756 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1759 else if (whichType == TX_SCRIPTHASH)
1761 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1764 // Multisig txns have more than one address...
1768 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1770 const CKeyStore &keystore;
1771 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1772 std::vector<CKeyID> &vKeys;
1775 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1777 void Process(const CScript &script) {
1779 std::vector<CTxDestination> vDest;
1781 if (ExtractDestinations(script, type, vDest, nRequired)) {
1782 for (const CTxDestination &dest : vDest)
1783 std::visit(*this, dest);
1787 void operator()(const CKeyID &keyId) {
1788 if (keystore.HaveKey(keyId))
1789 vKeys.push_back(keyId);
1792 void operator()(const CScriptID &scriptId) {
1794 if (keystore.GetCScript(scriptId, script))
1798 void operator()(const CNoDestination &none) {}
1802 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1803 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1806 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
1809 typeRet = TX_NONSTANDARD;
1810 std::vector<valtype> vSolutions;
1811 if (!Solver(scriptPubKey, typeRet, vSolutions))
1813 if (typeRet == TX_NULL_DATA)
1819 if (typeRet == TX_MULTISIG)
1821 nRequiredRet = vSolutions.front()[0];
1822 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1824 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1825 addressRet.push_back(address);
1831 if (typeRet == TX_PUBKEY_DROP)
1833 CTxDestination address;
1834 if (!ExtractDestination(scriptPubKey, address))
1836 addressRet.push_back(address);
1842 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1843 unsigned int flags, int nHashType)
1845 std::vector<std::vector<unsigned char> > stack, stackCopy;
1846 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1848 if (flags & SCRIPT_VERIFY_P2SH)
1850 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1855 if (CastToBool(stack.back()) == false)
1858 // Additional validation for spend-to-script-hash transactions:
1859 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1861 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1862 return false; // or validation fails
1864 // stackCopy cannot be empty here, because if it was the
1865 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1866 // an empty stack and the EvalScript above would return false.
1867 assert(!stackCopy.empty());
1869 const valtype& pubKeySerialized = stackCopy.back();
1870 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1871 popstack(stackCopy);
1873 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1875 if (stackCopy.empty())
1877 return CastToBool(stackCopy.back());
1883 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1885 assert(nIn < txTo.vin.size());
1886 CTxIn& txin = txTo.vin[nIn];
1888 // Leave out the signature from the hash, since a signature can't sign itself.
1889 // The checksig op will also drop the signatures from its hash.
1890 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1892 txnouttype whichType;
1893 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1896 if (whichType == TX_SCRIPTHASH)
1898 // Solver returns the subscript that need to be evaluated;
1899 // the final scriptSig is the signatures from that
1900 // and then the serialized subscript:
1901 CScript subscript = txin.scriptSig;
1903 // Recompute txn hash using subscript in place of scriptPubKey:
1904 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1908 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1909 // Append serialized subscript whether or not it is completely signed:
1910 txin.scriptSig << static_cast<valtype>(subscript);
1911 if (!fSolved) return false;
1915 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1918 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1920 assert(nIn < txTo.vin.size());
1921 CTxIn& txin = txTo.vin[nIn];
1922 assert(txin.prevout.n < txFrom.vout.size());
1923 assert(txin.prevout.hash == txFrom.GetHash());
1924 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1926 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1929 static CScript PushAll(const std::vector<valtype>& values)
1932 for (const valtype& v : values)
1937 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1938 const std::vector<valtype>& vSolutions,
1939 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1941 // Combine all the signatures we've got:
1942 std::set<valtype> allsigs;
1943 for (const valtype& v : sigs1)
1948 for (const valtype& v : sigs2)
1954 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1955 assert(vSolutions.size() > 1);
1956 unsigned int nSigsRequired = vSolutions.front()[0];
1957 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1958 std::map<valtype, valtype> sigs;
1959 for (const valtype& sig : allsigs)
1961 for (unsigned int i = 0; i < nPubKeys; i++)
1963 const valtype& pubkey = vSolutions[i+1];
1964 if (sigs.count(pubkey))
1965 continue; // Already got a sig for this pubkey
1967 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1974 // Now build a merged CScript:
1975 unsigned int nSigsHave = 0;
1976 CScript result; result << OP_0; // pop-one-too-many workaround
1977 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1979 if (sigs.count(vSolutions[i+1]))
1981 result << sigs[vSolutions[i+1]];
1985 // Fill any missing with OP_0:
1986 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1992 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1993 const txnouttype txType, const std::vector<valtype>& vSolutions,
1994 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1998 case TX_NONSTANDARD:
2000 // Don't know anything about this, assume bigger one is correct:
2001 if (sigs1.size() >= sigs2.size())
2002 return PushAll(sigs1);
2003 return PushAll(sigs2);
2005 case TX_PUBKEY_DROP:
2007 // Signatures are bigger than placeholders or empty scripts:
2008 if (sigs1.empty() || sigs1[0].empty())
2009 return PushAll(sigs2);
2010 return PushAll(sigs1);
2012 if (sigs1.empty() || sigs1.back().empty())
2013 return PushAll(sigs2);
2014 else if (sigs2.empty() || sigs2.back().empty())
2015 return PushAll(sigs1);
2018 // Recur to combine:
2019 valtype spk = sigs1.back();
2020 CScript pubKey2(spk.begin(), spk.end());
2023 std::vector<std::vector<unsigned char> > vSolutions2;
2024 Solver(pubKey2, txType2, vSolutions2);
2027 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2032 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2038 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2039 const CScript& scriptSig1, const CScript& scriptSig2)
2042 std::vector<std::vector<unsigned char> > vSolutions;
2043 Solver(scriptPubKey, txType, vSolutions);
2045 std::vector<valtype> stack1;
2046 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2047 std::vector<valtype> stack2;
2048 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2050 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2053 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2056 const_iterator pc = begin();
2057 opcodetype lastOpcode = OP_INVALIDOPCODE;
2061 if (!GetOp(pc, opcode))
2063 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2065 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2067 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2068 n += DecodeOP_N(lastOpcode);
2072 lastOpcode = opcode;
2077 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2079 if (!IsPayToScriptHash())
2080 return GetSigOpCount(true);
2082 // This is a pay-to-script-hash scriptPubKey;
2083 // get the last item that the scriptSig
2084 // pushes onto the stack:
2085 const_iterator pc = scriptSig.begin();
2086 vector<unsigned char> data;
2087 while (pc < scriptSig.end())
2090 if (!scriptSig.GetOp(pc, opcode, data))
2096 /// ... and return its opcount:
2097 CScript subscript(data.begin(), data.end());
2098 return subscript.GetSigOpCount(true);
2101 bool CScript::IsPayToScriptHash() const
2103 // Extra-fast test for pay-to-script-hash CScripts:
2104 return (this->size() == 23 &&
2105 this->at(0) == OP_HASH160 &&
2106 this->at(1) == 0x14 &&
2107 this->at(22) == OP_EQUAL);
2110 bool CScript::HasCanonicalPushes() const
2112 const_iterator pc = begin();
2116 std::vector<unsigned char> data;
2117 if (!GetOp(pc, opcode, data))
2121 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2122 // Could have used an OP_n code, rather than a 1-byte push.
2124 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2125 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2127 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2128 // Could have used an OP_PUSHDATA1.
2130 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2131 // Could have used an OP_PUSHDATA2.
2137 class CScriptVisitor : public boost::static_visitor<bool>
2142 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2144 bool operator()(const CNoDestination &dest) const {
2149 bool operator()(const CKeyID &keyID) const {
2151 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2155 bool operator()(const CScriptID &scriptID) const {
2157 *script << OP_HASH160 << scriptID << OP_EQUAL;
2162 void CScript::SetDestination(const CTxDestination& dest)
2164 std::visit(CScriptVisitor(this), dest);
2167 void CScript::SetAddress(const CBitcoinAddress& dest)
2170 if (dest.IsScript())
2171 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2172 else if (dest.IsPubKey())
2173 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2174 else if (dest.IsPair()) {
2175 // Pubkey pair address, going to generate
2176 // new one-time public key.
2177 CMalleablePubKey mpk;
2178 if (!mpk.setvch(dest.GetData()))
2180 CPubKey R, pubKeyVariant;
2181 mpk.GetVariant(R, pubKeyVariant);
2182 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2186 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2190 *this << EncodeOP_N(nRequired);
2191 for (const CPubKey& key : keys)
2193 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;