736fdb03e7b1843236bde7b04c16e88b2ad216a1
[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 #include "base58.h"
14
15 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
16
17 static const valtype vchFalse(0);
18 static const valtype vchZero(0);
19 static const valtype vchTrue(1, 1);
20 static const CBigNum bnZero(0);
21 static const CBigNum bnOne(1);
22 static const CBigNum bnFalse(0);
23 static const CBigNum bnTrue(1);
24 static const size_t nMaxNumSize = 4;
25
26
27 CBigNum CastToBigNum(const valtype& vch)
28 {
29     if (vch.size() > nMaxNumSize)
30         throw std::runtime_error("CastToBigNum() : overflow");
31     // Get rid of extra leading zeros
32     return CBigNum(CBigNum(vch).getvch());
33 }
34
35 bool CastToBool(const valtype& vch)
36 {
37     for (unsigned int i = 0; i < vch.size(); i++)
38     {
39         if (vch[i] != 0)
40         {
41             // Can be negative zero
42             if (i == vch.size()-1 && vch[i] == 0x80)
43                 return false;
44             return true;
45         }
46     }
47     return false;
48 }
49
50 //
51 // WARNING: This does not work as expected for signed integers; the sign-bit
52 // is left in place as the integer is zero-extended. The correct behavior
53 // would be to move the most significant bit of the last byte during the
54 // resize process. MakeSameSize() is currently only used by the disabled
55 // opcodes OP_AND, OP_OR, and OP_XOR.
56 //
57 void MakeSameSize(valtype& vch1, valtype& vch2)
58 {
59     // Lengthen the shorter one
60     if (vch1.size() < vch2.size())
61         // PATCH:
62         // +unsigned char msb = vch1[vch1.size()-1];
63         // +vch1[vch1.size()-1] &= 0x7f;
64         //  vch1.resize(vch2.size(), 0);
65         // +vch1[vch1.size()-1] = msb;
66         vch1.resize(vch2.size(), 0);
67     if (vch2.size() < vch1.size())
68         // PATCH:
69         // +unsigned char msb = vch2[vch2.size()-1];
70         // +vch2[vch2.size()-1] &= 0x7f;
71         //  vch2.resize(vch1.size(), 0);
72         // +vch2[vch2.size()-1] = msb;
73         vch2.resize(vch1.size(), 0);
74 }
75
76
77
78 //
79 // Script is a stack machine (like Forth) that evaluates a predicate
80 // returning a bool indicating valid or not.  There are no loops.
81 //
82 #define stacktop(i)  (stack.at(stack.size()+(i)))
83 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
84 static inline void popstack(std::vector<valtype>& stack)
85 {
86     if (stack.empty())
87         throw std::runtime_error("popstack() : stack empty");
88     stack.pop_back();
89 }
90
91
92 const char* GetTxnOutputType(txnouttype t)
93 {
94     switch (t)
95     {
96     case TX_NONSTANDARD: return "nonstandard";
97     case TX_PUBKEY: return "pubkey";
98     case TX_PUBKEY_DROP: return "pubkeydrop";
99     case TX_PUBKEYHASH: return "pubkeyhash";
100     case TX_SCRIPTHASH: return "scripthash";
101     case TX_MULTISIG: return "multisig";
102     case TX_NULL_DATA: return "nulldata";
103     }
104     return NULL;
105 }
106
107
108 const char* GetOpName(opcodetype opcode)
109 {
110     switch (opcode)
111     {
112     // push value
113     case OP_0                      : return "0";
114     case OP_PUSHDATA1              : return "OP_PUSHDATA1";
115     case OP_PUSHDATA2              : return "OP_PUSHDATA2";
116     case OP_PUSHDATA4              : return "OP_PUSHDATA4";
117     case OP_1NEGATE                : return "-1";
118     case OP_RESERVED               : return "OP_RESERVED";
119     case OP_1                      : return "1";
120     case OP_2                      : return "2";
121     case OP_3                      : return "3";
122     case OP_4                      : return "4";
123     case OP_5                      : return "5";
124     case OP_6                      : return "6";
125     case OP_7                      : return "7";
126     case OP_8                      : return "8";
127     case OP_9                      : return "9";
128     case OP_10                     : return "10";
129     case OP_11                     : return "11";
130     case OP_12                     : return "12";
131     case OP_13                     : return "13";
132     case OP_14                     : return "14";
133     case OP_15                     : return "15";
134     case OP_16                     : return "16";
135
136     // control
137     case OP_NOP                    : return "OP_NOP";
138     case OP_VER                    : return "OP_VER";
139     case OP_IF                     : return "OP_IF";
140     case OP_NOTIF                  : return "OP_NOTIF";
141     case OP_VERIF                  : return "OP_VERIF";
142     case OP_VERNOTIF               : return "OP_VERNOTIF";
143     case OP_ELSE                   : return "OP_ELSE";
144     case OP_ENDIF                  : return "OP_ENDIF";
145     case OP_VERIFY                 : return "OP_VERIFY";
146     case OP_RETURN                 : return "OP_RETURN";
147     case OP_CHECKLOCKTIMEVERIFY    : return "OP_CHECKLOCKTIMEVERIFY";
148     case OP_CHECKSEQUENCEVERIFY    : return "OP_CHECKSEQUENCEVERIFY";
149
150     // stack ops
151     case OP_TOALTSTACK             : return "OP_TOALTSTACK";
152     case OP_FROMALTSTACK           : return "OP_FROMALTSTACK";
153     case OP_2DROP                  : return "OP_2DROP";
154     case OP_2DUP                   : return "OP_2DUP";
155     case OP_3DUP                   : return "OP_3DUP";
156     case OP_2OVER                  : return "OP_2OVER";
157     case OP_2ROT                   : return "OP_2ROT";
158     case OP_2SWAP                  : return "OP_2SWAP";
159     case OP_IFDUP                  : return "OP_IFDUP";
160     case OP_DEPTH                  : return "OP_DEPTH";
161     case OP_DROP                   : return "OP_DROP";
162     case OP_DUP                    : return "OP_DUP";
163     case OP_NIP                    : return "OP_NIP";
164     case OP_OVER                   : return "OP_OVER";
165     case OP_PICK                   : return "OP_PICK";
166     case OP_ROLL                   : return "OP_ROLL";
167     case OP_ROT                    : return "OP_ROT";
168     case OP_SWAP                   : return "OP_SWAP";
169     case OP_TUCK                   : return "OP_TUCK";
170
171     // splice ops
172     case OP_CAT                    : return "OP_CAT";
173     case OP_SUBSTR                 : return "OP_SUBSTR";
174     case OP_LEFT                   : return "OP_LEFT";
175     case OP_RIGHT                  : return "OP_RIGHT";
176     case OP_SIZE                   : return "OP_SIZE";
177
178     // bit logic
179     case OP_INVERT                 : return "OP_INVERT";
180     case OP_AND                    : return "OP_AND";
181     case OP_OR                     : return "OP_OR";
182     case OP_XOR                    : return "OP_XOR";
183     case OP_EQUAL                  : return "OP_EQUAL";
184     case OP_EQUALVERIFY            : return "OP_EQUALVERIFY";
185     case OP_RESERVED1              : return "OP_RESERVED1";
186     case OP_RESERVED2              : return "OP_RESERVED2";
187
188     // numeric
189     case OP_1ADD                   : return "OP_1ADD";
190     case OP_1SUB                   : return "OP_1SUB";
191     case OP_2MUL                   : return "OP_2MUL";
192     case OP_2DIV                   : return "OP_2DIV";
193     case OP_NEGATE                 : return "OP_NEGATE";
194     case OP_ABS                    : return "OP_ABS";
195     case OP_NOT                    : return "OP_NOT";
196     case OP_0NOTEQUAL              : return "OP_0NOTEQUAL";
197     case OP_ADD                    : return "OP_ADD";
198     case OP_SUB                    : return "OP_SUB";
199     case OP_MUL                    : return "OP_MUL";
200     case OP_DIV                    : return "OP_DIV";
201     case OP_MOD                    : return "OP_MOD";
202     case OP_LSHIFT                 : return "OP_LSHIFT";
203     case OP_RSHIFT                 : return "OP_RSHIFT";
204     case OP_BOOLAND                : return "OP_BOOLAND";
205     case OP_BOOLOR                 : return "OP_BOOLOR";
206     case OP_NUMEQUAL               : return "OP_NUMEQUAL";
207     case OP_NUMEQUALVERIFY         : return "OP_NUMEQUALVERIFY";
208     case OP_NUMNOTEQUAL            : return "OP_NUMNOTEQUAL";
209     case OP_LESSTHAN               : return "OP_LESSTHAN";
210     case OP_GREATERTHAN            : return "OP_GREATERTHAN";
211     case OP_LESSTHANOREQUAL        : return "OP_LESSTHANOREQUAL";
212     case OP_GREATERTHANOREQUAL     : return "OP_GREATERTHANOREQUAL";
213     case OP_MIN                    : return "OP_MIN";
214     case OP_MAX                    : return "OP_MAX";
215     case OP_WITHIN                 : return "OP_WITHIN";
216
217     // crypto
218     case OP_RIPEMD160              : return "OP_RIPEMD160";
219     case OP_SHA1                   : return "OP_SHA1";
220     case OP_SHA256                 : return "OP_SHA256";
221     case OP_HASH160                : return "OP_HASH160";
222     case OP_HASH256                : return "OP_HASH256";
223     case OP_CODESEPARATOR          : return "OP_CODESEPARATOR";
224     case OP_CHECKSIG               : return "OP_CHECKSIG";
225     case OP_CHECKSIGVERIFY         : return "OP_CHECKSIGVERIFY";
226     case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
227     case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
228
229     // expanson
230     case OP_NOP1                   : return "OP_NOP1";
231     case OP_NOP4                   : return "OP_NOP4";
232     case OP_NOP5                   : return "OP_NOP5";
233     case OP_NOP6                   : return "OP_NOP6";
234     case OP_NOP7                   : return "OP_NOP7";
235     case OP_NOP8                   : return "OP_NOP8";
236     case OP_NOP9                   : return "OP_NOP9";
237     case OP_NOP10                  : return "OP_NOP10";
238
239
240
241     // template matching params
242     case OP_PUBKEYHASH             : return "OP_PUBKEYHASH";
243     case OP_PUBKEY                 : return "OP_PUBKEY";
244     case OP_SMALLDATA              : return "OP_SMALLDATA";
245
246     case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";
247     default:
248         return "OP_UNKNOWN";
249     }
250 }
251
252 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
253     if (!(flags & SCRIPT_VERIFY_STRICTENC))
254         return true;
255
256     if (vchPubKey.size() < 33)
257         return error("Non-canonical public key: too short");
258     if (vchPubKey[0] == 0x04) {
259         if (vchPubKey.size() != 65)
260             return error("Non-canonical public key: invalid length for uncompressed key");
261     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
262         if (vchPubKey.size() != 33)
263             return error("Non-canonical public key: invalid length for compressed key");
264     } else {
265         return error("Non-canonical public key: compressed nor uncompressed");
266     }
267     return true;
268 }
269
270 bool IsDERSignature(const valtype &vchSig, bool fWithHashType, bool fCheckLow) {
271     // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
272     // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
273     // Where R and S are not negative (their first byte has its highest bit not set), and not
274     // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
275     // in which case a single 0 byte is necessary and even required).
276     if (vchSig.size() < 9)
277         return error("Non-canonical signature: too short");
278     if (vchSig.size() > 73)
279         return error("Non-canonical signature: too long");
280     if (vchSig[0] != 0x30)
281         return error("Non-canonical signature: wrong type");
282     if (vchSig[1] != vchSig.size() - (fWithHashType ? 3 : 2))
283         return error("Non-canonical signature: wrong length marker");
284     if (fWithHashType) {
285         unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
286         if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
287             return error("Non-canonical signature: unknown hashtype byte");
288     }
289     unsigned int nLenR = vchSig[3];
290     if (5 + nLenR >= vchSig.size())
291         return error("Non-canonical signature: S length misplaced");
292     unsigned int nLenS = vchSig[5+nLenR];
293     if ((nLenR + nLenS + (fWithHashType ? 7 : 6)) != vchSig.size())
294         return error("Non-canonical signature: R+S length mismatch");
295
296     const unsigned char *R = &vchSig[4];
297     if (R[-2] != 0x02)
298         return error("Non-canonical signature: R value type mismatch");
299     if (nLenR == 0)
300         return error("Non-canonical signature: R length is zero");
301     if (R[0] & 0x80)
302         return error("Non-canonical signature: R value negative");
303     if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
304         return error("Non-canonical signature: R value excessively padded");
305
306     const unsigned char *S = &vchSig[6+nLenR];
307     if (S[-2] != 0x02)
308         return error("Non-canonical signature: S value type mismatch");
309     if (nLenS == 0)
310         return error("Non-canonical signature: S length is zero");
311     if (S[0] & 0x80)
312         return error("Non-canonical signature: S value negative");
313     if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
314         return error("Non-canonical signature: S value excessively padded");
315
316     if (fCheckLow) {
317         unsigned int nLenR = vchSig[3];
318         unsigned int nLenS = vchSig[5+nLenR];
319         const unsigned char *S = &vchSig[6+nLenR];
320         // If the S value is above the order of the curve divided by two, its
321         // complement modulo the order could have been used instead, which is
322         // one byte shorter when encoded correctly.
323         if (!CKey::CheckSignatureElement(S, nLenS, true))
324             return error("Non-canonical signature: S value is unnecessarily high");
325     }
326
327     return true;
328 }
329
330 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
331     if (!(flags & SCRIPT_VERIFY_STRICTENC))
332         return true;
333
334     return IsDERSignature(vchSig, true, (flags & SCRIPT_VERIFY_LOW_S) != 0);
335 }
336
337 bool CheckLockTime(const int64_t& nLockTime, const CTransaction &txTo, unsigned int nIn)
338 {
339     // There are two kinds of nLockTime: lock-by-blockheight
340     // and lock-by-blocktime, distinguished by whether
341     // nLockTime < LOCKTIME_THRESHOLD.
342     //
343     // We want to compare apples to apples, so fail the script
344     // unless the type of nLockTime being tested is the same as
345     // the nLockTime in the transaction.
346     if (!(
347         (txTo.nLockTime <  LOCKTIME_THRESHOLD && nLockTime <  LOCKTIME_THRESHOLD) ||
348         (txTo.nLockTime >= LOCKTIME_THRESHOLD && nLockTime >= LOCKTIME_THRESHOLD)
349     ))
350         return false;
351
352     // Now that we know we're comparing apples-to-apples, the
353     // comparison is a simple numeric one.
354     if (nLockTime > (int64_t)txTo.nLockTime)
355         return false;
356
357     // Finally the nLockTime feature can be disabled and thus
358     // CHECKLOCKTIMEVERIFY bypassed if every txin has been
359     // finalized by setting nSequence to maxint. The
360     // transaction would be allowed into the blockchain, making
361     // the opcode ineffective.
362     //
363     // Testing if this vin is not final is sufficient to
364     // prevent this condition. Alternatively we could test all
365     // inputs, but testing just this input minimizes the data
366     // required to prove correct CHECKLOCKTIMEVERIFY execution.
367     if (SEQUENCE_FINAL == txTo.vin[nIn].nSequence)
368         return false;
369
370     return true;
371 }
372
373 bool CheckSequence(const int64_t& nSequence, const CTransaction &txTo, unsigned int nIn)
374 {
375     // Relative lock times are supported by comparing the passed
376     // in operand to the sequence number of the input.
377     const int64_t txToSequence = (int64_t)txTo.vin[nIn].nSequence;
378
379     // Sequence numbers with their most significant bit set are not
380     // consensus constrained. Testing that the transaction's sequence
381     // number do not have this bit set prevents using this property
382     // to get around a CHECKSEQUENCEVERIFY check.
383     if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG)
384         return false;
385
386     // Mask off any bits that do not have consensus-enforced meaning
387     // before doing the integer comparisons
388     const uint32_t nLockTimeMask = SEQUENCE_LOCKTIME_TYPE_FLAG | SEQUENCE_LOCKTIME_MASK;
389     const int64_t txToSequenceMasked = txToSequence & nLockTimeMask;
390     const int64_t nSequenceMasked = nSequence & nLockTimeMask;
391
392     // There are two kinds of nSequence: lock-by-blockheight
393     // and lock-by-blocktime, distinguished by whether
394     // nSequenceMasked < CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
395     //
396     // We want to compare apples to apples, so fail the script
397     // unless the type of nSequenceMasked being tested is the same as
398     // the nSequenceMasked in the transaction.
399     if (!(
400         (txToSequenceMasked <  SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked <  SEQUENCE_LOCKTIME_TYPE_FLAG) ||
401         (txToSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG && nSequenceMasked >= SEQUENCE_LOCKTIME_TYPE_FLAG)
402     )) {
403         return false;
404     }
405
406     // Now that we know we're comparing apples-to-apples, the
407     // comparison is a simple numeric one.
408     if (nSequenceMasked > txToSequenceMasked)
409         return false;
410
411     return true;
412 }
413
414 bool EvalScript(std::vector<std::vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
415 {
416     CAutoBN_CTX pctx;
417     CScript::const_iterator pc = script.begin();
418     CScript::const_iterator pend = script.end();
419     CScript::const_iterator pbegincodehash = script.begin();
420     opcodetype opcode;
421     valtype vchPushValue;
422     std::vector<bool> vfExec;
423     std::vector<valtype> altstack;
424     if (script.size() > 10000)
425         return false;
426     int nOpCount = 0;
427
428     try
429     {
430         while (pc < pend)
431         {
432             bool fExec = !count(vfExec.begin(), vfExec.end(), false);
433
434             //
435             // Read instruction
436             //
437             if (!script.GetOp(pc, opcode, vchPushValue))
438                 return false;
439             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
440                 return false;
441             if (opcode > OP_16 && ++nOpCount > 201)
442                 return false;
443
444             if (opcode == OP_CAT ||
445                 opcode == OP_SUBSTR ||
446                 opcode == OP_LEFT ||
447                 opcode == OP_RIGHT ||
448                 opcode == OP_INVERT ||
449                 opcode == OP_AND ||
450                 opcode == OP_OR ||
451                 opcode == OP_XOR ||
452                 opcode == OP_2MUL ||
453                 opcode == OP_2DIV ||
454                 opcode == OP_MUL ||
455                 opcode == OP_DIV ||
456                 opcode == OP_MOD ||
457                 opcode == OP_LSHIFT ||
458                 opcode == OP_RSHIFT)
459                 return false; // Disabled opcodes.
460
461             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
462                 stack.push_back(vchPushValue);
463             else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
464             switch (opcode)
465             {
466                 //
467                 // Push value
468                 //
469                 case OP_1NEGATE:
470                 case OP_1:
471                 case OP_2:
472                 case OP_3:
473                 case OP_4:
474                 case OP_5:
475                 case OP_6:
476                 case OP_7:
477                 case OP_8:
478                 case OP_9:
479                 case OP_10:
480                 case OP_11:
481                 case OP_12:
482                 case OP_13:
483                 case OP_14:
484                 case OP_15:
485                 case OP_16:
486                 {
487                     // ( -- value)
488                     CBigNum bn((int)opcode - (int)(OP_1 - 1));
489                     stack.push_back(bn.getvch());
490                 }
491                 break;
492
493
494                 //
495                 // Control
496                 //
497                 case OP_NOP:
498                 case OP_NOP1: case OP_NOP4: case OP_NOP5:
499                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
500                 break;
501
502                 case OP_IF:
503                 case OP_NOTIF:
504                 {
505                     // <expression> if [statements] [else [statements]] endif
506                     bool fValue = false;
507                     if (fExec)
508                     {
509                         if (stack.size() < 1)
510                             return false;
511                         valtype& vch = stacktop(-1);
512                         fValue = CastToBool(vch);
513                         if (opcode == OP_NOTIF)
514                             fValue = !fValue;
515                         popstack(stack);
516                     }
517                     vfExec.push_back(fValue);
518                 }
519                 break;
520
521                 case OP_ELSE:
522                 {
523                     if (vfExec.empty())
524                         return false;
525                     vfExec.back() = !vfExec.back();
526                 }
527                 break;
528
529                 case OP_ENDIF:
530                 {
531                     if (vfExec.empty())
532                         return false;
533                     vfExec.pop_back();
534                 }
535                 break;
536
537                 case OP_VERIFY:
538                 {
539                     // (true -- ) or
540                     // (false -- false) and return
541                     if (stack.size() < 1)
542                         return false;
543                     bool fValue = CastToBool(stacktop(-1));
544                     if (fValue)
545                         popstack(stack);
546                     else
547                         return false;
548                 }
549                 break;
550
551                 case OP_RETURN:
552                 {
553                     return false;
554                 }
555                 break;
556
557                 case OP_CHECKLOCKTIMEVERIFY:
558                 {
559                     // CHECKLOCKTIMEVERIFY
560                     //
561                     // (nLockTime -- nLockTime)
562                     if (!(flags & SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
563                         // treat as a NOP2 if not enabled
564                         break;
565                     }
566
567                     if (stack.size() < 1)
568                         return false;
569
570                     CBigNum nLockTime = CastToBigNum(stacktop(-1));
571
572                     // In the rare event that the argument may be < 0 due to
573                     // some arithmetic being done first, you can always use
574                     // 0 MAX CHECKLOCKTIMEVERIFY.
575                     if (nLockTime < 0)
576                         return false;
577
578                     // Actually compare the specified lock time with the transaction.
579                     if (!CheckLockTime(nLockTime.getuint64(), txTo, nIn))
580                         return false;
581
582                     break;
583                 }
584
585                 case OP_CHECKSEQUENCEVERIFY:
586                 {
587                     if (!(flags & SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
588                         // treat as a NOP3 not enabled
589                         break;
590                     }
591
592                     if (stack.size() < 1)
593                         return false;
594
595                     // nSequence, like nLockTime, is a 32-bit unsigned integer
596                     // field. See the comment in CHECKLOCKTIMEVERIFY regarding
597                     // 5-byte numeric operands.
598                     CBigNum nSequence = CastToBigNum(stacktop(-1));
599
600                     // In the rare event that the argument may be < 0 due to
601                     // some arithmetic being done first, you can always use
602                     // 0 MAX CHECKSEQUENCEVERIFY.
603                     if (nSequence < 0)
604                         return false;
605
606                     // To provide for future soft-fork extensibility, if the
607                     // operand has the disabled lock-time flag set,
608                     // CHECKSEQUENCEVERIFY behaves as a NOP.
609                     if ((nSequence.getint32() & SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0)
610                         break;
611
612                     // Compare the specified sequence number with the input.
613                     if (!CheckSequence(nSequence.getuint64(), txTo, nIn))
614                         return false;
615
616                     break;
617                 }
618
619                 //
620                 // Stack ops
621                 //
622                 case OP_TOALTSTACK:
623                 {
624                     if (stack.size() < 1)
625                         return false;
626                     altstack.push_back(stacktop(-1));
627                     popstack(stack);
628                 }
629                 break;
630
631                 case OP_FROMALTSTACK:
632                 {
633                     if (altstack.size() < 1)
634                         return false;
635                     stack.push_back(altstacktop(-1));
636                     popstack(altstack);
637                 }
638                 break;
639
640                 case OP_2DROP:
641                 {
642                     // (x1 x2 -- )
643                     if (stack.size() < 2)
644                         return false;
645                     popstack(stack);
646                     popstack(stack);
647                 }
648                 break;
649
650                 case OP_2DUP:
651                 {
652                     // (x1 x2 -- x1 x2 x1 x2)
653                     if (stack.size() < 2)
654                         return false;
655                     valtype vch1 = stacktop(-2);
656                     valtype vch2 = stacktop(-1);
657                     stack.push_back(vch1);
658                     stack.push_back(vch2);
659                 }
660                 break;
661
662                 case OP_3DUP:
663                 {
664                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
665                     if (stack.size() < 3)
666                         return false;
667                     valtype vch1 = stacktop(-3);
668                     valtype vch2 = stacktop(-2);
669                     valtype vch3 = stacktop(-1);
670                     stack.push_back(vch1);
671                     stack.push_back(vch2);
672                     stack.push_back(vch3);
673                 }
674                 break;
675
676                 case OP_2OVER:
677                 {
678                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
679                     if (stack.size() < 4)
680                         return false;
681                     valtype vch1 = stacktop(-4);
682                     valtype vch2 = stacktop(-3);
683                     stack.push_back(vch1);
684                     stack.push_back(vch2);
685                 }
686                 break;
687
688                 case OP_2ROT:
689                 {
690                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
691                     if (stack.size() < 6)
692                         return false;
693                     valtype vch1 = stacktop(-6);
694                     valtype vch2 = stacktop(-5);
695                     stack.erase(stack.end()-6, stack.end()-4);
696                     stack.push_back(vch1);
697                     stack.push_back(vch2);
698                 }
699                 break;
700
701                 case OP_2SWAP:
702                 {
703                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
704                     if (stack.size() < 4)
705                         return false;
706                     swap(stacktop(-4), stacktop(-2));
707                     swap(stacktop(-3), stacktop(-1));
708                 }
709                 break;
710
711                 case OP_IFDUP:
712                 {
713                     // (x - 0 | x x)
714                     if (stack.size() < 1)
715                         return false;
716                     valtype vch = stacktop(-1);
717                     if (CastToBool(vch))
718                         stack.push_back(vch);
719                 }
720                 break;
721
722                 case OP_DEPTH:
723                 {
724                     // -- stacksize
725                     CBigNum bn((uint16_t) stack.size());
726                     stack.push_back(bn.getvch());
727                 }
728                 break;
729
730                 case OP_DROP:
731                 {
732                     // (x -- )
733                     if (stack.size() < 1)
734                         return false;
735                     popstack(stack);
736                 }
737                 break;
738
739                 case OP_DUP:
740                 {
741                     // (x -- x x)
742                     if (stack.size() < 1)
743                         return false;
744                     valtype vch = stacktop(-1);
745                     stack.push_back(vch);
746                 }
747                 break;
748
749                 case OP_NIP:
750                 {
751                     // (x1 x2 -- x2)
752                     if (stack.size() < 2)
753                         return false;
754                     stack.erase(stack.end() - 2);
755                 }
756                 break;
757
758                 case OP_OVER:
759                 {
760                     // (x1 x2 -- x1 x2 x1)
761                     if (stack.size() < 2)
762                         return false;
763                     valtype vch = stacktop(-2);
764                     stack.push_back(vch);
765                 }
766                 break;
767
768                 case OP_PICK:
769                 case OP_ROLL:
770                 {
771                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
772                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
773                     if (stack.size() < 2)
774                         return false;
775                     int n = CastToBigNum(stacktop(-1)).getint32();
776                     popstack(stack);
777                     if (n < 0 || n >= (int)stack.size())
778                         return false;
779                     valtype vch = stacktop(-n-1);
780                     if (opcode == OP_ROLL)
781                         stack.erase(stack.end()-n-1);
782                     stack.push_back(vch);
783                 }
784                 break;
785
786                 case OP_ROT:
787                 {
788                     // (x1 x2 x3 -- x2 x3 x1)
789                     //  x2 x1 x3  after first swap
790                     //  x2 x3 x1  after second swap
791                     if (stack.size() < 3)
792                         return false;
793                     swap(stacktop(-3), stacktop(-2));
794                     swap(stacktop(-2), stacktop(-1));
795                 }
796                 break;
797
798                 case OP_SWAP:
799                 {
800                     // (x1 x2 -- x2 x1)
801                     if (stack.size() < 2)
802                         return false;
803                     swap(stacktop(-2), stacktop(-1));
804                 }
805                 break;
806
807                 case OP_TUCK:
808                 {
809                     // (x1 x2 -- x2 x1 x2)
810                     if (stack.size() < 2)
811                         return false;
812                     valtype vch = stacktop(-1);
813                     stack.insert(stack.end()-2, vch);
814                 }
815                 break;
816
817
818                 case OP_SIZE:
819                 {
820                     // (in -- in size)
821                     if (stack.size() < 1)
822                         return false;
823                     CBigNum bn((uint16_t) stacktop(-1).size());
824                     stack.push_back(bn.getvch());
825                 }
826                 break;
827
828
829                 //
830                 // Bitwise logic
831                 //
832                 case OP_EQUAL:
833                 case OP_EQUALVERIFY:
834                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
835                 {
836                     // (x1 x2 - bool)
837                     if (stack.size() < 2)
838                         return false;
839                     valtype& vch1 = stacktop(-2);
840                     valtype& vch2 = stacktop(-1);
841                     bool fEqual = (vch1 == vch2);
842                     // OP_NOTEQUAL is disabled because it would be too easy to say
843                     // something like n != 1 and have some wiseguy pass in 1 with extra
844                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
845                     //if (opcode == OP_NOTEQUAL)
846                     //    fEqual = !fEqual;
847                     popstack(stack);
848                     popstack(stack);
849                     stack.push_back(fEqual ? vchTrue : vchFalse);
850                     if (opcode == OP_EQUALVERIFY)
851                     {
852                         if (fEqual)
853                             popstack(stack);
854                         else
855                             return false;
856                     }
857                 }
858                 break;
859
860
861                 //
862                 // Numeric
863                 //
864                 case OP_1ADD:
865                 case OP_1SUB:
866                 case OP_NEGATE:
867                 case OP_ABS:
868                 case OP_NOT:
869                 case OP_0NOTEQUAL:
870                 {
871                     // (in -- out)
872                     if (stack.size() < 1)
873                         return false;
874                     CBigNum bn = CastToBigNum(stacktop(-1));
875                     switch (opcode)
876                     {
877                     case OP_1ADD:       bn += bnOne; break;
878                     case OP_1SUB:       bn -= bnOne; break;
879                     case OP_NEGATE:     bn = -bn; break;
880                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
881                     case OP_NOT:        bn = (bn == bnZero); break;
882                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
883                     default:            assert(!"invalid opcode"); break;
884                     }
885                     popstack(stack);
886                     stack.push_back(bn.getvch());
887                 }
888                 break;
889
890                 case OP_ADD:
891                 case OP_SUB:
892                 case OP_BOOLAND:
893                 case OP_BOOLOR:
894                 case OP_NUMEQUAL:
895                 case OP_NUMEQUALVERIFY:
896                 case OP_NUMNOTEQUAL:
897                 case OP_LESSTHAN:
898                 case OP_GREATERTHAN:
899                 case OP_LESSTHANOREQUAL:
900                 case OP_GREATERTHANOREQUAL:
901                 case OP_MIN:
902                 case OP_MAX:
903                 {
904                     // (x1 x2 -- out)
905                     if (stack.size() < 2)
906                         return false;
907                     CBigNum bn1 = CastToBigNum(stacktop(-2));
908                     CBigNum bn2 = CastToBigNum(stacktop(-1));
909                     CBigNum bn;
910                     switch (opcode)
911                     {
912                     case OP_ADD:
913                         bn = bn1 + bn2;
914                         break;
915
916                     case OP_SUB:
917                         bn = bn1 - bn2;
918                         break;
919
920                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
921                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
922                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
923                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
924                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
925                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
926                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
927                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
928                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
929                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
930                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
931                     default:                     assert(!"invalid opcode"); break;
932                     }
933                     popstack(stack);
934                     popstack(stack);
935                     stack.push_back(bn.getvch());
936
937                     if (opcode == OP_NUMEQUALVERIFY)
938                     {
939                         if (CastToBool(stacktop(-1)))
940                             popstack(stack);
941                         else
942                             return false;
943                     }
944                 }
945                 break;
946
947                 case OP_WITHIN:
948                 {
949                     // (x min max -- out)
950                     if (stack.size() < 3)
951                         return false;
952                     CBigNum bn1 = CastToBigNum(stacktop(-3));
953                     CBigNum bn2 = CastToBigNum(stacktop(-2));
954                     CBigNum bn3 = CastToBigNum(stacktop(-1));
955                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
956                     popstack(stack);
957                     popstack(stack);
958                     popstack(stack);
959                     stack.push_back(fValue ? vchTrue : vchFalse);
960                 }
961                 break;
962
963
964                 //
965                 // Crypto
966                 //
967                 case OP_RIPEMD160:
968                 case OP_SHA1:
969                 case OP_SHA256:
970                 case OP_HASH160:
971                 case OP_HASH256:
972                 {
973                     // (in -- hash)
974                     if (stack.size() < 1)
975                         return false;
976                     valtype& vch = stacktop(-1);
977                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
978                     if (opcode == OP_RIPEMD160)
979                         RIPEMD160(&vch[0], vch.size(), &vchHash[0]);
980                     else if (opcode == OP_SHA1)
981                         SHA1(&vch[0], vch.size(), &vchHash[0]);
982                     else if (opcode == OP_SHA256)
983                         SHA256(&vch[0], vch.size(), &vchHash[0]);
984                     else if (opcode == OP_HASH160)
985                     {
986                         uint160 hash160 = Hash160(vch);
987                         memcpy(&vchHash[0], &hash160, sizeof(hash160));
988                     }
989                     else if (opcode == OP_HASH256)
990                     {
991                         uint256 hash = Hash(vch.begin(), vch.end());
992                         memcpy(&vchHash[0], &hash, sizeof(hash));
993                     }
994                     popstack(stack);
995                     stack.push_back(vchHash);
996                 }
997                 break;
998
999                 case OP_CODESEPARATOR:
1000                 {
1001                     // Hash starts after the code separator
1002                     pbegincodehash = pc;
1003                 }
1004                 break;
1005
1006                 case OP_CHECKSIG:
1007                 case OP_CHECKSIGVERIFY:
1008                 {
1009                     // (sig pubkey -- bool)
1010                     if (stack.size() < 2)
1011                         return false;
1012
1013                     valtype& vchSig    = stacktop(-2);
1014                     valtype& vchPubKey = stacktop(-1);
1015
1016                     ////// debug print
1017                     //PrintHex(vchSig.begin(), vchSig.end(), "sig: %s\n");
1018                     //PrintHex(vchPubKey.begin(), vchPubKey.end(), "pubkey: %s\n");
1019
1020                     // Subset of script starting at the most recent codeseparator
1021                     CScript scriptCode(pbegincodehash, pend);
1022
1023                     // Drop the signature, since there's no way for a signature to sign itself
1024                     scriptCode.FindAndDelete(CScript(vchSig));
1025
1026                     bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1027                         CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1028
1029                     popstack(stack);
1030                     popstack(stack);
1031                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1032                     if (opcode == OP_CHECKSIGVERIFY)
1033                     {
1034                         if (fSuccess)
1035                             popstack(stack);
1036                         else
1037                             return false;
1038                     }
1039                 }
1040                 break;
1041
1042                 case OP_CHECKMULTISIG:
1043                 case OP_CHECKMULTISIGVERIFY:
1044                 {
1045                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1046
1047                     int i = 1;
1048                     if ((int)stack.size() < i)
1049                         return false;
1050
1051                     int nKeysCount = CastToBigNum(stacktop(-i)).getint32();
1052                     if (nKeysCount < 0 || nKeysCount > 20)
1053                         return false;
1054                     nOpCount += nKeysCount;
1055                     if (nOpCount > 201)
1056                         return false;
1057                     int ikey = ++i;
1058                     i += nKeysCount;
1059                     if ((int)stack.size() < i)
1060                         return false;
1061
1062                     int nSigsCount = CastToBigNum(stacktop(-i)).getint32();
1063                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1064                         return false;
1065                     int isig = ++i;
1066                     i += nSigsCount;
1067                     if ((int)stack.size() < i)
1068                         return false;
1069
1070                     // Subset of script starting at the most recent codeseparator
1071                     CScript scriptCode(pbegincodehash, pend);
1072
1073                     // Drop the signatures, since there's no way for a signature to sign itself
1074                     for (int k = 0; k < nSigsCount; k++)
1075                     {
1076                         valtype& vchSig = stacktop(-isig-k);
1077                         scriptCode.FindAndDelete(CScript(vchSig));
1078                     }
1079
1080                     bool fSuccess = true;
1081                     while (fSuccess && nSigsCount > 0)
1082                     {
1083                         valtype& vchSig    = stacktop(-isig);
1084                         valtype& vchPubKey = stacktop(-ikey);
1085
1086                         // Check signature
1087                         bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
1088                             CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
1089
1090                         if (fOk) {
1091                             isig++;
1092                             nSigsCount--;
1093                         }
1094                         ikey++;
1095                         nKeysCount--;
1096
1097                         // If there are more signatures left than keys left,
1098                         // then too many signatures have failed
1099                         if (nSigsCount > nKeysCount)
1100                             fSuccess = false;
1101                     }
1102
1103                     while (i-- > 1)
1104                         popstack(stack);
1105
1106                     // A bug causes CHECKMULTISIG to consume one extra argument
1107                     // whose contents were not checked in any way.
1108                     //
1109                     // Unfortunately this is a potential source of mutability,
1110                     // so optionally verify it is exactly equal to zero prior
1111                     // to removing it from the stack.
1112                     if (stack.size() < 1)
1113                         return false;
1114                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
1115                         return error("CHECKMULTISIG dummy argument not null");
1116                     popstack(stack);
1117
1118                     stack.push_back(fSuccess ? vchTrue : vchFalse);
1119
1120                     if (opcode == OP_CHECKMULTISIGVERIFY)
1121                     {
1122                         if (fSuccess)
1123                             popstack(stack);
1124                         else
1125                             return false;
1126                     }
1127                 }
1128                 break;
1129
1130                 default:
1131                     return false;
1132             }
1133
1134             // Size limits
1135             if (stack.size() + altstack.size() > 1000)
1136                 return false;
1137         }
1138     }
1139     catch (...)
1140     {
1141         return false;
1142     }
1143
1144
1145     if (!vfExec.empty())
1146         return false;
1147
1148     return true;
1149 }
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159 uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1160 {
1161     if (nIn >= txTo.vin.size())
1162     {
1163         printf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1164         return 1;
1165     }
1166     CTransaction txTmp(txTo);
1167
1168     // In case concatenating two scripts ends up with two codeseparators,
1169     // or an extra one at the end, this prevents all those possible incompatibilities.
1170     scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR));
1171
1172     // Blank out other inputs' signatures
1173     for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1174         txTmp.vin[i].scriptSig = CScript();
1175     txTmp.vin[nIn].scriptSig = scriptCode;
1176
1177     // Blank out some of the outputs
1178     if ((nHashType & 0x1f) == SIGHASH_NONE)
1179     {
1180         // Wildcard payee
1181         txTmp.vout.clear();
1182
1183         // Let the others update at will
1184         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1185             if (i != nIn)
1186                 txTmp.vin[i].nSequence = 0;
1187     }
1188     else if ((nHashType & 0x1f) == SIGHASH_SINGLE)
1189     {
1190         // Only lock-in the txout payee at same index as txin
1191         unsigned int nOut = nIn;
1192         if (nOut >= txTmp.vout.size())
1193         {
1194             printf("ERROR: SignatureHash() : nOut=%d out of range\n", nOut);
1195             return 1;
1196         }
1197         txTmp.vout.resize(nOut+1);
1198         for (unsigned int i = 0; i < nOut; i++)
1199             txTmp.vout[i].SetNull();
1200
1201         // Let the others update at will
1202         for (unsigned int i = 0; i < txTmp.vin.size(); i++)
1203             if (i != nIn)
1204                 txTmp.vin[i].nSequence = 0;
1205     }
1206
1207     // Blank out other inputs completely, not recommended for open transactions
1208     if (nHashType & SIGHASH_ANYONECANPAY)
1209     {
1210         txTmp.vin[0] = txTmp.vin[nIn];
1211         txTmp.vin.resize(1);
1212     }
1213
1214     // Serialize and hash
1215     CDataStream ss(SER_GETHASH, 0);
1216     ss.reserve(10000);
1217     ss << txTmp << nHashType;
1218     return Hash(ss.begin(), ss.end());
1219 }
1220
1221
1222 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1223 // twice for every transaction (once when accepted into memory pool, and
1224 // again when accepted into the block chain)
1225
1226 class CSignatureCache
1227 {
1228 private:
1229      // sigdata_type is (signature hash, signature, public key):
1230     typedef std::tuple<uint256, std::vector<unsigned char>, CPubKey > sigdata_type;
1231     std::set< sigdata_type> setValid;
1232     boost::shared_mutex cs_sigcache;
1233
1234 public:
1235     bool
1236     Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1237     {
1238         boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1239
1240         sigdata_type k(hash, vchSig, pubKey);
1241         std::set<sigdata_type>::iterator mi = setValid.find(k);
1242         if (mi != setValid.end())
1243             return true;
1244         return false;
1245     }
1246
1247     void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1248     {
1249         // DoS prevention: limit cache size to less than 10MB
1250         // (~200 bytes per cache entry times 50,000 entries)
1251         // Since there are a maximum of 20,000 signature operations per block
1252         // 50,000 is a reasonable default.
1253         int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1254         if (nMaxCacheSize <= 0) return;
1255
1256         boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1257
1258         while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1259         {
1260             // Evict a random entry. Random because that helps
1261             // foil would-be DoS attackers who might try to pre-generate
1262             // and re-use a set of valid signatures just-slightly-greater
1263             // than our cache size.
1264             uint256 randomHash = GetRandHash();
1265             std::vector<unsigned char> unused;
1266             std::set<sigdata_type>::iterator it =
1267                 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1268             if (it == setValid.end())
1269                 it = setValid.begin();
1270             setValid.erase(*it);
1271         }
1272
1273         sigdata_type k(hash, vchSig, pubKey);
1274         setValid.insert(k);
1275     }
1276 };
1277
1278 bool CheckSig(std::vector<unsigned char> vchSig, const std::vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1279               const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
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     uint256 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, std::vector<std::vector<unsigned char> >& vSolutionsRet)
1315 {
1316     // Templates
1317     static std::map<txnouttype, CScript> mTemplates;
1318     if (mTemplates.empty())
1319     {
1320         // Standard tx, sender provides pubkey, receiver adds signature
1321         mTemplates.insert(make_pair(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(make_pair(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(make_pair(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(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1331
1332         // Empty, provably prunable, data-carrying output
1333         mTemplates.insert(make_pair(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         std::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 CScript& script1 = scriptPubKey;
1360     for (const auto& tplate : mTemplates)
1361     {
1362         const CScript& script2 = tplate.second;
1363         vSolutionsRet.clear();
1364
1365         opcodetype opcode1, opcode2;
1366         std::vector<unsigned char> vch1, vch2;
1367
1368         // Compare
1369         CScript::const_iterator pc1 = script1.begin();
1370         CScript::const_iterator 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                     unsigned char m = vSolutionsRet.front()[0];
1381                     unsigned char n = vSolutionsRet.back()[0];
1382                     if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
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                     CBigNum 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     std::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     std::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 std::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 (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1499     {
1500         const valtype& pubkey = multisigdata[i];
1501         CKeyID 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     std::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             CPubKey key = CPubKey(vSolutions[0]);
1535             CPubKey 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     std::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 std::vector<valtype>& pubkeys, const CKeyStore& keystore)
1604 {
1605     unsigned int nResult = 0;
1606     for (const valtype& pubkey : pubkeys)
1607     {
1608         CKeyID 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 /*
1628 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1629 {
1630     CScript script;
1631     script.SetDestination(dest);
1632     return IsMine(keystore, script);
1633 }*/
1634
1635 isminetype IsMine(const CKeyStore &keystore, const CBitcoinAddress& dest)
1636 {
1637     CScript script;
1638     script.SetAddress(dest);
1639     return IsMine(keystore, script);
1640 }
1641
1642 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1643 {
1644     std::vector<valtype> vSolutions;
1645     txnouttype whichType;
1646     if (!Solver(scriptPubKey, whichType, vSolutions)) {
1647         if (keystore.HaveWatchOnly(scriptPubKey))
1648             return MINE_WATCH_ONLY;
1649         return MINE_NO;
1650     }
1651
1652     CKeyID keyID;
1653     switch (whichType)
1654     {
1655     case TX_NONSTANDARD:
1656     case TX_NULL_DATA:
1657         break;
1658     case TX_PUBKEY:
1659         keyID = CPubKey(vSolutions[0]).GetID();
1660         if (keystore.HaveKey(keyID))
1661             return MINE_SPENDABLE;
1662         break;
1663     case TX_PUBKEY_DROP:
1664         {
1665             CPubKey key = CPubKey(vSolutions[0]);
1666             CPubKey R = CPubKey(vSolutions[1]);
1667             if (keystore.CheckOwnership(key, R))
1668                 return MINE_SPENDABLE;
1669         }
1670         break;
1671     case TX_PUBKEYHASH:
1672         keyID = CKeyID(uint160(vSolutions[0]));
1673         if (keystore.HaveKey(keyID))
1674             return MINE_SPENDABLE;
1675         break;
1676     case TX_SCRIPTHASH:
1677     {
1678         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1679         CScript subscript;
1680         if (keystore.GetCScript(scriptID, subscript)) {
1681             isminetype ret = IsMine(keystore, subscript);
1682             if (ret == MINE_SPENDABLE)
1683                 return ret;
1684         }
1685         break;
1686     }
1687     case TX_MULTISIG:
1688     {
1689         // Only consider transactions "mine" if we own ALL the
1690         // keys involved. multi-signature transactions that are
1691         // partially owned (somebody else has a key that can spend
1692         // them) enable spend-out-from-under-you attacks, especially
1693         // in shared-wallet situations.
1694         std::vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1695         if (HaveKeys(keys, keystore) == keys.size())
1696             return MINE_SPENDABLE;
1697         break;
1698     }
1699     }
1700
1701     if (keystore.HaveWatchOnly(scriptPubKey))
1702         return MINE_WATCH_ONLY;
1703     return MINE_NO;
1704 }
1705
1706 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1707 {
1708     std::vector<valtype> vSolutions;
1709     txnouttype whichType;
1710     if (!Solver(scriptPubKey, whichType, vSolutions))
1711         return false;
1712
1713     if (whichType == TX_PUBKEY)
1714     {
1715         addressRet = CPubKey(vSolutions[0]).GetID();
1716         return true;
1717     }
1718     else if (whichType == TX_PUBKEYHASH)
1719     {
1720         addressRet = CKeyID(uint160(vSolutions[0]));
1721         return true;
1722     }
1723     else if (whichType == TX_SCRIPTHASH)
1724     {
1725         addressRet = CScriptID(uint160(vSolutions[0]));
1726         return true;
1727     }
1728     // Multisig txns have more than one address...
1729     return false;
1730 }
1731
1732 bool ExtractAddress(const CKeyStore &keystore, const CScript& scriptPubKey, CBitcoinAddress& addressRet)
1733 {
1734     std::vector<valtype> vSolutions;
1735     txnouttype whichType;
1736     if (!Solver(scriptPubKey, whichType, vSolutions))
1737         return false;
1738
1739     if (whichType == TX_PUBKEY)
1740     {
1741         addressRet = CBitcoinAddress(CPubKey(vSolutions[0]).GetID());
1742         return true;
1743     }
1744     if (whichType == TX_PUBKEY_DROP)
1745     {
1746         // Pay-to-Pubkey-R
1747         CMalleableKeyView view;
1748         if (!keystore.CheckOwnership(CPubKey(vSolutions[0]), CPubKey(vSolutions[1]), view))
1749             return false;
1750
1751         addressRet = CBitcoinAddress(view.GetMalleablePubKey());
1752         return true;
1753     }
1754     else if (whichType == TX_PUBKEYHASH)
1755     {
1756         addressRet = CBitcoinAddress(CKeyID(uint160(vSolutions[0])));
1757         return true;
1758     }
1759     else if (whichType == TX_SCRIPTHASH)
1760     {
1761         addressRet = CBitcoinAddress(CScriptID(uint160(vSolutions[0])));
1762         return true;
1763     }
1764     // Multisig txns have more than one address...
1765     return false;
1766 }
1767
1768 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1769 private:
1770     const CKeyStore &keystore;
1771     CAffectedKeysVisitor& operator=(CAffectedKeysVisitor const&);
1772     std::vector<CKeyID> &vKeys;
1773
1774 public:
1775     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1776
1777     void Process(const CScript &script) {
1778         txnouttype type;
1779         std::vector<CTxDestination> vDest;
1780         int nRequired;
1781         if (ExtractDestinations(script, type, vDest, nRequired)) {
1782             for (const CTxDestination &dest : vDest)
1783                 boost::apply_visitor(*this, dest);
1784         }
1785     }
1786
1787     void operator()(const CKeyID &keyId) {
1788         if (keystore.HaveKey(keyId))
1789             vKeys.push_back(keyId);
1790     }
1791
1792     void operator()(const CScriptID &scriptId) {
1793         CScript script;
1794         if (keystore.GetCScript(scriptId, script))
1795             Process(script);
1796     }
1797
1798     void operator()(const CNoDestination &none) {}
1799 };
1800
1801
1802 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1803     CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1804 }
1805
1806 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector<CTxDestination>& addressRet, int& nRequiredRet)
1807 {
1808     addressRet.clear();
1809     typeRet = TX_NONSTANDARD;
1810     std::vector<valtype> vSolutions;
1811     if (!Solver(scriptPubKey, typeRet, vSolutions))
1812         return false;
1813     if (typeRet == TX_NULL_DATA)
1814     {
1815         nRequiredRet = 0;
1816         return true;
1817     }
1818
1819     if (typeRet == TX_MULTISIG)
1820     {
1821         nRequiredRet = vSolutions.front()[0];
1822         for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1823         {
1824             CTxDestination address = CPubKey(vSolutions[i]).GetID();
1825             addressRet.push_back(address);
1826         }
1827     }
1828     else
1829     {
1830         nRequiredRet = 1;
1831         if (typeRet == TX_PUBKEY_DROP)
1832             return true;
1833         CTxDestination address;
1834         if (!ExtractDestination(scriptPubKey, address))
1835            return false;
1836         addressRet.push_back(address);
1837     }
1838
1839     return true;
1840 }
1841
1842 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1843                   unsigned int flags, int nHashType)
1844 {
1845     std::vector<std::vector<unsigned char> > stack, stackCopy;
1846     if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1847         return false;
1848     if (flags & SCRIPT_VERIFY_P2SH)
1849         stackCopy = stack;
1850     if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1851         return false;
1852     if (stack.empty())
1853         return false;
1854
1855     if (CastToBool(stack.back()) == false)
1856         return false;
1857
1858     // Additional validation for spend-to-script-hash transactions:
1859     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1860     {
1861         if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1862             return false;            // or validation fails
1863
1864         // stackCopy cannot be empty here, because if it was the
1865         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1866         // an empty stack and the EvalScript above would return false.
1867         assert(!stackCopy.empty());
1868
1869         const valtype& pubKeySerialized = stackCopy.back();
1870         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1871         popstack(stackCopy);
1872
1873         if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1874             return false;
1875         if (stackCopy.empty())
1876             return false;
1877         return CastToBool(stackCopy.back());
1878     }
1879
1880     return true;
1881 }
1882
1883 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType)
1884 {
1885     assert(nIn < txTo.vin.size());
1886     CTxIn& txin = txTo.vin[nIn];
1887
1888     // Leave out the signature from the hash, since a signature can't sign itself.
1889     // The checksig op will also drop the signatures from its hash.
1890     uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1891
1892     txnouttype whichType;
1893     if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1894         return false;
1895
1896     if (whichType == TX_SCRIPTHASH)
1897     {
1898         // Solver returns the subscript that need to be evaluated;
1899         // the final scriptSig is the signatures from that
1900         // and then the serialized subscript:
1901         CScript subscript = txin.scriptSig;
1902
1903         // Recompute txn hash using subscript in place of scriptPubKey:
1904         uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1905
1906         txnouttype subType;
1907         bool fSolved =
1908             Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1909         // Append serialized subscript whether or not it is completely signed:
1910         txin.scriptSig << static_cast<valtype>(subscript);
1911         if (!fSolved) return false;
1912     }
1913
1914     // Test solution
1915     return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STRICT_FLAGS, 0);
1916 }
1917
1918 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType)
1919 {
1920     assert(nIn < txTo.vin.size());
1921     CTxIn& txin = txTo.vin[nIn];
1922     assert(txin.prevout.n < txFrom.vout.size());
1923     assert(txin.prevout.hash == txFrom.GetHash());
1924     const CTxOut& txout = txFrom.vout[txin.prevout.n];
1925
1926     return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1927 }
1928
1929 static CScript PushAll(const std::vector<valtype>& values)
1930 {
1931     CScript result;
1932     for (const valtype& v : values)
1933         result << v;
1934     return result;
1935 }
1936
1937 static CScript CombineMultisig(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1938                                const std::vector<valtype>& vSolutions,
1939                                std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1940 {
1941     // Combine all the signatures we've got:
1942     std::set<valtype> allsigs;
1943     for (const valtype& v : sigs1)
1944     {
1945         if (!v.empty())
1946             allsigs.insert(v);
1947     }
1948     for (const valtype& v : sigs2)
1949     {
1950         if (!v.empty())
1951             allsigs.insert(v);
1952     }
1953
1954     // Build a map of pubkey -> signature by matching sigs to pubkeys:
1955     assert(vSolutions.size() > 1);
1956     unsigned int nSigsRequired = vSolutions.front()[0];
1957     unsigned int nPubKeys = (unsigned int)(vSolutions.size()-2);
1958     std::map<valtype, valtype> sigs;
1959     for (const valtype& sig : allsigs)
1960     {
1961         for (unsigned int i = 0; i < nPubKeys; i++)
1962         {
1963             const valtype& pubkey = vSolutions[i+1];
1964             if (sigs.count(pubkey))
1965                 continue; // Already got a sig for this pubkey
1966
1967             if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1968             {
1969                 sigs[pubkey] = sig;
1970                 break;
1971             }
1972         }
1973     }
1974     // Now build a merged CScript:
1975     unsigned int nSigsHave = 0;
1976     CScript result; result << OP_0; // pop-one-too-many workaround
1977     for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1978     {
1979         if (sigs.count(vSolutions[i+1]))
1980         {
1981             result << sigs[vSolutions[i+1]];
1982             ++nSigsHave;
1983         }
1984     }
1985     // Fill any missing with OP_0:
1986     for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1987         result << OP_0;
1988
1989     return result;
1990 }
1991
1992 static CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1993                                  const txnouttype txType, const std::vector<valtype>& vSolutions,
1994                                  std::vector<valtype>& sigs1, std::vector<valtype>& sigs2)
1995 {
1996     switch (txType)
1997     {
1998     case TX_NONSTANDARD:
1999     case TX_NULL_DATA:
2000         // Don't know anything about this, assume bigger one is correct:
2001         if (sigs1.size() >= sigs2.size())
2002             return PushAll(sigs1);
2003         return PushAll(sigs2);
2004     case TX_PUBKEY:
2005     case TX_PUBKEY_DROP:
2006     case TX_PUBKEYHASH:
2007         // Signatures are bigger than placeholders or empty scripts:
2008         if (sigs1.empty() || sigs1[0].empty())
2009             return PushAll(sigs2);
2010         return PushAll(sigs1);
2011     case TX_SCRIPTHASH:
2012         if (sigs1.empty() || sigs1.back().empty())
2013             return PushAll(sigs2);
2014         else if (sigs2.empty() || sigs2.back().empty())
2015             return PushAll(sigs1);
2016         else
2017         {
2018             // Recur to combine:
2019             valtype spk = sigs1.back();
2020             CScript pubKey2(spk.begin(), spk.end());
2021
2022             txnouttype txType2;
2023             std::vector<std::vector<unsigned char> > vSolutions2;
2024             Solver(pubKey2, txType2, vSolutions2);
2025             sigs1.pop_back();
2026             sigs2.pop_back();
2027             CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
2028             result << spk;
2029             return result;
2030         }
2031     case TX_MULTISIG:
2032         return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
2033     }
2034
2035     return CScript();
2036 }
2037
2038 CScript CombineSignatures(const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
2039                           const CScript& scriptSig1, const CScript& scriptSig2)
2040 {
2041     txnouttype txType;
2042     std::vector<std::vector<unsigned char> > vSolutions;
2043     Solver(scriptPubKey, txType, vSolutions);
2044
2045     std::vector<valtype> stack1;
2046     EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2047     std::vector<valtype> stack2;
2048     EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
2049
2050     return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
2051 }
2052
2053 unsigned int CScript::GetSigOpCount(bool fAccurate) const
2054 {
2055     unsigned int n = 0;
2056     const_iterator pc = begin();
2057     opcodetype lastOpcode = OP_INVALIDOPCODE;
2058     while (pc < end())
2059     {
2060         opcodetype opcode;
2061         if (!GetOp(pc, opcode))
2062             break;
2063         if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
2064             n++;
2065         else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
2066         {
2067             if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
2068                 n += DecodeOP_N(lastOpcode);
2069             else
2070                 n += 20;
2071         }
2072         lastOpcode = opcode;
2073     }
2074     return n;
2075 }
2076
2077 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
2078 {
2079     if (!IsPayToScriptHash())
2080         return GetSigOpCount(true);
2081
2082     // This is a pay-to-script-hash scriptPubKey;
2083     // get the last item that the scriptSig
2084     // pushes onto the stack:
2085     const_iterator pc = scriptSig.begin();
2086     vector<unsigned char> data;
2087     while (pc < scriptSig.end())
2088     {
2089         opcodetype opcode;
2090         if (!scriptSig.GetOp(pc, opcode, data))
2091             return 0;
2092         if (opcode > OP_16)
2093             return 0;
2094     }
2095
2096     /// ... and return its opcount:
2097     CScript subscript(data.begin(), data.end());
2098     return subscript.GetSigOpCount(true);
2099 }
2100
2101 bool CScript::IsPayToScriptHash() const
2102 {
2103     // Extra-fast test for pay-to-script-hash CScripts:
2104     return (this->size() == 23 &&
2105             this->at(0) == OP_HASH160 &&
2106             this->at(1) == 0x14 &&
2107             this->at(22) == OP_EQUAL);
2108 }
2109
2110 bool CScript::HasCanonicalPushes() const
2111 {
2112     const_iterator pc = begin();
2113     while (pc < end())
2114     {
2115         opcodetype opcode;
2116         std::vector<unsigned char> data;
2117         if (!GetOp(pc, opcode, data))
2118             return false;
2119         if (opcode > OP_16)
2120             continue;
2121         if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
2122             // Could have used an OP_n code, rather than a 1-byte push.
2123             return false;
2124         if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
2125             // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
2126             return false;
2127         if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
2128             // Could have used an OP_PUSHDATA1.
2129             return false;
2130         if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
2131             // Could have used an OP_PUSHDATA2.
2132             return false;
2133     }
2134     return true;
2135 }
2136
2137 class CScriptVisitor : public boost::static_visitor<bool>
2138 {
2139 private:
2140     CScript *script;
2141 public:
2142     CScriptVisitor(CScript *scriptin) { script = scriptin; }
2143
2144     bool operator()(const CNoDestination &dest) const {
2145         script->clear();
2146         return false;
2147     }
2148
2149     bool operator()(const CKeyID &keyID) const {
2150         script->clear();
2151         *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
2152         return true;
2153     }
2154
2155     bool operator()(const CScriptID &scriptID) const {
2156         script->clear();
2157         *script << OP_HASH160 << scriptID << OP_EQUAL;
2158         return true;
2159     }
2160 };
2161
2162 void CScript::SetDestination(const CTxDestination& dest)
2163 {
2164     boost::apply_visitor(CScriptVisitor(this), dest);
2165 }
2166
2167 void CScript::SetAddress(const CBitcoinAddress& dest)
2168 {
2169     this->clear();
2170     if (dest.IsScript())
2171         *this << OP_HASH160 << dest.GetData() << OP_EQUAL;
2172     else if (dest.IsPubKey())
2173         *this << OP_DUP << OP_HASH160 << dest.GetData() << OP_EQUALVERIFY << OP_CHECKSIG;
2174     else if (dest.IsPair()) {
2175         // Pubkey pair address, going to generate
2176         //   new one-time public key.
2177         CMalleablePubKey mpk;
2178         if (!mpk.setvch(dest.GetData()))
2179             return;
2180         CPubKey R, pubKeyVariant;
2181         mpk.GetVariant(R, pubKeyVariant);
2182         *this << pubKeyVariant << R << OP_DROP << OP_CHECKSIG;
2183     }
2184 }
2185
2186 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
2187 {
2188     this->clear();
2189
2190     *this << EncodeOP_N(nRequired);
2191     for (const CPubKey& key : keys)
2192         *this << key;
2193     *this << EncodeOP_N((int)(keys.size())) << OP_CHECKMULTISIG;
2194 }