Make IsCanonicalPubKey, IsCanonicalSignature and CheckSig public. Wrap execution...
[NovacoinLibrary.git] / Novacoin / ScriptCode.cs
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 using System.Numerics;
7
8 // using Org.BouncyCastle.Math;
9
10 namespace Novacoin
11 {
12     /// <summary>
13     /// Script opcodes
14     /// </summary>
15     public enum instruction
16     {
17         // push value
18         OP_0 = 0x00,
19         OP_FALSE = OP_0,
20         OP_PUSHDATA1 = 0x4c,
21         OP_PUSHDATA2 = 0x4d,
22         OP_PUSHDATA4 = 0x4e,
23         OP_1NEGATE = 0x4f,
24         OP_RESERVED = 0x50,
25         OP_1 = 0x51,
26         OP_TRUE = OP_1,
27         OP_2 = 0x52,
28         OP_3 = 0x53,
29         OP_4 = 0x54,
30         OP_5 = 0x55,
31         OP_6 = 0x56,
32         OP_7 = 0x57,
33         OP_8 = 0x58,
34         OP_9 = 0x59,
35         OP_10 = 0x5a,
36         OP_11 = 0x5b,
37         OP_12 = 0x5c,
38         OP_13 = 0x5d,
39         OP_14 = 0x5e,
40         OP_15 = 0x5f,
41         OP_16 = 0x60,
42
43         // control
44         OP_NOP = 0x61,
45         OP_VER = 0x62,
46         OP_IF = 0x63,
47         OP_NOTIF = 0x64,
48         OP_VERIF = 0x65,
49         OP_VERNOTIF = 0x66,
50         OP_ELSE = 0x67,
51         OP_ENDIF = 0x68,
52         OP_VERIFY = 0x69,
53         OP_RETURN = 0x6a,
54
55         // stack ops
56         OP_TOALTSTACK = 0x6b,
57         OP_FROMALTSTACK = 0x6c,
58         OP_2DROP = 0x6d,
59         OP_2DUP = 0x6e,
60         OP_3DUP = 0x6f,
61         OP_2OVER = 0x70,
62         OP_2ROT = 0x71,
63         OP_2SWAP = 0x72,
64         OP_IFDUP = 0x73,
65         OP_DEPTH = 0x74,
66         OP_DROP = 0x75,
67         OP_DUP = 0x76,
68         OP_NIP = 0x77,
69         OP_OVER = 0x78,
70         OP_PICK = 0x79,
71         OP_ROLL = 0x7a,
72         OP_ROT = 0x7b,
73         OP_SWAP = 0x7c,
74         OP_TUCK = 0x7d,
75
76         // splice ops
77         OP_CAT = 0x7e,
78         OP_SUBSTR = 0x7f,
79         OP_LEFT = 0x80,
80         OP_RIGHT = 0x81,
81         OP_SIZE = 0x82,
82
83         // bit logic
84         OP_INVERT = 0x83,
85         OP_AND = 0x84,
86         OP_OR = 0x85,
87         OP_XOR = 0x86,
88         OP_EQUAL = 0x87,
89         OP_EQUALVERIFY = 0x88,
90         OP_RESERVED1 = 0x89,
91         OP_RESERVED2 = 0x8a,
92
93         // numeric
94         OP_1ADD = 0x8b,
95         OP_1SUB = 0x8c,
96         OP_2MUL = 0x8d,
97         OP_2DIV = 0x8e,
98         OP_NEGATE = 0x8f,
99         OP_ABS = 0x90,
100         OP_NOT = 0x91,
101         OP_0NOTEQUAL = 0x92,
102
103         OP_ADD = 0x93,
104         OP_SUB = 0x94,
105         OP_MUL = 0x95,
106         OP_DIV = 0x96,
107         OP_MOD = 0x97,
108         OP_LSHIFT = 0x98,
109         OP_RSHIFT = 0x99,
110
111         OP_BOOLAND = 0x9a,
112         OP_BOOLOR = 0x9b,
113         OP_NUMEQUAL = 0x9c,
114         OP_NUMEQUALVERIFY = 0x9d,
115         OP_NUMNOTEQUAL = 0x9e,
116         OP_LESSTHAN = 0x9f,
117         OP_GREATERTHAN = 0xa0,
118         OP_LESSTHANOREQUAL = 0xa1,
119         OP_GREATERTHANOREQUAL = 0xa2,
120         OP_MIN = 0xa3,
121         OP_MAX = 0xa4,
122
123         OP_WITHIN = 0xa5,
124
125         // crypto
126         OP_RIPEMD160 = 0xa6,
127         OP_SHA1 = 0xa7,
128         OP_SHA256 = 0xa8,
129         OP_HASH160 = 0xa9,
130         OP_HASH256 = 0xaa,
131         OP_CODESEPARATOR = 0xab,
132         OP_CHECKSIG = 0xac,
133         OP_CHECKSIGVERIFY = 0xad,
134         OP_CHECKMULTISIG = 0xae,
135         OP_CHECKMULTISIGVERIFY = 0xaf,
136
137         // expansion
138         OP_NOP1 = 0xb0,
139         OP_NOP2 = 0xb1,
140         OP_NOP3 = 0xb2,
141         OP_NOP4 = 0xb3,
142         OP_NOP5 = 0xb4,
143         OP_NOP6 = 0xb5,
144         OP_NOP7 = 0xb6,
145         OP_NOP8 = 0xb7,
146         OP_NOP9 = 0xb8,
147         OP_NOP10 = 0xb9,
148
149         // template matching params
150         OP_SMALLDATA = 0xf9,
151         OP_SMALLINTEGER = 0xfa,
152         OP_PUBKEYS = 0xfb,
153         OP_PUBKEYHASH = 0xfd,
154         OP_PUBKEY = 0xfe,
155
156         OP_INVALIDOPCODE = 0xff,
157     };
158
159     /// <summary>
160     /// Transaction output types.
161     /// </summary>
162     public enum txnouttype
163     {
164         TX_NONSTANDARD,
165
166         // 'standard' transaction types:
167         TX_PUBKEY,
168         TX_PUBKEYHASH,
169         TX_SCRIPTHASH,
170         TX_MULTISIG,
171         TX_NULL_DATA,
172     };
173
174     /// <summary>
175     /// Signature hash types/flags
176     /// </summary>
177     public enum sigflag
178     {
179         SIGHASH_ALL = 1,
180         SIGHASH_NONE = 2,
181         SIGHASH_SINGLE = 3,
182         SIGHASH_ANYONECANPAY = 0x80,
183     };
184
185     /** Script verification flags */
186     public enum scriptflag
187     {
188         SCRIPT_VERIFY_NONE = 0,
189         SCRIPT_VERIFY_P2SH = (1 << 0), // evaluate P2SH (BIP16) subscripts
190         SCRIPT_VERIFY_STRICTENC = (1 << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
191         SCRIPT_VERIFY_LOW_S = (1 << 2), // enforce low S values in signatures (depends on STRICTENC)
192         SCRIPT_VERIFY_NOCACHE = (1 << 3), // do not store results in signature cache (but do query it)
193         SCRIPT_VERIFY_NULLDUMMY = (1 << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
194     };
195
196     public static class ScriptCode
197     {
198         public static string GetTxnOutputType(txnouttype t)
199         {
200             switch (t)
201             {
202                 case txnouttype.TX_NONSTANDARD: return "nonstandard";
203                 case txnouttype.TX_PUBKEY: return "pubkey";
204                 case txnouttype.TX_PUBKEYHASH: return "pubkeyhash";
205                 case txnouttype.TX_SCRIPTHASH: return "scripthash";
206                 case txnouttype.TX_MULTISIG: return "multisig";
207                 case txnouttype.TX_NULL_DATA: return "nulldata";
208             }
209             return string.Empty;
210         }
211
212         /// <summary>
213         /// Get the name of supplied opcode
214         /// </summary>
215         /// <param name="opcode">Opcode</param>
216         /// <returns>Opcode name</returns>
217         public static string GetOpName(instruction opcode)
218         {
219             switch (opcode)
220             {
221                 // push value
222                 case instruction.OP_0:
223                     return "OP_0";
224                 case instruction.OP_PUSHDATA1:
225                     return "OP_PUSHDATA1";
226                 case instruction.OP_PUSHDATA2:
227                     return "OP_PUSHDATA2";
228                 case instruction.OP_PUSHDATA4:
229                     return "OP_PUSHDATA4";
230                 case instruction.OP_1NEGATE:
231                     return "OP_1NEGATE";
232                 case instruction.OP_RESERVED:
233                     return "OP_RESERVED";
234                 case instruction.OP_1:
235                     return "OP_1";
236                 case instruction.OP_2:
237                     return "OP_2";
238                 case instruction.OP_3:
239                     return "OP_3";
240                 case instruction.OP_4:
241                     return "OP_4";
242                 case instruction.OP_5:
243                     return "OP_5";
244                 case instruction.OP_6:
245                     return "OP_6";
246                 case instruction.OP_7:
247                     return "OP_7";
248                 case instruction.OP_8:
249                     return "OP_8";
250                 case instruction.OP_9:
251                     return "OP_9";
252                 case instruction.OP_10:
253                     return "OP_10";
254                 case instruction.OP_11:
255                     return "OP_11";
256                 case instruction.OP_12:
257                     return "OP_12";
258                 case instruction.OP_13:
259                     return "OP_13";
260                 case instruction.OP_14:
261                     return "OP_14";
262                 case instruction.OP_15:
263                     return "OP_15";
264                 case instruction.OP_16:
265                     return "OP_16";
266
267                 // control
268                 case instruction.OP_NOP:
269                     return "OP_NOP";
270                 case instruction.OP_VER:
271                     return "OP_VER";
272                 case instruction.OP_IF:
273                     return "OP_IF";
274                 case instruction.OP_NOTIF:
275                     return "OP_NOTIF";
276                 case instruction.OP_VERIF:
277                     return "OP_VERIF";
278                 case instruction.OP_VERNOTIF:
279                     return "OP_VERNOTIF";
280                 case instruction.OP_ELSE:
281                     return "OP_ELSE";
282                 case instruction.OP_ENDIF:
283                     return "OP_ENDIF";
284                 case instruction.OP_VERIFY:
285                     return "OP_VERIFY";
286                 case instruction.OP_RETURN:
287                     return "OP_RETURN";
288
289                 // stack ops
290                 case instruction.OP_TOALTSTACK:
291                     return "OP_TOALTSTACK";
292                 case instruction.OP_FROMALTSTACK:
293                     return "OP_FROMALTSTACK";
294                 case instruction.OP_2DROP:
295                     return "OP_2DROP";
296                 case instruction.OP_2DUP:
297                     return "OP_2DUP";
298                 case instruction.OP_3DUP:
299                     return "OP_3DUP";
300                 case instruction.OP_2OVER:
301                     return "OP_2OVER";
302                 case instruction.OP_2ROT:
303                     return "OP_2ROT";
304                 case instruction.OP_2SWAP:
305                     return "OP_2SWAP";
306                 case instruction.OP_IFDUP:
307                     return "OP_IFDUP";
308                 case instruction.OP_DEPTH:
309                     return "OP_DEPTH";
310                 case instruction.OP_DROP:
311                     return "OP_DROP";
312                 case instruction.OP_DUP:
313                     return "OP_DUP";
314                 case instruction.OP_NIP:
315                     return "OP_NIP";
316                 case instruction.OP_OVER:
317                     return "OP_OVER";
318                 case instruction.OP_PICK:
319                     return "OP_PICK";
320                 case instruction.OP_ROLL:
321                     return "OP_ROLL";
322                 case instruction.OP_ROT:
323                     return "OP_ROT";
324                 case instruction.OP_SWAP:
325                     return "OP_SWAP";
326                 case instruction.OP_TUCK:
327                     return "OP_TUCK";
328
329                 // splice ops
330                 case instruction.OP_CAT:
331                     return "OP_CAT";
332                 case instruction.OP_SUBSTR:
333                     return "OP_SUBSTR";
334                 case instruction.OP_LEFT:
335                     return "OP_LEFT";
336                 case instruction.OP_RIGHT:
337                     return "OP_RIGHT";
338                 case instruction.OP_SIZE:
339                     return "OP_SIZE";
340
341                 // bit logic
342                 case instruction.OP_INVERT:
343                     return "OP_INVERT";
344                 case instruction.OP_AND:
345                     return "OP_AND";
346                 case instruction.OP_OR:
347                     return "OP_OR";
348                 case instruction.OP_XOR:
349                     return "OP_XOR";
350                 case instruction.OP_EQUAL:
351                     return "OP_EQUAL";
352                 case instruction.OP_EQUALVERIFY:
353                     return "OP_EQUALVERIFY";
354                 case instruction.OP_RESERVED1:
355                     return "OP_RESERVED1";
356                 case instruction.OP_RESERVED2:
357                     return "OP_RESERVED2";
358
359                 // numeric
360                 case instruction.OP_1ADD:
361                     return "OP_1ADD";
362                 case instruction.OP_1SUB:
363                     return "OP_1SUB";
364                 case instruction.OP_2MUL:
365                     return "OP_2MUL";
366                 case instruction.OP_2DIV:
367                     return "OP_2DIV";
368                 case instruction.OP_NEGATE:
369                     return "OP_NEGATE";
370                 case instruction.OP_ABS:
371                     return "OP_ABS";
372                 case instruction.OP_NOT:
373                     return "OP_NOT";
374                 case instruction.OP_0NOTEQUAL:
375                     return "OP_0NOTEQUAL";
376                 case instruction.OP_ADD:
377                     return "OP_ADD";
378                 case instruction.OP_SUB:
379                     return "OP_SUB";
380                 case instruction.OP_MUL:
381                     return "OP_MUL";
382                 case instruction.OP_DIV:
383                     return "OP_DIV";
384                 case instruction.OP_MOD:
385                     return "OP_MOD";
386                 case instruction.OP_LSHIFT:
387                     return "OP_LSHIFT";
388                 case instruction.OP_RSHIFT:
389                     return "OP_RSHIFT";
390                 case instruction.OP_BOOLAND:
391                     return "OP_BOOLAND";
392                 case instruction.OP_BOOLOR:
393                     return "OP_BOOLOR";
394                 case instruction.OP_NUMEQUAL:
395                     return "OP_NUMEQUAL";
396                 case instruction.OP_NUMEQUALVERIFY:
397                     return "OP_NUMEQUALVERIFY";
398                 case instruction.OP_NUMNOTEQUAL:
399                     return "OP_NUMNOTEQUAL";
400                 case instruction.OP_LESSTHAN:
401                     return "OP_LESSTHAN";
402                 case instruction.OP_GREATERTHAN:
403                     return "OP_GREATERTHAN";
404                 case instruction.OP_LESSTHANOREQUAL:
405                     return "OP_LESSTHANOREQUAL";
406                 case instruction.OP_GREATERTHANOREQUAL:
407                     return "OP_GREATERTHANOREQUAL";
408                 case instruction.OP_MIN:
409                     return "OP_MIN";
410                 case instruction.OP_MAX:
411                     return "OP_MAX";
412                 case instruction.OP_WITHIN:
413                     return "OP_WITHIN";
414
415                 // crypto
416                 case instruction.OP_RIPEMD160:
417                     return "OP_RIPEMD160";
418                 case instruction.OP_SHA1:
419                     return "OP_SHA1";
420                 case instruction.OP_SHA256:
421                     return "OP_SHA256";
422                 case instruction.OP_HASH160:
423                     return "OP_HASH160";
424                 case instruction.OP_HASH256:
425                     return "OP_HASH256";
426                 case instruction.OP_CODESEPARATOR:
427                     return "OP_CODESEPARATOR";
428                 case instruction.OP_CHECKSIG:
429                     return "OP_CHECKSIG";
430                 case instruction.OP_CHECKSIGVERIFY:
431                     return "OP_CHECKSIGVERIFY";
432                 case instruction.OP_CHECKMULTISIG:
433                     return "OP_CHECKMULTISIG";
434                 case instruction.OP_CHECKMULTISIGVERIFY:
435                     return "OP_CHECKMULTISIGVERIFY";
436
437                 // expansion
438                 case instruction.OP_NOP1:
439                     return "OP_NOP1";
440                 case instruction.OP_NOP2:
441                     return "OP_NOP2";
442                 case instruction.OP_NOP3:
443                     return "OP_NOP3";
444                 case instruction.OP_NOP4:
445                     return "OP_NOP4";
446                 case instruction.OP_NOP5:
447                     return "OP_NOP5";
448                 case instruction.OP_NOP6:
449                     return "OP_NOP6";
450                 case instruction.OP_NOP7:
451                     return "OP_NOP7";
452                 case instruction.OP_NOP8:
453                     return "OP_NOP8";
454                 case instruction.OP_NOP9:
455                     return "OP_NOP9";
456                 case instruction.OP_NOP10:
457                     return "OP_NOP10";
458
459                 // template matching params
460                 case instruction.OP_SMALLINTEGER:
461                     return "OP_SMALLINTEGER";
462                 case instruction.OP_PUBKEYHASH:
463                     return "OP_PUBKEYHASH";
464                 case instruction.OP_PUBKEY:
465                     return "OP_PUBKEY";
466                 case instruction.OP_PUBKEYS:
467                     return "OP_PUBKEYS";
468                 case instruction.OP_SMALLDATA:
469                     return "OP_SMALLDATA";
470
471                 case instruction.OP_INVALIDOPCODE:
472                     return "OP_INVALIDOPCODE";
473                 default:
474                     return "OP_UNKNOWN";
475             }
476         }
477
478         /// <summary>
479         /// Get next opcode from passed list of bytes and extract push arguments if there are some.
480         /// </summary>
481         /// <param name="codeBytes">ByteQueue reference.</param>
482         /// <param name="opcodeRet">Found opcode.</param>
483         /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
484         /// <returns>Result of operation</returns>
485         public static bool GetOp(ref ByteQueue codeBytes, out instruction opcodeRet, out IEnumerable<byte> bytesRet)
486         {
487             bytesRet = new List<byte>();
488             opcodeRet = instruction.OP_INVALIDOPCODE;
489
490             instruction opcode;
491
492             try
493             {
494                 // Read instruction
495                 opcode = (instruction)codeBytes.Get();
496             }
497             catch (ByteQueueException)
498             {
499                 // No instruction found there
500                 return false;
501             }
502
503             // Immediate operand
504             if (opcode <= instruction.OP_PUSHDATA4)
505             {
506                 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
507
508                 try
509                 {
510                     if (opcode < instruction.OP_PUSHDATA1)
511                     {
512                         // Zero value opcodes (OP_0, OP_FALSE)
513                         szBytes[3] = (byte)opcode;
514                     }
515                     else if (opcode == instruction.OP_PUSHDATA1)
516                     {
517                         // The next byte contains the number of bytes to be pushed onto the stack, 
518                         //    i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
519                         szBytes[3] = (byte)codeBytes.Get();
520                     }
521                     else if (opcode == instruction.OP_PUSHDATA2)
522                     {
523                         // The next two bytes contain the number of bytes to be pushed onto the stack,
524                         //    i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
525                         codeBytes.Get(2).CopyTo(szBytes, 2);
526                     }
527                     else if (opcode == instruction.OP_PUSHDATA4)
528                     {
529                         // The next four bytes contain the number of bytes to be pushed onto the stack,
530                         //   OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
531                         szBytes = codeBytes.Get(4);
532                     }
533                 }
534                 catch (ByteQueueException)
535                 {
536                     // Unable to read operand length
537                     return false;
538                 }
539
540                 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
541
542                 if (nSize > 0)
543                 {
544                     // If nSize is greater than zero then there is some data available
545                     try
546                     {
547                         // Read found number of bytes into list of OP_PUSHDATAn arguments.
548                         bytesRet = codeBytes.GetEnumerable(nSize);
549                     }
550                     catch (ByteQueueException)
551                     {
552                         // Unable to read data
553                         return false;
554                     }
555                 }
556             }
557
558             opcodeRet = opcode;
559
560             return true;
561         }
562
563         /// <summary>
564         /// Convert value bytes into readable representation.
565         /// 
566         /// If list lengh is equal or lesser than 4 bytes then bytes are interpreted as integer value. Otherwise you will get hex representation of supplied data.
567         /// </summary>
568         /// <param name="bytes">Collection of value bytes.</param>
569         /// <returns>Formatted value.</returns>
570         public static string ValueString(IEnumerable<byte> bytes)
571         {
572             StringBuilder sb = new StringBuilder();
573
574             if (bytes.Count() <= 4)
575             {
576                 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
577                 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
578
579                 sb.Append(Interop.BEBytesToUInt32(valueBytes));
580             }
581             else
582             {
583                 return Interop.ToHex(bytes);
584             }
585
586             return sb.ToString();
587         }
588
589         /// <summary>
590         /// Convert list of stack items into human readable representation.
591         /// </summary>
592         /// <param name="stackList">List of stack items.</param>
593         /// <returns>Formatted value.</returns>
594         public static string StackString(IList<IList<byte>> stackList)
595         {
596             StringBuilder sb = new StringBuilder();
597             foreach (IList<byte> bytesList in stackList)
598             {
599                 sb.Append(ValueString(bytesList));
600             }
601
602             return sb.ToString();
603         }
604
605         /// <summary>
606         /// Decode instruction to integer value
607         /// </summary>
608         /// <param name="opcode">Small integer opcode (OP_1_NEGATE and OP_0 - OP_16)</param>
609         /// <returns>Small integer</returns>
610         public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
611         {
612             if (AllowNegate && opcode == instruction.OP_1NEGATE)
613             {
614                 return -1;
615             }
616
617             if (opcode == instruction.OP_0)
618             {
619                 return 0;
620             }
621
622             // Only OP_n opcodes are supported, throw exception otherwise.
623             if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
624             {
625                 throw new ArgumentException("Invalid integer instruction.");
626             }
627
628             return (int)opcode - (int)(instruction.OP_1 - 1);
629         }
630
631         /// <summary>
632         /// Converts integer into instruction
633         /// </summary>
634         /// <param name="n">Small integer from the range of -1 up to 16.</param>
635         /// <returns>Corresponding opcode.</returns>
636         public static instruction EncodeOP_N(int n, bool allowNegate = false)
637         {
638             if (allowNegate && n == -1)
639             {
640                 return instruction.OP_1NEGATE;
641             }
642
643             if (n == 0)
644             {
645                 return instruction.OP_0;
646             }
647
648             // The n value must be in the range of 0 to 16.
649             if (n < 0 || n > 16)
650                 throw new ArgumentException("Invalid integer value.");
651             return (instruction.OP_1 + n - 1);
652         }
653
654         public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
655         {
656             switch (t)
657             {
658                 case txnouttype.TX_NONSTANDARD:
659                     return -1;
660                 case txnouttype.TX_NULL_DATA:
661                     return 1;
662                 case txnouttype.TX_PUBKEY:
663                     return 1;
664                 case txnouttype.TX_PUBKEYHASH:
665                     return 2;
666                 case txnouttype.TX_MULTISIG:
667                     if (solutions.Count() < 1 || solutions.First().Count() < 1)
668                         return -1;
669                     return solutions.First().First() + 1;
670                 case txnouttype.TX_SCRIPTHASH:
671                     return 1; // doesn't include args needed by the script
672             }
673             return -1;
674         }
675
676         /// <summary>
677         /// Is it a standart type of scriptPubKey?
678         /// </summary>
679         /// <param name="scriptPubKey">CScript instance</param>
680         /// <param name="whichType">utut type</param>
681         /// <returns>Checking result</returns>
682         public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
683         {
684             IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
685
686             if (!Solver(scriptPubKey, out whichType, out solutions))
687             {
688                 // No solutions found
689                 return false;
690             }
691
692             if (whichType == txnouttype.TX_MULTISIG)
693             {
694                 // Additional verification of OP_CHECKMULTISIG arguments
695                 byte m = solutions.First().First();
696                 byte n = solutions.Last().First();
697
698                 // Support up to x-of-3 multisig txns as standard
699                 if (n < 1 || n > 3)
700                 {
701                     return false;
702                 }
703                 if (m < 1 || m > n)
704                 {
705                     return false;
706                 }
707             }
708
709             return whichType != txnouttype.TX_NONSTANDARD;
710         }
711
712         /// <summary>
713         /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
714         /// </summary>
715         /// <param name="scriptPubKey">CScript instance</param>
716         /// <param name="typeRet">Output type</param>
717         /// <param name="solutions">Set of solutions</param>
718         /// <returns>Result</returns>
719         public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<IEnumerable<byte>> solutions)
720         {
721             solutions = new List<IEnumerable<byte>>();
722
723             // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
724
725             // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
726             if (scriptPubKey.IsPayToScriptHash)
727             {
728                 typeRet = txnouttype.TX_SCRIPTHASH;
729
730                 // Take 20 bytes with offset of 2 bytes
731                 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
732                 solutions.Add(hashBytes);
733
734                 return true;
735             }
736
737             // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
738             if (scriptPubKey.IsPayToPubKeyHash)
739             {
740                 typeRet = txnouttype.TX_PUBKEYHASH;
741
742                 // Take 20 bytes with offset of 3 bytes
743                 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
744                 solutions.Add(hashBytes);
745
746                 return true;
747             }
748
749             List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
750
751             // Sender provides pubkey, receiver adds signature
752             // [ECDSA public key] OP_CHECKSIG
753             templateTuples.Add(
754                 new Tuple<txnouttype, IEnumerable<byte>>(
755                     txnouttype.TX_PUBKEY,
756                     new byte[] {
757                         (byte)instruction.OP_PUBKEY,
758                         (byte)instruction.OP_CHECKSIG
759                     })
760             );
761
762             // Sender provides N pubkeys, receivers provides M signatures
763             // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
764             // Where N and M are small integer opcodes (OP1 ... OP_16)
765             templateTuples.Add(
766                 new Tuple<txnouttype, IEnumerable<byte>>(
767                     txnouttype.TX_MULTISIG,
768                     new byte[] {
769                         (byte)instruction.OP_SMALLINTEGER,
770                         (byte)instruction.OP_PUBKEYS,
771                         (byte)instruction.OP_SMALLINTEGER,
772                         (byte)instruction.OP_CHECKMULTISIG
773                     })
774             );
775
776             // Data-carrying output
777             // OP_RETURN [up to 80 bytes of data]
778             templateTuples.Add(
779                 new Tuple<txnouttype, IEnumerable<byte>>(
780                     txnouttype.TX_NULL_DATA,
781                     new byte[] {
782                         (byte)instruction.OP_RETURN,
783                         (byte)instruction.OP_SMALLDATA
784                     })
785             );
786
787             // Nonstandard tx output
788             typeRet = txnouttype.TX_NONSTANDARD;
789
790             foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
791             {
792                 CScript script1 = scriptPubKey;
793                 CScript script2 = new CScript(templateTuple.Item2);
794
795                 instruction opcode1, opcode2;
796
797                 // Compare
798                 ByteQueue bq1 = script1.GetByteQUeue();
799                 ByteQueue bq2 = script2.GetByteQUeue();
800
801                 IEnumerable<byte> args1, args2;
802
803                 int last1 = script1.Bytes.Count() -1;
804                 int last2 = script2.Bytes.Count() - 1;
805
806                 while (true)
807                 {
808                     if (bq1.CurrentIndex == last1 && bq2.CurrentIndex == last2)
809                     {
810                         // Found a match
811                         typeRet = templateTuple.Item1;
812                         if (typeRet == txnouttype.TX_MULTISIG)
813                         {
814                             // Additional checks for TX_MULTISIG:
815                             byte m = solutions.First().First();
816                             byte n = solutions.Last().First();
817
818                             if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
819                             {
820                                 return false;
821                             }
822                         }
823                         return true;
824                     }
825
826                     if (!GetOp(ref bq1, out opcode1, out args1))
827                     {
828                         break;
829                     }
830                     if (!GetOp(ref bq2, out opcode2, out args2))
831                     {
832                         break;
833                     }
834
835                     // Template matching opcodes:
836                     if (opcode2 == instruction.OP_PUBKEYS)
837                     {
838                         while (args1.Count() >= 33 && args1.Count() <= 120)
839                         {
840                             solutions.Add(args1);
841                             if (!GetOp(ref bq1, out opcode1, out args1))
842                             {
843                                 break;
844                             }
845                         }
846                         if (!GetOp(ref bq2, out opcode2, out args2))
847                         {
848                             break;
849                         }
850                         // Normal situation is to fall through
851                         // to other if/else statements
852                     }
853                     if (opcode2 == instruction.OP_PUBKEY)
854                     {
855                         int PubKeyLen = args1.Count();
856                         if (PubKeyLen < 33 || PubKeyLen > 120)
857                         {
858                             break;
859                         }
860                         solutions.Add(args1);
861                     }
862                     else if (opcode2 == instruction.OP_PUBKEYHASH)
863                     {
864                         if (args1.Count() != 20) // hash160 size
865                         {
866                             break;
867                         }
868                         solutions.Add(args1);
869                     }
870                     else if (opcode2 == instruction.OP_SMALLINTEGER)
871                     {
872                         // Single-byte small integer pushed onto solutions
873                         try
874                         {
875                             byte n = (byte)DecodeOP_N(opcode1);
876                             solutions.Add(new byte[] { n });
877                         }
878                         catch (Exception)
879                         {
880                             break;
881                         }
882                     }
883                     else if (opcode2 == instruction.OP_SMALLDATA)
884                     {
885                         // small pushdata, <= 80 bytes
886                         if (args1.Count() > 80)
887                         {
888                             break;
889                         }
890                     }
891                     else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
892                     {
893                         // Others must match exactly
894                         break;
895                     }
896                 }
897             }
898
899             solutions.Clear();
900             typeRet = txnouttype.TX_NONSTANDARD;
901
902             return false;
903         }
904
905         /// <summary>
906         /// Generation of SignatureHash. This method is responsible for removal of transaction metadata. It's necessary signature can't sign itself. 
907         /// </summary>
908         /// <param name="script">Spending instructions</param>
909         /// <param name="txTo">Instance of transaction</param>
910         /// <param name="nIn">Input number</param>
911         /// <param name="nHashType">Hash type flag</param>
912         /// <returns></returns>
913         public static Hash256 SignatureHash(CScript script, CTransaction txTo, int nIn, int nHashType)
914         {
915             if (nIn >= txTo.vin.Length)
916             {
917                 StringBuilder sb = new StringBuilder();
918                 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
919                 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
920             }
921
922             // Init a copy of transaction
923             CTransaction txTmp = new CTransaction(txTo);
924
925             // In case concatenating two scripts ends up with two codeseparators,
926             // or an extra one at the end, this prevents all those possible incompatibilities.
927             script.RemovePattern(new byte[] { (byte)instruction.OP_CODESEPARATOR });
928
929             // Blank out other inputs' signatures
930             for (int i = 0; i < txTmp.vin.Length; i++)
931             {
932                 txTmp.vin[i].scriptSig = new CScript();
933             }
934             txTmp.vin[nIn].scriptSig = script;
935
936             // Blank out some of the outputs
937             if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
938             {
939                 // Wildcard payee
940                 txTmp.vout = new CTxOut[0];
941
942                 // Let the others update at will
943                 for (int i = 0; i < txTmp.vin.Length; i++)
944                 {
945                     if (i != nIn)
946                     {
947                         txTmp.vin[i].nSequence = 0;
948                     }
949                 }
950             }
951             else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
952             {
953                 // Only lock-in the txout payee at same index as txin
954                 int nOut = nIn;
955                 if (nOut >= txTmp.vout.Length)
956                 {
957                     StringBuilder sb = new StringBuilder();
958                     sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
959                     throw new ArgumentOutOfRangeException("nOut", sb.ToString());
960                 }
961                 Array.Resize(ref txTmp.vout, nOut + 1);
962
963                 for (int i = 0; i < nOut; i++)
964                 {
965                     txTmp.vout[i] = new CTxOut();
966                 }
967
968                 // Let the others update at will
969                 for (int i = 0; i < txTmp.vin.Length; i++)
970                 {
971                     if (i != nIn)
972                     {
973                         txTmp.vin[i].nSequence = 0;
974                     }
975                 }
976             }
977
978             // Blank out other inputs completely, not recommended for open transactions
979             if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
980             {
981                 txTmp.vin[0] = txTmp.vin[nIn];
982                 Array.Resize(ref txTmp.vin, 1);
983             }
984
985             // Serialize and hash
986             List<byte> b = new List<byte>();
987             b.AddRange(txTmp.Bytes);
988             b.AddRange(BitConverter.GetBytes(nHashType));
989
990             return Hash256.Compute256(b);
991         }
992
993         //
994         // Script is a stack machine (like Forth) that evaluates a predicate
995         // returning a bool indicating valid or not.  There are no loops.
996         //
997
998         /// <summary>
999         /// Script machine exception
1000         /// </summary>
1001         public class StackMachineException : Exception
1002         {
1003             public StackMachineException()
1004             {
1005             }
1006
1007             public StackMachineException(string message)
1008                 : base(message)
1009             {
1010             }
1011
1012             public StackMachineException(string message, Exception inner)
1013                 : base(message, inner)
1014             {
1015             }
1016         }
1017
1018         /// <summary>
1019         /// Remove last element from stack
1020         /// </summary>
1021         /// <param name="stack">Stack reference</param>
1022         private static void popstack(ref List<IEnumerable<byte>> stack)
1023         {
1024             int nCount = stack.Count;
1025             if (nCount == 0)
1026                 throw new StackMachineException("popstack() : stack empty");
1027             stack.RemoveAt(nCount - 1);
1028         }
1029
1030         /// <summary>
1031         /// Get element at specified stack depth
1032         /// </summary>
1033         /// <param name="stack">Stack reference</param>
1034         /// <param name="nDepth">Depth</param>
1035         /// <returns>Byte sequence</returns>
1036         private static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
1037         {
1038             int nStackElement = stack.Count + nDepth;
1039
1040             if (nDepth >= 0)
1041             {
1042                 StringBuilder sb = new StringBuilder();
1043                 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
1044
1045                 throw new StackMachineException(sb.ToString());
1046             }
1047
1048             if (nStackElement < 0)
1049             {
1050                 StringBuilder sb = new StringBuilder();
1051                 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
1052
1053                 throw new StackMachineException(sb.ToString());
1054             }
1055
1056             return stack[nStackElement];
1057         }
1058
1059         /// <summary>
1060         /// Cast argument to boolean value
1061         /// </summary>
1062         /// <param name="value">Some byte sequence</param>
1063         /// <returns></returns>
1064         private static bool CastToBool(IEnumerable<byte> arg)
1065         {
1066             byte[] value = arg.ToArray();
1067
1068             for (var i = 0; i < value.Length; i++)
1069             {
1070                 if (value[i] != 0)
1071                 {
1072                     // Can be negative zero
1073                     if (i == value.Length - 1 && value[i] == 0x80)
1074                     {
1075                         return false;
1076                     }
1077
1078                     return true;
1079                 }
1080             }
1081
1082             return false;
1083         }
1084
1085         /// <summary>
1086         /// Cast argument to integer value
1087         /// </summary>
1088         /// <param name="value"></param>
1089         /// <returns></returns>
1090         private static BigInteger CastToBigInteger(IEnumerable<byte> value)
1091         {
1092             if (value.Count() > 4)
1093             {
1094                 throw new StackMachineException("CastToBigInteger() : overflow");
1095             }
1096
1097             return new BigInteger(value.ToArray());
1098         }
1099
1100         /// <summary>
1101         /// Execution of script
1102         /// </summary>
1103         /// <param name="stack"></param>
1104         /// <param name="script">Script to execute</param>
1105         /// <param name="txTo">Transaction instance</param>
1106         /// <param name="nIn">Input number</param>
1107         /// <param name="flags">Signature checking flags</param>
1108         /// <param name="nHashType">Hash type flag</param>
1109         /// <returns></returns>
1110         public static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
1111         {
1112             if (script.Bytes.Count() > 10000)
1113             {
1114                 return false; // Size limit failed
1115             }
1116
1117             List<bool> vfExec = new List<bool>();
1118
1119             int nOpCount = 0;
1120             int nCodeHashBegin = 0;
1121
1122             byte[] falseBytes = new byte[0];
1123             byte[] trueBytes = new byte[] { 0x01 };
1124
1125             ByteQueue CodeQueue = script.GetByteQUeue();
1126             List<IEnumerable<byte>> altStack = new List<IEnumerable<byte>>();
1127
1128             try
1129             {
1130                 instruction opcode;
1131                 IEnumerable<byte> pushArg;
1132
1133                 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
1134                 {
1135                     bool fExec = vfExec.IndexOf(false) != -1;
1136
1137                     if (pushArg.Count() > 520)
1138                     {
1139                         return false; // Script element size limit failed
1140                     }
1141
1142                     if (opcode > instruction.OP_16 && ++nOpCount > 201)
1143                     {
1144                         return false;
1145                     }
1146
1147                     if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
1148                     {
1149                         stack.Add(pushArg); // Push argument to stack
1150                     }
1151                     else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
1152                         switch (opcode)
1153                         {
1154                             //
1155                             // Disabled opcodes
1156                             //
1157                             case instruction.OP_CAT:
1158                             case instruction.OP_SUBSTR:
1159                             case instruction.OP_LEFT:
1160                             case instruction.OP_RIGHT:
1161                             case instruction.OP_INVERT:
1162                             case instruction.OP_AND:
1163                             case instruction.OP_OR:
1164                             case instruction.OP_XOR:
1165                             case instruction.OP_2MUL:
1166                             case instruction.OP_2DIV:
1167                             case instruction.OP_MUL:
1168                             case instruction.OP_DIV:
1169                             case instruction.OP_MOD:
1170                             case instruction.OP_LSHIFT:
1171                             case instruction.OP_RSHIFT:
1172                                 return false;
1173
1174                             //
1175                             // Push integer instructions
1176                             //
1177                             case instruction.OP_1NEGATE:
1178                             case instruction.OP_1:
1179                             case instruction.OP_2:
1180                             case instruction.OP_3:
1181                             case instruction.OP_4:
1182                             case instruction.OP_5:
1183                             case instruction.OP_6:
1184                             case instruction.OP_7:
1185                             case instruction.OP_8:
1186                             case instruction.OP_9:
1187                             case instruction.OP_10:
1188                             case instruction.OP_11:
1189                             case instruction.OP_12:
1190                             case instruction.OP_13:
1191                             case instruction.OP_14:
1192                             case instruction.OP_15:
1193                             case instruction.OP_16:
1194                                 {
1195                                     // ( -- value)
1196                                     BigInteger bn = DecodeOP_N(opcode, true);
1197                                     stack.Add(bn.ToByteArray());
1198                                 }
1199                                 break;
1200
1201                             //
1202                             // Extension
1203                             //
1204                             case instruction.OP_NOP:
1205                             case instruction.OP_NOP1:
1206                             case instruction.OP_NOP2:
1207                             case instruction.OP_NOP3:
1208                             case instruction.OP_NOP4:
1209                             case instruction.OP_NOP5:
1210                             case instruction.OP_NOP6:
1211                             case instruction.OP_NOP7:
1212                             case instruction.OP_NOP8:
1213                             case instruction.OP_NOP9:
1214                             case instruction.OP_NOP10:
1215                                 {
1216                                     // Just do nothing
1217                                 }
1218                                 break;
1219
1220                             //
1221                             // Control
1222                             //
1223                             case instruction.OP_IF:
1224                             case instruction.OP_NOTIF:
1225                                 {
1226                                     // <expression> if [statements] [else [statements]] endif
1227                                     bool fValue = false;
1228                                     if (fExec)
1229                                     {
1230                                         if (stack.Count() < 1)
1231                                         {
1232                                             return false;
1233                                         }
1234                                         IEnumerable<byte> vch = stacktop(ref stack, -1);
1235                                         fValue = CastToBool(vch);
1236                                         if (opcode == instruction.OP_NOTIF)
1237                                         {
1238                                             fValue = !fValue;
1239                                         }
1240                                         popstack(ref stack);
1241                                     }
1242                                     vfExec.Add(fValue);
1243                                 }
1244                                 break;
1245
1246                             case instruction.OP_ELSE:
1247                                 {
1248                                     int nExecCount = vfExec.Count();
1249                                     if (nExecCount == 0)
1250                                     {
1251                                         return false;
1252                                     }
1253                                     vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1254                                 }
1255                                 break;
1256
1257                             case instruction.OP_ENDIF:
1258                                 {
1259                                     int nExecCount = vfExec.Count();
1260                                     if (nExecCount == 0)
1261                                     {
1262                                         return false;
1263                                     }
1264                                     vfExec.RemoveAt(nExecCount - 1);
1265                                 }
1266                                 break;
1267
1268                             case instruction.OP_VERIFY:
1269                                 {
1270                                     // (true -- ) or
1271                                     // (false -- false) and return
1272                                     if (stack.Count() < 1)
1273                                     {
1274                                         return false;
1275                                     }
1276
1277                                     bool fValue = CastToBool(stacktop(ref stack, -1));
1278                                     if (fValue)
1279                                     {
1280                                         popstack(ref stack);
1281                                     }
1282                                     else
1283                                     {
1284                                         return false;
1285                                     }
1286                                 }
1287                                 break;
1288
1289                             case instruction.OP_RETURN:
1290                                 {
1291                                     return false;
1292                                 }
1293
1294                             //
1295                             // Stack ops
1296                             //
1297                             case instruction.OP_TOALTSTACK:
1298                                 {
1299                                     if (stack.Count() < 1)
1300                                     {
1301                                         return false;
1302                                     }
1303                                     altStack.Add(stacktop(ref stack, -1));
1304                                     popstack(ref stack);
1305                                 }
1306                                 break;
1307
1308                             case instruction.OP_FROMALTSTACK:
1309                                 {
1310                                     if (altStack.Count() < 1)
1311                                     {
1312                                         return false;
1313                                     }
1314                                     stack.Add(stacktop(ref stack, -1));
1315                                     popstack(ref altStack);
1316                                 }
1317                                 break;
1318
1319                             case instruction.OP_2DROP:
1320                                 {
1321                                     // (x1 x2 -- )
1322                                     if (stack.Count() < 2)
1323                                     {
1324                                         return false;
1325                                     }
1326                                     popstack(ref stack);
1327                                     popstack(ref stack);
1328                                 }
1329                                 break;
1330
1331                             case instruction.OP_2DUP:
1332                                 {
1333                                     // (x1 x2 -- x1 x2 x1 x2)
1334                                     if (stack.Count() < 2)
1335                                     {
1336                                         return false;
1337                                     }
1338                                     IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1339                                     IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1340                                     stack.Add(vch1);
1341                                     stack.Add(vch2);
1342                                 }
1343                                 break;
1344
1345                             case instruction.OP_3DUP:
1346                                 {
1347                                     // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1348                                     if (stack.Count() < 3)
1349                                     {
1350                                         return false;
1351                                     }
1352                                     IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1353                                     IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1354                                     IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1355                                     stack.Add(vch1);
1356                                     stack.Add(vch2);
1357                                     stack.Add(vch3);
1358                                 }
1359                                 break;
1360
1361                             case instruction.OP_2OVER:
1362                                 {
1363                                     // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1364                                     if (stack.Count() < 4)
1365                                     {
1366                                         return false;
1367                                     }
1368                                     IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1369                                     IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1370                                     stack.Add(vch1);
1371                                     stack.Add(vch2);
1372                                 }
1373                                 break;
1374
1375                             case instruction.OP_2ROT:
1376                                 {
1377                                     int nStackDepth = stack.Count();
1378                                     // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1379                                     if (nStackDepth < 6)
1380                                     {
1381                                         return false;
1382                                     }
1383                                     IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1384                                     IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1385                                     stack.RemoveRange(nStackDepth - 6, 2);
1386                                     stack.Add(vch1);
1387                                     stack.Add(vch2);
1388                                 }
1389                                 break;
1390
1391                             case instruction.OP_2SWAP:
1392                                 {
1393                                     // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1394                                     int nStackDepth = stack.Count();
1395                                     if (nStackDepth < 4)
1396                                     {
1397                                         return false;
1398                                     }
1399                                     stack.Swap(nStackDepth - 4, nStackDepth - 2);
1400                                     stack.Swap(nStackDepth - 3, nStackDepth - 1);
1401                                 }
1402                                 break;
1403
1404                             case instruction.OP_IFDUP:
1405                                 {
1406                                     // (x - 0 | x x)
1407                                     if (stack.Count() < 1)
1408                                     {
1409                                         return false;
1410                                     }
1411
1412                                     IEnumerable<byte> vch = stacktop(ref stack, -1);
1413
1414                                     if (CastToBool(vch))
1415                                     {
1416                                         stack.Add(vch);
1417                                     }
1418                                 }
1419                                 break;
1420
1421                             case instruction.OP_DEPTH:
1422                                 {
1423                                     // -- stacksize
1424                                     BigInteger bn = new BigInteger((ushort)stack.Count());
1425                                     stack.Add(bn.ToByteArray());
1426                                 }
1427                                 break;
1428
1429                             case instruction.OP_DROP:
1430                                 {
1431                                     // (x -- )
1432                                     if (stack.Count() < 1)
1433                                     {
1434                                         return false;
1435                                     }
1436
1437                                     popstack(ref stack);
1438                                 }
1439                                 break;
1440
1441                             case instruction.OP_DUP:
1442                                 {
1443                                     // (x -- x x)
1444                                     if (stack.Count() < 1)
1445                                     {
1446                                         return false;
1447                                     }
1448
1449                                     IEnumerable<byte> vch = stacktop(ref stack, -1);
1450                                     stack.Add(vch);
1451                                 }
1452                                 break;
1453
1454                             case instruction.OP_NIP:
1455                                 {
1456                                     // (x1 x2 -- x2)
1457                                     int nStackDepth = stack.Count();
1458                                     if (nStackDepth < 2)
1459                                     {
1460                                         return false;
1461                                     }
1462
1463                                     stack.RemoveAt(nStackDepth - 2);
1464                                 }
1465                                 break;
1466
1467                             case instruction.OP_OVER:
1468                                 {
1469                                     // (x1 x2 -- x1 x2 x1)
1470                                     if (stack.Count() < 2)
1471                                     {
1472                                         return false;
1473                                     }
1474
1475                                     IEnumerable<byte> vch = stacktop(ref stack, -2);
1476                                     stack.Add(vch);
1477                                 }
1478                                 break;
1479
1480                             case instruction.OP_PICK:
1481                             case instruction.OP_ROLL:
1482                                 {
1483                                     // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1484                                     // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1485
1486                                     int nStackDepth = stack.Count();
1487                                     if (nStackDepth < 2)
1488                                     {
1489                                         return false;
1490                                     }
1491
1492                                     int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1493                                     popstack(ref stack);
1494
1495                                     if (n < 0 || n >= stack.Count())
1496                                     {
1497                                         return false;
1498                                     }
1499
1500                                     IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1501                                     if (opcode == instruction.OP_ROLL)
1502                                     {
1503                                         stack.RemoveAt(nStackDepth - n - 1);
1504                                     }
1505
1506                                     stack.Add(vch);
1507                                 }
1508                                 break;
1509
1510                             case instruction.OP_ROT:
1511                                 {
1512                                     // (x1 x2 x3 -- x2 x3 x1)
1513                                     //  x2 x1 x3  after first swap
1514                                     //  x2 x3 x1  after second swap
1515                                     int nStackDepth = stack.Count();
1516                                     if (nStackDepth < 3)
1517                                     {
1518                                         return false;
1519                                     }
1520                                     stack.Swap(nStackDepth - 3, nStackDepth - 2);
1521                                     stack.Swap(nStackDepth - 2, nStackDepth - 1);
1522
1523                                 }
1524                                 break;
1525
1526                             case instruction.OP_SWAP:
1527                                 {
1528                                     // (x1 x2 -- x2 x1)
1529                                     int nStackDepth = stack.Count();
1530                                     if (nStackDepth < 2)
1531                                     {
1532                                         return false;
1533                                     }
1534                                     stack.Swap(nStackDepth - 2, nStackDepth - 1);
1535                                 }
1536                                 break;
1537
1538                             case instruction.OP_TUCK:
1539                                 {
1540                                     // (x1 x2 -- x2 x1 x2)
1541                                     int nStackDepth = stack.Count();
1542                                     if (nStackDepth < 2)
1543                                     {
1544                                         return false;
1545                                     }
1546                                     IEnumerable<byte> vch = stacktop(ref stack, -1);
1547                                     stack.Insert(nStackDepth - 2, vch);
1548                                 }
1549                                 break;
1550
1551
1552                             case instruction.OP_SIZE:
1553                                 {
1554                                     // (in -- in size)
1555                                     if (stack.Count() < 1)
1556                                     {
1557                                         return false;
1558                                     }
1559
1560                                     BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1561                                     stack.Add(bnSize.ToByteArray());
1562                                 }
1563                                 break;
1564
1565
1566                             //
1567                             // Bitwise logic
1568                             //
1569                             case instruction.OP_EQUAL:
1570                             case instruction.OP_EQUALVERIFY:
1571                                 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1572                                 {
1573                                     // (x1 x2 - bool)
1574                                     if (stack.Count() < 2)
1575                                     {
1576                                         return false;
1577                                     }
1578
1579                                     IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1580                                     IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1581                                     bool fEqual = (vch1 == vch2);
1582                                     // OP_NOTEQUAL is disabled because it would be too easy to say
1583                                     // something like n != 1 and have some wiseguy pass in 1 with extra
1584                                     // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1585                                     //if (opcode == instruction.OP_NOTEQUAL)
1586                                     //    fEqual = !fEqual;
1587                                     popstack(ref stack);
1588                                     popstack(ref stack);
1589                                     stack.Add(fEqual ? trueBytes : falseBytes);
1590
1591                                     if (opcode == instruction.OP_EQUALVERIFY)
1592                                     {
1593                                         if (fEqual)
1594                                         {
1595                                             popstack(ref stack);
1596                                         }
1597                                         else
1598                                         {
1599                                             return false;
1600                                         }
1601                                     }
1602                                 }
1603                                 break;
1604
1605
1606                             //
1607                             // Numeric
1608                             //
1609                             case instruction.OP_1ADD:
1610                             case instruction.OP_1SUB:
1611                             case instruction.OP_NEGATE:
1612                             case instruction.OP_ABS:
1613                             case instruction.OP_NOT:
1614                             case instruction.OP_0NOTEQUAL:
1615                                 {
1616                                     // (in -- out)
1617                                     if (stack.Count() < 1)
1618                                     {
1619                                         return false;
1620                                     }
1621
1622                                     BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1623                                     switch (opcode)
1624                                     {
1625                                         case instruction.OP_1ADD:
1626                                             bn = bn + 1;
1627                                             break;
1628                                         case instruction.OP_1SUB:
1629                                             bn = bn - 1;
1630                                             break;
1631                                         case instruction.OP_NEGATE:
1632                                             bn = -bn;
1633                                             break;
1634                                         case instruction.OP_ABS:
1635                                             bn = BigInteger.Abs(bn);
1636                                             break;
1637                                         case instruction.OP_NOT:
1638                                             bn = bn == 0 ? 1 : 0;
1639                                             break;
1640                                         case instruction.OP_0NOTEQUAL:
1641                                             bn = bn != 0 ? 1 : 0;
1642                                             break;
1643                                     }
1644
1645                                     popstack(ref stack);
1646                                     stack.Add(bn.ToByteArray());
1647                                 }
1648                                 break;
1649
1650                             case instruction.OP_ADD:
1651                             case instruction.OP_SUB:
1652                             case instruction.OP_BOOLAND:
1653                             case instruction.OP_BOOLOR:
1654                             case instruction.OP_NUMEQUAL:
1655                             case instruction.OP_NUMEQUALVERIFY:
1656                             case instruction.OP_NUMNOTEQUAL:
1657                             case instruction.OP_LESSTHAN:
1658                             case instruction.OP_GREATERTHAN:
1659                             case instruction.OP_LESSTHANOREQUAL:
1660                             case instruction.OP_GREATERTHANOREQUAL:
1661                             case instruction.OP_MIN:
1662                             case instruction.OP_MAX:
1663                                 {
1664                                     // (x1 x2 -- out)
1665                                     if (stack.Count() < 2)
1666                                     {
1667                                         return false;
1668                                     }
1669
1670                                     BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1671                                     BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1672                                     BigInteger bn = 0;
1673
1674                                     switch (opcode)
1675                                     {
1676                                         case instruction.OP_ADD:
1677                                             bn = bn1 + bn2;
1678                                             break;
1679                                         case instruction.OP_SUB:
1680                                             bn = bn1 - bn2;
1681                                             break;
1682                                         case instruction.OP_BOOLAND:
1683                                             bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1684                                             break;
1685                                         case instruction.OP_BOOLOR:
1686                                             bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1687                                             break;
1688                                         case instruction.OP_NUMEQUAL:
1689                                             bn = (bn1 == bn2) ? 1 : 0;
1690                                             break;
1691                                         case instruction.OP_NUMEQUALVERIFY:
1692                                             bn = (bn1 == bn2) ? 1 : 0;
1693                                             break;
1694                                         case instruction.OP_NUMNOTEQUAL:
1695                                             bn = (bn1 != bn2) ? 1 : 0;
1696                                             break;
1697                                         case instruction.OP_LESSTHAN:
1698                                             bn = (bn1 < bn2) ? 1 : 0;
1699                                             break;
1700                                         case instruction.OP_GREATERTHAN:
1701                                             bn = (bn1 > bn2) ? 1 : 0;
1702                                             break;
1703                                         case instruction.OP_LESSTHANOREQUAL:
1704                                             bn = (bn1 <= bn2) ? 1 : 0;
1705                                             break;
1706                                         case instruction.OP_GREATERTHANOREQUAL:
1707                                             bn = (bn1 >= bn2) ? 1 : 0;
1708                                             break;
1709                                         case instruction.OP_MIN:
1710                                             bn = (bn1 < bn2 ? bn1 : bn2);
1711                                             break;
1712                                         case instruction.OP_MAX:
1713                                             bn = (bn1 > bn2 ? bn1 : bn2);
1714                                             break;
1715                                     }
1716
1717                                     popstack(ref stack);
1718                                     popstack(ref stack);
1719                                     stack.Add(bn.ToByteArray());
1720
1721                                     if (opcode == instruction.OP_NUMEQUALVERIFY)
1722                                     {
1723                                         if (CastToBool(stacktop(ref stack, -1)))
1724                                         {
1725                                             popstack(ref stack);
1726                                         }
1727                                         else
1728                                         {
1729                                             return false;
1730                                         }
1731                                     }
1732                                 }
1733                                 break;
1734
1735                             case instruction.OP_WITHIN:
1736                                 {
1737                                     // (x min max -- out)
1738                                     if (stack.Count() < 3)
1739                                     {
1740                                         return false;
1741                                     }
1742
1743                                     BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1744                                     BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1745                                     BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1746
1747                                     bool fValue = (bn2 <= bn1 && bn1 < bn3);
1748
1749                                     popstack(ref stack);
1750                                     popstack(ref stack);
1751                                     popstack(ref stack);
1752
1753                                     stack.Add(fValue ? trueBytes : falseBytes);
1754                                 }
1755                                 break;
1756
1757                             //
1758                             // Crypto
1759                             //
1760                             case instruction.OP_RIPEMD160:
1761                             case instruction.OP_SHA1:
1762                             case instruction.OP_SHA256:
1763                             case instruction.OP_HASH160:
1764                             case instruction.OP_HASH256:
1765                                 {
1766                                     // (in -- hash)
1767                                     if (stack.Count() < 1)
1768                                     {
1769                                         return false;
1770                                     }
1771                                     Hash hash = null;
1772                                     IEnumerable<byte> data = stacktop(ref stack, -1);
1773
1774                                     switch (opcode)
1775                                     {
1776                                         case instruction.OP_HASH160:
1777                                             hash = Hash160.Compute160(data);
1778                                             break;
1779                                         case instruction.OP_HASH256:
1780                                             hash = Hash256.Compute256(data);
1781                                             break;
1782                                         case instruction.OP_SHA1:
1783                                             hash = SHA1.Compute1(data);
1784                                             break;
1785                                         case instruction.OP_SHA256:
1786                                             hash = SHA256.Compute256(data);
1787                                             break;
1788                                         case instruction.OP_RIPEMD160:
1789                                             hash = RIPEMD160.Compute160(data);
1790                                             break;
1791                                     }
1792                                     popstack(ref stack);
1793                                     stack.Add(hash.hashBytes);
1794                                 }
1795                                 break;
1796
1797                             case instruction.OP_CODESEPARATOR:
1798                                 {
1799                                     // Hash starts after the code separator
1800                                     nCodeHashBegin = CodeQueue.CurrentIndex;
1801                                 }
1802                                 break;
1803
1804                             case instruction.OP_CHECKSIG:
1805                             case instruction.OP_CHECKSIGVERIFY:
1806                                 {
1807                                     // (sig pubkey -- bool)
1808                                     if (stack.Count() < 2)
1809                                     {
1810                                         return false;
1811                                     }
1812
1813                                     IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1814                                     IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1815
1816                                     // Subset of script starting at the most recent codeseparator
1817                                     CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1818
1819                                     // There's no way for a signature to sign itself
1820                                     scriptCode.RemovePattern(sigBytes);
1821
1822                                     bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1823
1824                                     popstack(ref stack);
1825                                     popstack(ref stack);
1826
1827                                     stack.Add(fSuccess ? trueBytes : falseBytes);
1828
1829                                     if (opcode == instruction.OP_CHECKSIGVERIFY)
1830                                     {
1831                                         if (fSuccess)
1832                                         {
1833                                             popstack(ref stack);
1834                                         }
1835                                         else
1836                                         {
1837                                             return false;
1838                                         }
1839                                     }
1840                                 }
1841                                 break;
1842
1843                             case instruction.OP_CHECKMULTISIG:
1844                             case instruction.OP_CHECKMULTISIGVERIFY:
1845                                 {
1846                                     // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1847
1848                                     int i = 1;
1849                                     if (stack.Count() < i)
1850                                     {
1851                                         return false;
1852                                     }
1853
1854                                     int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1855                                     if (nKeysCount < 0 || nKeysCount > 20)
1856                                     {
1857                                         return false;
1858                                     }
1859                                     nOpCount += nKeysCount;
1860                                     if (nOpCount > 201)
1861                                     {
1862                                         return false;
1863                                     }
1864                                     int ikey = ++i;
1865                                     i += nKeysCount;
1866                                     if (stack.Count() < i)
1867                                     {
1868                                         return false;
1869                                     }
1870
1871                                     int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1872                                     if (nSigsCount < 0 || nSigsCount > nKeysCount)
1873                                     {
1874                                         return false;
1875                                     }
1876                                     int isig = ++i;
1877                                     i += nSigsCount;
1878                                     if (stack.Count() < i)
1879                                     {
1880                                         return false;
1881                                     }
1882
1883                                     // Subset of script starting at the most recent codeseparator
1884                                     CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1885
1886                                     // There is no way for a signature to sign itself, so we need to drop the signatures
1887                                     for (int k = 0; k < nSigsCount; k++)
1888                                     {
1889                                         IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1890                                         scriptCode.RemovePattern(vchSig.ToList());
1891                                     }
1892
1893                                     bool fSuccess = true;
1894                                     while (fSuccess && nSigsCount > 0)
1895                                     {
1896                                         IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1897                                         IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1898
1899                                         // Check signature
1900                                         bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1901
1902                                         if (fOk)
1903                                         {
1904                                             isig++;
1905                                             nSigsCount--;
1906                                         }
1907                                         ikey++;
1908                                         nKeysCount--;
1909
1910                                         // If there are more signatures left than keys left,
1911                                         // then too many signatures have failed
1912                                         if (nSigsCount > nKeysCount)
1913                                         {
1914                                             fSuccess = false;
1915                                         }
1916                                     }
1917
1918                                     while (i-- > 1)
1919                                     {
1920                                         popstack(ref stack);
1921                                     }
1922
1923                                     // A bug causes CHECKMULTISIG to consume one extra argument
1924                                     // whose contents were not checked in any way.
1925                                     //
1926                                     // Unfortunately this is a potential source of mutability,
1927                                     // so optionally verify it is exactly equal to zero prior
1928                                     // to removing it from the stack.
1929                                     if (stack.Count() < 1)
1930                                     {
1931                                         return false;
1932                                     }
1933                                     if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1934                                     {
1935                                         return false; // CHECKMULTISIG dummy argument not null
1936                                     }
1937                                     popstack(ref stack);
1938
1939                                     stack.Add(fSuccess ? trueBytes : falseBytes);
1940
1941                                     if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1942                                     {
1943                                         if (fSuccess)
1944                                         {
1945                                             popstack(ref stack);
1946                                         }
1947                                         else
1948                                         {
1949                                             return false;
1950                                         }
1951                                     }
1952                                 }
1953                                 break;
1954
1955                             default:
1956                                 return false;
1957                         }
1958
1959                     // Size limits
1960                     if (stack.Count() + altStack.Count() > 1000)
1961                     {
1962                         return false;
1963                     }
1964                 }
1965             }
1966             catch (Exception)
1967             {
1968                 // If there are any exceptions then just return false.
1969                 return false;
1970             }
1971
1972             if (vfExec.Count() != 0)
1973             {
1974                 // Something went wrong with conditional instructions.
1975                 return false;
1976             }
1977
1978             return true;
1979         }
1980
1981
1982         public static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1983         {
1984             if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1985                 return true;
1986
1987             if (pubKeyBytes.Count < 33)
1988                 return false;  // Non-canonical public key: too short
1989             if (pubKeyBytes[0] == 0x04)
1990             {
1991                 if (pubKeyBytes.Count != 65)
1992                     return false; // Non-canonical public key: invalid length for uncompressed key
1993             }
1994             else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1995             {
1996                 if (pubKeyBytes.Count != 33)
1997                     return false; // Non-canonical public key: invalid length for compressed key
1998             }
1999             else
2000             {
2001                 return false; // Non-canonical public key: compressed nor uncompressed
2002             }
2003             return true;
2004         }
2005
2006         public static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
2007         {
2008             // STUB
2009
2010             return true;
2011         }
2012
2013         /// <summary>
2014         /// Check signature.
2015         /// </summary>
2016         /// <param name="sigBytes">Signature</param>
2017         /// <param name="pubkeyBytes">Public key</param>
2018         /// <param name="script">Spending script</param>
2019         /// <param name="txTo">CTransaction instance</param>
2020         /// <param name="nIn">Input number</param>
2021         /// <param name="nHashType">Hashing type flag</param>
2022         /// <param name="flags">Signature checking flags</param>
2023         /// <returns></returns>
2024         public static bool CheckSig(IList<byte> sigBytes, IList<byte> pubkeyBytes, CScript script, CTransaction txTo, int nIn, int nHashType, int flags)
2025         {
2026             CPubKey pubkey;
2027
2028             try
2029             {
2030                 // Trying to initialize the public key instance
2031
2032                 pubkey = new CPubKey(pubkeyBytes);
2033             }
2034             catch (Exception)
2035             {
2036                 // Exception occurred while initializing the public key
2037
2038                 return false; 
2039             }
2040
2041             if (!pubkey.IsValid)
2042             {
2043                 return false;
2044             }
2045
2046             if (sigBytes.Count == 0)
2047             {
2048                 return false;
2049             }
2050
2051             // Hash type is one byte tacked on to the end of the signature
2052             if (nHashType == 0)
2053             {
2054                 nHashType = sigBytes.Last();
2055             }
2056             else if (nHashType != sigBytes.Last())
2057             {
2058                 return false;
2059             }
2060
2061             // Remove hash type
2062             sigBytes.RemoveAt(sigBytes.Count - 1);
2063
2064             Hash256 sighash = SignatureHash(script, txTo, nIn, nHashType);
2065
2066             if (!pubkey.VerifySignature(sighash, sigBytes))
2067             {
2068                 return false;
2069             }
2070
2071             return true;
2072         }
2073     };
2074 }