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.
5 #include <boost/foreach.hpp>
6 #include <boost/tuple/tuple.hpp>
19 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
21 static const valtype vchFalse(0);
22 static const valtype vchZero(0);
23 static const valtype vchTrue(1, 1);
24 static const CBigNum bnZero(0);
25 static const CBigNum bnOne(1);
26 static const CBigNum bnFalse(0);
27 static const CBigNum bnTrue(1);
28 static const size_t nMaxNumSize = 4;
31 CBigNum CastToBigNum(const valtype& vch)
33 if (vch.size() > nMaxNumSize)
34 throw runtime_error("CastToBigNum() : overflow");
35 // Get rid of extra leading zeros
36 return CBigNum(CBigNum(vch).getvch());
39 bool CastToBool(const valtype& vch)
41 for (unsigned int i = 0; i < vch.size(); i++)
45 // Can be negative zero
46 if (i == vch.size()-1 && vch[i] == 0x80)
55 // WARNING: This does not work as expected for signed integers; the sign-bit
56 // is left in place as the integer is zero-extended. The correct behavior
57 // would be to move the most significant bit of the last byte during the
58 // resize process. MakeSameSize() is currently only used by the disabled
59 // opcodes OP_AND, OP_OR, and OP_XOR.
61 void MakeSameSize(valtype& vch1, valtype& vch2)
63 // Lengthen the shorter one
64 if (vch1.size() < vch2.size())
66 // +unsigned char msb = vch1[vch1.size()-1];
67 // +vch1[vch1.size()-1] &= 0x7f;
68 // vch1.resize(vch2.size(), 0);
69 // +vch1[vch1.size()-1] = msb;
70 vch1.resize(vch2.size(), 0);
71 if (vch2.size() < vch1.size())
73 // +unsigned char msb = vch2[vch2.size()-1];
74 // +vch2[vch2.size()-1] &= 0x7f;
75 // vch2.resize(vch1.size(), 0);
76 // +vch2[vch2.size()-1] = msb;
77 vch2.resize(vch1.size(), 0);
83 // Script is a stack machine (like Forth) that evaluates a predicate
84 // returning a bool indicating valid or not. There are no loops.
86 #define stacktop(i) (stack.at(stack.size()+(i)))
87 #define altstacktop(i) (altstack.at(altstack.size()+(i)))
88 static inline void popstack(vector<valtype>& stack)
91 throw runtime_error("popstack() : stack empty");
96 const char* GetTxnOutputType(txnouttype t)
100 case TX_NONSTANDARD: return "nonstandard";
101 case TX_PUBKEY: return "pubkey";
102 case TX_PUBKEY_DROP: return "pubkeydrop";
103 case TX_PUBKEYHASH: return "pubkeyhash";
104 case TX_SCRIPTHASH: return "scripthash";
105 case TX_MULTISIG: return "multisig";
106 case TX_NULL_DATA: return "nulldata";
112 const char* GetOpName(opcodetype opcode)
117 case OP_0 : return "0";
118 case OP_PUSHDATA1 : return "OP_PUSHDATA1";
119 case OP_PUSHDATA2 : return "OP_PUSHDATA2";
120 case OP_PUSHDATA4 : return "OP_PUSHDATA4";
121 case OP_1NEGATE : return "-1";
122 case OP_RESERVED : return "OP_RESERVED";
123 case OP_1 : return "1";
124 case OP_2 : return "2";
125 case OP_3 : return "3";
126 case OP_4 : return "4";
127 case OP_5 : return "5";
128 case OP_6 : return "6";
129 case OP_7 : return "7";
130 case OP_8 : return "8";
131 case OP_9 : return "9";
132 case OP_10 : return "10";
133 case OP_11 : return "11";
134 case OP_12 : return "12";
135 case OP_13 : return "13";
136 case OP_14 : return "14";
137 case OP_15 : return "15";
138 case OP_16 : return "16";
141 case OP_NOP : return "OP_NOP";
142 case OP_VER : return "OP_VER";
143 case OP_IF : return "OP_IF";
144 case OP_NOTIF : return "OP_NOTIF";
145 case OP_VERIF : return "OP_VERIF";
146 case OP_VERNOTIF : return "OP_VERNOTIF";
147 case OP_ELSE : return "OP_ELSE";
148 case OP_ENDIF : return "OP_ENDIF";
149 case OP_VERIFY : return "OP_VERIFY";
150 case OP_RETURN : return "OP_RETURN";
151 case OP_CHECKLOCKTIMEVERIFY : return "OP_CHECKLOCKTIMEVERIFY";
152 case OP_CHECKSEQUENCEVERIFY : return "OP_CHECKSEQUENCEVERIFY";
155 case OP_TOALTSTACK : return "OP_TOALTSTACK";
156 case OP_FROMALTSTACK : return "OP_FROMALTSTACK";
157 case OP_2DROP : return "OP_2DROP";
158 case OP_2DUP : return "OP_2DUP";
159 case OP_3DUP : return "OP_3DUP";
160 case OP_2OVER : return "OP_2OVER";
161 case OP_2ROT : return "OP_2ROT";
162 case OP_2SWAP : return "OP_2SWAP";
163 case OP_IFDUP : return "OP_IFDUP";
164 case OP_DEPTH : return "OP_DEPTH";
165 case OP_DROP : return "OP_DROP";
166 case OP_DUP : return "OP_DUP";
167 case OP_NIP : return "OP_NIP";
168 case OP_OVER : return "OP_OVER";
169 case OP_PICK : return "OP_PICK";
170 case OP_ROLL : return "OP_ROLL";
171 case OP_ROT : return "OP_ROT";
172 case OP_SWAP : return "OP_SWAP";
173 case OP_TUCK : return "OP_TUCK";
176 case OP_CAT : return "OP_CAT";
177 case OP_SUBSTR : return "OP_SUBSTR";
178 case OP_LEFT : return "OP_LEFT";
179 case OP_RIGHT : return "OP_RIGHT";
180 case OP_SIZE : return "OP_SIZE";
183 case OP_INVERT : return "OP_INVERT";
184 case OP_AND : return "OP_AND";
185 case OP_OR : return "OP_OR";
186 case OP_XOR : return "OP_XOR";
187 case OP_EQUAL : return "OP_EQUAL";
188 case OP_EQUALVERIFY : return "OP_EQUALVERIFY";
189 case OP_RESERVED1 : return "OP_RESERVED1";
190 case OP_RESERVED2 : return "OP_RESERVED2";
193 case OP_1ADD : return "OP_1ADD";
194 case OP_1SUB : return "OP_1SUB";
195 case OP_2MUL : return "OP_2MUL";
196 case OP_2DIV : return "OP_2DIV";
197 case OP_NEGATE : return "OP_NEGATE";
198 case OP_ABS : return "OP_ABS";
199 case OP_NOT : return "OP_NOT";
200 case OP_0NOTEQUAL : return "OP_0NOTEQUAL";
201 case OP_ADD : return "OP_ADD";
202 case OP_SUB : return "OP_SUB";
203 case OP_MUL : return "OP_MUL";
204 case OP_DIV : return "OP_DIV";
205 case OP_MOD : return "OP_MOD";
206 case OP_LSHIFT : return "OP_LSHIFT";
207 case OP_RSHIFT : return "OP_RSHIFT";
208 case OP_BOOLAND : return "OP_BOOLAND";
209 case OP_BOOLOR : return "OP_BOOLOR";
210 case OP_NUMEQUAL : return "OP_NUMEQUAL";
211 case OP_NUMEQUALVERIFY : return "OP_NUMEQUALVERIFY";
212 case OP_NUMNOTEQUAL : return "OP_NUMNOTEQUAL";
213 case OP_LESSTHAN : return "OP_LESSTHAN";
214 case OP_GREATERTHAN : return "OP_GREATERTHAN";
215 case OP_LESSTHANOREQUAL : return "OP_LESSTHANOREQUAL";
216 case OP_GREATERTHANOREQUAL : return "OP_GREATERTHANOREQUAL";
217 case OP_MIN : return "OP_MIN";
218 case OP_MAX : return "OP_MAX";
219 case OP_WITHIN : return "OP_WITHIN";
222 case OP_RIPEMD160 : return "OP_RIPEMD160";
223 case OP_SHA1 : return "OP_SHA1";
224 case OP_SHA256 : return "OP_SHA256";
225 case OP_HASH160 : return "OP_HASH160";
226 case OP_HASH256 : return "OP_HASH256";
227 case OP_CODESEPARATOR : return "OP_CODESEPARATOR";
228 case OP_CHECKSIG : return "OP_CHECKSIG";
229 case OP_CHECKSIGVERIFY : return "OP_CHECKSIGVERIFY";
230 case OP_CHECKMULTISIG : return "OP_CHECKMULTISIG";
231 case OP_CHECKMULTISIGVERIFY : return "OP_CHECKMULTISIGVERIFY";
234 case OP_NOP1 : return "OP_NOP1";
235 case OP_NOP4 : return "OP_NOP4";
236 case OP_NOP5 : return "OP_NOP5";
237 case OP_NOP6 : return "OP_NOP6";
238 case OP_NOP7 : return "OP_NOP7";
239 case OP_NOP8 : return "OP_NOP8";
240 case OP_NOP9 : return "OP_NOP9";
241 case OP_NOP10 : return "OP_NOP10";
245 // template matching params
246 case OP_PUBKEYHASH : return "OP_PUBKEYHASH";
247 case OP_PUBKEY : return "OP_PUBKEY";
248 case OP_SMALLDATA : return "OP_SMALLDATA";
250 case OP_INVALIDOPCODE : return "OP_INVALIDOPCODE";
256 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
257 if (!(flags & SCRIPT_VERIFY_STRICTENC))
260 if (vchPubKey.size() < 33)
261 return error("Non-canonical public key: too short");
262 if (vchPubKey[0] == 0x04) {
263 if (vchPubKey.size() != 65)
264 return error("Non-canonical public key: invalid length for uncompressed key");
265 } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
266 if (vchPubKey.size() != 33)
267 return error("Non-canonical public key: invalid length for compressed key");
269 return error("Non-canonical public key: compressed nor uncompressed");
274 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
275 // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
276 // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
277 // Where R and S are not negative (their first byte has its highest bit not set), and not
278 // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
279 // in which case a single 0 byte is necessary and even required).
280 if (vchSig.size() < 9)
281 return error("Non-canonical signature: too short");
282 if (vchSig.size() > 73)
283 return error("Non-canonical signature: too long");
284 if (vchSig[0] != 0x30)
285 return error("Non-canonical signature: wrong type");
286 if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
287 return error("Non-canonical signature: wrong length marker");
289 unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
290 if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
291 return error("Non-canonical signature: unknown hashtype byte");
293 unsigned int nLenR = vchSig[3];
294 if (5 + nLenR >= vchSig.size())
295 return error("Non-canonical signature: S length misplaced");
296 unsigned int nLenS = vchSig[5+nLenR];
297 if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
298 return error("Non-canonical signature: R+S length mismatch");
300 const unsigned char *R = &vchSig[4];
302 return error("Non-canonical signature: R value type mismatch");
304 return error("Non-canonical signature: R length is zero");
306 return error("Non-canonical signature: R value negative");
307 if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
308 return error("Non-canonical signature: R value excessively padded");
310 const unsigned char *S = &vchSig[6+nLenR];
312 return error("Non-canonical signature: S value type mismatch");
314 return error("Non-canonical signature: S length is zero");
316 return error("Non-canonical signature: S value negative");
317 if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
318 return error("Non-canonical signature: S value excessively padded");
321 unsigned int nLenR = vchSig[3];
322 unsigned int nLenS = vchSig[5+nLenR];
323 const unsigned char *S = &vchSig[6+nLenR];
324 // If the S value is above the order of the curve divided by two, its
325 // complement modulo the order could have been used instead, which is
326 // one byte shorter when encoded correctly.
327 if (!CKey::CheckSignatureElement(S, nLenS, true))
328 return error("Non-canonical signature: S value is unnecessarily high");
334 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
335 if (!(flags & SCRIPT_VERIFY_STRICTENC))
338 return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
341 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
343 // There are two kinds of nLockTime: lock-by-blockheight
344 // and lock-by-blocktime, distinguished by whether
345 // nLockTime < LOCKTIME_THRESHOLD.
347 // We want to compare apples to apples, so fail the script
348 // unless the type of nLockTime being tested is the same as
349 // the nLockTime in the transaction.
351 (txTo.nLockTime < LOCKTIME_THRESHOLD && nLockTime < LOCKTIME_THRESHOLD) ||
352 (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
356 // Now that we know we're comparing apples-to-apples, the
357 // comparison is a simple numeric one.
358 if (nLockTime > (int64_t)txTo.nLockTime)
361 // Finally the nLockTime feature can be disabled and thus
362 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
363 // finalized by setting nSequence to maxint. The
364 // transaction would be allowed into the blockchain, making
365 // the opcode ineffective.
367 // Testing if this vin is not final is sufficient to
368 // prevent this condition. Alternatively we could test all
369 // inputs, but testing just this input minimizes the data
370 // required to prove correct CHECKLOCKTIMEVERIFY execution.
371 if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
377 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
379 // Relative lock times are supported by comparing the passed
380 // in operand to the sequence number of the input.
381 const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
383 // Sequence numbers with their most significant bit set are not
384 // consensus constrained. Testing that the transaction's sequence
385 // number do not have this bit set prevents using this property
386 // to get around a CHECKSEQUENCEVERIFY check.
387 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
390 // Mask off any bits that do not have consensus-enforced meaning
391 // before doing the integer comparisons
392 const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
393 const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
394 const int64_t nSequenceMasked = nSequence & nLockTimeMask;
396 // There are two kinds of nSequence: lock-by-blockheight
397 // and lock-by-blocktime, distinguished by whether
398 // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
400 // We want to compare apples to apples, so fail the script
401 // unless the type of nSequenceMasked being tested is the same as
402 // the nSequenceMasked in the transaction.
404 (txToSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked < SEQUENCE_LOCKTIME_TYPE_FLAG) ||
405 (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
410 // Now that we know we're comparing apples-to-apples, the
411 // comparison is a simple numeric one.
412 if (nSequenceMasked > txToSequenceMasked)
418 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
421 CScript::const_iterator pc = script.begin();
422 CScript::const_iterator pend = script.end();
423 CScript::const_iterator pbegincodehash = script.begin();
425 valtype vchPushValue;
427 vector<valtype> altstack;
428 if (script.size() > 10000)
436 bool fExec = !count(vfExec.begin(), vfExec.end(), false);
441 if (!script.GetOp(pc, opcode, vchPushValue))
443 if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
445 if (opcode > OP_16 && ++nOpCount > 201)
448 if (opcode == OP_CAT ||
449 opcode == OP_SUBSTR ||
451 opcode == OP_RIGHT ||
452 opcode == OP_INVERT ||
461 opcode == OP_LSHIFT ||
463 return false; // Disabled opcodes.
465 if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
466 stack.push_back(vchPushValue);
467 else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
492 CBigNum bn((int)opcode - (int)(OP_1 - 1));
493 stack.push_back(bn.getvch());
502 case OP_NOP1: case OP_NOP4: case OP_NOP5:
503 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
509 // <expression> if [statements] [else [statements]] endif
513 if (stack.size() < 1)
515 valtype& vch = stacktop(-1);
516 fValue = CastToBool(vch);
517 if (opcode == OP_NOTIF)
521 vfExec.push_back(fValue);
529 vfExec.back() = !vfExec.back();
544 // (false -- false) and return
545 if (stack.size() < 1)
547 bool fValue = CastToBool(stacktop(-1));
561 case OP_CHECKLOCKTIMEVERIFY:
563 // CHECKLOCKTIMEVERIFY
565 // (nLockTime -- nLockTime)
566 if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
567 // treat as a NOP2 if not enabled
571 if (stack.size() < 1)
574 CBigNum nLockTime = CastToBigNum(stacktop(-1));
576 // In the rare event that the argument may be < 0 due to
577 // some arithmetic being done first, you can always use
578 // 0 MAX CHECKLOCKTIMEVERIFY.
582 // Actually compare the specified lock time with the transaction.
583 if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
589 case OP_CHECKSEQUENCEVERIFY:
591 if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
592 // treat as a NOP3 not enabled
596 if (stack.size() < 1)
599 // nSequence, like nLockTime, is a 32-bit unsigned integer
600 // field. See the comment in CHECKLOCKTIMEVERIFY regarding
601 // 5-byte numeric operands.
602 CBigNum nSequence = CastToBigNum(stacktop(-1));
604 // In the rare event that the argument may be < 0 due to
605 // some arithmetic being done first, you can always use
606 // 0 MAX CHECKSEQUENCEVERIFY.
610 // To provide for future soft-fork extensibility, if the
611 // operand has the disabled lock-time flag set,
612 // CHECKSEQUENCEVERIFY behaves as a NOP.
613 if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
616 // Compare the specified sequence number with the input.
617 if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
628 if (stack.size() < 1)
630 altstack.push_back(stacktop(-1));
635 case OP_FROMALTSTACK:
637 if (altstack.size() < 1)
639 stack.push_back(altstacktop(-1));
647 if (stack.size() < 2)
656 // (x1 x2 -- x1 x2 x1 x2)
657 if (stack.size() < 2)
659 valtype vch1 = stacktop(-2);
660 valtype vch2 = stacktop(-1);
661 stack.push_back(vch1);
662 stack.push_back(vch2);
668 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
669 if (stack.size() < 3)
671 valtype vch1 = stacktop(-3);
672 valtype vch2 = stacktop(-2);
673 valtype vch3 = stacktop(-1);
674 stack.push_back(vch1);
675 stack.push_back(vch2);
676 stack.push_back(vch3);
682 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
683 if (stack.size() < 4)
685 valtype vch1 = stacktop(-4);
686 valtype vch2 = stacktop(-3);
687 stack.push_back(vch1);
688 stack.push_back(vch2);
694 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
695 if (stack.size() < 6)
697 valtype vch1 = stacktop(-6);
698 valtype vch2 = stacktop(-5);
699 stack.erase(stack.end()-6, stack.end()-4);
700 stack.push_back(vch1);
701 stack.push_back(vch2);
707 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
708 if (stack.size() < 4)
710 swap(stacktop(-4), stacktop(-2));
711 swap(stacktop(-3), stacktop(-1));
718 if (stack.size() < 1)
720 valtype vch = stacktop(-1);
722 stack.push_back(vch);
729 CBigNum bn((uint16_t) stack.size());
730 stack.push_back(bn.getvch());
737 if (stack.size() < 1)
746 if (stack.size() < 1)
748 valtype vch = stacktop(-1);
749 stack.push_back(vch);
756 if (stack.size() < 2)
758 stack.erase(stack.end() - 2);
764 // (x1 x2 -- x1 x2 x1)
765 if (stack.size() < 2)
767 valtype vch = stacktop(-2);
768 stack.push_back(vch);
775 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
776 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
777 if (stack.size() < 2)
779 int n = CastToBigNum(stacktop(-1)).getint32();
781 if (n < 0 || n >= (int)stack.size())
783 valtype vch = stacktop(-n-1);
784 if (opcode == OP_ROLL)
785 stack.erase(stack.end()-n-1);
786 stack.push_back(vch);
792 // (x1 x2 x3 -- x2 x3 x1)
793 // x2 x1 x3 after first swap
794 // x2 x3 x1 after second swap
795 if (stack.size() < 3)
797 swap(stacktop(-3), stacktop(-2));
798 swap(stacktop(-2), stacktop(-1));
805 if (stack.size() < 2)
807 swap(stacktop(-2), stacktop(-1));
813 // (x1 x2 -- x2 x1 x2)
814 if (stack.size() < 2)
816 valtype vch = stacktop(-1);
817 stack.insert(stack.end()-2, vch);
825 if (stack.size() < 1)
827 CBigNum bn((uint16_t) stacktop(-1).size());
828 stack.push_back(bn.getvch());
838 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
841 if (stack.size() < 2)
843 valtype& vch1 = stacktop(-2);
844 valtype& vch2 = stacktop(-1);
845 bool fEqual = (vch1 == vch2);
846 // OP_NOTEQUAL is disabled because it would be too easy to say
847 // something like n != 1 and have some wiseguy pass in 1 with extra
848 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
849 //if (opcode == OP_NOTEQUAL)
853 stack.push_back(fEqual ? vchTrue : vchFalse);
854 if (opcode == OP_EQUALVERIFY)
876 if (stack.size() < 1)
878 CBigNum bn = CastToBigNum(stacktop(-1));
881 case OP_1ADD: bn += bnOne; break;
882 case OP_1SUB: bn -= bnOne; break;
883 case OP_NEGATE: bn = -bn; break;
884 case OP_ABS: if (bn < bnZero) bn = -bn; break;
885 case OP_NOT: bn = (bn == bnZero); break;
886 case OP_0NOTEQUAL: bn = (bn != bnZero); break;
887 default: assert(!"invalid opcode"); break;
890 stack.push_back(bn.getvch());
899 case OP_NUMEQUALVERIFY:
903 case OP_LESSTHANOREQUAL:
904 case OP_GREATERTHANOREQUAL:
909 if (stack.size() < 2)
911 CBigNum bn1 = CastToBigNum(stacktop(-2));
912 CBigNum bn2 = CastToBigNum(stacktop(-1));
924 case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
925 case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
926 case OP_NUMEQUAL: bn = (bn1 == bn2); break;
927 case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
928 case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
929 case OP_LESSTHAN: bn = (bn1 < bn2); break;
930 case OP_GREATERTHAN: bn = (bn1 > bn2); break;
931 case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
932 case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
933 case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break;
934 case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break;
935 default: assert(!"invalid opcode"); break;
939 stack.push_back(bn.getvch());
941 if (opcode == OP_NUMEQUALVERIFY)
943 if (CastToBool(stacktop(-1)))
953 // (x min max -- out)
954 if (stack.size() < 3)
956 CBigNum bn1 = CastToBigNum(stacktop(-3));
957 CBigNum bn2 = CastToBigNum(stacktop(-2));
958 CBigNum bn3 = CastToBigNum(stacktop(-1));
959 bool fValue = (bn2 <= bn1 && bn1 < bn3);
963 stack.push_back(fValue ? vchTrue : vchFalse);
978 if (stack.size() < 1)
980 valtype& vch = stacktop(-1);
981 valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
982 if (opcode == OP_RIPEMD160)
983 RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
984 else if (opcode == OP_SHA1)
985 SHA1(&vch[0], vch.size(), &vchHash[0]);
986 else if (opcode == OP_SHA256)
987 SHA256(&vch[0], vch.size(), &vchHash[0]);
988 else if (opcode == OP_HASH160)
990 uint160 hash160 = Hash160(vch);
991 memcpy(&vchHash[0], &hash160, sizeof(hash160));
993 else if (opcode == OP_HASH256)
995 uint256 hash = Hash(vch.begin(), vch.end());
996 memcpy(&vchHash[0], &hash, sizeof(hash));
999 stack.push_back(vchHash);
1003 case OP_CODESEPARATOR:
1005 // Hash starts after the code separator
1006 pbegincodehash = pc;
1011 case OP_CHECKSIGVERIFY:
1013 // (sig pubkey -- bool)
1014 if (stack.size() < 2)
1017 valtype& vchSig = stacktop(-2);
1018 valtype& vchPubKey = stacktop(-1);
1021 //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1022 //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1024 // Subset of script starting at the most recent codeseparator
1025 CScript scriptCode(pbegincodehash, pend);
1027 // Drop the signature, since there's no way for a signature to sign itself
1028 scriptCode.FindAndDelete(CScript(vchSig));
1030 bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1031 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1035 stack.push_back(fSuccess ? vchTrue : vchFalse);
1036 if (opcode == OP_CHECKSIGVERIFY)
1046 case OP_CHECKMULTISIG:
1047 case OP_CHECKMULTISIGVERIFY:
1049 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1052 if ((int)stack.size() < i)
1055 int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1056 if (nKeysCount < 0 || nKeysCount > 20)
1058 nOpCount += nKeysCount;
1063 if ((int)stack.size() < i)
1066 int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1067 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1071 if ((int)stack.size() < i)
1074 // Subset of script starting at the most recent codeseparator
1075 CScript scriptCode(pbegincodehash, pend);
1077 // Drop the signatures, since there's no way for a signature to sign itself
1078 for (int k = 0; k < nSigsCount; k++)
1080 valtype& vchSig = stacktop(-isig-k);
1081 scriptCode.FindAndDelete(CScript(vchSig));
1084 bool fSuccess = true;
1085 while (fSuccess && nSigsCount > 0)
1087 valtype& vchSig = stacktop(-isig);
1088 valtype& vchPubKey = stacktop(-ikey);
1091 bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1092 CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1101 // If there are more signatures left than keys left,
1102 // then too many signatures have failed
1103 if (nSigsCount > nKeysCount)
1110 // A bug causes CHECKMULTISIG to consume one extra argument
1111 // whose contents were not checked in any way.
1113 // Unfortunately this is a potential source of mutability,
1114 // so optionally verify it is exactly equal to zero prior
1115 // to removing it from the stack.
1116 if (stack.size() < 1)
1118 if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1119 return error("CHECKMULTISIG dummy argument not null");
1122 stack.push_back(fSuccess ? vchTrue : vchFalse);
1124 if (opcode == OP_CHECKMULTISIGVERIFY)
1139 if (stack.size() + altstack.size() > 1000)
1149 if (!vfExec.empty())
1163 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1165 if (nIn >= txTo.vin.size())
1167 printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1170 CTransaction txTmp(txTo);
1172 // In case concatenating two scripts ends up with two codeseparators,
1173 // or an extra one at the end, this prevents all those possible incompatibilities.
1174 scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1176 // Blank out other inputs' signatures
1177 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1178 txTmp.vin[i].scriptSig = CScript();
1179 txTmp.vin[nIn].scriptSig = scriptCode;
1181 // Blank out some of the outputs
1182 if ((nHashType & 0x1f) == SIGHASH_NONE)
1187 // Let the others update at will
1188 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1190 txTmp.vin[i].nSequence = 0;
1192 else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1194 // Only lock-in the txout payee at same index as txin
1195 unsigned int nOut = nIn;
1196 if (nOut >= txTmp.vout.size())
1198 printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1201 txTmp.vout.resize(nOut+1);
1202 for (unsigned int i = 0; i < nOut; i++)
1203 txTmp.vout[i].SetNull();
1205 // Let the others update at will
1206 for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1208 txTmp.vin[i].nSequence = 0;
1211 // Blank out other inputs completely, not recommended for open transactions
1212 if (nHashType & SIGHASH_ANYONECANPAY)
1214 txTmp.vin[0] = txTmp.vin[nIn];
1215 txTmp.vin.resize(1);
1218 // Serialize and hash
1219 CDataStream ss(SER_GETHASH, 0);
1221 ss << txTmp << nHashType;
1222 return Hash(ss.begin(), ss.end());
1226 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1227 // twice for every transaction (once when accepted into memory pool, and
1228 // again when accepted into the block chain)
1230 class CSignatureCache
1233 // sigdata_type is (signature hash, signature, public key):
1234 typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1235 std::set< sigdata_type> setValid;
1236 boost::shared_mutex cs_sigcache;
1240 Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1242 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1244 sigdata_type k(hash, vchSig, pubKey);
1245 std::set<sigdata_type>::iterator mi = setValid.find(k);
1246 if (mi != setValid.end())
1251 void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1253 // DoS prevention: limit cache size to less than 10MB
1254 // (~200 bytes per cache entry times 50,000 entries)
1255 // Since there are a maximum of 20,000 signature operations per block
1256 // 50,000 is a reasonable default.
1257 int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1258 if (nMaxCacheSize <= 0) return;
1260 boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1262 while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1264 // Evict a random entry. Random because that helps
1265 // foil would-be DoS attackers who might try to pre-generate
1266 // and re-use a set of valid signatures just-slightly-greater
1267 // than our cache size.
1268 uint256 randomHash = GetRandHash();
1269 std::vector<unsigned char> unused;
1270 std::set<sigdata_type>::iterator it =
1271 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1272 if (it == setValid.end())
1273 it = setValid.begin();
1274 setValid.erase(*it);
1277 sigdata_type k(hash, vchSig, pubKey);
1282 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1283 const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1285 static CSignatureCache signatureCache;
1287 CPubKey pubkey(vchPubKey);
1288 if (!pubkey.IsValid())
1291 // Hash type is one byte tacked on to the end of the signature
1295 nHashType = vchSig.back();
1296 else if (nHashType != vchSig.back())
1300 uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1302 if (signatureCache.Get(sighash, vchSig, pubkey))
1305 if (!pubkey.Verify(sighash, vchSig))
1308 if (!(flags & SCRIPT_VERIFY_NOCACHE))
1309 signatureCache.Set(sighash, vchSig, pubkey);
1316 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1318 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1321 static map<txnouttype, CScript> mTemplates;
1322 if (mTemplates.empty())
1324 // Standard tx, sender provides pubkey, receiver adds signature
1325 mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1327 // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1328 mTemplates.insert(make_pair(TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG));
1330 // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1331 mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1333 // Sender provides N pubkeys, receivers provides M signatures
1334 mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1336 // Empty, provably prunable, data-carrying output
1337 mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1340 vSolutionsRet.clear();
1342 // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1343 // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1344 if (scriptPubKey.IsPayToScriptHash())
1346 typeRet = TX_SCRIPTHASH;
1347 vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1348 vSolutionsRet.push_back(hashBytes);
1352 // Provably prunable, data-carrying output
1354 // So long as script passes the IsUnspendable() test and all but the first
1355 // byte passes the IsPushOnly() test we don't care what exactly is in the
1357 if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1358 typeRet = TX_NULL_DATA;
1363 const CScript& script1 = scriptPubKey;
1364 BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1366 const CScript& script2 = tplate.second;
1367 vSolutionsRet.clear();
1369 opcodetype opcode1, opcode2;
1370 vector<unsigned char> vch1, vch2;
1373 CScript::const_iterator pc1 = script1.begin();
1374 CScript::const_iterator pc2 = script2.begin();
1377 if (pc1 == script1.end() && pc2 == script2.end())
1380 typeRet = tplate.first;
1381 if (typeRet == TX_MULTISIG)
1383 // Additional checks for TX_MULTISIG:
1384 unsigned char m = vSolutionsRet.front()[0];
1385 unsigned char n = vSolutionsRet.back()[0];
1386 if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1391 if (!script1.GetOp(pc1, opcode1, vch1))
1393 if (!script2.GetOp(pc2, opcode2, vch2))
1396 // Template matching opcodes:
1397 if (opcode2 == OP_PUBKEYS)
1399 while (vch1.size() >= 33 && vch1.size() <= 120)
1401 vSolutionsRet.push_back(vch1);
1402 if (!script1.GetOp(pc1, opcode1, vch1))
1405 if (!script2.GetOp(pc2, opcode2, vch2))
1407 // Normal situation is to fall through
1408 // to other if/else statements
1411 if (opcode2 == OP_PUBKEY)
1413 if (vch1.size() < 33 || vch1.size() > 120)
1415 vSolutionsRet.push_back(vch1);
1417 else if (opcode2 == OP_PUBKEYHASH)
1419 if (vch1.size() != sizeof(uint160))
1421 vSolutionsRet.push_back(vch1);
1423 else if (opcode2 == OP_SMALLINTEGER)
1424 { // Single-byte small integer pushed onto vSolutions
1425 if (opcode1 == OP_0 ||
1426 (opcode1 >= OP_1 && opcode1 <= OP_16))
1428 char n = (char)CScript::DecodeOP_N(opcode1);
1429 vSolutionsRet.push_back(valtype(1, n));
1434 else if (opcode2 == OP_INTEGER)
1435 { // Up to four-byte integer pushed onto vSolutions
1438 CBigNum bnVal = CastToBigNum(vch1);
1440 break; // It's better to use OP_0 ... OP_16 for small integers.
1441 vSolutionsRet.push_back(vch1);
1448 else if (opcode2 == OP_SMALLDATA)
1450 // small pushdata, <= 1024 bytes
1451 if (vch1.size() > 1024)
1454 else if (opcode1 != opcode2 || vch1 != vch2)
1456 // Others must match exactly
1462 vSolutionsRet.clear();
1463 typeRet = TX_NONSTANDARD;
1468 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1471 if (!keystore.GetKey(address, key))
1474 vector<unsigned char> vchSig;
1475 if (!key.Sign(hash, vchSig))
1477 vchSig.push_back((unsigned char)nHashType);
1478 scriptSigRet << vchSig;
1483 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1486 if (!keystore.CreatePrivKey(pubKey, R, key))
1489 vector<unsigned char> vchSig;
1490 if (!key.Sign(hash, vchSig))
1492 vchSig.push_back((unsigned char)nHashType);
1493 scriptSigRet << vchSig;
1498 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1501 int nRequired = multisigdata.front()[0];
1502 for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1504 const valtype& pubkey = multisigdata[i];
1505 CKeyID keyID = CPubKey(pubkey).GetID();
1506 if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1509 return nSigned==nRequired;
1513 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1514 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1515 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1516 // Returns false if scriptPubKey could not be completely satisfied.
1518 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1519 CScript& scriptSigRet, txnouttype& whichTypeRet)
1521 scriptSigRet.clear();
1523 vector<valtype> vSolutions;
1524 if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1528 switch (whichTypeRet)
1530 case TX_NONSTANDARD:
1534 keyID = CPubKey(vSolutions[0]).GetID();
1535 return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1536 case TX_PUBKEY_DROP:
1538 CPubKey key = CPubKey(vSolutions[0]);
1539 CPubKey R = CPubKey(vSolutions[1]);
1540 return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1543 keyID = CKeyID(uint160(vSolutions[0]));
1544 if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1549 keystore.GetPubKey(keyID, vch);
1550 scriptSigRet << vch;
1554 return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1557 scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1558 return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1563 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1567 case TX_NONSTANDARD:
1572 case TX_PUBKEY_DROP:
1577 if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1579 return vSolutions[0][0] + 1;
1581 return 1; // doesn't include args needed by the script
1586 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1588 vector<valtype> vSolutions;
1589 if (!Solver(scriptPubKey, whichType, vSolutions))
1592 if (whichType == TX_MULTISIG)
1594 unsigned char m = vSolutions.front()[0];
1595 unsigned char n = vSolutions.back()[0];
1596 // Support up to x-of-3 multisig txns as standard
1603 return whichType != TX_NONSTANDARD;
1607 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1609 unsigned int nResult = 0;
1610 BOOST_FOREACH(const valtype& pubkey, pubkeys)
1612 CKeyID keyID = CPubKey(pubkey).GetID();
1613 if (keystore.HaveKey(keyID))
1620 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1623 const CKeyStore *keystore;
1625 CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1626 bool operator()(const CNoDestination &dest) const { return false; }
1627 bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1628 bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1632 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1635 script.SetDestination(dest);
1636 return IsMine(keystore, script);
1639 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1642 script.SetAddress(dest);
1643 return IsMine(keystore, script);
1646 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1648 vector<valtype> vSolutions;
1649 txnouttype whichType;
1650 if (!Solver(scriptPubKey, whichType, vSolutions)) {
1651 if (keystore.HaveWatchOnly(scriptPubKey))
1652 return MINE_WATCH_ONLY;
1659 case TX_NONSTANDARD:
1663 keyID = CPubKey(vSolutions[0]).GetID();
1664 if (keystore.HaveKey(keyID))
1665 return MINE_SPENDABLE;
1667 case TX_PUBKEY_DROP:
1669 CPubKey key = CPubKey(vSolutions[0]);
1670 CPubKey R = CPubKey(vSolutions[1]);
1671 if (keystore.CheckOwnership(key, R))
1672 return MINE_SPENDABLE;
1676 keyID = CKeyID(uint160(vSolutions[0]));
1677 if (keystore.HaveKey(keyID))
1678 return MINE_SPENDABLE;
1682 CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1684 if (keystore.GetCScript(scriptID, subscript)) {
1685 isminetype ret = IsMine(keystore, subscript);
1686 if (ret == MINE_SPENDABLE)
1693 // Only consider transactions "mine" if we own ALL the
1694 // keys involved. multi-signature transactions that are
1695 // partially owned (somebody else has a key that can spend
1696 // them) enable spend-out-from-under-you attacks, especially
1697 // in shared-wallet situations.
1698 vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1699 if (HaveKeys(keys, keystore) == keys.size())
1700 return MINE_SPENDABLE;
1705 if (keystore.HaveWatchOnly(scriptPubKey))
1706 return MINE_WATCH_ONLY;
1710 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1712 vector<valtype> vSolutions;
1713 txnouttype whichType;
1714 if (!Solver(scriptPubKey, whichType, vSolutions))
1717 if (whichType == TX_PUBKEY)
1719 addressRet = CPubKey(vSolutions[0]).GetID();
1722 else if (whichType == TX_PUBKEYHASH)
1724 addressRet = CKeyID(uint160(vSolutions[0]));
1727 else if (whichType == TX_SCRIPTHASH)
1729 addressRet = CScriptID(uint160(vSolutions[0]));
1732 // Multisig txns have more than one address...
1736 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1738 vector<valtype> vSolutions;
1739 txnouttype whichType;
1740 if (!Solver(scriptPubKey, whichType, vSolutions))
1743 if (whichType == TX_PUBKEY)
1745 addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1748 if (whichType == TX_PUBKEY_DROP)
1751 CMalleableKeyView view;
1752 if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1755 addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1758 else if (whichType == TX_PUBKEYHASH)
1760 addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1763 else if (whichType == TX_SCRIPTHASH)
1765 addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1768 // Multisig txns have more than one address...
1772 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1774 const CKeyStore &keystore;
1775 CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1776 std::vector<CKeyID> &vKeys;
1779 CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1781 void Process(const CScript &script) {
1783 std::vector<CTxDestination> vDest;
1785 if (ExtractDestinations(script, type, vDest, nRequired)) {
1786 BOOST_FOREACH(const CTxDestination &dest, vDest)
1787 boost::apply_visitor(*this, dest);
1791 void operator()(const CKeyID &keyId) {
1792 if (keystore.HaveKey(keyId))
1793 vKeys.push_back(keyId);
1796 void operator()(const CScriptID &scriptId) {
1798 if (keystore.GetCScript(scriptId, script))
1802 void operator()(const CNoDestination &none) {}
1806 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1807 CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1810 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1813 typeRet = TX_NONSTANDARD;
1814 vector<valtype> vSolutions;
1815 if (!Solver(scriptPubKey, typeRet, vSolutions))
1817 if (typeRet == TX_NULL_DATA)
1823 if (typeRet == TX_MULTISIG)
1825 nRequiredRet = vSolutions.front()[0];
1826 for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1828 CTxDestination address = CPubKey(vSolutions[i]).GetID();
1829 addressRet.push_back(address);
1835 if (typeRet == TX_PUBKEY_DROP)
1837 CTxDestination address;
1838 if (!ExtractDestination(scriptPubKey, address))
1840 addressRet.push_back(address);
1846 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1847 unsigned int flags, int nHashType)
1849 vector<vector<unsigned char> > stack, stackCopy;
1850 if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1852 if (flags & SCRIPT_VERIFY_P2SH)
1854 if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1859 if (CastToBool(stack.back()) == false)
1862 // Additional validation for spend-to-script-hash transactions:
1863 if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1865 if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1866 return false; // or validation fails
1868 // stackCopy cannot be empty here, because if it was the
1869 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1870 // an empty stack and the EvalScript above would return false.
1871 assert(!stackCopy.empty());
1873 const valtype& pubKeySerialized = stackCopy.back();
1874 CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1875 popstack(stackCopy);
1877 if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1879 if (stackCopy.empty())
1881 return CastToBool(stackCopy.back());
1887 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1889 assert(nIn < txTo.vin.size());
1890 CTxIn& txin = txTo.vin[nIn];
1892 // Leave out the signature from the hash, since a signature can't sign itself.
1893 // The checksig op will also drop the signatures from its hash.
1894 uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1896 txnouttype whichType;
1897 if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1900 if (whichType == TX_SCRIPTHASH)
1902 // Solver returns the subscript that need to be evaluated;
1903 // the final scriptSig is the signatures from that
1904 // and then the serialized subscript:
1905 CScript subscript = txin.scriptSig;
1907 // Recompute txn hash using subscript in place of scriptPubKey:
1908 uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1912 Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1913 // Append serialized subscript whether or not it is completely signed:
1914 txin.scriptSig << static_cast<valtype>(subscript);
1915 if (!fSolved) return false;
1919 return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1922 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1924 assert(nIn < txTo.vin.size());
1925 CTxIn& txin = txTo.vin[nIn];
1926 assert(txin.prevout.n < txFrom.vout.size());
1927 assert(txin.prevout.hash == txFrom.GetHash());
1928 const CTxOut& txout = txFrom.vout[txin.prevout.n];
1930 return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1933 static CScript PushAll(const vector<valtype>& values)
1936 BOOST_FOREACH(const valtype& v, values)
1941 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1942 const vector<valtype>& vSolutions,
1943 vector<valtype>& sigs1, vector<valtype>& sigs2)
1945 // Combine all the signatures we've got:
1946 set<valtype> allsigs;
1947 BOOST_FOREACH(const valtype& v, sigs1)
1952 BOOST_FOREACH(const valtype& v, sigs2)
1958 // Build a map of pubkey -> signature by matching sigs to pubkeys:
1959 assert(vSolutions.size() > 1);
1960 unsigned int nSigsRequired = vSolutions.front()[0];
1961 unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1962 map<valtype, valtype> sigs;
1963 BOOST_FOREACH(const valtype& sig, allsigs)
1965 for (unsigned int i = 0; i < nPubKeys; i++)
1967 const valtype& pubkey = vSolutions[i+1];
1968 if (sigs.count(pubkey))
1969 continue; // Already got a sig for this pubkey
1971 if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1978 // Now build a merged CScript:
1979 unsigned int nSigsHave = 0;
1980 CScript result; result << OP_0; // pop-one-too-many workaround
1981 for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1983 if (sigs.count(vSolutions[i+1]))
1985 result << sigs[vSolutions[i+1]];
1989 // Fill any missing with OP_0:
1990 for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1996 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1997 const txnouttype txType, const vector<valtype>& vSolutions,
1998 vector<valtype>& sigs1, vector<valtype>& sigs2)
2002 case TX_NONSTANDARD:
2004 // Don't know anything about this, assume bigger one is correct:
2005 if (sigs1.size() >= sigs2.size())
2006 return PushAll(sigs1);
2007 return PushAll(sigs2);
2009 case TX_PUBKEY_DROP:
2011 // Signatures are bigger than placeholders or empty scripts:
2012 if (sigs1.empty() || sigs1[0].empty())
2013 return PushAll(sigs2);
2014 return PushAll(sigs1);
2016 if (sigs1.empty() || sigs1.back().empty())
2017 return PushAll(sigs2);
2018 else if (sigs2.empty() || sigs2.back().empty())
2019 return PushAll(sigs1);
2022 // Recur to combine:
2023 valtype spk = sigs1.back();
2024 CScript pubKey2(spk.begin(), spk.end());
2027 vector<vector<unsigned char> > vSolutions2;
2028 Solver(pubKey2, txType2, vSolutions2);
2031 CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2036 return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2042 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2043 const CScript& scriptSig1, const CScript& scriptSig2)
2046 vector<vector<unsigned char> > vSolutions;
2047 Solver(scriptPubKey, txType, vSolutions);
2049 vector<valtype> stack1;
2050 EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2051 vector<valtype> stack2;
2052 EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2054 return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2057 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2060 const_iterator pc = begin();
2061 opcodetype lastOpcode = OP_INVALIDOPCODE;
2065 if (!GetOp(pc, opcode))
2067 if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2069 else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2071 if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2072 n += DecodeOP_N(lastOpcode);
2076 lastOpcode = opcode;
2081 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2083 if (!IsPayToScriptHash())
2084 return GetSigOpCount(true);
2086 // This is a pay-to-script-hash scriptPubKey;
2087 // get the last item that the scriptSig
2088 // pushes onto the stack:
2089 const_iterator pc = scriptSig.begin();
2090 vector<unsigned char> data;
2091 while (pc < scriptSig.end())
2094 if (!scriptSig.GetOp(pc, opcode, data))
2100 /// ... and return its opcount:
2101 CScript subscript(data.begin(), data.end());
2102 return subscript.GetSigOpCount(true);
2105 bool CScript::IsPayToScriptHash() const
2107 // Extra-fast test for pay-to-script-hash CScripts:
2108 return (this->size() == 23 &&
2109 this->at(0) == OP_HASH160 &&
2110 this->at(1) == 0x14 &&
2111 this->at(22) == OP_EQUAL);
2114 bool CScript::HasCanonicalPushes() const
2116 const_iterator pc = begin();
2120 std::vector<unsigned char> data;
2121 if (!GetOp(pc, opcode, data))
2125 if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2126 // Could have used an OP_n code, rather than a 1-byte push.
2128 if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2129 // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2131 if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2132 // Could have used an OP_PUSHDATA1.
2134 if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2135 // Could have used an OP_PUSHDATA2.
2141 class CScriptVisitor : public boost::static_visitor<bool>
2146 CScriptVisitor(CScript *scriptin) { script = scriptin; }
2148 bool operator()(const CNoDestination &dest) const {
2153 bool operator()(const CKeyID &keyID) const {
2155 *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2159 bool operator()(const CScriptID &scriptID) const {
2161 *script << OP_HASH160 << scriptID << OP_EQUAL;
2166 void CScript::SetDestination(const CTxDestination& dest)
2168 boost::apply_visitor(CScriptVisitor(this), dest);
2171 void CScript::SetAddress(const CBitcoinAddress& dest)
2174 if (dest.IsScript())
2175 *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2176 else if (dest.IsPubKey())
2177 *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2178 else if (dest.IsPair()) {
2179 // Pubkey pair address, going to generate
2180 // new one-time public key.
2181 CMalleablePubKey mpk;
2182 if (!mpk.setvch(dest.GetData()))
2184 CPubKey R, pubKeyVariant;
2185 mpk.GetVariant(R, pubKeyVariant);
2186 *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2190 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2194 *this << EncodeOP_N(nRequired);
2195 BOOST_FOREACH(const CPubKey& key, keys)
2197 *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;