From bitcoin https://github.com/bitcoin/bitcoin/pull/7907
[novacoin.git] / src / script.cpp
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
6 #include "script.h"
7 #include "keystore.h"
8 #include "bignum.h"
9 #include "key.h"
10 #include "main.h"
11 #include "sync.h"
12 #include "util.h"
13
14 using namespace std;
15
16 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
17
18 static const valtype vchFalse(0);
19 static const valtype vchZero(0);
20 static const valtype vchTrue(1, 1);
21 static const CBigNum bnZero(0);
22 static const CBigNum bnOne(1);
23 static const CBigNum bnFalse(0);
24 static const CBigNum bnTrue(1);
25 static const size_t nMaxNumSize = 4;
26
27
28 CBigNum CastToBigNum(const valtype& vch)
29 {
30     if (vch.size() > nMaxNumSize)
31         throw runtime_error("CastToBigNum() : overflow");
32     // Get rid of extra leading zeros
33     return CBigNum(CBigNum(vch).getvch());
34 }
35
36 bool CastToBool(const valtype& vch)
37 {
38     for (unsigned int i = 0; i < vch.size(); i++)
39     {
40         if (vch[i] != 0)
41         {
42             // Can be negative zero
43             if (i == vch.size()-1 && vch[i] == 0x80)
44                 return false;
45             return true;
46         }
47     }
48     return false;
49 }
50
51 //
52 // WARNING: This does not work as expected for signed integers; the sign-bit
53 // is left in place as the integer is zero-extended. The correct behavior
54 // would be to move the most significant bit of the last byte during the
55 // resize process. MakeSameSize() is currently only used by the disabled
56 // opcodes OP_AND, OP_OR, and OP_XOR.
57 //
58 void MakeSameSize(valtype& vch1, valtype& vch2)
59 {
60     // Lengthen the shorter one
61     if (vch1.size() < vch2.size())
62         // PATCH:
63         // +unsigned char msb = vch1[vch1.size()-1];
64         // +vch1[vch1.size()-1] &= 0x7f;
65         //  vch1.resize(vch2.size(), 0);
66         // +vch1[vch1.size()-1] = msb;
67         vch1.resize(vch2.size(), 0);
68     if (vch2.size() < vch1.size())
69         // PATCH:
70         // +unsigned char msb = vch2[vch2.size()-1];
71         // +vch2[vch2.size()-1] &= 0x7f;
72         //  vch2.resize(vch1.size(), 0);
73         // +vch2[vch2.size()-1] = msb;
74         vch2.resize(vch1.size(), 0);
75 }
76
77
78
79 //
80 // Script is a stack machine (like Forth) that evaluates a predicate
81 // returning a bool indicating valid or not.  There are no loops.
82 //
83 #define stacktop(i)  (stack.at(stack.size()+(i)))
84 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
85 static inline void popstack(vector<valtype>& stack)
86 {
87     if (stack.empty())
88         throw runtime_error("popstack() : stack empty");
89     stack.pop_back();
90 }
91
92
93 const char* GetTxnOutputType(txnouttype t)
94 {
95     switch (t)
96     {
97     case TX_NONSTANDARD: return "nonstandard";
98     case TX_PUBKEY: return "pubkey";
99     case TX_PUBKEY_DROP: return "pubkeydrop";
100     case TX_PUBKEYHASH: return "pubkeyhash";
101     case TX_SCRIPTHASH: return "scripthash";
102     case TX_MULTISIG: return "multisig";
103     case TX_NULL_DATA: return "nulldata";
104     }
105     return NULL;
106 }
107
108
109 const char* GetOpName(opcodetype opcode)
110 {
111     switch (opcode)
112     {
113     // push value
114     case OP_0                      : return "0";
115     case OP_PUSHDATA1              : return "OP_PUSHDATA1";
116     case OP_PUSHDATA2              : return "OP_PUSHDATA2";
117     case OP_PUSHDATA4              : return "OP_PUSHDATA4";
118     case OP_1NEGATE                : return "-1";
119     case OP_RESERVED               : return "OP_RESERVED";
120     case OP_1                      : return "1";
121     case OP_2                      : return "2";
122     case OP_3                      : return "3";
123     case OP_4                      : return "4";
124     case OP_5                      : return "5";
125     case OP_6                      : return "6";
126     case OP_7                      : return "7";
127     case OP_8                      : return "8";
128     case OP_9                      : return "9";
129     case OP_10                     : return "10";
130     case OP_11                     : return "11";
131     case OP_12                     : return "12";
132     case OP_13                     : return "13";
133     case OP_14                     : return "14";
134     case OP_15                     : return "15";
135     case OP_16                     : return "16";
136
137     // control
138     case OP_NOP                    : return "OP_NOP";
139     case OP_VER                    : return "OP_VER";
140     case OP_IF                     : return "OP_IF";
141     case OP_NOTIF                  : return "OP_NOTIF";
142     case OP_VERIF                  : return "OP_VERIF";
143     case OP_VERNOTIF               : return "OP_VERNOTIF";
144     case OP_ELSE                   : return "OP_ELSE";
145     case OP_ENDIF                  : return "OP_ENDIF";
146     case OP_VERIFY                 : return "OP_VERIFY";
147     case OP_RETURN                 : return "OP_RETURN";
148     case OP_CHECKLOCKTIMEVERIFY    : return "OP_CHECKLOCKTIMEVERIFY";
149     case OP_CHECKSEQUENCEVERIFY    : return "OP_CHECKSEQUENCEVERIFY";
150
151     // stack ops
152     case OP_TOALTSTACK             : return "OP_TOALTSTACK";
153     case OP_FROMALTSTACK           : return "OP_FROMALTSTACK";
154     case OP_2DROP                  : return "OP_2DROP";
155     case OP_2DUP                   : return "OP_2DUP";
156     case OP_3DUP                   : return "OP_3DUP";
157     case OP_2OVER                  : return "OP_2OVER";
158     case OP_2ROT                   : return "OP_2ROT";
159     case OP_2SWAP                  : return "OP_2SWAP";
160     case OP_IFDUP                  : return "OP_IFDUP";
161     case OP_DEPTH                  : return "OP_DEPTH";
162     case OP_DROP                   : return "OP_DROP";
163     case OP_DUP                    : return "OP_DUP";
164     case OP_NIP                    : return "OP_NIP";
165     case OP_OVER                   : return "OP_OVER";
166     case OP_PICK                   : return "OP_PICK";
167     case OP_ROLL                   : return "OP_ROLL";
168     case OP_ROT                    : return "OP_ROT";
169     case OP_SWAP                   : return "OP_SWAP";
170     case OP_TUCK                   : return "OP_TUCK";
171
172     // splice ops
173     case OP_CAT                    : return "OP_CAT";
174     case OP_SUBSTR                 : return "OP_SUBSTR";
175     case OP_LEFT                   : return "OP_LEFT";
176     case OP_RIGHT                  : return "OP_RIGHT";
177     case OP_SIZE                   : return "OP_SIZE";
178
179     // bit logic
180     case OP_INVERT                 : return "OP_INVERT";
181     case OP_AND                    : return "OP_AND";
182     case OP_OR                     : return "OP_OR";
183     case OP_XOR                    : return "OP_XOR";
184     case OP_EQUAL                  : return "OP_EQUAL";
185     case OP_EQUALVERIFY            : return "OP_EQUALVERIFY";
186     case OP_RESERVED1              : return "OP_RESERVED1";
187     case OP_RESERVED2              : return "OP_RESERVED2";
188
189     // numeric
190     case OP_1ADD                   : return "OP_1ADD";
191     case OP_1SUB                   : return "OP_1SUB";
192     case OP_2MUL                   : return "OP_2MUL";
193     case OP_2DIV                   : return "OP_2DIV";
194     case OP_NEGATE                 : return "OP_NEGATE";
195     case OP_ABS                    : return "OP_ABS";
196     case OP_NOT                    : return "OP_NOT";
197     case OP_0NOTEQUAL              : return "OP_0NOTEQUAL";
198     case OP_ADD                    : return "OP_ADD";
199     case OP_SUB                    : return "OP_SUB";
200     case OP_MUL                    : return "OP_MUL";
201     case OP_DIV                    : return "OP_DIV";
202     case OP_MOD                    : return "OP_MOD";
203     case OP_LSHIFT                 : return "OP_LSHIFT";
204     case OP_RSHIFT                 : return "OP_RSHIFT";
205     case OP_BOOLAND                : return "OP_BOOLAND";
206     case OP_BOOLOR                 : return "OP_BOOLOR";
207     case OP_NUMEQUAL               : return "OP_NUMEQUAL";
208     case OP_NUMEQUALVERIFY         : return "OP_NUMEQUALVERIFY";
209     case OP_NUMNOTEQUAL            : return "OP_NUMNOTEQUAL";
210     case OP_LESSTHAN               : return "OP_LESSTHAN";
211     case OP_GREATERTHAN            : return "OP_GREATERTHAN";
212     case OP_LESSTHANOREQUAL        : return "OP_LESSTHANOREQUAL";
213     case OP_GREATERTHANOREQUAL     : return "OP_GREATERTHANOREQUAL";
214     case OP_MIN                    : return "OP_MIN";
215     case OP_MAX                    : return "OP_MAX";
216     case OP_WITHIN                 : return "OP_WITHIN";
217
218     // crypto
219     case OP_RIPEMD160              : return "OP_RIPEMD160";
220     case OP_SHA1                   : return "OP_SHA1";
221     case OP_SHA256                 : return "OP_SHA256";
222     case OP_HASH160                : return "OP_HASH160";
223     case OP_HASH256                : return "OP_HASH256";
224     case OP_CODESEPARATOR          : return "OP_CODESEPARATOR";
225     case OP_CHECKSIG               : return "OP_CHECKSIG";
226     case OP_CHECKSIGVERIFY         : return "OP_CHECKSIGVERIFY";
227     case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
228     case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
229
230     // expanson
231     case OP_NOP1                   : return "OP_NOP1";
232     case OP_NOP4                   : return "OP_NOP4";
233     case OP_NOP5                   : return "OP_NOP5";
234     case OP_NOP6                   : return "OP_NOP6";
235     case OP_NOP7                   : return "OP_NOP7";
236     case OP_NOP8                   : return "OP_NOP8";
237     case OP_NOP9                   : return "OP_NOP9";
238     case OP_NOP10                  : return "OP_NOP10";
239
240
241
242     // template matching params
243     case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";
244     case OP_PUBKEY                 : return "OP_PUBKEY";
245     case OP_SMALLDATA              : return "OP_SMALLDATA";
246
247     case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";
248     default:
249         return "OP_UNKNOWN";
250     }
251 }
252
253 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
254     if (!(flags & SCRIPT_VERIFY_STRICTENC))
255         return true;
256
257     if (vchPubKey.size() < 33)
258         return error("Non-canonical public key: too short");
259     if (vchPubKey[0] == 0x04) {
260         if (vchPubKey.size() != 65)
261             return error("Non-canonical public key: invalid length for uncompressed key");
262     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
263         if (vchPubKey.size() != 33)
264             return error("Non-canonical public key: invalid length for compressed key");
265     } else {
266         return error("Non-canonical public key: compressed nor uncompressed");
267     }
268     return true;
269 }
270
271 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
272     // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
273     // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
274     // Where R and S are not negative (their first byte has its highest bit not set), and not
275     // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
276     // in which case a single 0 byte is necessary and even required).
277     if (vchSig.size() < 9)
278         return error("Non-canonical signature: too short");
279     if (vchSig.size() > 73)
280         return error("Non-canonical signature: too long");
281     if (vchSig[0] != 0x30)
282         return error("Non-canonical signature: wrong type");
283     if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
284         return error("Non-canonical signature: wrong length marker");
285     if (fWithHashType) {
286         unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
287         if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
288             return error("Non-canonical signature: unknown hashtype byte");
289     }
290     unsigned int nLenR = vchSig[3];
291     if (5 + nLenR >= vchSig.size())
292         return error("Non-canonical signature: S length misplaced");
293     unsigned int nLenS = vchSig[5+nLenR];
294     if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
295         return error("Non-canonical signature: R+S length mismatch");
296
297     const unsigned char *R = &vchSig[4];
298     if (R[-2] != 0x02)
299         return error("Non-canonical signature: R value type mismatch");
300     if (nLenR == 0)
301         return error("Non-canonical signature: R length is zero");
302     if (R[0] & 0x80)
303         return error("Non-canonical signature: R value negative");
304     if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
305         return error("Non-canonical signature: R value excessively padded");
306
307     const unsigned char *S = &vchSig[6+nLenR];
308     if (S[-2] != 0x02)
309         return error("Non-canonical signature: S value type mismatch");
310     if (nLenS == 0)
311         return error("Non-canonical signature: S length is zero");
312     if (S[0] & 0x80)
313         return error("Non-canonical signature: S value negative");
314     if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
315         return error("Non-canonical signature: S value excessively padded");
316
317     if (fCheckLow) {
318         unsigned int nLenR = vchSig[3];
319         unsigned int nLenS = vchSig[5+nLenR];
320         const unsigned char *S = &vchSig[6+nLenR];
321         // If the S value is above the order of the curve divided by two, its
322         // complement modulo the order could have been used instead, which is
323         // one byte shorter when encoded correctly.
324         if (!CKey::CheckSignatureElement(S, nLenS, true))
325             return error("Non-canonical signature: S value is unnecessarily high");
326     }
327
328     return true;
329 }
330
331 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
332     if (!(flags & SCRIPT_VERIFY_STRICTENC))
333         return true;
334
335     return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
336 }
337
338 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
339 {
340     // There are two kinds of nLockTime: lock-by-blockheight
341     // and lock-by-blocktime, distinguished by whether
342     // nLockTime < LOCKTIME_THRESHOLD.
343     //
344     // We want to compare apples to apples, so fail the script
345     // unless the type of nLockTime being tested is the same as
346     // the nLockTime in the transaction.
347     if (!(
348         (txTo.nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
349         (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
350     ))
351         return false;
352
353     // Now that we know we're comparing apples-to-apples, the
354     // comparison is a simple numeric one.
355     if (nLockTime > (int64_t)txTo.nLockTime)
356         return false;
357
358     // Finally the nLockTime feature can be disabled and thus
359     // CHECKLOCKTIMEVERIFY bypassed if every txin has been
360     // finalized by setting nSequence to maxint. The
361     // transaction would be allowed into the blockchain, making
362     // the opcode ineffective.
363     //
364     // Testing if this vin is not final is sufficient to
365     // prevent this condition. Alternatively we could test all
366     // inputs, but testing just this input minimizes the data
367     // required to prove correct CHECKLOCKTIMEVERIFY execution.
368     if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
369         return false;
370
371     return true;
372 }
373
374 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
375 {
376     // Relative lock times are supported by comparing the passed
377     // in operand to the sequence number of the input.
378     const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
379
380     // Sequence numbers with their most significant bit set are not
381     // consensus constrained. Testing that the transaction's sequence
382     // number do not have this bit set prevents using this property
383     // to get around a CHECKSEQUENCEVERIFY check.
384     if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
385         return false;
386
387     // Mask off any bits that do not have consensus-enforced meaning
388     // before doing the integer comparisons
389     const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
390     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
391     const int64_t nSequenceMasked = nSequence & nLockTimeMask;
392
393     // There are two kinds of nSequence: lock-by-blockheight
394     // and lock-by-blocktime, distinguished by whether
395     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
396     //
397     // We want to compare apples to apples, so fail the script
398     // unless the type of nSequenceMasked being tested is the same as
399     // the nSequenceMasked in the transaction.
400     if (!(
401         (txToSequenceMasked <  SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  SEQUENCE_LOCKTIME_TYPE_FLAG) ||
402         (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
403     )) {
404         return false;
405     }
406
407     // Now that we know we're comparing apples-to-apples, the
408     // comparison is a simple numeric one.
409     if (nSequenceMasked > txToSequenceMasked)
410         return false;
411
412     return true;
413 }
414
415 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
416 {
417     CAutoBN_CTX pctx;
418     auto pc = script.begin();
419     auto pend = script.end();
420     auto pbegincodehash = script.begin();
421     opcodetype opcode;
422     valtype vchPushValue;
423     vector<bool> vfExec;
424     vector<valtype> altstack;
425     if (script.size() > 10000)
426         return false;
427     int nOpCount = 0;
428
429     try
430     {
431         while (pc < pend)
432         {
433             bool fExec = !count(vfExec.begin(), vfExec.end(), false);
434
435             //
436             // Read instruction
437             //
438             if (!script.GetOp(pc, opcode, vchPushValue))
439                 return false;
440             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
441                 return false;
442             if (opcode > OP_16 && ++nOpCount > 201)
443                 return false;
444
445             if (opcode == OP_CAT ||
446                 opcode == OP_SUBSTR ||
447                 opcode == OP_LEFT ||
448                 opcode == OP_RIGHT ||
449                 opcode == OP_INVERT ||
450                 opcode == OP_AND ||
451                 opcode == OP_OR ||
452                 opcode == OP_XOR ||
453                 opcode == OP_2MUL ||
454                 opcode == OP_2DIV ||
455                 opcode == OP_MUL ||
456                 opcode == OP_DIV ||
457                 opcode == OP_MOD ||
458                 opcode == OP_LSHIFT ||
459                 opcode == OP_RSHIFT)
460                 return false; // Disabled opcodes.
461
462             if (fExec && opcode <= OP_PUSHDATA4)
463                 stack.push_back(vchPushValue);
464             else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
465             switch (opcode)
466             {
467                 //
468                 // Push value
469                 //
470                 case OP_1NEGATE:
471                 case OP_1:
472                 case OP_2:
473                 case OP_3:
474                 case OP_4:
475                 case OP_5:
476                 case OP_6:
477                 case OP_7:
478                 case OP_8:
479                 case OP_9:
480                 case OP_10:
481                 case OP_11:
482                 case OP_12:
483                 case OP_13:
484                 case OP_14:
485                 case OP_15:
486                 case OP_16:
487                 {
488                     // ( -- value)
489                     CBigNum bn(opcode - (OP_1 - 1));
490                     stack.push_back(bn.getvch());
491                 }
492                 break;
493
494
495                 //
496                 // Control
497                 //
498                 case OP_NOP:
499                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
500                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
501                 break;
502
503                 case OP_IF:
504                 case OP_NOTIF:
505                 {
506                     // <expression> if [statements] [else [statements]] endif
507                     bool fValue = false;
508                     if (fExec)
509                     {
510                         if (stack.size() < 1)
511                             return false;
512                         auto& vch = stacktop(-1);
513                         fValue = CastToBool(vch);
514                         if (opcode == OP_NOTIF)
515                             fValue = !fValue;
516                         popstack(stack);
517                     }
518                     vfExec.push_back(fValue);
519                 }
520                 break;
521
522                 case OP_ELSE:
523                 {
524                     if (vfExec.empty())
525                         return false;
526                     vfExec.back() = !vfExec.back();
527                 }
528                 break;
529
530                 case OP_ENDIF:
531                 {
532                     if (vfExec.empty())
533                         return false;
534                     vfExec.pop_back();
535                 }
536                 break;
537
538                 case OP_VERIFY:
539                 {
540                     // (true -- ) or
541                     // (false -- false) and return
542                     if (stack.size() < 1)
543                         return false;
544                     bool fValue = CastToBool(stacktop(-1));
545                     if (fValue)
546                         popstack(stack);
547                     else
548                         return false;
549                 }
550                 break;
551
552                 case OP_RETURN:
553                 {
554                     return false;
555                 }
556                 break;
557
558                 case OP_CHECKLOCKTIMEVERIFY:
559                 {
560                     // CHECKLOCKTIMEVERIFY
561                     //
562                     // (nLockTime -- nLockTime)
563                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
564                         // treat as a NOP2 if not enabled
565                         break;
566                     }
567
568                     if (stack.size() < 1)
569                         return false;
570
571                     auto nLockTime = CastToBigNum(stacktop(-1));
572
573                     // In the rare event that the argument may be < 0 due to
574                     // some arithmetic being done first, you can always use
575                     // 0 MAX CHECKLOCKTIMEVERIFY.
576                     if (nLockTime < 0)
577                         return false;
578
579                     // Actually compare the specified lock time with the transaction.
580                     if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
581                         return false;
582
583                     break;
584                 }
585
586                 case OP_CHECKSEQUENCEVERIFY:
587                 {
588                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
589                         // treat as a NOP3 not enabled
590                         break;
591                     }
592
593                     if (stack.size() < 1)
594                         return false;
595
596                     // nSequence, like nLockTime, is a 32-bit unsigned integer
597                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
598                     // 5-byte numeric operands.
599                     auto nSequence = CastToBigNum(stacktop(-1));
600
601                     // In the rare event that the argument may be < 0 due to
602                     // some arithmetic being done first, you can always use
603                     // 0 MAX CHECKSEQUENCEVERIFY.
604                     if (nSequence < 0)
605                         return false;
606
607                     // To provide for future soft-fork extensibility, if the
608                     // operand has the disabled lock-time flag set,
609                     // CHECKSEQUENCEVERIFY behaves as a NOP.
610                     if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
611                         break;
612
613                     // Compare the specified sequence number with the input.
614                     if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
615                         return false;
616
617                     break;
618                 }
619
620                 //
621                 // Stack ops
622                 //
623                 case OP_TOALTSTACK:
624                 {
625                     if (stack.size() < 1)
626                         return false;
627                     altstack.push_back(stacktop(-1));
628                     popstack(stack);
629                 }
630                 break;
631
632                 case OP_FROMALTSTACK:
633                 {
634                     if (altstack.size() < 1)
635                         return false;
636                     stack.push_back(altstacktop(-1));
637                     popstack(altstack);
638                 }
639                 break;
640
641                 case OP_2DROP:
642                 {
643                     // (x1 x2 -- )
644                     if (stack.size() < 2)
645                         return false;
646                     popstack(stack);
647                     popstack(stack);
648                 }
649                 break;
650
651                 case OP_2DUP:
652                 {
653                     // (x1 x2 -- x1 x2 x1 x2)
654                     if (stack.size() < 2)
655                         return false;
656                     auto vch1 = stacktop(-2);
657                     auto vch2 = stacktop(-1);
658                     stack.push_back(vch1);
659                     stack.push_back(vch2);
660                 }
661                 break;
662
663                 case OP_3DUP:
664                 {
665                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
666                     if (stack.size() < 3)
667                         return false;
668                     auto vch1 = stacktop(-3);
669                     auto vch2 = stacktop(-2);
670                     auto vch3 = stacktop(-1);
671                     stack.push_back(vch1);
672                     stack.push_back(vch2);
673                     stack.push_back(vch3);
674                 }
675                 break;
676
677                 case OP_2OVER:
678                 {
679                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
680                     if (stack.size() < 4)
681                         return false;
682                     auto vch1 = stacktop(-4);
683                     auto vch2 = stacktop(-3);
684                     stack.push_back(vch1);
685                     stack.push_back(vch2);
686                 }
687                 break;
688
689                 case OP_2ROT:
690                 {
691                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
692                     if (stack.size() < 6)
693                         return false;
694                     auto vch1 = stacktop(-6);
695                     auto vch2 = stacktop(-5);
696                     stack.erase(stack.end()-6, stack.end()-4);
697                     stack.push_back(vch1);
698                     stack.push_back(vch2);
699                 }
700                 break;
701
702                 case OP_2SWAP:
703                 {
704                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
705                     if (stack.size() < 4)
706                         return false;
707                     swap(stacktop(-4), stacktop(-2));
708                     swap(stacktop(-3), stacktop(-1));
709                 }
710                 break;
711
712                 case OP_IFDUP:
713                 {
714                     // (x - 0 | x x)
715                     if (stack.size() < 1)
716                         return false;
717                     auto vch = stacktop(-1);
718                     if (CastToBool(vch))
719                         stack.push_back(vch);
720                 }
721                 break;
722
723                 case OP_DEPTH:
724                 {
725                     // -- stacksize
726                     CBigNum bn((uint16_t) stack.size());
727                     stack.push_back(bn.getvch());
728                 }
729                 break;
730
731                 case OP_DROP:
732                 {
733                     // (x -- )
734                     if (stack.size() < 1)
735                         return false;
736                     popstack(stack);
737                 }
738                 break;
739
740                 case OP_DUP:
741                 {
742                     // (x -- x x)
743                     if (stack.size() < 1)
744                         return false;
745                     auto vch = stacktop(-1);
746                     stack.push_back(vch);
747                 }
748                 break;
749
750                 case OP_NIP:
751                 {
752                     // (x1 x2 -- x2)
753                     if (stack.size() < 2)
754                         return false;
755                     stack.erase(stack.end() - 2);
756                 }
757                 break;
758
759                 case OP_OVER:
760                 {
761                     // (x1 x2 -- x1 x2 x1)
762                     if (stack.size() < 2)
763                         return false;
764                     auto vch = stacktop(-2);
765                     stack.push_back(vch);
766                 }
767                 break;
768
769                 case OP_PICK:
770                 case OP_ROLL:
771                 {
772                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
773                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
774                     if (stack.size() < 2)
775                         return false;
776                     int n = CastToBigNum(stacktop(-1)).getint32();
777                     popstack(stack);
778                     if (n < 0 || n >= (int)stack.size())
779                         return false;
780                     auto vch = stacktop(-n-1);
781                     if (opcode == OP_ROLL)
782                         stack.erase(stack.end()-n-1);
783                     stack.push_back(vch);
784                 }
785                 break;
786
787                 case OP_ROT:
788                 {
789                     // (x1 x2 x3 -- x2 x3 x1)
790                     //  x2 x1 x3  after first swap
791                     //  x2 x3 x1  after second swap
792                     if (stack.size() < 3)
793                         return false;
794                     swap(stacktop(-3), stacktop(-2));
795                     swap(stacktop(-2), stacktop(-1));
796                 }
797                 break;
798
799                 case OP_SWAP:
800                 {
801                     // (x1 x2 -- x2 x1)
802                     if (stack.size() < 2)
803                         return false;
804                     swap(stacktop(-2), stacktop(-1));
805                 }
806                 break;
807
808                 case OP_TUCK:
809                 {
810                     // (x1 x2 -- x2 x1 x2)
811                     if (stack.size() < 2)
812                         return false;
813                     auto vch = stacktop(-1);
814                     stack.insert(stack.end()-2, vch);
815                 }
816                 break;
817
818
819                 case OP_SIZE:
820                 {
821                     // (in -- in size)
822                     if (stack.size() < 1)
823                         return false;
824                     CBigNum bn((uint16_t) stacktop(-1).size());
825                     stack.push_back(bn.getvch());
826                 }
827                 break;
828
829
830                 //
831                 // Bitwise logic
832                 //
833                 case OP_EQUAL:
834                 case OP_EQUALVERIFY:
835                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
836                 {
837                     // (x1 x2 - bool)
838                     if (stack.size() < 2)
839                         return false;
840                     auto& vch1 = stacktop(-2);
841                     auto& vch2 = stacktop(-1);
842                     bool fEqual = (vch1 == vch2);
843                     // OP_NOTEQUAL is disabled because it would be too easy to say
844                     // something like n != 1 and have some wiseguy pass in 1 with extra
845                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
846                     //if (opcode == OP_NOTEQUAL)
847                     //    fEqual = !fEqual;
848                     popstack(stack);
849                     popstack(stack);
850                     stack.push_back(fEqual ? vchTrue : vchFalse);
851                     if (opcode == OP_EQUALVERIFY)
852                     {
853                         if (fEqual)
854                             popstack(stack);
855                         else
856                             return false;
857                     }
858                 }
859                 break;
860
861
862                 //
863                 // Numeric
864                 //
865                 case OP_1ADD:
866                 case OP_1SUB:
867                 case OP_NEGATE:
868                 case OP_ABS:
869                 case OP_NOT:
870                 case OP_0NOTEQUAL:
871                 {
872                     // (in -- out)
873                     if (stack.size() < 1)
874                         return false;
875                     auto bn = CastToBigNum(stacktop(-1));
876                     switch (opcode)
877                     {
878                     case OP_1ADD:       bn += bnOne; break;
879                     case OP_1SUB:       bn -= bnOne; break;
880                     case OP_NEGATE:     bn = -bn; break;
881                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
882                     case OP_NOT:        bn = (bn == bnZero); break;
883                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
884                     default:            assert(!"invalid opcode"); break;
885                     }
886                     popstack(stack);
887                     stack.push_back(bn.getvch());
888                 }
889                 break;
890
891                 case OP_ADD:
892                 case OP_SUB:
893                 case OP_BOOLAND:
894                 case OP_BOOLOR:
895                 case OP_NUMEQUAL:
896                 case OP_NUMEQUALVERIFY:
897                 case OP_NUMNOTEQUAL:
898                 case OP_LESSTHAN:
899                 case OP_GREATERTHAN:
900                 case OP_LESSTHANOREQUAL:
901                 case OP_GREATERTHANOREQUAL:
902                 case OP_MIN:
903                 case OP_MAX:
904                 {
905                     // (x1 x2 -- out)
906                     if (stack.size() < 2)
907                         return false;
908                     auto bn1 = CastToBigNum(stacktop(-2));
909                     auto bn2 = CastToBigNum(stacktop(-1));
910                     CBigNum bn;
911                     switch (opcode)
912                     {
913                     case OP_ADD:
914                         bn = bn1 + bn2;
915                         break;
916
917                     case OP_SUB:
918                         bn = bn1 - bn2;
919                         break;
920
921                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
922                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
923                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
924                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
925                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
926                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
927                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
928                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
929                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
930                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
931                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
932                     default:                     assert(!"invalid opcode"); break;
933                     }
934                     popstack(stack);
935                     popstack(stack);
936                     stack.push_back(bn.getvch());
937
938                     if (opcode == OP_NUMEQUALVERIFY)
939                     {
940                         if (CastToBool(stacktop(-1)))
941                             popstack(stack);
942                         else
943                             return false;
944                     }
945                 }
946                 break;
947
948                 case OP_WITHIN:
949                 {
950                     // (x min max -- out)
951                     if (stack.size() < 3)
952                         return false;
953                     auto bn1 = CastToBigNum(stacktop(-3));
954                     auto bn2 = CastToBigNum(stacktop(-2));
955                     auto bn3 = CastToBigNum(stacktop(-1));
956                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
957                     popstack(stack);
958                     popstack(stack);
959                     popstack(stack);
960                     stack.push_back(fValue ? vchTrue : vchFalse);
961                 }
962                 break;
963
964
965                 //
966                 // Crypto
967                 //
968                 case OP_RIPEMD160:
969                 case OP_SHA1:
970                 case OP_SHA256:
971                 case OP_HASH160:
972                 case OP_HASH256:
973                 {
974                     // (in -- hash)
975                     if (stack.size() < 1)
976                         return false;
977                     auto& vch = stacktop(-1);
978                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
979                     if (opcode == OP_RIPEMD160)
980                         RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
981                     else if (opcode == OP_SHA1)
982                         SHA1(&vch[0], vch.size(), &vchHash[0]);
983                     else if (opcode == OP_SHA256)
984                         SHA256(&vch[0], vch.size(), &vchHash[0]);
985                     else if (opcode == OP_HASH160)
986                     {
987                         auto hash160 = Hash160(vch);
988                         memcpy(&vchHash[0], &hash160, sizeof(hash160));
989                     }
990                     else if (opcode == OP_HASH256)
991                     {
992                         auto hash = Hash(vch.begin(), vch.end());
993                         memcpy(&vchHash[0], &hash, sizeof(hash));
994                     }
995                     popstack(stack);
996                     stack.push_back(vchHash);
997                 }
998                 break;
999
1000                 case OP_CODESEPARATOR:
1001                 {
1002                     // Hash starts after the code separator
1003                     pbegincodehash = pc;
1004                 }
1005                 break;
1006
1007                 case OP_CHECKSIG:
1008                 case OP_CHECKSIGVERIFY:
1009                 {
1010                     // (sig pubkey -- bool)
1011                     if (stack.size() < 2)
1012                         return false;
1013
1014                     auto& vchSig    = stacktop(-2);
1015                     auto& vchPubKey = stacktop(-1);
1016
1017                     ////// debug print
1018                     //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1019                     //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1020
1021                     // Subset of script starting at the most recent codeseparator
1022                     CScript scriptCode(pbegincodehash, pend);
1023
1024                     // Drop the signature, since there's no way for a signature to sign itself
1025                     scriptCode.FindAndDelete(CScript(vchSig));
1026
1027                     bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1028                         CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1029
1030                     popstack(stack);
1031                     popstack(stack);
1032                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1033                     if (opcode == OP_CHECKSIGVERIFY)
1034                     {
1035                         if (fSuccess)
1036                             popstack(stack);
1037                         else
1038                             return false;
1039                     }
1040                 }
1041                 break;
1042
1043                 case OP_CHECKMULTISIG:
1044                 case OP_CHECKMULTISIGVERIFY:
1045                 {
1046                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1047
1048                     int i = 1;
1049                     if ((int)stack.size() < i)
1050                         return false;
1051
1052                     int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1053                     if (nKeysCount < 0 || nKeysCount > 20)
1054                         return false;
1055                     nOpCount += nKeysCount;
1056                     if (nOpCount > 201)
1057                         return false;
1058                     int ikey = ++i;
1059                     i += nKeysCount;
1060                     if ((int)stack.size() < i)
1061                         return false;
1062
1063                     int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1064                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1065                         return false;
1066                     int isig = ++i;
1067                     i += nSigsCount;
1068                     if ((int)stack.size() < i)
1069                         return false;
1070
1071                     // Subset of script starting at the most recent codeseparator
1072                     CScript scriptCode(pbegincodehash, pend);
1073
1074                     // Drop the signatures, since there's no way for a signature to sign itself
1075                     for (int k = 0; k < nSigsCount; k++)
1076                     {
1077                         auto& vchSig = stacktop(-isig-k);
1078                         scriptCode.FindAndDelete(CScript(vchSig));
1079                     }
1080
1081                     bool fSuccess = true;
1082                     while (fSuccess && nSigsCount > 0)
1083                     {
1084                         auto& vchSig    = stacktop(-isig);
1085                         auto& vchPubKey = stacktop(-ikey);
1086
1087                         // Check signature
1088                         bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1089                             CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1090
1091                         if (fOk) {
1092                             isig++;
1093                             nSigsCount--;
1094                         }
1095                         ikey++;
1096                         nKeysCount--;
1097
1098                         // If there are more signatures left than keys left,
1099                         // then too many signatures have failed
1100                         if (nSigsCount > nKeysCount)
1101                             fSuccess = false;
1102                     }
1103
1104                     while (i-- > 1)
1105                         popstack(stack);
1106
1107                     // A bug causes CHECKMULTISIG to consume one extra argument
1108                     // whose contents were not checked in any way.
1109                     //
1110                     // Unfortunately this is a potential source of mutability,
1111                     // so optionally verify it is exactly equal to zero prior
1112                     // to removing it from the stack.
1113                     if (stack.size() < 1)
1114                         return false;
1115                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1116                         return error("CHECKMULTISIG dummy argument not null");
1117                     popstack(stack);
1118
1119                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1120
1121                     if (opcode == OP_CHECKMULTISIGVERIFY)
1122                     {
1123                         if (fSuccess)
1124                             popstack(stack);
1125                         else
1126                             return false;
1127                     }
1128                 }
1129                 break;
1130
1131                 default:
1132                     return false;
1133             }
1134
1135             // Size limits
1136             if (stack.size() + altstack.size() > 1000)
1137                 return false;
1138         }
1139     }
1140     catch (...)
1141     {
1142         return false;
1143     }
1144
1145
1146     if (!vfExec.empty())
1147         return false;
1148
1149     return true;
1150 }
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, uint32_t nIn, int nHashType)
1161 {
1162     if (nIn >= txTo.vin.size())
1163     {
1164         printf("ERROR: SignatureHash() : nIn=%" PRIu32 " out of range\n", nIn);
1165         return 1;
1166     }
1167     CTransaction txTmp(txTo);
1168
1169     // In case concatenating two scripts ends up with two codeseparators,
1170     // or an extra one at the end, this prevents all those possible incompatibilities.
1171     scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1172
1173     // Blank out other inputs' signatures
1174     for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1175         txTmp.vin[i].scriptSig = CScript();
1176     txTmp.vin[nIn].scriptSig = scriptCode;
1177
1178     // Blank out some of the outputs
1179     if ((nHashType & 0x1f) == SIGHASH_NONE)
1180     {
1181         // Wildcard payee
1182         txTmp.vout.clear();
1183
1184         // Let the others update at will
1185         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1186             if (i != nIn)
1187                 txTmp.vin[i].nSequence = 0;
1188     }
1189     else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1190     {
1191         // Only lock-in the txout payee at same index as txin
1192         uint32_t nOut = nIn;
1193         if (nOut >= txTmp.vout.size())
1194         {
1195             printf("ERROR: SignatureHash() : nOut=%" PRIu32 " out of range\n", nOut);
1196             return 1;
1197         }
1198         txTmp.vout.resize(nOut+1);
1199         for (unsigned int i = 0; i < nOut; i++)
1200             txTmp.vout[i].SetNull();
1201
1202         // Let the others update at will
1203         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1204             if (i != nIn)
1205                 txTmp.vin[i].nSequence = 0;
1206     }
1207
1208     // Blank out other inputs completely, not recommended for open transactions
1209     if (nHashType & SIGHASH_ANYONECANPAY)
1210     {
1211         txTmp.vin[0] = txTmp.vin[nIn];
1212         txTmp.vin.resize(1);
1213     }
1214
1215     // Serialize and hash
1216     CDataStream ss(SER_GETHASH, 0);
1217     ss.reserve(10000);
1218     ss << txTmp << nHashType;
1219     return Hash(ss.begin(), ss.end());
1220 }
1221
1222
1223 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1224 // twice for every transaction (once when accepted into memory pool, and
1225 // again when accepted into the block chain)
1226
1227 class CSignatureCache
1228 {
1229 private:
1230      // sigdata_type is (signature hash, signature, public key):
1231     typedef tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1232     set< sigdata_type> setValid;
1233     boost::shared_mutex cs_sigcache;
1234
1235 public:
1236     bool
1237     Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1238     {
1239         boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1240
1241         sigdata_type k(hash, vchSig, pubKey);
1242         auto mi = setValid.find(k);
1243         if (mi != setValid.end())
1244             return true;
1245         return false;
1246     }
1247
1248     void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1249     {
1250         // DoS prevention: limit cache size to less than 10MB
1251         // (~200 bytes per cache entry times 50,000 entries)
1252         // Since there are a maximum of 20,000 signature operations per block
1253         // 50,000 is a reasonable default.
1254         int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1255         if (nMaxCacheSize <= 0) return;
1256
1257         boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1258
1259         while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1260         {
1261             // Evict a random entry. Random because that helps
1262             // foil would-be DoS attackers who might try to pre-generate
1263             // and re-use a set of valid signatures just-slightly-greater
1264             // than our cache size.
1265             auto randomHash = GetRandHash();
1266             std::vector<unsigned char> unused;
1267             auto it = setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1268             if (it == setValid.end())
1269                 it = setValid.begin();
1270             setValid.erase(*it);
1271         }
1272
1273         sigdata_type k(hash, vchSig, pubKey);
1274         setValid.insert(k);
1275     }
1276 };
1277
1278 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1279               const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1280 {
1281     static CSignatureCache signatureCache;
1282
1283     CPubKey pubkey(vchPubKey);
1284     if (!pubkey.IsValid())
1285         return false;
1286
1287     // Hash type is one byte tacked on to the end of the signature
1288     if (vchSig.empty())
1289         return false;
1290     if (nHashType == 0)
1291         nHashType = vchSig.back();
1292     else if (nHashType != vchSig.back())
1293         return false;
1294     vchSig.pop_back();
1295
1296     auto sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1297
1298     if (signatureCache.Get(sighash, vchSig, pubkey))
1299         return true;
1300
1301     if (!pubkey.Verify(sighash, vchSig))
1302         return false;
1303
1304     if (!(flags & SCRIPT_VERIFY_NOCACHE))
1305         signatureCache.Set(sighash, vchSig, pubkey);
1306
1307     return true;
1308 }
1309
1310
1311 //
1312 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1313 //
1314 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1315 {
1316     // Templates
1317     static map<txnouttype, CScript> mTemplates;
1318     if (mTemplates.empty())
1319     {
1320         // Standard tx, sender provides pubkey, receiver adds signature
1321         mTemplates.insert({ TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG });
1322
1323         // Malleable pubkey tx hack, sender provides generated pubkey combined with R parameter. The R parameter is dropped before checking a signature.
1324         mTemplates.insert({ TX_PUBKEY_DROP, CScript() << OP_PUBKEY << OP_PUBKEY << OP_DROP << OP_CHECKSIG });
1325
1326         // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1327         mTemplates.insert({ TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG });
1328
1329         // Sender provides N pubkeys, receivers provides M signatures
1330         mTemplates.insert({ TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG });
1331
1332         // Empty, provably prunable, data-carrying output
1333         mTemplates.insert({ TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA });
1334     }
1335
1336     vSolutionsRet.clear();
1337
1338     // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1339     // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1340     if (scriptPubKey.IsPayToScriptHash())
1341     {
1342         typeRet = TX_SCRIPTHASH;
1343         vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1344         vSolutionsRet.push_back(hashBytes);
1345         return true;
1346     }
1347
1348     // Provably prunable, data-carrying output
1349     //
1350     // So long as script passes the IsUnspendable() test and all but the first
1351     // byte passes the IsPushOnly() test we don't care what exactly is in the
1352     // script.
1353     if (scriptPubKey.size() >= 1 && scriptPubKey[0] == OP_RETURN && scriptPubKey.IsPushOnly(scriptPubKey.begin()+1)) {
1354         typeRet = TX_NULL_DATA;
1355         return true;
1356     }
1357
1358     // Scan templates
1359     const auto& script1 = scriptPubKey;
1360     for(const auto& tplate : mTemplates)
1361     {
1362         const auto& script2 = tplate.second;
1363         vSolutionsRet.clear();
1364
1365         opcodetype opcode1, opcode2;
1366         vector<unsigned char> vch1, vch2;
1367
1368         // Compare
1369         auto pc1 = script1.begin();
1370         auto pc2 = script2.begin();
1371         for ( ; ; )
1372         {
1373             if (pc1 == script1.end() && pc2 == script2.end())
1374             {
1375                 // Found a match
1376                 typeRet = tplate.first;
1377                 if (typeRet == TX_MULTISIG)
1378                 {
1379                     // Additional checks for TX_MULTISIG:
1380                     auto m = vSolutionsRet.front()[0];
1381                     auto n = vSolutionsRet.back()[0];
1382                     if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1383                         return false;
1384                 }
1385                 return true;
1386             }
1387             if (!script1.GetOp(pc1, opcode1, vch1))
1388                 break;
1389             if (!script2.GetOp(pc2, opcode2, vch2))
1390                 break;
1391
1392             // Template matching opcodes:
1393             if (opcode2 == OP_PUBKEYS)
1394             {
1395                 while (vch1.size() >= 33 && vch1.size() <= 120)
1396                 {
1397                     vSolutionsRet.push_back(vch1);
1398                     if (!script1.GetOp(pc1, opcode1, vch1))
1399                         break;
1400                 }
1401                 if (!script2.GetOp(pc2, opcode2, vch2))
1402                     break;
1403                 // Normal situation is to fall through
1404                 // to other if/else statements
1405             }
1406
1407             if (opcode2 == OP_PUBKEY)
1408             {
1409                 if (vch1.size() < 33 || vch1.size() > 120)
1410                     break;
1411                 vSolutionsRet.push_back(vch1);
1412             }
1413             else if (opcode2 == OP_PUBKEYHASH)
1414             {
1415                 if (vch1.size() != sizeof(uint160))
1416                     break;
1417                 vSolutionsRet.push_back(vch1);
1418             }
1419             else if (opcode2 == OP_SMALLINTEGER)
1420             {   // Single-byte small integer pushed onto vSolutions
1421                 if (opcode1 == OP_0 ||
1422                     (opcode1 >= OP_1 && opcode1 <= OP_16))
1423                 {
1424                     char n = (char)CScript::DecodeOP_N(opcode1);
1425                     vSolutionsRet.push_back(valtype(1, n));
1426                 }
1427                 else
1428                     break;
1429             }
1430             else if (opcode2 == OP_INTEGER)
1431             {   // Up to four-byte integer pushed onto vSolutions
1432                 try
1433                 {
1434                     auto bnVal = CastToBigNum(vch1);
1435                     if (bnVal <= 16)
1436                         break; // It's better to use OP_0 ... OP_16 for small integers.
1437                     vSolutionsRet.push_back(vch1);
1438                 }
1439                 catch(...)
1440                 {
1441                     break;
1442                 }
1443             }
1444             else if (opcode2 == OP_SMALLDATA)
1445             {
1446                 // small pushdata, <= 1024 bytes
1447                 if (vch1.size() > 1024)
1448                     break;
1449             }
1450             else if (opcode1 != opcode2 || vch1 != vch2)
1451             {
1452                 // Others must match exactly
1453                 break;
1454             }
1455         }
1456     }
1457
1458     vSolutionsRet.clear();
1459     typeRet = TX_NONSTANDARD;
1460     return false;
1461 }
1462
1463
1464 bool Sign1(const CKeyID& address, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1465 {
1466     CKey key;
1467     if (!keystore.GetKey(address, key))
1468         return false;
1469
1470     vector<unsigned char> vchSig;
1471     if (!key.Sign(hash, vchSig))
1472         return false;
1473     vchSig.push_back((unsigned char)nHashType);
1474     scriptSigRet << vchSig;
1475
1476     return true;
1477 }
1478
1479 bool SignR(const CPubKey& pubKey, const CPubKey& R, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1480 {
1481     CKey key;
1482     if (!keystore.CreatePrivKey(pubKey, R, key))
1483         return false;
1484
1485     vector<unsigned char> vchSig;
1486     if (!key.Sign(hash, vchSig))
1487         return false;
1488     vchSig.push_back((unsigned char)nHashType);
1489     scriptSigRet << vchSig;
1490
1491     return true;
1492 }
1493
1494 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, const uint256& hash, int nHashType, CScript& scriptSigRet)
1495 {
1496     int nSigned = 0;
1497     int nRequired = multisigdata.front()[0];
1498     for (uint32_t i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1499     {
1500         const auto& pubkey = multisigdata[i];
1501         auto keyID = CPubKey(pubkey).GetID();
1502         if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1503             ++nSigned;
1504     }
1505     return nSigned==nRequired;
1506 }
1507
1508 //
1509 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1510 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1511 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1512 // Returns false if scriptPubKey could not be completely satisfied.
1513 //
1514 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, const uint256& hash, int nHashType,
1515                   CScript& scriptSigRet, txnouttype& whichTypeRet)
1516 {
1517     scriptSigRet.clear();
1518
1519     vector<valtype> vSolutions;
1520     if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1521         return false;
1522
1523     CKeyID keyID;
1524     switch (whichTypeRet)
1525     {
1526     case TX_NONSTANDARD:
1527     case TX_NULL_DATA:
1528         return false;
1529     case TX_PUBKEY:
1530         keyID = CPubKey(vSolutions[0]).GetID();
1531         return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1532     case TX_PUBKEY_DROP:
1533         {
1534             auto key = CPubKey(vSolutions[0]);
1535             auto R = CPubKey(vSolutions[1]);
1536             return SignR(key, R, keystore, hash, nHashType, scriptSigRet);
1537         }
1538     case TX_PUBKEYHASH:
1539         keyID = CKeyID(uint160(vSolutions[0]));
1540         if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1541             return false;
1542         else
1543         {
1544             CPubKey vch;
1545             keystore.GetPubKey(keyID, vch);
1546             scriptSigRet << vch;
1547         }
1548         return true;
1549     case TX_SCRIPTHASH:
1550         return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1551
1552     case TX_MULTISIG:
1553         scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1554         return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1555     }
1556     return false;
1557 }
1558
1559 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1560 {
1561     switch (t)
1562     {
1563     case TX_NONSTANDARD:
1564         return -1;
1565     case TX_NULL_DATA:
1566         return 1;
1567     case TX_PUBKEY:
1568     case TX_PUBKEY_DROP:
1569         return 1;
1570     case TX_PUBKEYHASH:
1571         return 2;
1572     case TX_MULTISIG:
1573         if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1574             return -1;
1575         return vSolutions[0][0] + 1;
1576     case TX_SCRIPTHASH:
1577         return 1; // doesn't include args needed by the script
1578     }
1579     return -1;
1580 }
1581
1582 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1583 {
1584     vector<valtype> vSolutions;
1585     if (!Solver(scriptPubKey, whichType, vSolutions))
1586         return false;
1587
1588     if (whichType == TX_MULTISIG)
1589     {
1590         unsigned char m = vSolutions.front()[0];
1591         unsigned char n = vSolutions.back()[0];
1592         // Support up to x-of-3 multisig txns as standard
1593         if (n < 1 || n > 3)
1594             return false;
1595         if (m < 1 || m > n)
1596             return false;
1597     }
1598
1599     return whichType != TX_NONSTANDARD;
1600 }
1601
1602
1603 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1604 {
1605     uint32_t nResult = 0;
1606     for(const auto& pubkey :  pubkeys)
1607     {
1608         auto keyID = CPubKey(pubkey).GetID();
1609         if (keystore.HaveKey(keyID))
1610             ++nResult;
1611     }
1612     return nResult;
1613 }
1614
1615
1616 class CKeyStoreIsMineVisitor : public boost::static_visitor<bool>
1617 {
1618 private:
1619     const CKeyStore *keystore;
1620 public:
1621     CKeyStoreIsMineVisitor(const CKeyStore *keystoreIn) : keystore(keystoreIn) { }
1622     bool operator()(const CNoDestination &dest) const { return false; }
1623     bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); }
1624     bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); }
1625 };
1626
1627 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1628 {
1629     CScript script;
1630     script.SetAddress(dest);
1631     return IsMine(keystore, script);
1632 }
1633
1634 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1635 {
1636     vector<valtype> vSolutions;
1637     txnouttype whichType;
1638     if (!Solver(scriptPubKey, whichType, vSolutions)) {
1639         if (keystore.HaveWatchOnly(scriptPubKey))
1640             return MINE_WATCH_ONLY;
1641         return MINE_NO;
1642     }
1643
1644     CKeyID keyID;
1645     switch (whichType)
1646     {
1647     case TX_NONSTANDARD:
1648     case TX_NULL_DATA:
1649         break;
1650     case TX_PUBKEY:
1651         keyID = CPubKey(vSolutions[0]).GetID();
1652         if (keystore.HaveKey(keyID))
1653             return MINE_SPENDABLE;
1654         break;
1655     case TX_PUBKEY_DROP:
1656         {
1657             auto key = CPubKey(vSolutions[0]);
1658             auto R = CPubKey(vSolutions[1]);
1659             if (keystore.CheckOwnership(key, R))
1660                 return MINE_SPENDABLE;
1661         }
1662         break;
1663     case TX_PUBKEYHASH:
1664         keyID = CKeyID(uint160(vSolutions[0]));
1665         if (keystore.HaveKey(keyID))
1666             return MINE_SPENDABLE;
1667         break;
1668     case TX_SCRIPTHASH:
1669     {
1670         auto scriptID = CScriptID(uint160(vSolutions[0]));
1671         CScript subscript;
1672         if (keystore.GetCScript(scriptID, subscript)) {
1673             auto ret = IsMine(keystore, subscript);
1674             if (ret == MINE_SPENDABLE)
1675                 return ret;
1676         }
1677         break;
1678     }
1679     case TX_MULTISIG:
1680     {
1681         // Only consider transactions "mine" if we own ALL the
1682         // keys involved. multi-signature transactions that are
1683         // partially owned (somebody else has a key that can spend
1684         // them) enable spend-out-from-under-you attacks, especially
1685         // in shared-wallet situations.
1686         vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1687         if (HaveKeys(keys, keystore) == keys.size())
1688             return MINE_SPENDABLE;
1689         break;
1690     }
1691     }
1692
1693     if (keystore.HaveWatchOnly(scriptPubKey))
1694         return MINE_WATCH_ONLY;
1695     return MINE_NO;
1696 }
1697
1698 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1699 {
1700     vector<valtype> vSolutions;
1701     txnouttype whichType;
1702     if (!Solver(scriptPubKey, whichType, vSolutions))
1703         return false;
1704
1705     if (whichType == TX_PUBKEY)
1706     {
1707         addressRet = CPubKey(vSolutions[0]).GetID();
1708         return true;
1709     }
1710     else if (whichType == TX_PUBKEYHASH)
1711     {
1712         addressRet = CKeyID(uint160(vSolutions[0]));
1713         return true;
1714     }
1715     else if (whichType == TX_SCRIPTHASH)
1716     {
1717         addressRet = CScriptID(uint160(vSolutions[0]));
1718         return true;
1719     }
1720     // Multisig txns have more than one address...
1721     return false;
1722 }
1723
1724 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1725 {
1726     vector<valtype> vSolutions;
1727     txnouttype whichType;
1728     if (!Solver(scriptPubKey, whichType, vSolutions))
1729         return false;
1730
1731     if (whichType == TX_PUBKEY)
1732     {
1733         addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1734         return true;
1735     }
1736     if (whichType == TX_PUBKEY_DROP)
1737     {
1738         // Pay-to-Pubkey-R
1739         CMalleableKeyView view;
1740         if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1741             return false;
1742
1743         addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1744         return true;
1745     }
1746     else if (whichType == TX_PUBKEYHASH)
1747     {
1748         addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1749         return true;
1750     }
1751     else if (whichType == TX_SCRIPTHASH)
1752     {
1753         addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1754         return true;
1755     }
1756     // Multisig txns have more than one address...
1757     return false;
1758 }
1759
1760 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1761 private:
1762     const CKeyStore &keystore;
1763     CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1764     std::vector<CKeyID> &vKeys;
1765
1766 public:
1767     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1768
1769     void Process(const CScript &script) {
1770         txnouttype type;
1771         std::vector<CTxDestination> vDest;
1772         int nRequired;
1773         if (ExtractDestinations(script, type, vDest, nRequired)) {
1774             for(const CTxDestination &dest :  vDest)
1775                 boost::apply_visitor(*this, dest);
1776         }
1777     }
1778
1779     void operator()(const CKeyID &keyId) {
1780         if (keystore.HaveKey(keyId))
1781             vKeys.push_back(keyId);
1782     }
1783
1784     void operator()(const CScriptID &scriptId) {
1785         CScript script;
1786         if (keystore.GetCScript(scriptId, script))
1787             Process(script);
1788     }
1789
1790     void operator()(const CNoDestination &none) {}
1791 };
1792
1793
1794 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1795     CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1796 }
1797
1798 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1799 {
1800     addressRet.clear();
1801     typeRet = TX_NONSTANDARD;
1802     vector<valtype> vSolutions;
1803     if (!Solver(scriptPubKey, typeRet, vSolutions))
1804         return false;
1805     if (typeRet == TX_NULL_DATA)
1806     {
1807         nRequiredRet = 0;
1808         return true;
1809     }
1810
1811     if (typeRet == TX_MULTISIG)
1812     {
1813         nRequiredRet = vSolutions.front()[0];
1814         for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1815         {
1816             CTxDestination address = CPubKey(vSolutions[i]).GetID();
1817             addressRet.push_back(address);
1818         }
1819     }
1820     else
1821     {
1822         nRequiredRet = 1;
1823         if (typeRet == TX_PUBKEY_DROP)
1824             return true;
1825         CTxDestination address;
1826         if (!ExtractDestination(scriptPubKey, address))
1827            return false;
1828         addressRet.push_back(address);
1829     }
1830
1831     return true;
1832 }
1833
1834 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn, unsigned int flags, int nHashType)
1835 {
1836     vector<vector<unsigned char> > stack, stackCopy;
1837     if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1838         return false;
1839     if (flags & SCRIPT_VERIFY_P2SH)
1840         stackCopy = stack;
1841     if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1842         return false;
1843     if (stack.empty())
1844         return false;
1845
1846     if (CastToBool(stack.back()) == false)
1847         return false;
1848
1849     // Additional validation for spend-to-script-hash transactions:
1850     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1851     {
1852         if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1853             return false;            // or validation fails
1854
1855         // stackCopy cannot be empty here, because if it was the
1856         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1857         // an empty stack and the EvalScript above would return false.
1858         assert(!stackCopy.empty());
1859
1860         const auto& pubKeySerialized = stackCopy.back();
1861         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1862         popstack(stackCopy);
1863
1864         if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1865             return false;
1866         if (stackCopy.empty())
1867             return false;
1868         return CastToBool(stackCopy.back());
1869     }
1870
1871     return true;
1872 }
1873
1874 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, uint32_t nIn, int nHashType)
1875 {
1876     assert(nIn < txTo.vin.size());
1877     auto& txin = txTo.vin[nIn];
1878
1879     // Leave out the signature from the hash, since a signature can't sign itself.
1880     // The checksig op will also drop the signatures from its hash.
1881     auto hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1882
1883     txnouttype whichType;
1884     if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1885         return false;
1886
1887     if (whichType == TX_SCRIPTHASH)
1888     {
1889         // Solver returns the subscript that need to be evaluated;
1890         // the final scriptSig is the signatures from that
1891         // and then the serialized subscript:
1892         auto subscript = txin.scriptSig;
1893
1894         // Recompute txn hash using subscript in place of scriptPubKey:
1895         auto hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1896
1897         txnouttype subType;
1898         bool fSolved = Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1899         // Append serialized subscript whether or not it is completely signed:
1900         txin.scriptSig << static_cast<valtype>(subscript);
1901         if (!fSolved) return false;
1902     }
1903
1904     // Test solution
1905     return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1906 }
1907
1908 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, uint32_t nIn, int nHashType)
1909 {
1910     assert(nIn < txTo.vin.size());
1911     auto& txin = txTo.vin[nIn];
1912     assert(txin.prevout.n < txFrom.vout.size());
1913     assert(txin.prevout.hash == txFrom.GetHash());
1914     const auto& txout = txFrom.vout[txin.prevout.n];
1915
1916     return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1917 }
1918
1919 static CScript PushAll(const vector<valtype>& values)
1920 {
1921     CScript result;
1922     for(const auto& v :  values)
1923         result << v;
1924     return result;
1925 }
1926
1927 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1928                                const vector<valtype>& vSolutions,
1929                                vector<valtype>& sigs1, vector<valtype>& sigs2)
1930 {
1931     // Combine all the signatures we've got:
1932     set<valtype> allsigs;
1933     for(const auto& v :  sigs1)
1934     {
1935         if (!v.empty())
1936             allsigs.insert(v);
1937     }
1938     for(const auto& v :  sigs2)
1939     {
1940         if (!v.empty())
1941             allsigs.insert(v);
1942     }
1943
1944     // Build a map of pubkey -> signature by matching sigs to pubkeys:
1945     assert(vSolutions.size() > 1);
1946     auto nSigsRequired = (uint32_t)vSolutions.front()[0];
1947     auto nPubKeys = (uint32_t)(vSolutions.size()-2);
1948
1949     map<valtype, valtype> sigs;
1950     for(const auto& sig :  allsigs)
1951     {
1952         for (unsigned int i = 0; i < nPubKeys; i++)
1953         {
1954             const auto& pubkey = vSolutions[i+1];
1955             if (sigs.count(pubkey))
1956                 continue; // Already got a sig for this pubkey
1957
1958             if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1959             {
1960                 sigs[pubkey] = sig;
1961                 break;
1962             }
1963         }
1964     }
1965     // Now build a merged CScript:
1966     uint32_t nSigsHave = 0;
1967     CScript result; result << OP_0; // pop-one-too-many workaround
1968     for (uint32_t i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1969     {
1970         if (sigs.count(vSolutions[i+1]))
1971         {
1972             result << sigs[vSolutions[i+1]];
1973             ++nSigsHave;
1974         }
1975     }
1976     // Fill any missing with OP_0:
1977     for (auto i = nSigsHave; i < nSigsRequired; i++)
1978         result << OP_0;
1979
1980     return result;
1981 }
1982
1983 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1984                                  const txnouttype txType, const vector<valtype>& vSolutions,
1985                                  vector<valtype>& sigs1, vector<valtype>& sigs2)
1986 {
1987     switch (txType)
1988     {
1989     case TX_NONSTANDARD:
1990     case TX_NULL_DATA:
1991         // Don't know anything about this, assume bigger one is correct:
1992         if (sigs1.size() >= sigs2.size())
1993             return PushAll(sigs1);
1994         return PushAll(sigs2);
1995     case TX_PUBKEY:
1996     case TX_PUBKEY_DROP:
1997     case TX_PUBKEYHASH:
1998         // Signatures are bigger than placeholders or empty scripts:
1999         if (sigs1.empty() || sigs1[0].empty())
2000             return PushAll(sigs2);
2001         return PushAll(sigs1);
2002     case TX_SCRIPTHASH:
2003         if (sigs1.empty() || sigs1.back().empty())
2004             return PushAll(sigs2);
2005         else if (sigs2.empty() || sigs2.back().empty())
2006             return PushAll(sigs1);
2007         else
2008         {
2009             // Recur to combine:
2010             auto spk = sigs1.back();
2011             CScript pubKey2(spk.begin(), spk.end());
2012
2013             txnouttype txType2;
2014             vector<vector<unsigned char> > vSolutions2;
2015             Solver(pubKey2, txType2, vSolutions2);
2016             sigs1.pop_back();
2017             sigs2.pop_back();
2018             auto result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2019             result << spk;
2020             return result;
2021         }
2022     case TX_MULTISIG:
2023         return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2024     }
2025
2026     return CScript();
2027 }
2028
2029 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, uint32_t nIn,
2030                           const CScript& scriptSig1, const CScript& scriptSig2)
2031 {
2032     txnouttype txType;
2033     vector<vector<unsigned char> > vSolutions;
2034     Solver(scriptPubKey, txType, vSolutions);
2035
2036     vector<valtype> stack1;
2037     EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2038     vector<valtype> stack2;
2039     EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2040
2041     return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2042 }
2043
2044 //
2045 //CScript
2046 //
2047
2048 CScript& CScript::push_int64(int64_t n)
2049 {
2050     if (n == -1 || (n >= 1 && n <= 16))
2051     {
2052         push_back((uint8_t)n + (OP_1 - 1));
2053     }
2054     else
2055     {
2056         CBigNum bn(n);
2057         *this << bn.getvch();
2058     }
2059     return *this;
2060 }
2061
2062 CScript& CScript::push_uint64(uint64_t n)
2063 {
2064     if (n >= 1 && n <= 16)
2065     {
2066         push_back((uint8_t)n + (OP_1 - 1));
2067     }
2068     else
2069     {
2070         CBigNum bn(n);
2071         *this << bn.getvch();
2072     }
2073     return *this;
2074 }
2075
2076 CScript& CScript::operator+=(const CScript& b)
2077 {
2078     insert(end(), b.begin(), b.end());
2079     return *this;
2080 }
2081
2082 CScript& CScript::operator<<(opcodetype opcode)
2083 {
2084     insert(end(), opcode);
2085     return *this;
2086 }
2087
2088 CScript& CScript::operator<<(const uint160& b)
2089 {
2090     insert(end(), sizeof(b));
2091     insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2092     return *this;
2093 }
2094
2095 CScript& CScript::operator<<(const uint256& b)
2096 {
2097     insert(end(), sizeof(b));
2098     insert(end(), (uint8_t*)&b, (uint8_t*)&b + sizeof(b));
2099     return *this;
2100 }
2101
2102 CScript& CScript::operator<<(const CPubKey& key)
2103 {
2104     std::vector<uint8_t> vchKey(key.begin(), key.end());
2105     return (*this) << vchKey;
2106 }
2107
2108 CScript& CScript::operator<<(const CBigNum& b)
2109 {
2110     *this << b.getvch();
2111     return *this;
2112 }
2113
2114 CScript& CScript::operator<<(const std::vector<uint8_t>& b)
2115 {
2116     if (b.size() < OP_PUSHDATA1)
2117     {
2118         insert(end(), (uint8_t)b.size());
2119     }
2120     else if (b.size() <= 0xff)
2121     {
2122         insert(end(), OP_PUSHDATA1);
2123         insert(end(), (uint8_t)b.size());
2124     }
2125     else if (b.size() <= 0xffff)
2126     {
2127         insert(end(), OP_PUSHDATA2);
2128         uint16_t nSize = (uint16_t) b.size();
2129         insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2130     }
2131     else
2132     {
2133         insert(end(), OP_PUSHDATA4);
2134         uint32_t nSize = (uint32_t) b.size();
2135         insert(end(), (uint8_t*)&nSize, (uint8_t*)&nSize + sizeof(nSize));
2136     }
2137     insert(end(), b.begin(), b.end());
2138     return *this;
2139 }
2140
2141 CScript& CScript::operator<<(const CScript& b)
2142 {
2143     // I'm not sure if this should push the script or concatenate scripts.
2144     // If there's ever a use for pushing a script onto a script, delete this member fn
2145     assert(!"Warning: Pushing a CScript onto a CScript with << is probably not intended, use + to concatenate!");
2146     return *this;
2147 }
2148
2149 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet)
2150 {
2151      // Wrapper so it can be called with either iterator or const_iterator
2152      const_iterator pc2 = pc;
2153      bool fRet = GetOp2(pc2, opcodeRet, &vchRet);
2154      pc = begin() + (pc2 - begin());
2155      return fRet;
2156 }
2157
2158 bool CScript::GetOp(iterator& pc, opcodetype& opcodeRet)
2159 {
2160      const_iterator pc2 = pc;
2161      bool fRet = GetOp2(pc2, opcodeRet, NULL);
2162      pc = begin() + (pc2 - begin());
2163      return fRet;
2164 }
2165
2166 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>& vchRet) const
2167 {
2168     return GetOp2(pc, opcodeRet, &vchRet);
2169 }
2170
2171 bool CScript::GetOp(const_iterator& pc, opcodetype& opcodeRet) const
2172 {
2173     return GetOp2(pc, opcodeRet, NULL);
2174 }
2175
2176 bool CScript::GetOp2(const_iterator& pc, opcodetype& opcodeRet, std::vector<uint8_t>* pvchRet) const
2177 {
2178     opcodeRet = OP_INVALIDOPCODE;
2179     if (pvchRet)
2180         pvchRet->clear();
2181     if (pc >= end())
2182         return false;
2183
2184     // Read instruction
2185     if (end() - pc < 1)
2186         return false;
2187     uint32_t opcode = *pc++;
2188
2189     // Immediate operand
2190     if (opcode <= OP_PUSHDATA4)
2191     {
2192         uint32_t nSize = OP_0;
2193         if (opcode < OP_PUSHDATA1)
2194         {
2195             nSize = opcode;
2196         }
2197         else if (opcode == OP_PUSHDATA1)
2198         {
2199             if (end() - pc < 1)
2200                 return false;
2201             nSize = *pc++;
2202         }
2203         else if (opcode == OP_PUSHDATA2)
2204         {
2205             if (end() - pc < 2)
2206                 return false;
2207             memcpy(&nSize, &pc[0], 2);
2208             pc += 2;
2209         }
2210         else if (opcode == OP_PUSHDATA4)
2211         {
2212             if (end() - pc < 4)
2213                 return false;
2214             memcpy(&nSize, &pc[0], 4);
2215             pc += 4;
2216         }
2217         if (end() - pc < 0 || (uint32_t)(end() - pc) < nSize)
2218             return false;
2219         if (pvchRet)
2220             pvchRet->assign(pc, pc + nSize);
2221         pc += nSize;
2222     }
2223
2224     opcodeRet = (opcodetype)opcode;
2225     return true;
2226 }
2227
2228 int CScript::DecodeOP_N(opcodetype opcode)
2229 {
2230     if (opcode == OP_0)
2231         return 0;
2232     assert(opcode >= OP_1 && opcode <= OP_16);
2233     return (opcode - (OP_1 - 1));
2234 }
2235
2236 opcodetype CScript::EncodeOP_N(int n)
2237 {
2238     assert(n >= 0 && n <= 16);
2239     if (n == 0)
2240         return OP_0;
2241     return (opcodetype)(OP_1+n-1);
2242 }
2243
2244 int CScript::FindAndDelete(const CScript& b)
2245 {
2246     int nFound = 0;
2247     if (b.empty())
2248         return nFound;
2249     CScript result;
2250     iterator pc = begin(), pc2 = begin();
2251     opcodetype opcode;
2252     do
2253     {
2254         result.insert(result.end(), pc2, pc);
2255         while (static_cast<size_t>(end() - pc) >= b.size() && equal(b.begin(), b.end(), pc))
2256         {
2257             pc = pc + b.size();
2258             ++nFound;
2259         }
2260         pc2 = pc;
2261     }
2262     while (GetOp(pc, opcode));
2263
2264     if (nFound > 0) {
2265         result.insert(result.end(), pc2, end());
2266         *this = result;
2267     }
2268     return nFound;
2269 }
2270
2271 int CScript::Find(opcodetype op) const
2272 {
2273     int nFound = 0;
2274     opcodetype opcode;
2275     for (const_iterator pc = begin(); pc != end() && GetOp(pc, opcode);)
2276         if (opcode == op)
2277             ++nFound;
2278     return nFound;
2279 }
2280
2281 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2282 {
2283     uint32_t n = 0;
2284     auto pc = begin();
2285     auto lastOpcode = OP_INVALIDOPCODE;
2286     while (pc < end())
2287     {
2288         opcodetype opcode;
2289         if (!GetOp(pc, opcode))
2290             break;
2291         if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2292             n++;
2293         else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2294         {
2295             if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2296                 n += DecodeOP_N(lastOpcode);
2297             else
2298                 n += 20;
2299         }
2300         lastOpcode = opcode;
2301     }
2302     return n;
2303 }
2304
2305 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2306 {
2307     if (!IsPayToScriptHash())
2308         return GetSigOpCount(true);
2309
2310     // This is a pay-to-script-hash scriptPubKey;
2311     // get the last item that the scriptSig
2312     // pushes onto the stack:
2313     auto pc = scriptSig.begin();
2314     vector<unsigned char> data;
2315     while (pc < scriptSig.end())
2316     {
2317         opcodetype opcode;
2318         if (!scriptSig.GetOp(pc, opcode, data))
2319             return 0;
2320         if (opcode > OP_16)
2321             return 0;
2322     }
2323
2324     /// ... and return its opcount:
2325     CScript subscript(data.begin(), data.end());
2326     return subscript.GetSigOpCount(true);
2327 }
2328
2329 bool CScript::IsPayToScriptHash() const
2330 {
2331     // Extra-fast test for pay-to-script-hash CScripts:
2332     return (this->size() == 23 &&
2333             this->at(0) == OP_HASH160 &&
2334             this->at(1) == 0x14 &&
2335             this->at(22) == OP_EQUAL);
2336 }
2337
2338 bool CScript::IsPushOnly(const_iterator pc) const
2339 {
2340     while (pc < end())
2341     {
2342         opcodetype opcode;
2343         if (!GetOp(pc, opcode))
2344             return false;
2345         if (opcode > OP_16)
2346             return false;
2347     }
2348     return true;
2349 }
2350
2351 // Called by CTransaction::IsStandard and P2SH VerifyScript (which makes it consensus-critical).
2352 bool CScript::IsPushOnly() const
2353 {
2354     return this->IsPushOnly(begin());
2355 }
2356
2357 bool CScript::HasCanonicalPushes() const
2358 {
2359     auto pc = begin();
2360     while (pc < end())
2361     {
2362         opcodetype opcode;
2363         std::vector<unsigned char> data;
2364         if (!GetOp(pc, opcode, data))
2365             return false;
2366         if (opcode > OP_16)
2367             continue;
2368         if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2369             // Could have used an OP_n code, rather than a 1-byte push.
2370             return false;
2371         if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2372             // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2373             return false;
2374         if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2375             // Could have used an OP_PUSHDATA1.
2376             return false;
2377         if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2378             // Could have used an OP_PUSHDATA2.
2379             return false;
2380     }
2381     return true;
2382 }
2383
2384 class CScriptVisitor : public boost::static_visitor<bool>
2385 {
2386 private:
2387     CScript *script;
2388 public:
2389     CScriptVisitor(CScript *scriptin) { script = scriptin; }
2390
2391     bool operator()(const CNoDestination &dest) const {
2392         script->clear();
2393         return false;
2394     }
2395
2396     bool operator()(const CKeyID &keyID) const {
2397         script->clear();
2398         *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2399         return true;
2400     }
2401
2402     bool operator()(const CScriptID &scriptID) const {
2403         script->clear();
2404         *script << OP_HASH160 << scriptID << OP_EQUAL;
2405         return true;
2406     }
2407 };
2408
2409 void CScript::SetDestination(const CTxDestination& dest)
2410 {
2411     boost::apply_visitor(CScriptVisitor(this), dest);
2412 }
2413
2414 void CScript::SetAddress(const CBitcoinAddress& dest)
2415 {
2416     this->clear();
2417     if (dest.IsScript())
2418         *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2419     else if (dest.IsPubKey())
2420         *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2421     else if (dest.IsPair()) {
2422         // Pubkey pair address, going to generate
2423         //   new one-time public key.
2424         CMalleablePubKey mpk;
2425         if (!mpk.setvch(dest.GetData()))
2426             return;
2427         CPubKey R, pubKeyVariant;
2428         mpk.GetVariant(R, pubKeyVariant);
2429         *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2430     }
2431 }
2432
2433 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2434 {
2435     this->clear();
2436
2437     *this << EncodeOP_N(nRequired);
2438     for(const auto& key :  keys)
2439         *this << key;
2440     *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2441 }
2442
2443 void CScript::PrintHex() const
2444 {
2445     printf("CScript(%s)\n", HexStr(begin(), end(), true).c_str());
2446 }
2447
2448 std::string CScript::ToString(bool fShort) const
2449 {
2450     std::string str;
2451     opcodetype opcode;
2452     std::vector<uint8_t> vch;
2453     const_iterator pc = begin();
2454     while (pc < end())
2455     {
2456         if (!str.empty())
2457             str += " ";
2458         if (!GetOp(pc, opcode, vch))
2459         {
2460             str += "[error]";
2461             return str;
2462         }
2463         if (opcode <= OP_PUSHDATA4)
2464             str += fShort? ValueString(vch).substr(0, 10) : ValueString(vch);
2465         else
2466             str += GetOpName(opcode);
2467     }
2468     return str;
2469 }
2470
2471 void CScript::print() const
2472 {
2473     printf("%s\n", ToString().c_str());
2474 }
2475
2476 CScriptID CScript::GetID() const
2477 {
2478     return CScriptID(Hash160(*this));
2479 }