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