]> Git Repo - VerusCoin.git/blob - src/script.cpp
Merge pull request #4654
[VerusCoin.git] / src / script.cpp
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 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
8 #include "crypto/ripemd160.h"
9 #include "crypto/sha1.h"
10 #include "crypto/sha2.h"
11 #include "core.h"
12 #include "hash.h"
13 #include "key.h"
14 #include "keystore.h"
15 #include "random.h"
16 #include "sync.h"
17 #include "uint256.h"
18 #include "util.h"
19
20 #include <boost/foreach.hpp>
21 #include <boost/tuple/tuple.hpp>
22 #include <boost/tuple/tuple_comparison.hpp>
23
24 using namespace std;
25 using namespace boost;
26
27 typedef vector<unsigned char> valtype;
28 static const valtype vchFalse(0);
29 static const valtype vchZero(0);
30 static const valtype vchTrue(1, 1);
31 static const CScriptNum bnZero(0);
32 static const CScriptNum bnOne(1);
33 static const CScriptNum bnFalse(0);
34 static const CScriptNum bnTrue(1);
35
36 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags);
37
38 bool CastToBool(const valtype& vch)
39 {
40     for (unsigned int i = 0; i < vch.size(); i++)
41     {
42         if (vch[i] != 0)
43         {
44             // Can be negative zero
45             if (i == vch.size()-1 && vch[i] == 0x80)
46                 return false;
47             return true;
48         }
49     }
50     return false;
51 }
52
53
54
55 //
56 // Script is a stack machine (like Forth) that evaluates a predicate
57 // returning a bool indicating valid or not.  There are no loops.
58 //
59 #define stacktop(i)  (stack.at(stack.size()+(i)))
60 #define altstacktop(i)  (altstack.at(altstack.size()+(i)))
61 static inline void popstack(vector<valtype>& stack)
62 {
63     if (stack.empty())
64         throw runtime_error("popstack() : stack empty");
65     stack.pop_back();
66 }
67
68
69 const char* GetTxnOutputType(txnouttype t)
70 {
71     switch (t)
72     {
73     case TX_NONSTANDARD: return "nonstandard";
74     case TX_PUBKEY: return "pubkey";
75     case TX_PUBKEYHASH: return "pubkeyhash";
76     case TX_SCRIPTHASH: return "scripthash";
77     case TX_MULTISIG: return "multisig";
78     case TX_NULL_DATA: return "nulldata";
79     }
80     return NULL;
81 }
82
83
84 const char* GetOpName(opcodetype opcode)
85 {
86     switch (opcode)
87     {
88     // push value
89     case OP_0                      : return "0";
90     case OP_PUSHDATA1              : return "OP_PUSHDATA1";
91     case OP_PUSHDATA2              : return "OP_PUSHDATA2";
92     case OP_PUSHDATA4              : return "OP_PUSHDATA4";
93     case OP_1NEGATE                : return "-1";
94     case OP_RESERVED               : return "OP_RESERVED";
95     case OP_1                      : return "1";
96     case OP_2                      : return "2";
97     case OP_3                      : return "3";
98     case OP_4                      : return "4";
99     case OP_5                      : return "5";
100     case OP_6                      : return "6";
101     case OP_7                      : return "7";
102     case OP_8                      : return "8";
103     case OP_9                      : return "9";
104     case OP_10                     : return "10";
105     case OP_11                     : return "11";
106     case OP_12                     : return "12";
107     case OP_13                     : return "13";
108     case OP_14                     : return "14";
109     case OP_15                     : return "15";
110     case OP_16                     : return "16";
111
112     // control
113     case OP_NOP                    : return "OP_NOP";
114     case OP_VER                    : return "OP_VER";
115     case OP_IF                     : return "OP_IF";
116     case OP_NOTIF                  : return "OP_NOTIF";
117     case OP_VERIF                  : return "OP_VERIF";
118     case OP_VERNOTIF               : return "OP_VERNOTIF";
119     case OP_ELSE                   : return "OP_ELSE";
120     case OP_ENDIF                  : return "OP_ENDIF";
121     case OP_VERIFY                 : return "OP_VERIFY";
122     case OP_RETURN                 : return "OP_RETURN";
123
124     // stack ops
125     case OP_TOALTSTACK             : return "OP_TOALTSTACK";
126     case OP_FROMALTSTACK           : return "OP_FROMALTSTACK";
127     case OP_2DROP                  : return "OP_2DROP";
128     case OP_2DUP                   : return "OP_2DUP";
129     case OP_3DUP                   : return "OP_3DUP";
130     case OP_2OVER                  : return "OP_2OVER";
131     case OP_2ROT                   : return "OP_2ROT";
132     case OP_2SWAP                  : return "OP_2SWAP";
133     case OP_IFDUP                  : return "OP_IFDUP";
134     case OP_DEPTH                  : return "OP_DEPTH";
135     case OP_DROP                   : return "OP_DROP";
136     case OP_DUP                    : return "OP_DUP";
137     case OP_NIP                    : return "OP_NIP";
138     case OP_OVER                   : return "OP_OVER";
139     case OP_PICK                   : return "OP_PICK";
140     case OP_ROLL                   : return "OP_ROLL";
141     case OP_ROT                    : return "OP_ROT";
142     case OP_SWAP                   : return "OP_SWAP";
143     case OP_TUCK                   : return "OP_TUCK";
144
145     // splice ops
146     case OP_CAT                    : return "OP_CAT";
147     case OP_SUBSTR                 : return "OP_SUBSTR";
148     case OP_LEFT                   : return "OP_LEFT";
149     case OP_RIGHT                  : return "OP_RIGHT";
150     case OP_SIZE                   : return "OP_SIZE";
151
152     // bit logic
153     case OP_INVERT                 : return "OP_INVERT";
154     case OP_AND                    : return "OP_AND";
155     case OP_OR                     : return "OP_OR";
156     case OP_XOR                    : return "OP_XOR";
157     case OP_EQUAL                  : return "OP_EQUAL";
158     case OP_EQUALVERIFY            : return "OP_EQUALVERIFY";
159     case OP_RESERVED1              : return "OP_RESERVED1";
160     case OP_RESERVED2              : return "OP_RESERVED2";
161
162     // numeric
163     case OP_1ADD                   : return "OP_1ADD";
164     case OP_1SUB                   : return "OP_1SUB";
165     case OP_2MUL                   : return "OP_2MUL";
166     case OP_2DIV                   : return "OP_2DIV";
167     case OP_NEGATE                 : return "OP_NEGATE";
168     case OP_ABS                    : return "OP_ABS";
169     case OP_NOT                    : return "OP_NOT";
170     case OP_0NOTEQUAL              : return "OP_0NOTEQUAL";
171     case OP_ADD                    : return "OP_ADD";
172     case OP_SUB                    : return "OP_SUB";
173     case OP_MUL                    : return "OP_MUL";
174     case OP_DIV                    : return "OP_DIV";
175     case OP_MOD                    : return "OP_MOD";
176     case OP_LSHIFT                 : return "OP_LSHIFT";
177     case OP_RSHIFT                 : return "OP_RSHIFT";
178     case OP_BOOLAND                : return "OP_BOOLAND";
179     case OP_BOOLOR                 : return "OP_BOOLOR";
180     case OP_NUMEQUAL               : return "OP_NUMEQUAL";
181     case OP_NUMEQUALVERIFY         : return "OP_NUMEQUALVERIFY";
182     case OP_NUMNOTEQUAL            : return "OP_NUMNOTEQUAL";
183     case OP_LESSTHAN               : return "OP_LESSTHAN";
184     case OP_GREATERTHAN            : return "OP_GREATERTHAN";
185     case OP_LESSTHANOREQUAL        : return "OP_LESSTHANOREQUAL";
186     case OP_GREATERTHANOREQUAL     : return "OP_GREATERTHANOREQUAL";
187     case OP_MIN                    : return "OP_MIN";
188     case OP_MAX                    : return "OP_MAX";
189     case OP_WITHIN                 : return "OP_WITHIN";
190
191     // crypto
192     case OP_RIPEMD160              : return "OP_RIPEMD160";
193     case OP_SHA1                   : return "OP_SHA1";
194     case OP_SHA256                 : return "OP_SHA256";
195     case OP_HASH160                : return "OP_HASH160";
196     case OP_HASH256                : return "OP_HASH256";
197     case OP_CODESEPARATOR          : return "OP_CODESEPARATOR";
198     case OP_CHECKSIG               : return "OP_CHECKSIG";
199     case OP_CHECKSIGVERIFY         : return "OP_CHECKSIGVERIFY";
200     case OP_CHECKMULTISIG          : return "OP_CHECKMULTISIG";
201     case OP_CHECKMULTISIGVERIFY    : return "OP_CHECKMULTISIGVERIFY";
202
203     // expanson
204     case OP_NOP1                   : return "OP_NOP1";
205     case OP_NOP2                   : return "OP_NOP2";
206     case OP_NOP3                   : return "OP_NOP3";
207     case OP_NOP4                   : return "OP_NOP4";
208     case OP_NOP5                   : return "OP_NOP5";
209     case OP_NOP6                   : return "OP_NOP6";
210     case OP_NOP7                   : return "OP_NOP7";
211     case OP_NOP8                   : return "OP_NOP8";
212     case OP_NOP9                   : return "OP_NOP9";
213     case OP_NOP10                  : return "OP_NOP10";
214
215     case OP_INVALIDOPCODE          : return "OP_INVALIDOPCODE";
216
217     // Note:
218     //  The template matching params OP_SMALLDATA/etc are defined in opcodetype enum
219     //  as kind of implementation hack, they are *NOT* real opcodes.  If found in real
220     //  Script, just let the default: case deal with them.
221
222     default:
223         return "OP_UNKNOWN";
224     }
225 }
226
227 bool IsCanonicalPubKey(const valtype &vchPubKey, unsigned int flags) {
228     if (!(flags & SCRIPT_VERIFY_STRICTENC))
229         return true;
230
231     if (vchPubKey.size() < 33)
232         return error("Non-canonical public key: too short");
233     if (vchPubKey[0] == 0x04) {
234         if (vchPubKey.size() != 65)
235             return error("Non-canonical public key: invalid length for uncompressed key");
236     } else if (vchPubKey[0] == 0x02 || vchPubKey[0] == 0x03) {
237         if (vchPubKey.size() != 33)
238             return error("Non-canonical public key: invalid length for compressed key");
239     } else {
240         return error("Non-canonical public key: compressed nor uncompressed");
241     }
242     return true;
243 }
244
245 bool IsCanonicalSignature(const valtype &vchSig, unsigned int flags) {
246     if (!(flags & SCRIPT_VERIFY_STRICTENC))
247         return true;
248
249     // See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
250     // A canonical signature exists of: <30> <total len> <02> <len R> <R> <02> <len S> <S> <hashtype>
251     // Where R and S are not negative (their first byte has its highest bit not set), and not
252     // excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
253     // in which case a single 0 byte is necessary and even required).
254     if (vchSig.size() < 9)
255         return error("Non-canonical signature: too short");
256     if (vchSig.size() > 73)
257         return error("Non-canonical signature: too long");
258     unsigned char nHashType = vchSig[vchSig.size() - 1] & (~(SIGHASH_ANYONECANPAY));
259     if (nHashType < SIGHASH_ALL || nHashType > SIGHASH_SINGLE)
260         return error("Non-canonical signature: unknown hashtype byte");
261     if (vchSig[0] != 0x30)
262         return error("Non-canonical signature: wrong type");
263     if (vchSig[1] != vchSig.size()-3)
264         return error("Non-canonical signature: wrong length marker");
265     unsigned int nLenR = vchSig[3];
266     if (5 + nLenR >= vchSig.size())
267         return error("Non-canonical signature: S length misplaced");
268     unsigned int nLenS = vchSig[5+nLenR];
269     if ((unsigned long)(nLenR+nLenS+7) != vchSig.size())
270         return error("Non-canonical signature: R+S length mismatch");
271
272     const unsigned char *R = &vchSig[4];
273     if (R[-2] != 0x02)
274         return error("Non-canonical signature: R value type mismatch");
275     if (nLenR == 0)
276         return error("Non-canonical signature: R length is zero");
277     if (R[0] & 0x80)
278         return error("Non-canonical signature: R value negative");
279     if (nLenR > 1 && (R[0] == 0x00) && !(R[1] & 0x80))
280         return error("Non-canonical signature: R value excessively padded");
281
282     const unsigned char *S = &vchSig[6+nLenR];
283     if (S[-2] != 0x02)
284         return error("Non-canonical signature: S value type mismatch");
285     if (nLenS == 0)
286         return error("Non-canonical signature: S length is zero");
287     if (S[0] & 0x80)
288         return error("Non-canonical signature: S value negative");
289     if (nLenS > 1 && (S[0] == 0x00) && !(S[1] & 0x80))
290         return error("Non-canonical signature: S value excessively padded");
291
292     if (flags & SCRIPT_VERIFY_LOW_S) {
293         // If the S value is above the order of the curve divided by two, its
294         // complement modulo the order could have been used instead, which is
295         // one byte shorter when encoded correctly.
296         if (!CKey::CheckSignatureElement(S, nLenS, true))
297             return error("Non-canonical signature: S value is unnecessarily high");
298     }
299
300     return true;
301 }
302
303 bool EvalScript(vector<vector<unsigned char> >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType)
304 {
305     CScript::const_iterator pc = script.begin();
306     CScript::const_iterator pend = script.end();
307     CScript::const_iterator pbegincodehash = script.begin();
308     opcodetype opcode;
309     valtype vchPushValue;
310     vector<bool> vfExec;
311     vector<valtype> altstack;
312     if (script.size() > 10000)
313         return false;
314     int nOpCount = 0;
315
316     try
317     {
318         while (pc < pend)
319         {
320             bool fExec = !count(vfExec.begin(), vfExec.end(), false);
321
322             //
323             // Read instruction
324             //
325             if (!script.GetOp(pc, opcode, vchPushValue))
326                 return false;
327             if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE)
328                 return false;
329
330             // Note how OP_RESERVED does not count towards the opcode limit.
331             if (opcode > OP_16 && ++nOpCount > 201)
332                 return false;
333
334             if (opcode == OP_CAT ||
335                 opcode == OP_SUBSTR ||
336                 opcode == OP_LEFT ||
337                 opcode == OP_RIGHT ||
338                 opcode == OP_INVERT ||
339                 opcode == OP_AND ||
340                 opcode == OP_OR ||
341                 opcode == OP_XOR ||
342                 opcode == OP_2MUL ||
343                 opcode == OP_2DIV ||
344                 opcode == OP_MUL ||
345                 opcode == OP_DIV ||
346                 opcode == OP_MOD ||
347                 opcode == OP_LSHIFT ||
348                 opcode == OP_RSHIFT)
349                 return false; // Disabled opcodes.
350
351             if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4)
352                 stack.push_back(vchPushValue);
353             else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF))
354             switch (opcode)
355             {
356                 //
357                 // Push value
358                 //
359                 case OP_1NEGATE:
360                 case OP_1:
361                 case OP_2:
362                 case OP_3:
363                 case OP_4:
364                 case OP_5:
365                 case OP_6:
366                 case OP_7:
367                 case OP_8:
368                 case OP_9:
369                 case OP_10:
370                 case OP_11:
371                 case OP_12:
372                 case OP_13:
373                 case OP_14:
374                 case OP_15:
375                 case OP_16:
376                 {
377                     // ( -- value)
378                     CScriptNum bn((int)opcode - (int)(OP_1 - 1));
379                     stack.push_back(bn.getvch());
380                 }
381                 break;
382
383
384                 //
385                 // Control
386                 //
387                 case OP_NOP:
388                 case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5:
389                 case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10:
390                 break;
391
392                 case OP_IF:
393                 case OP_NOTIF:
394                 {
395                     // <expression> if [statements] [else [statements]] endif
396                     bool fValue = false;
397                     if (fExec)
398                     {
399                         if (stack.size() < 1)
400                             return false;
401                         valtype& vch = stacktop(-1);
402                         fValue = CastToBool(vch);
403                         if (opcode == OP_NOTIF)
404                             fValue = !fValue;
405                         popstack(stack);
406                     }
407                     vfExec.push_back(fValue);
408                 }
409                 break;
410
411                 case OP_ELSE:
412                 {
413                     if (vfExec.empty())
414                         return false;
415                     vfExec.back() = !vfExec.back();
416                 }
417                 break;
418
419                 case OP_ENDIF:
420                 {
421                     if (vfExec.empty())
422                         return false;
423                     vfExec.pop_back();
424                 }
425                 break;
426
427                 case OP_VERIFY:
428                 {
429                     // (true -- ) or
430                     // (false -- false) and return
431                     if (stack.size() < 1)
432                         return false;
433                     bool fValue = CastToBool(stacktop(-1));
434                     if (fValue)
435                         popstack(stack);
436                     else
437                         return false;
438                 }
439                 break;
440
441                 case OP_RETURN:
442                 {
443                     return false;
444                 }
445                 break;
446
447
448                 //
449                 // Stack ops
450                 //
451                 case OP_TOALTSTACK:
452                 {
453                     if (stack.size() < 1)
454                         return false;
455                     altstack.push_back(stacktop(-1));
456                     popstack(stack);
457                 }
458                 break;
459
460                 case OP_FROMALTSTACK:
461                 {
462                     if (altstack.size() < 1)
463                         return false;
464                     stack.push_back(altstacktop(-1));
465                     popstack(altstack);
466                 }
467                 break;
468
469                 case OP_2DROP:
470                 {
471                     // (x1 x2 -- )
472                     if (stack.size() < 2)
473                         return false;
474                     popstack(stack);
475                     popstack(stack);
476                 }
477                 break;
478
479                 case OP_2DUP:
480                 {
481                     // (x1 x2 -- x1 x2 x1 x2)
482                     if (stack.size() < 2)
483                         return false;
484                     valtype vch1 = stacktop(-2);
485                     valtype vch2 = stacktop(-1);
486                     stack.push_back(vch1);
487                     stack.push_back(vch2);
488                 }
489                 break;
490
491                 case OP_3DUP:
492                 {
493                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
494                     if (stack.size() < 3)
495                         return false;
496                     valtype vch1 = stacktop(-3);
497                     valtype vch2 = stacktop(-2);
498                     valtype vch3 = stacktop(-1);
499                     stack.push_back(vch1);
500                     stack.push_back(vch2);
501                     stack.push_back(vch3);
502                 }
503                 break;
504
505                 case OP_2OVER:
506                 {
507                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
508                     if (stack.size() < 4)
509                         return false;
510                     valtype vch1 = stacktop(-4);
511                     valtype vch2 = stacktop(-3);
512                     stack.push_back(vch1);
513                     stack.push_back(vch2);
514                 }
515                 break;
516
517                 case OP_2ROT:
518                 {
519                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
520                     if (stack.size() < 6)
521                         return false;
522                     valtype vch1 = stacktop(-6);
523                     valtype vch2 = stacktop(-5);
524                     stack.erase(stack.end()-6, stack.end()-4);
525                     stack.push_back(vch1);
526                     stack.push_back(vch2);
527                 }
528                 break;
529
530                 case OP_2SWAP:
531                 {
532                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
533                     if (stack.size() < 4)
534                         return false;
535                     swap(stacktop(-4), stacktop(-2));
536                     swap(stacktop(-3), stacktop(-1));
537                 }
538                 break;
539
540                 case OP_IFDUP:
541                 {
542                     // (x - 0 | x x)
543                     if (stack.size() < 1)
544                         return false;
545                     valtype vch = stacktop(-1);
546                     if (CastToBool(vch))
547                         stack.push_back(vch);
548                 }
549                 break;
550
551                 case OP_DEPTH:
552                 {
553                     // -- stacksize
554                     CScriptNum bn(stack.size());
555                     stack.push_back(bn.getvch());
556                 }
557                 break;
558
559                 case OP_DROP:
560                 {
561                     // (x -- )
562                     if (stack.size() < 1)
563                         return false;
564                     popstack(stack);
565                 }
566                 break;
567
568                 case OP_DUP:
569                 {
570                     // (x -- x x)
571                     if (stack.size() < 1)
572                         return false;
573                     valtype vch = stacktop(-1);
574                     stack.push_back(vch);
575                 }
576                 break;
577
578                 case OP_NIP:
579                 {
580                     // (x1 x2 -- x2)
581                     if (stack.size() < 2)
582                         return false;
583                     stack.erase(stack.end() - 2);
584                 }
585                 break;
586
587                 case OP_OVER:
588                 {
589                     // (x1 x2 -- x1 x2 x1)
590                     if (stack.size() < 2)
591                         return false;
592                     valtype vch = stacktop(-2);
593                     stack.push_back(vch);
594                 }
595                 break;
596
597                 case OP_PICK:
598                 case OP_ROLL:
599                 {
600                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
601                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
602                     if (stack.size() < 2)
603                         return false;
604                     int n = CScriptNum(stacktop(-1)).getint();
605                     popstack(stack);
606                     if (n < 0 || n >= (int)stack.size())
607                         return false;
608                     valtype vch = stacktop(-n-1);
609                     if (opcode == OP_ROLL)
610                         stack.erase(stack.end()-n-1);
611                     stack.push_back(vch);
612                 }
613                 break;
614
615                 case OP_ROT:
616                 {
617                     // (x1 x2 x3 -- x2 x3 x1)
618                     //  x2 x1 x3  after first swap
619                     //  x2 x3 x1  after second swap
620                     if (stack.size() < 3)
621                         return false;
622                     swap(stacktop(-3), stacktop(-2));
623                     swap(stacktop(-2), stacktop(-1));
624                 }
625                 break;
626
627                 case OP_SWAP:
628                 {
629                     // (x1 x2 -- x2 x1)
630                     if (stack.size() < 2)
631                         return false;
632                     swap(stacktop(-2), stacktop(-1));
633                 }
634                 break;
635
636                 case OP_TUCK:
637                 {
638                     // (x1 x2 -- x2 x1 x2)
639                     if (stack.size() < 2)
640                         return false;
641                     valtype vch = stacktop(-1);
642                     stack.insert(stack.end()-2, vch);
643                 }
644                 break;
645
646
647                 case OP_SIZE:
648                 {
649                     // (in -- in size)
650                     if (stack.size() < 1)
651                         return false;
652                     CScriptNum bn(stacktop(-1).size());
653                     stack.push_back(bn.getvch());
654                 }
655                 break;
656
657
658                 //
659                 // Bitwise logic
660                 //
661                 case OP_EQUAL:
662                 case OP_EQUALVERIFY:
663                 //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL
664                 {
665                     // (x1 x2 - bool)
666                     if (stack.size() < 2)
667                         return false;
668                     valtype& vch1 = stacktop(-2);
669                     valtype& vch2 = stacktop(-1);
670                     bool fEqual = (vch1 == vch2);
671                     // OP_NOTEQUAL is disabled because it would be too easy to say
672                     // something like n != 1 and have some wiseguy pass in 1 with extra
673                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
674                     //if (opcode == OP_NOTEQUAL)
675                     //    fEqual = !fEqual;
676                     popstack(stack);
677                     popstack(stack);
678                     stack.push_back(fEqual ? vchTrue : vchFalse);
679                     if (opcode == OP_EQUALVERIFY)
680                     {
681                         if (fEqual)
682                             popstack(stack);
683                         else
684                             return false;
685                     }
686                 }
687                 break;
688
689
690                 //
691                 // Numeric
692                 //
693                 case OP_1ADD:
694                 case OP_1SUB:
695                 case OP_NEGATE:
696                 case OP_ABS:
697                 case OP_NOT:
698                 case OP_0NOTEQUAL:
699                 {
700                     // (in -- out)
701                     if (stack.size() < 1)
702                         return false;
703                     CScriptNum bn(stacktop(-1));
704                     switch (opcode)
705                     {
706                     case OP_1ADD:       bn += bnOne; break;
707                     case OP_1SUB:       bn -= bnOne; break;
708                     case OP_NEGATE:     bn = -bn; break;
709                     case OP_ABS:        if (bn < bnZero) bn = -bn; break;
710                     case OP_NOT:        bn = (bn == bnZero); break;
711                     case OP_0NOTEQUAL:  bn = (bn != bnZero); break;
712                     default:            assert(!"invalid opcode"); break;
713                     }
714                     popstack(stack);
715                     stack.push_back(bn.getvch());
716                 }
717                 break;
718
719                 case OP_ADD:
720                 case OP_SUB:
721                 case OP_BOOLAND:
722                 case OP_BOOLOR:
723                 case OP_NUMEQUAL:
724                 case OP_NUMEQUALVERIFY:
725                 case OP_NUMNOTEQUAL:
726                 case OP_LESSTHAN:
727                 case OP_GREATERTHAN:
728                 case OP_LESSTHANOREQUAL:
729                 case OP_GREATERTHANOREQUAL:
730                 case OP_MIN:
731                 case OP_MAX:
732                 {
733                     // (x1 x2 -- out)
734                     if (stack.size() < 2)
735                         return false;
736                     CScriptNum bn1(stacktop(-2));
737                     CScriptNum bn2(stacktop(-1));
738                     CScriptNum bn(0);
739                     switch (opcode)
740                     {
741                     case OP_ADD:
742                         bn = bn1 + bn2;
743                         break;
744
745                     case OP_SUB:
746                         bn = bn1 - bn2;
747                         break;
748
749                     case OP_BOOLAND:             bn = (bn1 != bnZero && bn2 != bnZero); break;
750                     case OP_BOOLOR:              bn = (bn1 != bnZero || bn2 != bnZero); break;
751                     case OP_NUMEQUAL:            bn = (bn1 == bn2); break;
752                     case OP_NUMEQUALVERIFY:      bn = (bn1 == bn2); break;
753                     case OP_NUMNOTEQUAL:         bn = (bn1 != bn2); break;
754                     case OP_LESSTHAN:            bn = (bn1 < bn2); break;
755                     case OP_GREATERTHAN:         bn = (bn1 > bn2); break;
756                     case OP_LESSTHANOREQUAL:     bn = (bn1 <= bn2); break;
757                     case OP_GREATERTHANOREQUAL:  bn = (bn1 >= bn2); break;
758                     case OP_MIN:                 bn = (bn1 < bn2 ? bn1 : bn2); break;
759                     case OP_MAX:                 bn = (bn1 > bn2 ? bn1 : bn2); break;
760                     default:                     assert(!"invalid opcode"); break;
761                     }
762                     popstack(stack);
763                     popstack(stack);
764                     stack.push_back(bn.getvch());
765
766                     if (opcode == OP_NUMEQUALVERIFY)
767                     {
768                         if (CastToBool(stacktop(-1)))
769                             popstack(stack);
770                         else
771                             return false;
772                     }
773                 }
774                 break;
775
776                 case OP_WITHIN:
777                 {
778                     // (x min max -- out)
779                     if (stack.size() < 3)
780                         return false;
781                     CScriptNum bn1(stacktop(-3));
782                     CScriptNum bn2(stacktop(-2));
783                     CScriptNum bn3(stacktop(-1));
784                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
785                     popstack(stack);
786                     popstack(stack);
787                     popstack(stack);
788                     stack.push_back(fValue ? vchTrue : vchFalse);
789                 }
790                 break;
791
792
793                 //
794                 // Crypto
795                 //
796                 case OP_RIPEMD160:
797                 case OP_SHA1:
798                 case OP_SHA256:
799                 case OP_HASH160:
800                 case OP_HASH256:
801                 {
802                     // (in -- hash)
803                     if (stack.size() < 1)
804                         return false;
805                     valtype& vch = stacktop(-1);
806                     valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32);
807                     if (opcode == OP_RIPEMD160)
808                         CRIPEMD160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
809                     else if (opcode == OP_SHA1)
810                         CSHA1().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
811                     else if (opcode == OP_SHA256)
812                         CSHA256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
813                     else if (opcode == OP_HASH160)
814                         CHash160().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
815                     else if (opcode == OP_HASH256)
816                         CHash256().Write(&vch[0], vch.size()).Finalize(&vchHash[0]);
817                     popstack(stack);
818                     stack.push_back(vchHash);
819                 }
820                 break;
821
822                 case OP_CODESEPARATOR:
823                 {
824                     // Hash starts after the code separator
825                     pbegincodehash = pc;
826                 }
827                 break;
828
829                 case OP_CHECKSIG:
830                 case OP_CHECKSIGVERIFY:
831                 {
832                     // (sig pubkey -- bool)
833                     if (stack.size() < 2)
834                         return false;
835
836                     valtype& vchSig    = stacktop(-2);
837                     valtype& vchPubKey = stacktop(-1);
838
839                     // Subset of script starting at the most recent codeseparator
840                     CScript scriptCode(pbegincodehash, pend);
841
842                     // Drop the signature, since there's no way for a signature to sign itself
843                     scriptCode.FindAndDelete(CScript(vchSig));
844
845                     bool fSuccess = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
846                         CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
847
848                     popstack(stack);
849                     popstack(stack);
850                     stack.push_back(fSuccess ? vchTrue : vchFalse);
851                     if (opcode == OP_CHECKSIGVERIFY)
852                     {
853                         if (fSuccess)
854                             popstack(stack);
855                         else
856                             return false;
857                     }
858                 }
859                 break;
860
861                 case OP_CHECKMULTISIG:
862                 case OP_CHECKMULTISIGVERIFY:
863                 {
864                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
865
866                     int i = 1;
867                     if ((int)stack.size() < i)
868                         return false;
869
870                     int nKeysCount = CScriptNum(stacktop(-i)).getint();
871                     if (nKeysCount < 0 || nKeysCount > 20)
872                         return false;
873                     nOpCount += nKeysCount;
874                     if (nOpCount > 201)
875                         return false;
876                     int ikey = ++i;
877                     i += nKeysCount;
878                     if ((int)stack.size() < i)
879                         return false;
880
881                     int nSigsCount = CScriptNum(stacktop(-i)).getint();
882                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
883                         return false;
884                     int isig = ++i;
885                     i += nSigsCount;
886                     if ((int)stack.size() < i)
887                         return false;
888
889                     // Subset of script starting at the most recent codeseparator
890                     CScript scriptCode(pbegincodehash, pend);
891
892                     // Drop the signatures, since there's no way for a signature to sign itself
893                     for (int k = 0; k < nSigsCount; k++)
894                     {
895                         valtype& vchSig = stacktop(-isig-k);
896                         scriptCode.FindAndDelete(CScript(vchSig));
897                     }
898
899                     bool fSuccess = true;
900                     while (fSuccess && nSigsCount > 0)
901                     {
902                         valtype& vchSig    = stacktop(-isig);
903                         valtype& vchPubKey = stacktop(-ikey);
904
905                         // Check signature
906                         bool fOk = IsCanonicalSignature(vchSig, flags) && IsCanonicalPubKey(vchPubKey, flags) &&
907                             CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags);
908
909                         if (fOk) {
910                             isig++;
911                             nSigsCount--;
912                         }
913                         ikey++;
914                         nKeysCount--;
915
916                         // If there are more signatures left than keys left,
917                         // then too many signatures have failed
918                         if (nSigsCount > nKeysCount)
919                             fSuccess = false;
920                     }
921
922                     // Clean up stack of actual arguments
923                     while (i-- > 1)
924                         popstack(stack);
925
926                     // A bug causes CHECKMULTISIG to consume one extra argument
927                     // whose contents were not checked in any way.
928                     //
929                     // Unfortunately this is a potential source of mutability,
930                     // so optionally verify it is exactly equal to zero prior
931                     // to removing it from the stack.
932                     if (stack.size() < 1)
933                         return false;
934                     if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size())
935                         return error("CHECKMULTISIG dummy argument not null");
936                     popstack(stack);
937
938                     stack.push_back(fSuccess ? vchTrue : vchFalse);
939
940                     if (opcode == OP_CHECKMULTISIGVERIFY)
941                     {
942                         if (fSuccess)
943                             popstack(stack);
944                         else
945                             return false;
946                     }
947                 }
948                 break;
949
950                 default:
951                     return false;
952             }
953
954             // Size limits
955             if (stack.size() + altstack.size() > 1000)
956                 return false;
957         }
958     }
959     catch (...)
960     {
961         return false;
962     }
963
964
965     if (!vfExec.empty())
966         return false;
967
968     return true;
969 }
970
971
972
973
974
975
976
977 namespace {
978
979 /** Wrapper that serializes like CTransaction, but with the modifications
980  *  required for the signature hash done in-place
981  */
982 class CTransactionSignatureSerializer {
983 private:
984     const CTransaction &txTo;  // reference to the spending transaction (the one being serialized)
985     const CScript &scriptCode; // output script being consumed
986     const unsigned int nIn;    // input index of txTo being signed
987     const bool fAnyoneCanPay;  // whether the hashtype has the SIGHASH_ANYONECANPAY flag set
988     const bool fHashSingle;    // whether the hashtype is SIGHASH_SINGLE
989     const bool fHashNone;      // whether the hashtype is SIGHASH_NONE
990
991 public:
992     CTransactionSignatureSerializer(const CTransaction &txToIn, const CScript &scriptCodeIn, unsigned int nInIn, int nHashTypeIn) :
993         txTo(txToIn), scriptCode(scriptCodeIn), nIn(nInIn),
994         fAnyoneCanPay(!!(nHashTypeIn & SIGHASH_ANYONECANPAY)),
995         fHashSingle((nHashTypeIn & 0x1f) == SIGHASH_SINGLE),
996         fHashNone((nHashTypeIn & 0x1f) == SIGHASH_NONE) {}
997
998     /** Serialize the passed scriptCode, skipping OP_CODESEPARATORs */
999     template<typename S>
1000     void SerializeScriptCode(S &s, int nType, int nVersion) const {
1001         CScript::const_iterator it = scriptCode.begin();
1002         CScript::const_iterator itBegin = it;
1003         opcodetype opcode;
1004         unsigned int nCodeSeparators = 0;
1005         while (scriptCode.GetOp(it, opcode)) {
1006             if (opcode == OP_CODESEPARATOR)
1007                 nCodeSeparators++;
1008         }
1009         ::WriteCompactSize(s, scriptCode.size() - nCodeSeparators);
1010         it = itBegin;
1011         while (scriptCode.GetOp(it, opcode)) {
1012             if (opcode == OP_CODESEPARATOR) {
1013                 s.write((char*)&itBegin[0], it-itBegin-1);
1014                 itBegin = it;
1015             }
1016         }
1017         s.write((char*)&itBegin[0], it-itBegin);
1018     }
1019
1020     /** Serialize an input of txTo */
1021     template<typename S>
1022     void SerializeInput(S &s, unsigned int nInput, int nType, int nVersion) const {
1023         // In case of SIGHASH_ANYONECANPAY, only the input being signed is serialized
1024         if (fAnyoneCanPay)
1025             nInput = nIn;
1026         // Serialize the prevout
1027         ::Serialize(s, txTo.vin[nInput].prevout, nType, nVersion);
1028         // Serialize the script
1029         if (nInput != nIn)
1030             // Blank out other inputs' signatures
1031             ::Serialize(s, CScript(), nType, nVersion);
1032         else
1033             SerializeScriptCode(s, nType, nVersion);
1034         // Serialize the nSequence
1035         if (nInput != nIn && (fHashSingle || fHashNone))
1036             // let the others update at will
1037             ::Serialize(s, (int)0, nType, nVersion);
1038         else
1039             ::Serialize(s, txTo.vin[nInput].nSequence, nType, nVersion);
1040     }
1041
1042     /** Serialize an output of txTo */
1043     template<typename S>
1044     void SerializeOutput(S &s, unsigned int nOutput, int nType, int nVersion) const {
1045         if (fHashSingle && nOutput != nIn)
1046             // Do not lock-in the txout payee at other indices as txin
1047             ::Serialize(s, CTxOut(), nType, nVersion);
1048         else
1049             ::Serialize(s, txTo.vout[nOutput], nType, nVersion);
1050     }
1051
1052     /** Serialize txTo */
1053     template<typename S>
1054     void Serialize(S &s, int nType, int nVersion) const {
1055         // Serialize nVersion
1056         ::Serialize(s, txTo.nVersion, nType, nVersion);
1057         // Serialize vin
1058         unsigned int nInputs = fAnyoneCanPay ? 1 : txTo.vin.size();
1059         ::WriteCompactSize(s, nInputs);
1060         for (unsigned int nInput = 0; nInput < nInputs; nInput++)
1061              SerializeInput(s, nInput, nType, nVersion);
1062         // Serialize vout
1063         unsigned int nOutputs = fHashNone ? 0 : (fHashSingle ? nIn+1 : txTo.vout.size());
1064         ::WriteCompactSize(s, nOutputs);
1065         for (unsigned int nOutput = 0; nOutput < nOutputs; nOutput++)
1066              SerializeOutput(s, nOutput, nType, nVersion);
1067         // Serialie nLockTime
1068         ::Serialize(s, txTo.nLockTime, nType, nVersion);
1069     }
1070 };
1071
1072 } // anon namespace
1073
1074 uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType)
1075 {
1076     if (nIn >= txTo.vin.size()) {
1077         LogPrintf("ERROR: SignatureHash() : nIn=%d out of range\n", nIn);
1078         return 1;
1079     }
1080
1081     // Check for invalid use of SIGHASH_SINGLE
1082     if ((nHashType & 0x1f) == SIGHASH_SINGLE) {
1083         if (nIn >= txTo.vout.size()) {
1084             LogPrintf("ERROR: SignatureHash() : nOut=%d out of range\n", nIn);
1085             return 1;
1086         }
1087     }
1088
1089     // Wrapper to serialize only the necessary parts of the transaction being signed
1090     CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType);
1091
1092     // Serialize and hash
1093     CHashWriter ss(SER_GETHASH, 0);
1094     ss << txTmp << nHashType;
1095     return ss.GetHash();
1096 }
1097
1098 // Valid signature cache, to avoid doing expensive ECDSA signature checking
1099 // twice for every transaction (once when accepted into memory pool, and
1100 // again when accepted into the block chain)
1101 class CSignatureCache
1102 {
1103 private:
1104      // sigdata_type is (signature hash, signature, public key):
1105     typedef boost::tuple<uint256, std::vector<unsigned char>, CPubKey> sigdata_type;
1106     std::set< sigdata_type> setValid;
1107     boost::shared_mutex cs_sigcache;
1108
1109 public:
1110     bool
1111     Get(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1112     {
1113         boost::shared_lock<boost::shared_mutex> lock(cs_sigcache);
1114
1115         sigdata_type k(hash, vchSig, pubKey);
1116         std::set<sigdata_type>::iterator mi = setValid.find(k);
1117         if (mi != setValid.end())
1118             return true;
1119         return false;
1120     }
1121
1122     void Set(const uint256 &hash, const std::vector<unsigned char>& vchSig, const CPubKey& pubKey)
1123     {
1124         // DoS prevention: limit cache size to less than 10MB
1125         // (~200 bytes per cache entry times 50,000 entries)
1126         // Since there are a maximum of 20,000 signature operations per block
1127         // 50,000 is a reasonable default.
1128         int64_t nMaxCacheSize = GetArg("-maxsigcachesize", 50000);
1129         if (nMaxCacheSize <= 0) return;
1130
1131         boost::unique_lock<boost::shared_mutex> lock(cs_sigcache);
1132
1133         while (static_cast<int64_t>(setValid.size()) > nMaxCacheSize)
1134         {
1135             // Evict a random entry. Random because that helps
1136             // foil would-be DoS attackers who might try to pre-generate
1137             // and re-use a set of valid signatures just-slightly-greater
1138             // than our cache size.
1139             uint256 randomHash = GetRandHash();
1140             std::vector<unsigned char> unused;
1141             std::set<sigdata_type>::iterator it =
1142                 setValid.lower_bound(sigdata_type(randomHash, unused, unused));
1143             if (it == setValid.end())
1144                 it = setValid.begin();
1145             setValid.erase(*it);
1146         }
1147
1148         sigdata_type k(hash, vchSig, pubKey);
1149         setValid.insert(k);
1150     }
1151 };
1152
1153 bool CheckSig(vector<unsigned char> vchSig, const vector<unsigned char> &vchPubKey, const CScript &scriptCode,
1154               const CTransaction& txTo, unsigned int nIn, int nHashType, int flags)
1155 {
1156     static CSignatureCache signatureCache;
1157
1158     CPubKey pubkey(vchPubKey);
1159     if (!pubkey.IsValid())
1160         return false;
1161
1162     // Hash type is one byte tacked on to the end of the signature
1163     if (vchSig.empty())
1164         return false;
1165     if (nHashType == 0)
1166         nHashType = vchSig.back();
1167     else if (nHashType != vchSig.back())
1168         return false;
1169     vchSig.pop_back();
1170
1171     uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
1172
1173     if (signatureCache.Get(sighash, vchSig, pubkey))
1174         return true;
1175
1176     if (!pubkey.Verify(sighash, vchSig))
1177         return false;
1178
1179     if (!(flags & SCRIPT_VERIFY_NOCACHE))
1180         signatureCache.Set(sighash, vchSig, pubkey);
1181
1182     return true;
1183 }
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193 //
1194 // Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
1195 //
1196 bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, vector<vector<unsigned char> >& vSolutionsRet)
1197 {
1198     // Templates
1199     static multimap<txnouttype, CScript> mTemplates;
1200     if (mTemplates.empty())
1201     {
1202         // Standard tx, sender provides pubkey, receiver adds signature
1203         mTemplates.insert(make_pair(TX_PUBKEY, CScript() << OP_PUBKEY << OP_CHECKSIG));
1204
1205         // Bitcoin address tx, sender provides hash of pubkey, receiver provides signature and pubkey
1206         mTemplates.insert(make_pair(TX_PUBKEYHASH, CScript() << OP_DUP << OP_HASH160 << OP_PUBKEYHASH << OP_EQUALVERIFY << OP_CHECKSIG));
1207
1208         // Sender provides N pubkeys, receivers provides M signatures
1209         mTemplates.insert(make_pair(TX_MULTISIG, CScript() << OP_SMALLINTEGER << OP_PUBKEYS << OP_SMALLINTEGER << OP_CHECKMULTISIG));
1210
1211         // Empty, provably prunable, data-carrying output
1212         if (GetBoolArg("-datacarrier", true))
1213             mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN << OP_SMALLDATA));
1214         mTemplates.insert(make_pair(TX_NULL_DATA, CScript() << OP_RETURN));
1215     }
1216
1217     // Shortcut for pay-to-script-hash, which are more constrained than the other types:
1218     // it is always OP_HASH160 20 [20 byte hash] OP_EQUAL
1219     if (scriptPubKey.IsPayToScriptHash())
1220     {
1221         typeRet = TX_SCRIPTHASH;
1222         vector<unsigned char> hashBytes(scriptPubKey.begin()+2, scriptPubKey.begin()+22);
1223         vSolutionsRet.push_back(hashBytes);
1224         return true;
1225     }
1226
1227     // Scan templates
1228     const CScript& script1 = scriptPubKey;
1229     BOOST_FOREACH(const PAIRTYPE(txnouttype, CScript)& tplate, mTemplates)
1230     {
1231         const CScript& script2 = tplate.second;
1232         vSolutionsRet.clear();
1233
1234         opcodetype opcode1, opcode2;
1235         vector<unsigned char> vch1, vch2;
1236
1237         // Compare
1238         CScript::const_iterator pc1 = script1.begin();
1239         CScript::const_iterator pc2 = script2.begin();
1240         while (true)
1241         {
1242             if (pc1 == script1.end() && pc2 == script2.end())
1243             {
1244                 // Found a match
1245                 typeRet = tplate.first;
1246                 if (typeRet == TX_MULTISIG)
1247                 {
1248                     // Additional checks for TX_MULTISIG:
1249                     unsigned char m = vSolutionsRet.front()[0];
1250                     unsigned char n = vSolutionsRet.back()[0];
1251                     if (m < 1 || n < 1 || m > n || vSolutionsRet.size()-2 != n)
1252                         return false;
1253                 }
1254                 return true;
1255             }
1256             if (!script1.GetOp(pc1, opcode1, vch1))
1257                 break;
1258             if (!script2.GetOp(pc2, opcode2, vch2))
1259                 break;
1260
1261             // Template matching opcodes:
1262             if (opcode2 == OP_PUBKEYS)
1263             {
1264                 while (vch1.size() >= 33 && vch1.size() <= 65)
1265                 {
1266                     vSolutionsRet.push_back(vch1);
1267                     if (!script1.GetOp(pc1, opcode1, vch1))
1268                         break;
1269                 }
1270                 if (!script2.GetOp(pc2, opcode2, vch2))
1271                     break;
1272                 // Normal situation is to fall through
1273                 // to other if/else statements
1274             }
1275
1276             if (opcode2 == OP_PUBKEY)
1277             {
1278                 if (vch1.size() < 33 || vch1.size() > 65)
1279                     break;
1280                 vSolutionsRet.push_back(vch1);
1281             }
1282             else if (opcode2 == OP_PUBKEYHASH)
1283             {
1284                 if (vch1.size() != sizeof(uint160))
1285                     break;
1286                 vSolutionsRet.push_back(vch1);
1287             }
1288             else if (opcode2 == OP_SMALLINTEGER)
1289             {   // Single-byte small integer pushed onto vSolutions
1290                 if (opcode1 == OP_0 ||
1291                     (opcode1 >= OP_1 && opcode1 <= OP_16))
1292                 {
1293                     char n = (char)CScript::DecodeOP_N(opcode1);
1294                     vSolutionsRet.push_back(valtype(1, n));
1295                 }
1296                 else
1297                     break;
1298             }
1299             else if (opcode2 == OP_SMALLDATA)
1300             {
1301                 // small pushdata, <= MAX_OP_RETURN_RELAY bytes
1302                 if (vch1.size() > MAX_OP_RETURN_RELAY)
1303                     break;
1304             }
1305             else if (opcode1 != opcode2 || vch1 != vch2)
1306             {
1307                 // Others must match exactly
1308                 break;
1309             }
1310         }
1311     }
1312
1313     vSolutionsRet.clear();
1314     typeRet = TX_NONSTANDARD;
1315     return false;
1316 }
1317
1318
1319 bool Sign1(const CKeyID& address, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1320 {
1321     CKey key;
1322     if (!keystore.GetKey(address, key))
1323         return false;
1324
1325     vector<unsigned char> vchSig;
1326     if (!key.Sign(hash, vchSig))
1327         return false;
1328     vchSig.push_back((unsigned char)nHashType);
1329     scriptSigRet << vchSig;
1330
1331     return true;
1332 }
1333
1334 bool SignN(const vector<valtype>& multisigdata, const CKeyStore& keystore, uint256 hash, int nHashType, CScript& scriptSigRet)
1335 {
1336     int nSigned = 0;
1337     int nRequired = multisigdata.front()[0];
1338     for (unsigned int i = 1; i < multisigdata.size()-1 && nSigned < nRequired; i++)
1339     {
1340         const valtype& pubkey = multisigdata[i];
1341         CKeyID keyID = CPubKey(pubkey).GetID();
1342         if (Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1343             ++nSigned;
1344     }
1345     return nSigned==nRequired;
1346 }
1347
1348 //
1349 // Sign scriptPubKey with private keys stored in keystore, given transaction hash and hash type.
1350 // Signatures are returned in scriptSigRet (or returns false if scriptPubKey can't be signed),
1351 // unless whichTypeRet is TX_SCRIPTHASH, in which case scriptSigRet is the redemption script.
1352 // Returns false if scriptPubKey could not be completely satisfied.
1353 //
1354 bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType,
1355                   CScript& scriptSigRet, txnouttype& whichTypeRet)
1356 {
1357     scriptSigRet.clear();
1358
1359     vector<valtype> vSolutions;
1360     if (!Solver(scriptPubKey, whichTypeRet, vSolutions))
1361         return false;
1362
1363     CKeyID keyID;
1364     switch (whichTypeRet)
1365     {
1366     case TX_NONSTANDARD:
1367     case TX_NULL_DATA:
1368         return false;
1369     case TX_PUBKEY:
1370         keyID = CPubKey(vSolutions[0]).GetID();
1371         return Sign1(keyID, keystore, hash, nHashType, scriptSigRet);
1372     case TX_PUBKEYHASH:
1373         keyID = CKeyID(uint160(vSolutions[0]));
1374         if (!Sign1(keyID, keystore, hash, nHashType, scriptSigRet))
1375             return false;
1376         else
1377         {
1378             CPubKey vch;
1379             keystore.GetPubKey(keyID, vch);
1380             scriptSigRet << vch;
1381         }
1382         return true;
1383     case TX_SCRIPTHASH:
1384         return keystore.GetCScript(uint160(vSolutions[0]), scriptSigRet);
1385
1386     case TX_MULTISIG:
1387         scriptSigRet << OP_0; // workaround CHECKMULTISIG bug
1388         return (SignN(vSolutions, keystore, hash, nHashType, scriptSigRet));
1389     }
1390     return false;
1391 }
1392
1393 int ScriptSigArgsExpected(txnouttype t, const std::vector<std::vector<unsigned char> >& vSolutions)
1394 {
1395     switch (t)
1396     {
1397     case TX_NONSTANDARD:
1398     case TX_NULL_DATA:
1399         return -1;
1400     case TX_PUBKEY:
1401         return 1;
1402     case TX_PUBKEYHASH:
1403         return 2;
1404     case TX_MULTISIG:
1405         if (vSolutions.size() < 1 || vSolutions[0].size() < 1)
1406             return -1;
1407         return vSolutions[0][0] + 1;
1408     case TX_SCRIPTHASH:
1409         return 1; // doesn't include args needed by the script
1410     }
1411     return -1;
1412 }
1413
1414 bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType)
1415 {
1416     vector<valtype> vSolutions;
1417     if (!Solver(scriptPubKey, whichType, vSolutions))
1418         return false;
1419
1420     if (whichType == TX_MULTISIG)
1421     {
1422         unsigned char m = vSolutions.front()[0];
1423         unsigned char n = vSolutions.back()[0];
1424         // Support up to x-of-3 multisig txns as standard
1425         if (n < 1 || n > 3)
1426             return false;
1427         if (m < 1 || m > n)
1428             return false;
1429     }
1430
1431     return whichType != TX_NONSTANDARD;
1432 }
1433
1434
1435 unsigned int HaveKeys(const vector<valtype>& pubkeys, const CKeyStore& keystore)
1436 {
1437     unsigned int nResult = 0;
1438     BOOST_FOREACH(const valtype& pubkey, pubkeys)
1439     {
1440         CKeyID keyID = CPubKey(pubkey).GetID();
1441         if (keystore.HaveKey(keyID))
1442             ++nResult;
1443     }
1444     return nResult;
1445 }
1446
1447 isminetype IsMine(const CKeyStore &keystore, const CTxDestination& dest)
1448 {
1449     CScript script;
1450     script.SetDestination(dest);
1451     return IsMine(keystore, script);
1452 }
1453
1454 isminetype IsMine(const CKeyStore &keystore, const CScript& scriptPubKey)
1455 {
1456     vector<valtype> vSolutions;
1457     txnouttype whichType;
1458     if (!Solver(scriptPubKey, whichType, vSolutions)) {
1459         if (keystore.HaveWatchOnly(scriptPubKey))
1460             return ISMINE_WATCH_ONLY;
1461         return ISMINE_NO;
1462     }
1463
1464     CKeyID keyID;
1465     switch (whichType)
1466     {
1467     case TX_NONSTANDARD:
1468     case TX_NULL_DATA:
1469         break;
1470     case TX_PUBKEY:
1471         keyID = CPubKey(vSolutions[0]).GetID();
1472         if (keystore.HaveKey(keyID))
1473             return ISMINE_SPENDABLE;
1474         break;
1475     case TX_PUBKEYHASH:
1476         keyID = CKeyID(uint160(vSolutions[0]));
1477         if (keystore.HaveKey(keyID))
1478             return ISMINE_SPENDABLE;
1479         break;
1480     case TX_SCRIPTHASH:
1481     {
1482         CScriptID scriptID = CScriptID(uint160(vSolutions[0]));
1483         CScript subscript;
1484         if (keystore.GetCScript(scriptID, subscript)) {
1485             isminetype ret = IsMine(keystore, subscript);
1486             if (ret == ISMINE_SPENDABLE)
1487                 return ret;
1488         }
1489         break;
1490     }
1491     case TX_MULTISIG:
1492     {
1493         // Only consider transactions "mine" if we own ALL the
1494         // keys involved. multi-signature transactions that are
1495         // partially owned (somebody else has a key that can spend
1496         // them) enable spend-out-from-under-you attacks, especially
1497         // in shared-wallet situations.
1498         vector<valtype> keys(vSolutions.begin()+1, vSolutions.begin()+vSolutions.size()-1);
1499         if (HaveKeys(keys, keystore) == keys.size())
1500             return ISMINE_SPENDABLE;
1501         break;
1502     }
1503     }
1504
1505     if (keystore.HaveWatchOnly(scriptPubKey))
1506         return ISMINE_WATCH_ONLY;
1507     return ISMINE_NO;
1508 }
1509
1510 bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet)
1511 {
1512     vector<valtype> vSolutions;
1513     txnouttype whichType;
1514     if (!Solver(scriptPubKey, whichType, vSolutions))
1515         return false;
1516
1517     if (whichType == TX_PUBKEY)
1518     {
1519         addressRet = CPubKey(vSolutions[0]).GetID();
1520         return true;
1521     }
1522     else if (whichType == TX_PUBKEYHASH)
1523     {
1524         addressRet = CKeyID(uint160(vSolutions[0]));
1525         return true;
1526     }
1527     else if (whichType == TX_SCRIPTHASH)
1528     {
1529         addressRet = CScriptID(uint160(vSolutions[0]));
1530         return true;
1531     }
1532     // Multisig txns have more than one address...
1533     return false;
1534 }
1535
1536 bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vector<CTxDestination>& addressRet, int& nRequiredRet)
1537 {
1538     addressRet.clear();
1539     typeRet = TX_NONSTANDARD;
1540     vector<valtype> vSolutions;
1541     if (!Solver(scriptPubKey, typeRet, vSolutions))
1542         return false;
1543     if (typeRet == TX_NULL_DATA){
1544         // This is data, not addresses
1545         return false;
1546     }
1547
1548     if (typeRet == TX_MULTISIG)
1549     {
1550         nRequiredRet = vSolutions.front()[0];
1551         for (unsigned int i = 1; i < vSolutions.size()-1; i++)
1552         {
1553             CTxDestination address = CPubKey(vSolutions[i]).GetID();
1554             addressRet.push_back(address);
1555         }
1556     }
1557     else
1558     {
1559         nRequiredRet = 1;
1560         CTxDestination address;
1561         if (!ExtractDestination(scriptPubKey, address))
1562            return false;
1563         addressRet.push_back(address);
1564     }
1565
1566     return true;
1567 }
1568
1569 class CAffectedKeysVisitor : public boost::static_visitor<void> {
1570 private:
1571     const CKeyStore &keystore;
1572     std::vector<CKeyID> &vKeys;
1573
1574 public:
1575     CAffectedKeysVisitor(const CKeyStore &keystoreIn, std::vector<CKeyID> &vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {}
1576
1577     void Process(const CScript &script) {
1578         txnouttype type;
1579         std::vector<CTxDestination> vDest;
1580         int nRequired;
1581         if (ExtractDestinations(script, type, vDest, nRequired)) {
1582             BOOST_FOREACH(const CTxDestination &dest, vDest)
1583                 boost::apply_visitor(*this, dest);
1584         }
1585     }
1586
1587     void operator()(const CKeyID &keyId) {
1588         if (keystore.HaveKey(keyId))
1589             vKeys.push_back(keyId);
1590     }
1591
1592     void operator()(const CScriptID &scriptId) {
1593         CScript script;
1594         if (keystore.GetCScript(scriptId, script))
1595             Process(script);
1596     }
1597
1598     void operator()(const CNoDestination &none) {}
1599 };
1600
1601 void ExtractAffectedKeys(const CKeyStore &keystore, const CScript& scriptPubKey, std::vector<CKeyID> &vKeys) {
1602     CAffectedKeysVisitor(keystore, vKeys).Process(scriptPubKey);
1603 }
1604
1605 bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1606                   unsigned int flags, int nHashType)
1607 {
1608     vector<vector<unsigned char> > stack, stackCopy;
1609     if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType))
1610         return false;
1611     if (flags & SCRIPT_VERIFY_P2SH)
1612         stackCopy = stack;
1613     if (!EvalScript(stack, scriptPubKey, txTo, nIn, flags, nHashType))
1614         return false;
1615     if (stack.empty())
1616         return false;
1617
1618     if (CastToBool(stack.back()) == false)
1619         return false;
1620
1621     // Additional validation for spend-to-script-hash transactions:
1622     if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash())
1623     {
1624         if (!scriptSig.IsPushOnly()) // scriptSig must be literals-only
1625             return false;            // or validation fails
1626
1627         // stackCopy cannot be empty here, because if it was the
1628         // P2SH  HASH <> EQUAL  scriptPubKey would be evaluated with
1629         // an empty stack and the EvalScript above would return false.
1630         assert(!stackCopy.empty());
1631
1632         const valtype& pubKeySerialized = stackCopy.back();
1633         CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end());
1634         popstack(stackCopy);
1635
1636         if (!EvalScript(stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1637             return false;
1638         if (stackCopy.empty())
1639             return false;
1640         return CastToBool(stackCopy.back());
1641     }
1642
1643     return true;
1644 }
1645
1646
1647 bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1648 {
1649     assert(nIn < txTo.vin.size());
1650     CTxIn& txin = txTo.vin[nIn];
1651
1652     // Leave out the signature from the hash, since a signature can't sign itself.
1653     // The checksig op will also drop the signatures from its hash.
1654     uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType);
1655
1656     txnouttype whichType;
1657     if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType))
1658         return false;
1659
1660     if (whichType == TX_SCRIPTHASH)
1661     {
1662         // Solver returns the subscript that need to be evaluated;
1663         // the final scriptSig is the signatures from that
1664         // and then the serialized subscript:
1665         CScript subscript = txin.scriptSig;
1666
1667         // Recompute txn hash using subscript in place of scriptPubKey:
1668         uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType);
1669
1670         txnouttype subType;
1671         bool fSolved =
1672             Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH;
1673         // Append serialized subscript whether or not it is completely signed:
1674         txin.scriptSig << static_cast<valtype>(subscript);
1675         if (!fSolved) return false;
1676     }
1677
1678     // Test solution
1679     return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0);
1680 }
1681
1682 bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CMutableTransaction& txTo, unsigned int nIn, int nHashType)
1683 {
1684     assert(nIn < txTo.vin.size());
1685     CTxIn& txin = txTo.vin[nIn];
1686     assert(txin.prevout.n < txFrom.vout.size());
1687     const CTxOut& txout = txFrom.vout[txin.prevout.n];
1688
1689     return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType);
1690 }
1691
1692 static CScript PushAll(const vector<valtype>& values)
1693 {
1694     CScript result;
1695     BOOST_FOREACH(const valtype& v, values)
1696         result << v;
1697     return result;
1698 }
1699
1700 static CScript CombineMultisig(CScript scriptPubKey, const CMutableTransaction& txTo, unsigned int nIn,
1701                                const vector<valtype>& vSolutions,
1702                                vector<valtype>& sigs1, vector<valtype>& sigs2)
1703 {
1704     // Combine all the signatures we've got:
1705     set<valtype> allsigs;
1706     BOOST_FOREACH(const valtype& v, sigs1)
1707     {
1708         if (!v.empty())
1709             allsigs.insert(v);
1710     }
1711     BOOST_FOREACH(const valtype& v, sigs2)
1712     {
1713         if (!v.empty())
1714             allsigs.insert(v);
1715     }
1716
1717     // Build a map of pubkey -> signature by matching sigs to pubkeys:
1718     assert(vSolutions.size() > 1);
1719     unsigned int nSigsRequired = vSolutions.front()[0];
1720     unsigned int nPubKeys = vSolutions.size()-2;
1721     map<valtype, valtype> sigs;
1722     BOOST_FOREACH(const valtype& sig, allsigs)
1723     {
1724         for (unsigned int i = 0; i < nPubKeys; i++)
1725         {
1726             const valtype& pubkey = vSolutions[i+1];
1727             if (sigs.count(pubkey))
1728                 continue; // Already got a sig for this pubkey
1729
1730             if (CheckSig(sig, pubkey, scriptPubKey, txTo, nIn, 0, 0))
1731             {
1732                 sigs[pubkey] = sig;
1733                 break;
1734             }
1735         }
1736     }
1737     // Now build a merged CScript:
1738     unsigned int nSigsHave = 0;
1739     CScript result; result << OP_0; // pop-one-too-many workaround
1740     for (unsigned int i = 0; i < nPubKeys && nSigsHave < nSigsRequired; i++)
1741     {
1742         if (sigs.count(vSolutions[i+1]))
1743         {
1744             result << sigs[vSolutions[i+1]];
1745             ++nSigsHave;
1746         }
1747     }
1748     // Fill any missing with OP_0:
1749     for (unsigned int i = nSigsHave; i < nSigsRequired; i++)
1750         result << OP_0;
1751
1752     return result;
1753 }
1754
1755 static CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1756                                  const txnouttype txType, const vector<valtype>& vSolutions,
1757                                  vector<valtype>& sigs1, vector<valtype>& sigs2)
1758 {
1759     switch (txType)
1760     {
1761     case TX_NONSTANDARD:
1762     case TX_NULL_DATA:
1763         // Don't know anything about this, assume bigger one is correct:
1764         if (sigs1.size() >= sigs2.size())
1765             return PushAll(sigs1);
1766         return PushAll(sigs2);
1767     case TX_PUBKEY:
1768     case TX_PUBKEYHASH:
1769         // Signatures are bigger than placeholders or empty scripts:
1770         if (sigs1.empty() || sigs1[0].empty())
1771             return PushAll(sigs2);
1772         return PushAll(sigs1);
1773     case TX_SCRIPTHASH:
1774         if (sigs1.empty() || sigs1.back().empty())
1775             return PushAll(sigs2);
1776         else if (sigs2.empty() || sigs2.back().empty())
1777             return PushAll(sigs1);
1778         else
1779         {
1780             // Recur to combine:
1781             valtype spk = sigs1.back();
1782             CScript pubKey2(spk.begin(), spk.end());
1783
1784             txnouttype txType2;
1785             vector<vector<unsigned char> > vSolutions2;
1786             Solver(pubKey2, txType2, vSolutions2);
1787             sigs1.pop_back();
1788             sigs2.pop_back();
1789             CScript result = CombineSignatures(pubKey2, txTo, nIn, txType2, vSolutions2, sigs1, sigs2);
1790             result << spk;
1791             return result;
1792         }
1793     case TX_MULTISIG:
1794         return CombineMultisig(scriptPubKey, txTo, nIn, vSolutions, sigs1, sigs2);
1795     }
1796
1797     return CScript();
1798 }
1799
1800 CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn,
1801                           const CScript& scriptSig1, const CScript& scriptSig2)
1802 {
1803     txnouttype txType;
1804     vector<vector<unsigned char> > vSolutions;
1805     Solver(scriptPubKey, txType, vSolutions);
1806
1807     vector<valtype> stack1;
1808     EvalScript(stack1, scriptSig1, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1809     vector<valtype> stack2;
1810     EvalScript(stack2, scriptSig2, CTransaction(), 0, SCRIPT_VERIFY_STRICTENC, 0);
1811
1812     return CombineSignatures(scriptPubKey, txTo, nIn, txType, vSolutions, stack1, stack2);
1813 }
1814
1815 unsigned int CScript::GetSigOpCount(bool fAccurate) const
1816 {
1817     unsigned int n = 0;
1818     const_iterator pc = begin();
1819     opcodetype lastOpcode = OP_INVALIDOPCODE;
1820     while (pc < end())
1821     {
1822         opcodetype opcode;
1823         if (!GetOp(pc, opcode))
1824             break;
1825         if (opcode == OP_CHECKSIG || opcode == OP_CHECKSIGVERIFY)
1826             n++;
1827         else if (opcode == OP_CHECKMULTISIG || opcode == OP_CHECKMULTISIGVERIFY)
1828         {
1829             if (fAccurate && lastOpcode >= OP_1 && lastOpcode <= OP_16)
1830                 n += DecodeOP_N(lastOpcode);
1831             else
1832                 n += 20;
1833         }
1834         lastOpcode = opcode;
1835     }
1836     return n;
1837 }
1838
1839 unsigned int CScript::GetSigOpCount(const CScript& scriptSig) const
1840 {
1841     if (!IsPayToScriptHash())
1842         return GetSigOpCount(true);
1843
1844     // This is a pay-to-script-hash scriptPubKey;
1845     // get the last item that the scriptSig
1846     // pushes onto the stack:
1847     const_iterator pc = scriptSig.begin();
1848     vector<unsigned char> data;
1849     while (pc < scriptSig.end())
1850     {
1851         opcodetype opcode;
1852         if (!scriptSig.GetOp(pc, opcode, data))
1853             return 0;
1854         if (opcode > OP_16)
1855             return 0;
1856     }
1857
1858     /// ... and return its opcount:
1859     CScript subscript(data.begin(), data.end());
1860     return subscript.GetSigOpCount(true);
1861 }
1862
1863 bool CScript::IsPayToScriptHash() const
1864 {
1865     // Extra-fast test for pay-to-script-hash CScripts:
1866     return (this->size() == 23 &&
1867             this->at(0) == OP_HASH160 &&
1868             this->at(1) == 0x14 &&
1869             this->at(22) == OP_EQUAL);
1870 }
1871
1872 bool CScript::IsPushOnly() const
1873 {
1874     const_iterator pc = begin();
1875     while (pc < end())
1876     {
1877         opcodetype opcode;
1878         if (!GetOp(pc, opcode))
1879             return false;
1880         // Note that IsPushOnly() *does* consider OP_RESERVED to be a
1881         // push-type opcode, however execution of OP_RESERVED fails, so
1882         // it's not relevant to P2SH as the scriptSig would fail prior to
1883         // the P2SH special validation code being executed.
1884         if (opcode > OP_16)
1885             return false;
1886     }
1887     return true;
1888 }
1889
1890 bool CScript::HasCanonicalPushes() const
1891 {
1892     const_iterator pc = begin();
1893     while (pc < end())
1894     {
1895         opcodetype opcode;
1896         std::vector<unsigned char> data;
1897         if (!GetOp(pc, opcode, data))
1898             return false;
1899         if (opcode > OP_16)
1900             continue;
1901         if (opcode < OP_PUSHDATA1 && opcode > OP_0 && (data.size() == 1 && data[0] <= 16))
1902             // Could have used an OP_n code, rather than a 1-byte push.
1903             return false;
1904         if (opcode == OP_PUSHDATA1 && data.size() < OP_PUSHDATA1)
1905             // Could have used a normal n-byte push, rather than OP_PUSHDATA1.
1906             return false;
1907         if (opcode == OP_PUSHDATA2 && data.size() <= 0xFF)
1908             // Could have used an OP_PUSHDATA1.
1909             return false;
1910         if (opcode == OP_PUSHDATA4 && data.size() <= 0xFFFF)
1911             // Could have used an OP_PUSHDATA2.
1912             return false;
1913     }
1914     return true;
1915 }
1916
1917 class CScriptVisitor : public boost::static_visitor<bool>
1918 {
1919 private:
1920     CScript *script;
1921 public:
1922     CScriptVisitor(CScript *scriptin) { script = scriptin; }
1923
1924     bool operator()(const CNoDestination &dest) const {
1925         script->clear();
1926         return false;
1927     }
1928
1929     bool operator()(const CKeyID &keyID) const {
1930         script->clear();
1931         *script << OP_DUP << OP_HASH160 << keyID << OP_EQUALVERIFY << OP_CHECKSIG;
1932         return true;
1933     }
1934
1935     bool operator()(const CScriptID &scriptID) const {
1936         script->clear();
1937         *script << OP_HASH160 << scriptID << OP_EQUAL;
1938         return true;
1939     }
1940 };
1941
1942 void CScript::SetDestination(const CTxDestination& dest)
1943 {
1944     boost::apply_visitor(CScriptVisitor(this), dest);
1945 }
1946
1947 void CScript::SetMultisig(int nRequired, const std::vector<CPubKey>& keys)
1948 {
1949     this->clear();
1950
1951     *this << EncodeOP_N(nRequired);
1952     BOOST_FOREACH(const CPubKey& key, keys)
1953         *this << key;
1954     *this << EncodeOP_N(keys.size()) << OP_CHECKMULTISIG;
1955 }
1956
1957 bool CScriptCompressor::IsToKeyID(CKeyID &hash) const
1958 {
1959     if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160
1960                             && script[2] == 20 && script[23] == OP_EQUALVERIFY
1961                             && script[24] == OP_CHECKSIG) {
1962         memcpy(&hash, &script[3], 20);
1963         return true;
1964     }
1965     return false;
1966 }
1967
1968 bool CScriptCompressor::IsToScriptID(CScriptID &hash) const
1969 {
1970     if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20
1971                             && script[22] == OP_EQUAL) {
1972         memcpy(&hash, &script[2], 20);
1973         return true;
1974     }
1975     return false;
1976 }
1977
1978 bool CScriptCompressor::IsToPubKey(CPubKey &pubkey) const
1979 {
1980     if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG
1981                             && (script[1] == 0x02 || script[1] == 0x03)) {
1982         pubkey.Set(&script[1], &script[34]);
1983         return true;
1984     }
1985     if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG
1986                             && script[1] == 0x04) {
1987         pubkey.Set(&script[1], &script[66]);
1988         return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
1989     }
1990     return false;
1991 }
1992
1993 bool CScriptCompressor::Compress(std::vector<unsigned char> &out) const
1994 {
1995     CKeyID keyID;
1996     if (IsToKeyID(keyID)) {
1997         out.resize(21);
1998         out[0] = 0x00;
1999         memcpy(&out[1], &keyID, 20);
2000         return true;
2001     }
2002     CScriptID scriptID;
2003     if (IsToScriptID(scriptID)) {
2004         out.resize(21);
2005         out[0] = 0x01;
2006         memcpy(&out[1], &scriptID, 20);
2007         return true;
2008     }
2009     CPubKey pubkey;
2010     if (IsToPubKey(pubkey)) {
2011         out.resize(33);
2012         memcpy(&out[1], &pubkey[1], 32);
2013         if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
2014             out[0] = pubkey[0];
2015             return true;
2016         } else if (pubkey[0] == 0x04) {
2017             out[0] = 0x04 | (pubkey[64] & 0x01);
2018             return true;
2019         }
2020     }
2021     return false;
2022 }
2023
2024 unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
2025 {
2026     if (nSize == 0 || nSize == 1)
2027         return 20;
2028     if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
2029         return 32;
2030     return 0;
2031 }
2032
2033 bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char> &in)
2034 {
2035     switch(nSize) {
2036     case 0x00:
2037         script.resize(25);
2038         script[0] = OP_DUP;
2039         script[1] = OP_HASH160;
2040         script[2] = 20;
2041         memcpy(&script[3], &in[0], 20);
2042         script[23] = OP_EQUALVERIFY;
2043         script[24] = OP_CHECKSIG;
2044         return true;
2045     case 0x01:
2046         script.resize(23);
2047         script[0] = OP_HASH160;
2048         script[1] = 20;
2049         memcpy(&script[2], &in[0], 20);
2050         script[22] = OP_EQUAL;
2051         return true;
2052     case 0x02:
2053     case 0x03:
2054         script.resize(35);
2055         script[0] = 33;
2056         script[1] = nSize;
2057         memcpy(&script[2], &in[0], 32);
2058         script[34] = OP_CHECKSIG;
2059         return true;
2060     case 0x04:
2061     case 0x05:
2062         unsigned char vch[33] = {};
2063         vch[0] = nSize - 2;
2064         memcpy(&vch[1], &in[0], 32);
2065         CPubKey pubkey(&vch[0], &vch[33]);
2066         if (!pubkey.Decompress())
2067             return false;
2068         assert(pubkey.size() == 65);
2069         script.resize(67);
2070         script[0] = 65;
2071         memcpy(&script[1], pubkey.begin(), 65);
2072         script[66] = OP_CHECKSIG;
2073         return true;
2074     }
2075     return false;
2076 }
This page took 0.148912 seconds and 4 git commands to generate.