1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
14 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);
16 static const valtype vchFalse(0);
17 static const valtype vchZero(0);
18 static const valtype vchTrue(1, 1);
19 static const CBigNum bnZero(0);
20 static const CBigNum bnOne(1);
21 static const CBigNum bnFalse(0);
22 static const CBigNum bnTrue(1);
23 static const size_t nMaxNumSize = 4;
26 CBigNum CastToBigNum(const valtype& vch)
28 if (vch.size() > nMaxNumSize)
29 throw std::runtime_error("CastToBigNum() : overflow");
30 // Get rid of extra leading zeros
31 return CBigNum(CBigNum(vch).getvch());
34 bool CastToBool(const valtype& vch)
36 for (unsigned int i = 0; i < vch.size(); i++)
40 // Can be negative zero
41 if (i == vch.size()-1 && vch[i] == 0x80)
50 // WARNING: This does not work as expected for signed integers; the sign-bit
51 // is left in place as the integer is zero-extended. The correct behavior
52 // would be to move the most significant bit of the last byte during the
53 // resize process. MakeSameSize() is currently only used by the disabled
54 // opcodes OP_AND, OP_OR, and OP_XOR.
56 void MakeSameSize(valtype& vch1, valtype& vch2)
58 // Lengthen the shorter one
59 if (vch1.size() < vch2.size())
61 // +unsigned char msb = vch1[vch1.size()-1];
62 // +vch1[vch1.size()-1] &= 0x7f;
63 // vch1.resize(vch2.size(), 0);
64 // +vch1[vch1.size()-1] = msb;
65 vch1.resize(vch2.size(), 0);
66 if (vch2.size() < vch1.size())
68 // +unsigned char msb = vch2[vch2.size()-1];
69 // +vch2[vch2.size()-1] &= 0x7f;
70 // vch2.resize(vch1.size(), 0);
71 // +vch2[vch2.size()-1] = msb;
72 vch2.resize(vch1.size(), 0);
78 // Script is a stack machine (like Forth) that evaluates a predicate
79 // returning a bool indicating valid or not. There are no loops.
81 #define stacktop(i) (stack.at(stack.size()+(i)))
82 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
83 static inline void popstack(std::vector<valtype>& stack)
86 throw std::runtime_error("popstack() : stack empty");
91 const char* GetTxnOutputType(txnouttype t)
95 case TX_NONSTANDARD: return "nonstandard";
96 case TX_PUBKEY: return "pubkey";
97 case TX_PUBKEY_DROP: return "pubkeydrop";
98 case TX_PUBKEYHASH: return "pubkeyhash";
99 case TX_SCRIPTHASH: return "scripthash";
100 case TX_MULTISIG: return "multisig";
101 case TX_NULL_DATA: return "nulldata";
107 const char* GetOpName(opcodetype opcode)
112 case OP_0 : return "0";
113 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
114 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
115 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
116 case OP_1NEGATE : return "-1";
117 case OP_RESERVED : return "OP_RESERVED";
118 case OP_1 : return "1";
119 case OP_2 : return "2";
120 case OP_3 : return "3";
121 case OP_4 : return "4";
122 case OP_5 : return "5";
123 case OP_6 : return "6";
124 case OP_7 : return "7";
125 case OP_8 : return "8";
126 case OP_9 : return "9";
127 case OP_10 : return "10";
128 case OP_11 : return "11";
129 case OP_12 : return "12";
130 case OP_13 : return "13";
131 case OP_14 : return "14";
132 case OP_15 : return "15";
133 case OP_16 : return "16";
136 case OP_NOP : return "OP_NOP";
137 case OP_VER : return "OP_VER";
138 case OP_IF : return "OP_IF";
139 case OP_NOTIF : return "OP_NOTIF";
140 case OP_VERIF : return "OP_VERIF";
141 case OP_VERNOTIF : return "OP_VERNOTIF";
142 case OP_ELSE : return "OP_ELSE";
143 case OP_ENDIF : return "OP_ENDIF";
144 case OP_VERIFY : return "OP_VERIFY";
145 case OP_RETURN : return "OP_RETURN";
146 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
147 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
150 case OP_TOALTSTACK : return "OP_TOALTSTACK";
151 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
152 case OP_2DROP : return "OP_2DROP";
153 case OP_2DUP : return "OP_2DUP";
154 case OP_3DUP : return "OP_3DUP";
155 case OP_2OVER : return "OP_2OVER";
156 case OP_2ROT : return "OP_2ROT";
157 case OP_2SWAP : return "OP_2SWAP";
158 case OP_IFDUP : return "OP_IFDUP";
159 case OP_DEPTH : return "OP_DEPTH";
160 case OP_DROP : return "OP_DROP";
161 case OP_DUP : return "OP_DUP";
162 case OP_NIP : return "OP_NIP";
163 case OP_OVER : return "OP_OVER";
164 case OP_PICK : return "OP_PICK";
165 case OP_ROLL : return "OP_ROLL";
166 case OP_ROT : return "OP_ROT";
167 case OP_SWAP : return "OP_SWAP";
168 case OP_TUCK : return "OP_TUCK";
171 case OP_CAT : return "OP_CAT";
172 case OP_SUBSTR : return "OP_SUBSTR";
173 case OP_LEFT : return "OP_LEFT";
174 case OP_RIGHT : return "OP_RIGHT";
175 case OP_SIZE : return "OP_SIZE";
178 case OP_INVERT : return "OP_INVERT";
179 case OP_AND : return "OP_AND";
180 case OP_OR : return "OP_OR";
181 case OP_XOR : return "OP_XOR";
182 case OP_EQUAL : return "OP_EQUAL";
183 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
184 case OP_RESERVED1 : return "OP_RESERVED1";
185 case OP_RESERVED2 : return "OP_RESERVED2";
188 case OP_1ADD : return "OP_1ADD";
189 case OP_1SUB : return "OP_1SUB";
190 case OP_2MUL : return "OP_2MUL";
191 case OP_2DIV : return "OP_2DIV";
192 case OP_NEGATE : return "OP_NEGATE";
193 case OP_ABS : return "OP_ABS";
194 case OP_NOT : return "OP_NOT";
195 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
196 case OP_ADD : return "OP_ADD";
197 case OP_SUB : return "OP_SUB";
198 case OP_MUL : return "OP_MUL";
199 case OP_DIV : return "OP_DIV";
200 case OP_MOD : return "OP_MOD";
201 case OP_LSHIFT : return "OP_LSHIFT";
202 case OP_RSHIFT : return "OP_RSHIFT";
203 case OP_BOOLAND : return "OP_BOOLAND";
204 case OP_BOOLOR : return "OP_BOOLOR";
205 case OP_NUMEQUAL : return "OP_NUMEQUAL";
206 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
207 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
208 case OP_LESSTHAN : return "OP_LESSTHAN";
209 case OP_GREATERTHAN : return "OP_GREATERTHAN";
210 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
211 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
212 case OP_MIN : return "OP_MIN";
213 case OP_MAX : return "OP_MAX";
214 case OP_WITHIN : return "OP_WITHIN";
217 case OP_RIPEMD160 : return "OP_RIPEMD160";
218 case OP_SHA1 : return "OP_SHA1";
219 case OP_SHA256 : return "OP_SHA256";
220 case OP_HASH160 : return "OP_HASH160";
221 case OP_HASH256 : return "OP_HASH256";
222 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
223 case OP_CHECKSIG : return "OP_CHECKSIG";
224 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
225 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
226 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
229 case OP_NOP1 : return "OP_NOP1";
230 case OP_NOP4 : return "OP_NOP4";
231 case OP_NOP5 : return "OP_NOP5";
232 case OP_NOP6 : return "OP_NOP6";
233 case OP_NOP7 : return "OP_NOP7";
234 case OP_NOP8 : return "OP_NOP8";
235 case OP_NOP9 : return "OP_NOP9";
236 case OP_NOP10 : return "OP_NOP10";
240 // template matching params
241 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
242 case OP_PUBKEY : return "OP_PUBKEY";
243 case OP_SMALLDATA : return "OP_SMALLDATA";
245 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
251 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
252 if (!(flags & SCRIPT_VERIFY_STRICTENC))
255 if (vchPubKey.size() < 33)
256 return error("Non-canonical public key: too short");
257 if (vchPubKey[0] == 0x04) {
258 if (vchPubKey.size() != 65)
259 return error("Non-canonical public key: invalid length for uncompressed key");
260 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
261 if (vchPubKey.size() != 33)
262 return error("Non-canonical public key: invalid length for compressed key");
264 return error("Non-canonical public key: compressed nor uncompressed");
269 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
270 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
271 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
272 // Where R and S are not negative (their first byte has its highest bit not set), and not
273 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
274 // in which case a single 0 byte is necessary and even required).
275 if (vchSig.size() < 9)
276 return error("Non-canonical signature: too short");
277 if (vchSig.size() > 73)
278 return error("Non-canonical signature: too long");
279 if (vchSig[0] != 0x30)
280 return error("Non-canonical signature: wrong type");
281 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
282 return error("Non-canonical signature: wrong length marker");
284 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
285 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
286 return error("Non-canonical signature: unknown hashtype byte");
288 unsigned int nLenR = vchSig[3];
289 if (5 + nLenR >= vchSig.size())
290 return error("Non-canonical signature: S length misplaced");
291 unsigned int nLenS = vchSig[5+nLenR];
292 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
293 return error("Non-canonical signature: R+S length mismatch");
295 const unsigned char *R = &vchSig[4];
297 return error("Non-canonical signature: R value type mismatch");
299 return error("Non-canonical signature: R length is zero");
301 return error("Non-canonical signature: R value negative");
302 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
303 return error("Non-canonical signature: R value excessively padded");
305 const unsigned char *S = &vchSig[6+nLenR];
307 return error("Non-canonical signature: S value type mismatch");
309 return error("Non-canonical signature: S length is zero");
311 return error("Non-canonical signature: S value negative");
312 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
313 return error("Non-canonical signature: S value excessively padded");
316 unsigned int nLenR = vchSig[3];
317 unsigned int nLenS = vchSig[5+nLenR];
318 const unsigned char *S = &vchSig[6+nLenR];
319 // If the S value is above the order of the curve divided by two, its
320 // complement modulo the order could have been used instead, which is
321 // one byte shorter when encoded correctly.
322 if (!CKey::CheckSignatureElement(S, nLenS, true))
323 return error("Non-canonical signature: S value is unnecessarily high");
329 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
330 if (!(flags & SCRIPT_VERIFY_STRICTENC))
333 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
336 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
338 // There are two kinds of nLockTime: lock-by-blockheight
339 // and lock-by-blocktime, distinguished by whether
340 // nLockTime < LOCKTIME_THRESHOLD.
342 // We want to compare apples to apples, so fail the script
343 // unless the type of nLockTime being tested is the same as
344 // the nLockTime in the transaction.
346 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
347 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
351 // Now that we know we're comparing apples-to-apples, the
352 // comparison is a simple numeric one.
353 if (nLockTime > (int64_t)txTo.nLockTime)
356 // Finally the nLockTime feature can be disabled and thus
357 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
358 // finalized by setting nSequence to maxint. The
359 // transaction would be allowed into the blockchain, making
360 // the opcode ineffective.
362 // Testing if this vin is not final is sufficient to
363 // prevent this condition. Alternatively we could test all
364 // inputs, but testing just this input minimizes the data
365 // required to prove correct CHECKLOCKTIMEVERIFY execution.
366 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
372 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
374 // Relative lock times are supported by comparing the passed
375 // in operand to the sequence number of the input.
376 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
378 // Sequence numbers with their most significant bit set are not
379 // consensus constrained. Testing that the transaction's sequence
380 // number do not have this bit set prevents using this property
381 // to get around a CHECKSEQUENCEVERIFY check.
382 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
385 // Mask off any bits that do not have consensus-enforced meaning
386 // before doing the integer comparisons
387 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
388 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
389 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
391 // There are two kinds of nSequence: lock-by-blockheight
392 // and lock-by-blocktime, distinguished by whether
393 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
395 // We want to compare apples to apples, so fail the script
396 // unless the type of nSequenceMasked being tested is the same as
397 // the nSequenceMasked in the transaction.
399 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
400 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
405 // Now that we know we're comparing apples-to-apples, the
406 // comparison is a simple numeric one.
407 if (nSequenceMasked > txToSequenceMasked)
413 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
416 CScript::const_iterator pc = script.begin();
417 CScript::const_iterator pend = script.end();
418 CScript::const_iterator pbegincodehash = script.begin();
420 valtype vchPushValue;
421 std::vector<bool> vfExec;
422 std::vector<valtype> altstack;
423 if (script.size() > 10000)
431 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
436 if (!script.GetOp(pc, opcode, vchPushValue))
438 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
440 if (opcode > OP_16 && ++nOpCount > 201)
443 if (opcode == OP_CAT ||
444 opcode == OP_SUBSTR ||
446 opcode == OP_RIGHT ||
447 opcode == OP_INVERT ||
456 opcode == OP_LSHIFT ||
458 return false; // Disabled opcodes.
460 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
461 stack.push_back(vchPushValue);
462 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
487 CBigNum bn((int)opcode - (int)(OP_1 - 1));
488 stack.push_back(bn.getvch());
497 case OP_NOP1: case OP_NOP4: case OP_NOP5:
498 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
504 // <expression> if [statements] [else [statements]] endif
508 if (stack.size() < 1)
510 valtype& vch = stacktop(-1);
511 fValue = CastToBool(vch);
512 if (opcode == OP_NOTIF)
516 vfExec.push_back(fValue);
524 vfExec.back() = !vfExec.back();
539 // (false -- false) and return
540 if (stack.size() < 1)
542 bool fValue = CastToBool(stacktop(-1));
556 case OP_CHECKLOCKTIMEVERIFY:
558 // CHECKLOCKTIMEVERIFY
560 // (nLockTime -- nLockTime)
561 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
562 // treat as a NOP2 if not enabled
566 if (stack.size() < 1)
569 CBigNum nLockTime = CastToBigNum(stacktop(-1));
571 // In the rare event that the argument may be < 0 due to
572 // some arithmetic being done first, you can always use
573 // 0 MAX CHECKLOCKTIMEVERIFY.
577 // Actually compare the specified lock time with the transaction.
578 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
584 case OP_CHECKSEQUENCEVERIFY:
586 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
587 // treat as a NOP3 not enabled
591 if (stack.size() < 1)
594 // nSequence, like nLockTime, is a 32-bit unsigned integer
595 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
596 // 5-byte numeric operands.
597 CBigNum nSequence = CastToBigNum(stacktop(-1));
599 // In the rare event that the argument may be < 0 due to
600 // some arithmetic being done first, you can always use
601 // 0 MAX CHECKSEQUENCEVERIFY.
605 // To provide for future soft-fork extensibility, if the
606 // operand has the disabled lock-time flag set,
607 // CHECKSEQUENCEVERIFY behaves as a NOP.
608 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
611 // Compare the specified sequence number with the input.
612 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
623 if (stack.size() < 1)
625 altstack.push_back(stacktop(-1));
630 case OP_FROMALTSTACK:
632 if (altstack.size() < 1)
634 stack.push_back(altstacktop(-1));
642 if (stack.size() < 2)
651 // (x1 x2 -- x1 x2 x1 x2)
652 if (stack.size() < 2)
654 valtype vch1 = stacktop(-2);
655 valtype vch2 = stacktop(-1);
656 stack.push_back(vch1);
657 stack.push_back(vch2);
663 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
664 if (stack.size() < 3)
666 valtype vch1 = stacktop(-3);
667 valtype vch2 = stacktop(-2);
668 valtype vch3 = stacktop(-1);
669 stack.push_back(vch1);
670 stack.push_back(vch2);
671 stack.push_back(vch3);
677 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
678 if (stack.size() < 4)
680 valtype vch1 = stacktop(-4);
681 valtype vch2 = stacktop(-3);
682 stack.push_back(vch1);
683 stack.push_back(vch2);
689 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
690 if (stack.size() < 6)
692 valtype vch1 = stacktop(-6);
693 valtype vch2 = stacktop(-5);
694 stack.erase(stack.end()-6, stack.end()-4);
695 stack.push_back(vch1);
696 stack.push_back(vch2);
702 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
703 if (stack.size() < 4)
705 swap(stacktop(-4), stacktop(-2));
706 swap(stacktop(-3), stacktop(-1));
713 if (stack.size() < 1)
715 valtype vch = stacktop(-1);
717 stack.push_back(vch);
724 CBigNum bn((uint16_t) stack.size());
725 stack.push_back(bn.getvch());
732 if (stack.size() < 1)
741 if (stack.size() < 1)
743 valtype vch = stacktop(-1);
744 stack.push_back(vch);
751 if (stack.size() < 2)
753 stack.erase(stack.end() - 2);
759 // (x1 x2 -- x1 x2 x1)
760 if (stack.size() < 2)
762 valtype vch = stacktop(-2);
763 stack.push_back(vch);
770 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
771 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
772 if (stack.size() < 2)
774 int n = CastToBigNum(stacktop(-1)).getint32();
776 if (n < 0 || n >= (int)stack.size())
778 valtype vch = stacktop(-n-1);
779 if (opcode == OP_ROLL)
780 stack.erase(stack.end()-n-1);
781 stack.push_back(vch);
787 // (x1 x2 x3 -- x2 x3 x1)
788 // x2 x1 x3 after first swap
789 // x2 x3 x1 after second swap
790 if (stack.size() < 3)
792 swap(stacktop(-3), stacktop(-2));
793 swap(stacktop(-2), stacktop(-1));
800 if (stack.size() < 2)
802 swap(stacktop(-2), stacktop(-1));
808 // (x1 x2 -- x2 x1 x2)
809 if (stack.size() < 2)
811 valtype vch = stacktop(-1);
812 stack.insert(stack.end()-2, vch);
820 if (stack.size() < 1)
822 CBigNum bn((uint16_t) stacktop(-1).size());
823 stack.push_back(bn.getvch());
833 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
836 if (stack.size() < 2)
838 valtype& vch1 = stacktop(-2);
839 valtype& vch2 = stacktop(-1);
840 bool fEqual = (vch1 == vch2);
841 // OP_NOTEQUAL is disabled because it would be too easy to say
842 // something like n != 1 and have some wiseguy pass in 1 with extra
843 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
844 //if (opcode == OP_NOTEQUAL)
848 stack.push_back(fEqual ? vchTrue : vchFalse);
849 if (opcode == OP_EQUALVERIFY)
871 if (stack.size() < 1)
873 CBigNum bn = CastToBigNum(stacktop(-1));
876 case OP_1ADD: bn += bnOne; break;
877 case OP_1SUB: bn -= bnOne; break;
878 case OP_NEGATE: bn = -bn; break;
879 case OP_ABS: if (bn < bnZero) bn = -bn; break;
880 case OP_NOT: bn = (bn == bnZero); break;
881 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
882 default: assert(!"invalid opcode"); break;
885 stack.push_back(bn.getvch());
894 case OP_NUMEQUALVERIFY:
898 case OP_LESSTHANOREQUAL:
899 case OP_GREATERTHANOREQUAL:
904 if (stack.size() < 2)
906 CBigNum bn1 = CastToBigNum(stacktop(-2));
907 CBigNum bn2 = CastToBigNum(stacktop(-1));
919 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
920 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
921 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
922 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
923 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
924 case OP_LESSTHAN: bn = (bn1 < bn2); break;
925 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
926 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
927 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
928 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
929 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
930 default: assert(!"invalid opcode"); break;
934 stack.push_back(bn.getvch());
936 if (opcode == OP_NUMEQUALVERIFY)
938 if (CastToBool(stacktop(-1)))
948 // (x min max -- out)
949 if (stack.size() < 3)
951 CBigNum bn1 = CastToBigNum(stacktop(-3));
952 CBigNum bn2 = CastToBigNum(stacktop(-2));
953 CBigNum bn3 = CastToBigNum(stacktop(-1));
954 bool fValue = (bn2 <= bn1 && bn1 < bn3);
958 stack.push_back(fValue ? vchTrue : vchFalse);
973 if (stack.size() < 1)
975 valtype& vch = stacktop(-1);
976 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
977 if (opcode == OP_RIPEMD160)
978 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
979 else if (opcode == OP_SHA1)
980 SHA1(&vch[0], vch.size(), &vchHash[0]);
981 else if (opcode == OP_SHA256)
982 SHA256(&vch[0], vch.size(), &vchHash[0]);
983 else if (opcode == OP_HASH160)
985 uint160 hash160 = Hash160(vch);
986 memcpy(&vchHash[0], &hash160, sizeof(hash160));
988 else if (opcode == OP_HASH256)
990 uint256 hash = Hash(vch.begin(), vch.end());
991 memcpy(&vchHash[0], &hash, sizeof(hash));
994 stack.push_back(vchHash);
998 case OP_CODESEPARATOR:
1000 // Hash starts after the code separator
1001 pbegincodehash = pc;
1006 case OP_CHECKSIGVERIFY:
1008 // (sig pubkey -- bool)
1009 if (stack.size() < 2)
1012 valtype& vchSig = stacktop(-2);
1013 valtype& vchPubKey = stacktop(-1);
1016 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1017 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1019 // Subset of script starting at the most recent codeseparator
1020 CScript scriptCode(pbegincodehash, pend);
1022 // Drop the signature, since there's no way for a signature to sign itself
1023 scriptCode.FindAndDelete(CScript(vchSig));
1025 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1026 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1030 stack.push_back(fSuccess ? vchTrue : vchFalse);
1031 if (opcode == OP_CHECKSIGVERIFY)
1041 case OP_CHECKMULTISIG:
1042 case OP_CHECKMULTISIGVERIFY:
1044 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1047 if ((int)stack.size() < i)
1050 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1051 if (nKeysCount < 0 || nKeysCount > 20)
1053 nOpCount += nKeysCount;
1058 if ((int)stack.size() < i)
1061 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1062 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1066 if ((int)stack.size() < i)
1069 // Subset of script starting at the most recent codeseparator
1070 CScript scriptCode(pbegincodehash, pend);
1072 // Drop the signatures, since there's no way for a signature to sign itself
1073 for (int k = 0; k < nSigsCount; k++)
1075 valtype& vchSig = stacktop(-isig-k);
1076 scriptCode.FindAndDelete(CScript(vchSig));
1079 bool fSuccess = true;
1080 while (fSuccess && nSigsCount > 0)
1082 valtype& vchSig = stacktop(-isig);
1083 valtype& vchPubKey = stacktop(-ikey);
1086 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1087 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1096 // If there are more signatures left than keys left,
1097 // then too many signatures have failed
1098 if (nSigsCount > nKeysCount)
1105 // A bug causes CHECKMULTISIG to consume one extra argument
1106 // whose contents were not checked in any way.
1108 // Unfortunately this is a potential source of mutability,
1109 // so optionally verify it is exactly equal to zero prior
1110 // to removing it from the stack.
1111 if (stack.size() < 1)
1113 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1114 return error("CHECKMULTISIG dummy argument not null");
1117 stack.push_back(fSuccess ? vchTrue : vchFalse);
1119 if (opcode == OP_CHECKMULTISIGVERIFY)
1134 if (stack.size() + altstack.size() > 1000)
1144 if (!vfExec.empty())
1158 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1160 if (nIn >= txTo.vin.size())
1162 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1165 CTransaction txTmp(txTo);
1167 // In case concatenating two scripts ends up with two codeseparators,
1168 // or an extra one at the end, this prevents all those possible incompatibilities.
1169 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1171 // Blank out other inputs' signatures
1172 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1173 txTmp.vin[i].scriptSig = CScript();
1174 txTmp.vin[nIn].scriptSig = scriptCode;
1176 // Blank out some of the outputs
1177 if ((nHashType & 0x1f) == SIGHASH_NONE)
1182 // Let the others update at will
1183 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1185 txTmp.vin[i].nSequence = 0;
1187 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1189 // Only lock-in the txout payee at same index as txin
1190 unsigned int nOut = nIn;
1191 if (nOut >= txTmp.vout.size())
1193 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1196 txTmp.vout.resize(nOut+1);
1197 for (unsigned int i = 0; i < nOut; i++)
1198 txTmp.vout[i].SetNull();
1200 // Let the others update at will
1201 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1203 txTmp.vin[i].nSequence = 0;
1206 // Blank out other inputs completely, not recommended for open transactions
1207 if (nHashType & SIGHASH_ANYONECANPAY)
1209 txTmp.vin[0] = txTmp.vin[nIn];
1210 txTmp.vin.resize(1);
1213 // Serialize and hash
1214 CDataStream ss(SER_GETHASH, 0);
1216 ss << txTmp << nHashType;
1217 return Hash(ss.begin(), ss.end());
1221 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1222 // twice for every transaction (once when accepted into memory pool, and
1223 // again when accepted into the block chain)
1225 class CSignatureCache
1228 // sigdata_type is (signature hash, signature, public key):
1229 typedef std::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1230 std::set< sigdata_type> setValid;
1231 boost::shared_mutex cs_sigcache;
1235 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1237 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1239 sigdata_type k(hash, vchSig, pubKey);
1240 std::set<sigdata_type>::iterator mi = setValid.find(k);
1241 if (mi != setValid.end())
1246 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1248 // DoS prevention: limit cache size to less than 10MB
1249 // (~200 bytes per cache entry times 50,000 entries)
1250 // Since there are a maximum of 20,000 signature operations per block
1251 // 50,000 is a reasonable default.
1252 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1253 if (nMaxCacheSize <= 0) return;
1255 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1257 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1259 // Evict a random entry. Random because that helps
1260 // foil would-be DoS attackers who might try to pre-generate
1261 // and re-use a set of valid signatures just-slightly-greater
1262 // than our cache size.
1263 uint256 randomHash = GetRandHash();
1264 std::vector<unsigned char> unused;
1265 std::set<sigdata_type>::iterator it =
1266 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1267 if (it == setValid.end())
1268 it = setValid.begin();
1269 setValid.erase(*it);
1272 sigdata_type k(hash, vchSig, pubKey);
1277 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1278 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1280 static CSignatureCache signatureCache;
1282 CPubKey pubkey(vchPubKey);
1283 if (!pubkey.IsValid())
1286 // Hash type is one byte tacked on to the end of the signature
1290 nHashType = vchSig.back();
1291 else if (nHashType != vchSig.back())
1295 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1297 if (signatureCache.Get(sighash, vchSig, pubkey))
1300 if (!pubkey.Verify(sighash, vchSig))
1303 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1304 signatureCache.Set(sighash, vchSig, pubkey);
1311 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1313 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<std::vector<unsigned char> >& vSolutionsRet)
1316 static std::map<txnouttype, CScript> mTemplates;
1317 if (mTemplates.empty())
1319 // Standard tx, sender provides pubkey, receiver adds signature
1320 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1322 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1323 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1325 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1326 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1328 // Sender provides N pubkeys, receivers provides M signatures
1329 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1331 // Empty, provably prunable, data-carrying output
1332 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1335 vSolutionsRet.clear();
1337 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1338 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1339 if (scriptPubKey.IsPayToScriptHash())
1341 typeRet = TX_SCRIPTHASH;
1342 std::vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1343 vSolutionsRet.push_back(hashBytes);
1347 // Provably prunable, data-carrying output
1349 // So long as script passes the IsUnspendable() test and all but the first
1350 // byte passes the IsPushOnly() test we don't care what exactly is in the
1352 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1353 typeRet = TX_NULL_DATA;
1358 const CScript& script1 = scriptPubKey;
1359 for (const auto& tplate : mTemplates)
1361 const CScript& script2 = tplate.second;
1362 vSolutionsRet.clear();
1364 opcodetype opcode1, opcode2;
1365 std::vector<unsigned char> vch1, vch2;
1368 CScript::const_iterator pc1 = script1.begin();
1369 CScript::const_iterator pc2 = script2.begin();
1372 if (pc1 == script1.end() && pc2 == script2.end())
1375 typeRet = tplate.first;
1376 if (typeRet == TX_MULTISIG)
1378 // Additional checks for TX_MULTISIG:
1379 unsigned char m = vSolutionsRet.front()[0];
1380 unsigned char n = vSolutionsRet.back()[0];
1381 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1386 if (!script1.GetOp(pc1, opcode1, vch1))
1388 if (!script2.GetOp(pc2, opcode2, vch2))
1391 // Template matching opcodes:
1392 if (opcode2 == OP_PUBKEYS)
1394 while (vch1.size() >= 33 && vch1.size() <= 120)
1396 vSolutionsRet.push_back(vch1);
1397 if (!script1.GetOp(pc1, opcode1, vch1))
1400 if (!script2.GetOp(pc2, opcode2, vch2))
1402 // Normal situation is to fall through
1403 // to other if/else statements
1406 if (opcode2 == OP_PUBKEY)
1408 if (vch1.size() < 33 || vch1.size() > 120)
1410 vSolutionsRet.push_back(vch1);
1412 else if (opcode2 == OP_PUBKEYHASH)
1414 if (vch1.size() != sizeof(uint160))
1416 vSolutionsRet.push_back(vch1);
1418 else if (opcode2 == OP_SMALLINTEGER)
1419 { // Single-byte small integer pushed onto vSolutions
1420 if (opcode1 == OP_0 ||
1421 (opcode1 >= OP_1 && opcode1 <= OP_16))
1423 char n = (char)CScript::DecodeOP_N(opcode1);
1424 vSolutionsRet.push_back(valtype(1, n));
1429 else if (opcode2 == OP_INTEGER)
1430 { // Up to four-byte integer pushed onto vSolutions
1433 CBigNum bnVal = CastToBigNum(vch1);
1435 break; // It's better to use OP_0 ... OP_16 for small integers.
1436 vSolutionsRet.push_back(vch1);
1443 else if (opcode2 == OP_SMALLDATA)
1445 // small pushdata, <= 1024 bytes
1446 if (vch1.size() > 1024)
1449 else if (opcode1 != opcode2 || vch1 != vch2)
1451 // Others must match exactly
1457 vSolutionsRet.clear();
1458 typeRet = TX_NONSTANDARD;
1463 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1466 if (!keystore.GetKey(address, key))
1469 std::vector<unsigned char> vchSig;
1470 if (!key.Sign(hash, vchSig))
1472 vchSig.push_back((unsigned char)nHashType);
1473 scriptSigRet << vchSig;
1478 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1481 if (!keystore.CreatePrivKey(pubKey, R, key))
1484 std::vector<unsigned char> vchSig;
1485 if (!key.Sign(hash, vchSig))
1487 vchSig.push_back((unsigned char)nHashType);
1488 scriptSigRet << vchSig;
1493 bool SignN(const std::vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1496 int nRequired = multisigdata.front()[0];
1497 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1499 const valtype& pubkey = multisigdata[i];
1500 CKeyID keyID = CPubKey(pubkey).GetID();
1501 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1504 return nSigned==nRequired;
1508 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1509 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1510 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1511 // Returns false if scriptPubKey could not be completely satisfied.
1513 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1514 CScript& scriptSigRet, txnouttype& whichTypeRet)
1516 scriptSigRet.clear();
1518 std::vector<valtype> vSolutions;
1519 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1523 switch (whichTypeRet)
1525 case TX_NONSTANDARD:
1529 keyID = CPubKey(vSolutions[0]).GetID();
1530 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1531 case TX_PUBKEY_DROP:
1533 CPubKey key = CPubKey(vSolutions[0]);
1534 CPubKey R = CPubKey(vSolutions[1]);
1535 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1538 keyID = CKeyID(uint160(vSolutions[0]));
1539 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1544 keystore.GetPubKey(keyID, vch);
1545 scriptSigRet << vch;
1549 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1552 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1553 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1558 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1562 case TX_NONSTANDARD:
1567 case TX_PUBKEY_DROP:
1572 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1574 return vSolutions[0][0] + 1;
1576 return 1; // doesn't include args needed by the script
1581 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1583 std::vector<valtype> vSolutions;
1584 if (!Solver(scriptPubKey, whichType, vSolutions))
1587 if (whichType == TX_MULTISIG)
1589 unsigned char m = vSolutions.front()[0];
1590 unsigned char n = vSolutions.back()[0];
1591 // Support up to x-of-3 multisig txns as standard
1598 return whichType != TX_NONSTANDARD;
1602 unsigned int HaveKeys(const std::vector<valtype>& pubkeys, const CKeyStore& keystore)
1604 unsigned int nResult = 0;
1605 for (const valtype& pubkey : pubkeys)
1607 CKeyID keyID = CPubKey(pubkey).GetID();
1608 if (keystore.HaveKey(keyID))
1615 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1618 const CKeyStore *keystore;
1620 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1621 bool operator()(const CNoDestination &dest) const { return false; }
1622 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1623 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1627 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1630 script.SetDestination(dest);
1631 return IsMine(keystore, script);
1634 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1637 script.SetAddress(dest);
1638 return IsMine(keystore, script);
1641 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1643 std::vector<valtype> vSolutions;
1644 txnouttype whichType;
1645 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1646 if (keystore.HaveWatchOnly(scriptPubKey))
1647 return MINE_WATCH_ONLY;
1654 case TX_NONSTANDARD:
1658 keyID = CPubKey(vSolutions[0]).GetID();
1659 if (keystore.HaveKey(keyID))
1660 return MINE_SPENDABLE;
1662 case TX_PUBKEY_DROP:
1664 CPubKey key = CPubKey(vSolutions[0]);
1665 CPubKey R = CPubKey(vSolutions[1]);
1666 if (keystore.CheckOwnership(key, R))
1667 return MINE_SPENDABLE;
1671 keyID = CKeyID(uint160(vSolutions[0]));
1672 if (keystore.HaveKey(keyID))
1673 return MINE_SPENDABLE;
1677 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1679 if (keystore.GetCScript(scriptID, subscript)) {
1680 isminetype ret = IsMine(keystore, subscript);
1681 if (ret == MINE_SPENDABLE)
1688 // Only consider transactions "mine" if we own ALL the
1689 // keys involved. multi-signature transactions that are
1690 // partially owned (somebody else has a key that can spend
1691 // them) enable spend-out-from-under-you attacks, especially
1692 // in shared-wallet situations.
1693 std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1694 if (HaveKeys(keys, keystore) == keys.size())
1695 return MINE_SPENDABLE;
1700 if (keystore.HaveWatchOnly(scriptPubKey))
1701 return MINE_WATCH_ONLY;
1705 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1707 std::vector<valtype> vSolutions;
1708 txnouttype whichType;
1709 if (!Solver(scriptPubKey, whichType, vSolutions))
1712 if (whichType == TX_PUBKEY)
1714 addressRet = CPubKey(vSolutions[0]).GetID();
1717 else if (whichType == TX_PUBKEYHASH)
1719 addressRet = CKeyID(uint160(vSolutions[0]));
1722 else if (whichType == TX_SCRIPTHASH)
1724 addressRet = CScriptID(uint160(vSolutions[0]));
1727 // Multisig txns have more than one address...
1731 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1733 std::vector<valtype> vSolutions;
1734 txnouttype whichType;
1735 if (!Solver(scriptPubKey, whichType, vSolutions))
1738 if (whichType == TX_PUBKEY)
1740 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1743 if (whichType == TX_PUBKEY_DROP)
1746 CMalleableKeyView view;
1747 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1750 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1753 else if (whichType == TX_PUBKEYHASH)
1755 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1758 else if (whichType == TX_SCRIPTHASH)
1760 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1763 // Multisig txns have more than one address...
1767 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1769 const CKeyStore &keystore;
1770 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1771 std::vector<CKeyID> &vKeys;
1774 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1776 void Process(const CScript &script) {
1778 std::vector<CTxDestination> vDest;
1780 if (ExtractDestinations(script, type, vDest, nRequired)) {
1781 for (const CTxDestination &dest : vDest)
1782 boost::apply_visitor(*this, dest);
1786 void operator()(const CKeyID &keyId) {
1787 if (keystore.HaveKey(keyId))
1788 vKeys.push_back(keyId);
1791 void operator()(const CScriptID &scriptId) {
1793 if (keystore.GetCScript(scriptId, script))
1797 void operator()(const CNoDestination &none) {}
1801 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1802 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1805 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
1808 typeRet = TX_NONSTANDARD;
1809 std::vector<valtype> vSolutions;
1810 if (!Solver(scriptPubKey, typeRet, vSolutions))
1812 if (typeRet == TX_NULL_DATA)
1818 if (typeRet == TX_MULTISIG)
1820 nRequiredRet = vSolutions.front()[0];
1821 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1823 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1824 addressRet.push_back(address);
1830 if (typeRet == TX_PUBKEY_DROP)
1832 CTxDestination address;
1833 if (!ExtractDestination(scriptPubKey, address))
1835 addressRet.push_back(address);
1841 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1842 unsigned int flags, int nHashType)
1844 std::vector<std::vector<unsigned char> > stack, stackCopy;
1845 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1847 if (flags & SCRIPT_VERIFY_P2SH)
1849 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1854 if (CastToBool(stack.back()) == false)
1857 // Additional validation for spend-to-script-hash transactions:
1858 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1860 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1861 return false; // or validation fails
1863 // stackCopy cannot be empty here, because if it was the
1864 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1865 // an empty stack and the EvalScript above would return false.
1866 assert(!stackCopy.empty());
1868 const valtype& pubKeySerialized = stackCopy.back();
1869 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1870 popstack(stackCopy);
1872 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1874 if (stackCopy.empty())
1876 return CastToBool(stackCopy.back());
1882 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1884 assert(nIn < txTo.vin.size());
1885 CTxIn& txin = txTo.vin[nIn];
1887 // Leave out the signature from the hash, since a signature can't sign itself.
1888 // The checksig op will also drop the signatures from its hash.
1889 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1891 txnouttype whichType;
1892 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1895 if (whichType == TX_SCRIPTHASH)
1897 // Solver returns the subscript that need to be evaluated;
1898 // the final scriptSig is the signatures from that
1899 // and then the serialized subscript:
1900 CScript subscript = txin.scriptSig;
1902 // Recompute txn hash using subscript in place of scriptPubKey:
1903 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1907 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1908 // Append serialized subscript whether or not it is completely signed:
1909 txin.scriptSig << static_cast<valtype>(subscript);
1910 if (!fSolved) return false;
1914 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1917 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1919 assert(nIn < txTo.vin.size());
1920 CTxIn& txin = txTo.vin[nIn];
1921 assert(txin.prevout.n < txFrom.vout.size());
1922 assert(txin.prevout.hash == txFrom.GetHash());
1923 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1925 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1928 static CScript PushAll(const std::vector<valtype>& values)
1931 for (const valtype& v : values)
1936 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1937 const std::vector<valtype>& vSolutions,
1938 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1940 // Combine all the signatures we've got:
1941 std::set<valtype> allsigs;
1942 for (const valtype& v : sigs1)
1947 for (const valtype& v : sigs2)
1953 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1954 assert(vSolutions.size() > 1);
1955 unsigned int nSigsRequired = vSolutions.front()[0];
1956 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1957 std::map<valtype, valtype> sigs;
1958 for (const valtype& sig : allsigs)
1960 for (unsigned int i = 0; i < nPubKeys; i++)
1962 const valtype& pubkey = vSolutions[i+1];
1963 if (sigs.count(pubkey))
1964 continue; // Already got a sig for this pubkey
1966 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1973 // Now build a merged CScript:
1974 unsigned int nSigsHave = 0;
1975 CScript result; result << OP_0; // pop-one-too-many workaround
1976 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1978 if (sigs.count(vSolutions[i+1]))
1980 result << sigs[vSolutions[i+1]];
1984 // Fill any missing with OP_0:
1985 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1991 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1992 const txnouttype txType, const std::vector<valtype>& vSolutions,
1993 std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1997 case TX_NONSTANDARD:
1999 // Don't know anything about this, assume bigger one is correct:
2000 if (sigs1.size() >= sigs2.size())
2001 return PushAll(sigs1);
2002 return PushAll(sigs2);
2004 case TX_PUBKEY_DROP:
2006 // Signatures are bigger than placeholders or empty scripts:
2007 if (sigs1.empty() || sigs1[0].empty())
2008 return PushAll(sigs2);
2009 return PushAll(sigs1);
2011 if (sigs1.empty() || sigs1.back().empty())
2012 return PushAll(sigs2);
2013 else if (sigs2.empty() || sigs2.back().empty())
2014 return PushAll(sigs1);
2017 // Recur to combine:
2018 valtype spk = sigs1.back();
2019 CScript pubKey2(spk.begin(), spk.end());
2022 std::vector<std::vector<unsigned char> > vSolutions2;
2023 Solver(pubKey2, txType2, vSolutions2);
2026 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2031 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2037 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2038 const CScript& scriptSig1, const CScript& scriptSig2)
2041 std::vector<std::vector<unsigned char> > vSolutions;
2042 Solver(scriptPubKey, txType, vSolutions);
2044 std::vector<valtype> stack1;
2045 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2046 std::vector<valtype> stack2;
2047 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2049 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2052 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2055 const_iterator pc = begin();
2056 opcodetype lastOpcode = OP_INVALIDOPCODE;
2060 if (!GetOp(pc, opcode))
2062 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2064 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2066 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2067 n += DecodeOP_N(lastOpcode);
2071 lastOpcode = opcode;
2076 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2078 if (!IsPayToScriptHash())
2079 return GetSigOpCount(true);
2081 // This is a pay-to-script-hash scriptPubKey;
2082 // get the last item that the scriptSig
2083 // pushes onto the stack:
2084 const_iterator pc = scriptSig.begin();
2085 vector<unsigned char> data;
2086 while (pc < scriptSig.end())
2089 if (!scriptSig.GetOp(pc, opcode, data))
2095 /// ... and return its opcount:
2096 CScript subscript(data.begin(), data.end());
2097 return subscript.GetSigOpCount(true);
2100 bool CScript::IsPayToScriptHash() const
2102 // Extra-fast test for pay-to-script-hash CScripts:
2103 return (this->size() == 23 &&
2104 this->at(0) == OP_HASH160 &&
2105 this->at(1) == 0x14 &&
2106 this->at(22) == OP_EQUAL);
2109 bool CScript::HasCanonicalPushes() const
2111 const_iterator pc = begin();
2115 std::vector<unsigned char> data;
2116 if (!GetOp(pc, opcode, data))
2120 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2121 // Could have used an OP_n code, rather than a 1-byte push.
2123 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2124 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2126 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2127 // Could have used an OP_PUSHDATA1.
2129 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2130 // Could have used an OP_PUSHDATA2.
2136 class CScriptVisitor : public boost::static_visitor<bool>
2141 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2143 bool operator()(const CNoDestination &dest) const {
2148 bool operator()(const CKeyID &keyID) const {
2150 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2154 bool operator()(const CScriptID &scriptID) const {
2156 *script << OP_HASH160 << scriptID << OP_EQUAL;
2161 void CScript::SetDestination(const CTxDestination& dest)
2163 boost::apply_visitor(CScriptVisitor(this), dest);
2166 void CScript::SetAddress(const CBitcoinAddress& dest)
2169 if (dest.IsScript())
2170 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2171 else if (dest.IsPubKey())
2172 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2173 else if (dest.IsPair()) {
2174 // Pubkey pair address, going to generate
2175 // new one-time public key.
2176 CMalleablePubKey mpk;
2177 if (!mpk.setvch(dest.GetData()))
2179 CPubKey R, pubKeyVariant;
2180 mpk.GetVariant(R, pubKeyVariant);
2181 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2185 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2189 *this << EncodeOP_N(nRequired);
2190 for (const CPubKey& key : keys)
2192 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;