2 using System.Collections.Generic;
8 // using Org.BouncyCastle.Math;
15 public enum instruction
57 OP_FROMALTSTACK = 0x6c,
89 OP_EQUALVERIFY = 0x88,
114 OP_NUMEQUALVERIFY = 0x9d,
115 OP_NUMNOTEQUAL = 0x9e,
117 OP_GREATERTHAN = 0xa0,
118 OP_LESSTHANOREQUAL = 0xa1,
119 OP_GREATERTHANOREQUAL = 0xa2,
131 OP_CODESEPARATOR = 0xab,
133 OP_CHECKSIGVERIFY = 0xad,
134 OP_CHECKMULTISIG = 0xae,
135 OP_CHECKMULTISIGVERIFY = 0xaf,
149 // template matching params
151 OP_SMALLINTEGER = 0xfa,
153 OP_PUBKEYHASH = 0xfd,
156 OP_INVALIDOPCODE = 0xff,
160 /// Transaction output types.
162 public enum txnouttype
166 // 'standard' transaction types:
175 /// Signature hash types/flags
182 SIGHASH_ANYONECANPAY = 0x80,
185 /** Script verification flags */
186 public enum scriptflag
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
196 public static class ScriptCode
198 public static string GetTxnOutputType(txnouttype t)
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";
213 /// Get the name of supplied opcode
215 /// <param name="opcode">Opcode</param>
216 /// <returns>Opcode name</returns>
217 public static string GetOpName(instruction opcode)
222 case instruction.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:
232 case instruction.OP_RESERVED:
233 return "OP_RESERVED";
234 case instruction.OP_1:
236 case instruction.OP_2:
238 case instruction.OP_3:
240 case instruction.OP_4:
242 case instruction.OP_5:
244 case instruction.OP_6:
246 case instruction.OP_7:
248 case instruction.OP_8:
250 case instruction.OP_9:
252 case instruction.OP_10:
254 case instruction.OP_11:
256 case instruction.OP_12:
258 case instruction.OP_13:
260 case instruction.OP_14:
262 case instruction.OP_15:
264 case instruction.OP_16:
268 case instruction.OP_NOP:
270 case instruction.OP_VER:
272 case instruction.OP_IF:
274 case instruction.OP_NOTIF:
276 case instruction.OP_VERIF:
278 case instruction.OP_VERNOTIF:
279 return "OP_VERNOTIF";
280 case instruction.OP_ELSE:
282 case instruction.OP_ENDIF:
284 case instruction.OP_VERIFY:
286 case instruction.OP_RETURN:
290 case instruction.OP_TOALTSTACK:
291 return "OP_TOALTSTACK";
292 case instruction.OP_FROMALTSTACK:
293 return "OP_FROMALTSTACK";
294 case instruction.OP_2DROP:
296 case instruction.OP_2DUP:
298 case instruction.OP_3DUP:
300 case instruction.OP_2OVER:
302 case instruction.OP_2ROT:
304 case instruction.OP_2SWAP:
306 case instruction.OP_IFDUP:
308 case instruction.OP_DEPTH:
310 case instruction.OP_DROP:
312 case instruction.OP_DUP:
314 case instruction.OP_NIP:
316 case instruction.OP_OVER:
318 case instruction.OP_PICK:
320 case instruction.OP_ROLL:
322 case instruction.OP_ROT:
324 case instruction.OP_SWAP:
326 case instruction.OP_TUCK:
330 case instruction.OP_CAT:
332 case instruction.OP_SUBSTR:
334 case instruction.OP_LEFT:
336 case instruction.OP_RIGHT:
338 case instruction.OP_SIZE:
342 case instruction.OP_INVERT:
344 case instruction.OP_AND:
346 case instruction.OP_OR:
348 case instruction.OP_XOR:
350 case instruction.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";
360 case instruction.OP_1ADD:
362 case instruction.OP_1SUB:
364 case instruction.OP_2MUL:
366 case instruction.OP_2DIV:
368 case instruction.OP_NEGATE:
370 case instruction.OP_ABS:
372 case instruction.OP_NOT:
374 case instruction.OP_0NOTEQUAL:
375 return "OP_0NOTEQUAL";
376 case instruction.OP_ADD:
378 case instruction.OP_SUB:
380 case instruction.OP_MUL:
382 case instruction.OP_DIV:
384 case instruction.OP_MOD:
386 case instruction.OP_LSHIFT:
388 case instruction.OP_RSHIFT:
390 case instruction.OP_BOOLAND:
392 case instruction.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:
410 case instruction.OP_MAX:
412 case instruction.OP_WITHIN:
416 case instruction.OP_RIPEMD160:
417 return "OP_RIPEMD160";
418 case instruction.OP_SHA1:
420 case instruction.OP_SHA256:
422 case instruction.OP_HASH160:
424 case instruction.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";
438 case instruction.OP_NOP1:
440 case instruction.OP_NOP2:
442 case instruction.OP_NOP3:
444 case instruction.OP_NOP4:
446 case instruction.OP_NOP5:
448 case instruction.OP_NOP6:
450 case instruction.OP_NOP7:
452 case instruction.OP_NOP8:
454 case instruction.OP_NOP9:
456 case instruction.OP_NOP10:
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:
466 case instruction.OP_PUBKEYS:
468 case instruction.OP_SMALLDATA:
469 return "OP_SMALLDATA";
471 case instruction.OP_INVALIDOPCODE:
472 return "OP_INVALIDOPCODE";
479 /// Get next opcode from passed list of bytes and extract push arguments if there are some.
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)
487 bytesRet = new List<byte>();
488 opcodeRet = instruction.OP_INVALIDOPCODE;
495 opcode = (instruction)codeBytes.Get();
497 catch (ByteQueueException)
499 // No instruction found there
504 if (opcode <= instruction.OP_PUSHDATA4)
506 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
510 if (opcode < instruction.OP_PUSHDATA1)
512 // Zero value opcodes (OP_0, OP_FALSE)
513 szBytes[3] = (byte)opcode;
515 else if (opcode == instruction.OP_PUSHDATA1)
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();
521 else if (opcode == instruction.OP_PUSHDATA2)
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);
527 else if (opcode == instruction.OP_PUSHDATA4)
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);
534 catch (ByteQueueException)
536 // Unable to read operand length
540 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
544 // If nSize is greater than zero then there is some data available
547 // Read found number of bytes into list of OP_PUSHDATAn arguments.
548 bytesRet = codeBytes.GetEnumerable(nSize);
550 catch (ByteQueueException)
552 // Unable to read data
564 /// Convert value bytes into readable representation.
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.
568 /// <param name="bytes">Collection of value bytes.</param>
569 /// <returns>Formatted value.</returns>
570 public static string ValueString(IEnumerable<byte> bytes)
572 StringBuilder sb = new StringBuilder();
574 if (bytes.Count() <= 4)
576 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
577 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
579 sb.Append(Interop.BEBytesToUInt32(valueBytes));
583 return Interop.ToHex(bytes);
586 return sb.ToString();
590 /// Convert list of stack items into human readable representation.
592 /// <param name="stackList">List of stack items.</param>
593 /// <returns>Formatted value.</returns>
594 public static string StackString(IList<IList<byte>> stackList)
596 StringBuilder sb = new StringBuilder();
597 foreach (IList<byte> bytesList in stackList)
599 sb.Append(ValueString(bytesList));
602 return sb.ToString();
606 /// Decode instruction to integer value
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)
612 if (AllowNegate && opcode == instruction.OP_1NEGATE)
617 if (opcode == instruction.OP_0)
622 // Only OP_n opcodes are supported, throw exception otherwise.
623 if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
625 throw new ArgumentException("Invalid integer instruction.");
628 return (int)opcode - (int)(instruction.OP_1 - 1);
632 /// Converts integer into instruction
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)
638 if (allowNegate && n == -1)
640 return instruction.OP_1NEGATE;
645 return instruction.OP_0;
648 // The n value must be in the range of 0 to 16.
650 throw new ArgumentException("Invalid integer value.");
651 return (instruction.OP_1 + n - 1);
654 public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
658 case txnouttype.TX_NONSTANDARD:
660 case txnouttype.TX_NULL_DATA:
662 case txnouttype.TX_PUBKEY:
664 case txnouttype.TX_PUBKEYHASH:
666 case txnouttype.TX_MULTISIG:
667 if (solutions.Count() < 1 || solutions.First().Count() < 1)
669 return solutions.First().First() + 1;
670 case txnouttype.TX_SCRIPTHASH:
671 return 1; // doesn't include args needed by the script
677 /// Is it a standart type of scriptPubKey?
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)
684 IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
686 if (!Solver(scriptPubKey, out whichType, out solutions))
688 // No solutions found
692 if (whichType == txnouttype.TX_MULTISIG)
694 // Additional verification of OP_CHECKMULTISIG arguments
695 byte m = solutions.First().First();
696 byte n = solutions.Last().First();
698 // Support up to x-of-3 multisig txns as standard
709 return whichType != txnouttype.TX_NONSTANDARD;
713 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
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)
721 solutions = new List<IEnumerable<byte>>();
723 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
725 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
726 if (scriptPubKey.IsPayToScriptHash)
728 typeRet = txnouttype.TX_SCRIPTHASH;
730 // Take 20 bytes with offset of 2 bytes
731 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
732 solutions.Add(hashBytes);
737 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
738 if (scriptPubKey.IsPayToPubKeyHash)
740 typeRet = txnouttype.TX_PUBKEYHASH;
742 // Take 20 bytes with offset of 3 bytes
743 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
744 solutions.Add(hashBytes);
749 List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
751 // Sender provides pubkey, receiver adds signature
752 // [ECDSA public key] OP_CHECKSIG
754 new Tuple<txnouttype, IEnumerable<byte>>(
755 txnouttype.TX_PUBKEY,
757 (byte)instruction.OP_PUBKEY,
758 (byte)instruction.OP_CHECKSIG
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)
766 new Tuple<txnouttype, IEnumerable<byte>>(
767 txnouttype.TX_MULTISIG,
769 (byte)instruction.OP_SMALLINTEGER,
770 (byte)instruction.OP_PUBKEYS,
771 (byte)instruction.OP_SMALLINTEGER,
772 (byte)instruction.OP_CHECKMULTISIG
776 // Data-carrying output
777 // OP_RETURN [up to 80 bytes of data]
779 new Tuple<txnouttype, IEnumerable<byte>>(
780 txnouttype.TX_NULL_DATA,
782 (byte)instruction.OP_RETURN,
783 (byte)instruction.OP_SMALLDATA
787 // Nonstandard tx output
788 typeRet = txnouttype.TX_NONSTANDARD;
790 foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
792 CScript script1 = scriptPubKey;
793 CScript script2 = new CScript(templateTuple.Item2);
795 instruction opcode1, opcode2;
798 ByteQueue bq1 = script1.GetByteQUeue();
799 ByteQueue bq2 = script2.GetByteQUeue();
801 IEnumerable<byte> args1, args2;
803 int last1 = script1.Bytes.Count() -1;
804 int last2 = script2.Bytes.Count() - 1;
808 if (bq1.CurrentIndex == last1 && bq2.CurrentIndex == last2)
811 typeRet = templateTuple.Item1;
812 if (typeRet == txnouttype.TX_MULTISIG)
814 // Additional checks for TX_MULTISIG:
815 byte m = solutions.First().First();
816 byte n = solutions.Last().First();
818 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
826 if (!GetOp(ref bq1, out opcode1, out args1))
830 if (!GetOp(ref bq2, out opcode2, out args2))
835 // Template matching opcodes:
836 if (opcode2 == instruction.OP_PUBKEYS)
838 while (args1.Count() >= 33 && args1.Count() <= 120)
840 solutions.Add(args1);
841 if (!GetOp(ref bq1, out opcode1, out args1))
846 if (!GetOp(ref bq2, out opcode2, out args2))
850 // Normal situation is to fall through
851 // to other if/else statements
853 if (opcode2 == instruction.OP_PUBKEY)
855 int PubKeyLen = args1.Count();
856 if (PubKeyLen < 33 || PubKeyLen > 120)
860 solutions.Add(args1);
862 else if (opcode2 == instruction.OP_PUBKEYHASH)
864 if (args1.Count() != 20) // hash160 size
868 solutions.Add(args1);
870 else if (opcode2 == instruction.OP_SMALLINTEGER)
872 // Single-byte small integer pushed onto solutions
875 byte n = (byte)DecodeOP_N(opcode1);
876 solutions.Add(new byte[] { n });
883 else if (opcode2 == instruction.OP_SMALLDATA)
885 // small pushdata, <= 80 bytes
886 if (args1.Count() > 80)
891 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
893 // Others must match exactly
900 typeRet = txnouttype.TX_NONSTANDARD;
906 /// Generation of SignatureHash. This method is responsible for removal of transaction metadata. It's necessary signature can't sign itself.
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)
915 if (nIn >= txTo.vin.Length)
917 StringBuilder sb = new StringBuilder();
918 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
919 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
922 // Init a copy of transaction
923 CTransaction txTmp = new CTransaction(txTo);
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 });
929 // Blank out other inputs' signatures
930 for (int i = 0; i < txTmp.vin.Length; i++)
932 txTmp.vin[i].scriptSig = new CScript();
934 txTmp.vin[nIn].scriptSig = script;
936 // Blank out some of the outputs
937 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
940 txTmp.vout = new CTxOut[0];
942 // Let the others update at will
943 for (int i = 0; i < txTmp.vin.Length; i++)
947 txTmp.vin[i].nSequence = 0;
951 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
953 // Only lock-in the txout payee at same index as txin
955 if (nOut >= txTmp.vout.Length)
957 StringBuilder sb = new StringBuilder();
958 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
959 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
961 Array.Resize(ref txTmp.vout, nOut + 1);
963 for (int i = 0; i < nOut; i++)
965 txTmp.vout[i] = new CTxOut();
968 // Let the others update at will
969 for (int i = 0; i < txTmp.vin.Length; i++)
973 txTmp.vin[i].nSequence = 0;
978 // Blank out other inputs completely, not recommended for open transactions
979 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
981 txTmp.vin[0] = txTmp.vin[nIn];
982 Array.Resize(ref txTmp.vin, 1);
985 // Serialize and hash
986 List<byte> b = new List<byte>();
987 b.AddRange(txTmp.Bytes);
988 b.AddRange(BitConverter.GetBytes(nHashType));
990 return Hash256.Compute256(b);
994 // Script is a stack machine (like Forth) that evaluates a predicate
995 // returning a bool indicating valid or not. There are no loops.
999 /// Script machine exception
1001 public class StackMachineException : Exception
1003 public StackMachineException()
1007 public StackMachineException(string message)
1012 public StackMachineException(string message, Exception inner)
1013 : base(message, inner)
1019 /// Remove last element from stack
1021 /// <param name="stack">Stack reference</param>
1022 static void popstack(ref List<IEnumerable<byte>> stack)
1024 int nCount = stack.Count;
1026 throw new StackMachineException("popstack() : stack empty");
1027 stack.RemoveAt(nCount - 1);
1031 /// Get element at specified stack depth
1033 /// <param name="stack">Stack reference</param>
1034 /// <param name="nDepth">Depth</param>
1035 /// <returns>Byte sequence</returns>
1036 static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
1038 int nStackElement = stack.Count + nDepth;
1042 StringBuilder sb = new StringBuilder();
1043 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
1045 throw new StackMachineException(sb.ToString());
1048 if (nStackElement < 0)
1050 StringBuilder sb = new StringBuilder();
1051 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
1053 throw new StackMachineException(sb.ToString());
1056 return stack[nStackElement];
1060 /// Cast argument to boolean value
1062 /// <param name="value">Some byte sequence</param>
1063 /// <returns></returns>
1064 private static bool CastToBool(IEnumerable<byte> arg)
1066 byte[] value = arg.ToArray();
1068 for (var i = 0; i < value.Length; i++)
1072 // Can be negative zero
1073 if (i == value.Length - 1 && value[i] == 0x80)
1086 /// Cast argument to integer value
1088 /// <param name="value"></param>
1089 /// <returns></returns>
1090 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
1092 if (value.Count() > 4)
1094 throw new StackMachineException("CastToBigInteger() : overflow");
1097 return new BigInteger(value.ToArray());
1101 /// Execution of script
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 static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
1114 ByteQueue CodeQueue = script.GetByteQUeue();
1116 List<bool> vfExec = new List<bool>();
1117 List<IEnumerable<byte>> altStack = new List<IEnumerable<byte>>();
1119 byte[] falseBytes = new byte[0];
1120 byte[] trueBytes = new byte[] { 0x01 };
1122 if (script.Bytes.Count() > 10000)
1124 return false; // Size limit failed
1128 int nCodeHashBegin = 0;
1130 IEnumerable<byte> pushArg;
1132 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
1134 bool fExec = vfExec.IndexOf(false) != -1;
1136 if (pushArg.Count() > 520)
1138 return false; // Script element size limit failed
1141 if (opcode > instruction.OP_16 && ++nOpCount > 201)
1146 if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
1148 stack.Add(pushArg); // Push argument to stack
1150 else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
1156 case instruction.OP_CAT:
1157 case instruction.OP_SUBSTR:
1158 case instruction.OP_LEFT:
1159 case instruction.OP_RIGHT:
1160 case instruction.OP_INVERT:
1161 case instruction.OP_AND:
1162 case instruction.OP_OR:
1163 case instruction.OP_XOR:
1164 case instruction.OP_2MUL:
1165 case instruction.OP_2DIV:
1166 case instruction.OP_MUL:
1167 case instruction.OP_DIV:
1168 case instruction.OP_MOD:
1169 case instruction.OP_LSHIFT:
1170 case instruction.OP_RSHIFT:
1174 // Push integer instructions
1176 case instruction.OP_1NEGATE:
1177 case instruction.OP_1:
1178 case instruction.OP_2:
1179 case instruction.OP_3:
1180 case instruction.OP_4:
1181 case instruction.OP_5:
1182 case instruction.OP_6:
1183 case instruction.OP_7:
1184 case instruction.OP_8:
1185 case instruction.OP_9:
1186 case instruction.OP_10:
1187 case instruction.OP_11:
1188 case instruction.OP_12:
1189 case instruction.OP_13:
1190 case instruction.OP_14:
1191 case instruction.OP_15:
1192 case instruction.OP_16:
1195 BigInteger bn = DecodeOP_N(opcode, true);
1196 stack.Add(bn.ToByteArray());
1203 case instruction.OP_NOP:
1204 case instruction.OP_NOP1:
1205 case instruction.OP_NOP2:
1206 case instruction.OP_NOP3:
1207 case instruction.OP_NOP4:
1208 case instruction.OP_NOP5:
1209 case instruction.OP_NOP6:
1210 case instruction.OP_NOP7:
1211 case instruction.OP_NOP8:
1212 case instruction.OP_NOP9:
1213 case instruction.OP_NOP10:
1222 case instruction.OP_IF:
1223 case instruction.OP_NOTIF:
1225 // <expression> if [statements] [else [statements]] endif
1226 bool fValue = false;
1229 if (stack.Count() < 1)
1233 IEnumerable<byte> vch = stacktop(ref stack, -1);
1234 fValue = CastToBool(vch);
1235 if (opcode == instruction.OP_NOTIF)
1239 popstack(ref stack);
1245 case instruction.OP_ELSE:
1247 int nExecCount = vfExec.Count();
1248 if (nExecCount == 0)
1252 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1256 case instruction.OP_ENDIF:
1258 int nExecCount = vfExec.Count();
1259 if (nExecCount == 0)
1263 vfExec.RemoveAt(nExecCount - 1);
1267 case instruction.OP_VERIFY:
1270 // (false -- false) and return
1271 if (stack.Count() < 1)
1276 bool fValue = CastToBool(stacktop(ref stack, -1));
1279 popstack(ref stack);
1288 case instruction.OP_RETURN:
1296 case instruction.OP_TOALTSTACK:
1298 if (stack.Count() < 1)
1302 altStack.Add(stacktop(ref stack, -1));
1303 popstack(ref stack);
1307 case instruction.OP_FROMALTSTACK:
1309 if (altStack.Count() < 1)
1313 stack.Add(stacktop(ref stack, -1));
1314 popstack(ref altStack);
1318 case instruction.OP_2DROP:
1321 if (stack.Count() < 2)
1325 popstack(ref stack);
1326 popstack(ref stack);
1330 case instruction.OP_2DUP:
1332 // (x1 x2 -- x1 x2 x1 x2)
1333 if (stack.Count() < 2)
1337 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1338 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1344 case instruction.OP_3DUP:
1346 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1347 if (stack.Count() < 3)
1351 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1352 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1353 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1360 case instruction.OP_2OVER:
1362 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1363 if (stack.Count() < 4)
1367 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1368 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1374 case instruction.OP_2ROT:
1376 int nStackDepth = stack.Count();
1377 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1378 if (nStackDepth < 6)
1382 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1383 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1384 stack.RemoveRange(nStackDepth - 6, 2);
1390 case instruction.OP_2SWAP:
1392 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1393 int nStackDepth = stack.Count();
1394 if (nStackDepth < 4)
1398 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1399 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1403 case instruction.OP_IFDUP:
1406 if (stack.Count() < 1)
1411 IEnumerable<byte> vch = stacktop(ref stack, -1);
1413 if (CastToBool(vch))
1420 case instruction.OP_DEPTH:
1423 BigInteger bn = new BigInteger((ushort)stack.Count());
1424 stack.Add(bn.ToByteArray());
1428 case instruction.OP_DROP:
1431 if (stack.Count() < 1)
1436 popstack(ref stack);
1440 case instruction.OP_DUP:
1443 if (stack.Count() < 1)
1448 IEnumerable<byte> vch = stacktop(ref stack, -1);
1453 case instruction.OP_NIP:
1456 int nStackDepth = stack.Count();
1457 if (nStackDepth < 2)
1462 stack.RemoveAt(nStackDepth - 2);
1466 case instruction.OP_OVER:
1468 // (x1 x2 -- x1 x2 x1)
1469 if (stack.Count() < 2)
1474 IEnumerable<byte> vch = stacktop(ref stack, -2);
1479 case instruction.OP_PICK:
1480 case instruction.OP_ROLL:
1482 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1483 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1485 int nStackDepth = stack.Count();
1486 if (nStackDepth < 2)
1491 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1492 popstack(ref stack);
1494 if (n < 0 || n >= stack.Count())
1499 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1500 if (opcode == instruction.OP_ROLL)
1502 stack.RemoveAt(nStackDepth - n - 1);
1509 case instruction.OP_ROT:
1511 // (x1 x2 x3 -- x2 x3 x1)
1512 // x2 x1 x3 after first swap
1513 // x2 x3 x1 after second swap
1514 int nStackDepth = stack.Count();
1515 if (nStackDepth < 3)
1519 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1520 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1525 case instruction.OP_SWAP:
1528 int nStackDepth = stack.Count();
1529 if (nStackDepth < 2)
1533 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1537 case instruction.OP_TUCK:
1539 // (x1 x2 -- x2 x1 x2)
1540 int nStackDepth = stack.Count();
1541 if (nStackDepth < 2)
1545 IEnumerable<byte> vch = stacktop(ref stack, -1);
1546 stack.Insert(nStackDepth - 2, vch);
1551 case instruction.OP_SIZE:
1554 if (stack.Count() < 1)
1559 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1560 stack.Add(bnSize.ToByteArray());
1568 case instruction.OP_EQUAL:
1569 case instruction.OP_EQUALVERIFY:
1570 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1573 if (stack.Count() < 2)
1578 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1579 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1580 bool fEqual = (vch1 == vch2);
1581 // OP_NOTEQUAL is disabled because it would be too easy to say
1582 // something like n != 1 and have some wiseguy pass in 1 with extra
1583 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1584 //if (opcode == instruction.OP_NOTEQUAL)
1585 // fEqual = !fEqual;
1586 popstack(ref stack);
1587 popstack(ref stack);
1588 stack.Add(fEqual ? trueBytes : falseBytes);
1590 if (opcode == instruction.OP_EQUALVERIFY)
1594 popstack(ref stack);
1608 case instruction.OP_1ADD:
1609 case instruction.OP_1SUB:
1610 case instruction.OP_NEGATE:
1611 case instruction.OP_ABS:
1612 case instruction.OP_NOT:
1613 case instruction.OP_0NOTEQUAL:
1616 if (stack.Count() < 1)
1621 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1624 case instruction.OP_1ADD:
1627 case instruction.OP_1SUB:
1630 case instruction.OP_NEGATE:
1633 case instruction.OP_ABS:
1634 bn = BigInteger.Abs(bn);
1636 case instruction.OP_NOT:
1637 bn = bn == 0 ? 1 : 0;
1639 case instruction.OP_0NOTEQUAL:
1640 bn = bn != 0 ? 1 : 0;
1644 popstack(ref stack);
1645 stack.Add(bn.ToByteArray());
1649 case instruction.OP_ADD:
1650 case instruction.OP_SUB:
1651 case instruction.OP_BOOLAND:
1652 case instruction.OP_BOOLOR:
1653 case instruction.OP_NUMEQUAL:
1654 case instruction.OP_NUMEQUALVERIFY:
1655 case instruction.OP_NUMNOTEQUAL:
1656 case instruction.OP_LESSTHAN:
1657 case instruction.OP_GREATERTHAN:
1658 case instruction.OP_LESSTHANOREQUAL:
1659 case instruction.OP_GREATERTHANOREQUAL:
1660 case instruction.OP_MIN:
1661 case instruction.OP_MAX:
1664 if (stack.Count() < 2)
1669 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1670 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1675 case instruction.OP_ADD:
1678 case instruction.OP_SUB:
1681 case instruction.OP_BOOLAND:
1682 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1684 case instruction.OP_BOOLOR:
1685 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1687 case instruction.OP_NUMEQUAL:
1688 bn = (bn1 == bn2) ? 1 : 0;
1690 case instruction.OP_NUMEQUALVERIFY:
1691 bn = (bn1 == bn2) ? 1 : 0;
1693 case instruction.OP_NUMNOTEQUAL:
1694 bn = (bn1 != bn2) ? 1 : 0;
1696 case instruction.OP_LESSTHAN:
1697 bn = (bn1 < bn2) ? 1 : 0;
1699 case instruction.OP_GREATERTHAN:
1700 bn = (bn1 > bn2) ? 1 : 0;
1702 case instruction.OP_LESSTHANOREQUAL:
1703 bn = (bn1 <= bn2) ? 1 : 0;
1705 case instruction.OP_GREATERTHANOREQUAL:
1706 bn = (bn1 >= bn2) ? 1 : 0;
1708 case instruction.OP_MIN:
1709 bn = (bn1 < bn2 ? bn1 : bn2);
1711 case instruction.OP_MAX:
1712 bn = (bn1 > bn2 ? bn1 : bn2);
1716 popstack(ref stack);
1717 popstack(ref stack);
1718 stack.Add(bn.ToByteArray());
1720 if (opcode == instruction.OP_NUMEQUALVERIFY)
1722 if (CastToBool(stacktop(ref stack, -1)))
1724 popstack(ref stack);
1734 case instruction.OP_WITHIN:
1736 // (x min max -- out)
1737 if (stack.Count() < 3)
1739 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1740 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1741 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1742 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1743 popstack(ref stack);
1744 popstack(ref stack);
1745 popstack(ref stack);
1746 stack.Add(fValue ? trueBytes : falseBytes);
1753 case instruction.OP_RIPEMD160:
1754 case instruction.OP_SHA1:
1755 case instruction.OP_SHA256:
1756 case instruction.OP_HASH160:
1757 case instruction.OP_HASH256:
1760 if (stack.Count() < 1)
1765 IEnumerable<byte> data = stacktop(ref stack, -1);
1769 case instruction.OP_HASH160:
1770 hash = Hash160.Compute160(data);
1772 case instruction.OP_HASH256:
1773 hash = Hash256.Compute256(data);
1775 case instruction.OP_SHA1:
1776 hash = SHA1.Compute1(data);
1778 case instruction.OP_SHA256:
1779 hash = SHA256.Compute256(data);
1781 case instruction.OP_RIPEMD160:
1782 hash = RIPEMD160.Compute160(data);
1785 popstack(ref stack);
1786 stack.Add(hash.hashBytes);
1790 case instruction.OP_CODESEPARATOR:
1792 // Hash starts after the code separator
1793 nCodeHashBegin = CodeQueue.CurrentIndex;
1797 case instruction.OP_CHECKSIG:
1798 case instruction.OP_CHECKSIGVERIFY:
1800 // (sig pubkey -- bool)
1801 if (stack.Count() < 2)
1806 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1807 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1809 // Subset of script starting at the most recent codeseparator
1810 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1812 // There's no way for a signature to sign itself
1813 scriptCode.RemovePattern(sigBytes);
1815 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1817 popstack(ref stack);
1818 popstack(ref stack);
1819 stack.Add(fSuccess ? trueBytes : falseBytes);
1820 if (opcode == instruction.OP_CHECKSIGVERIFY)
1824 popstack(ref stack);
1834 case instruction.OP_CHECKMULTISIG:
1835 case instruction.OP_CHECKMULTISIGVERIFY:
1837 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1840 if (stack.Count() < i)
1845 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1846 if (nKeysCount < 0 || nKeysCount > 20)
1850 nOpCount += nKeysCount;
1857 if (stack.Count() < i)
1862 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1863 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1869 if (stack.Count() < i)
1874 // Subset of script starting at the most recent codeseparator
1875 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1877 // There is no way for a signature to sign itself, so we need to drop the signatures
1878 for (int k = 0; k < nSigsCount; k++)
1880 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1881 scriptCode.RemovePattern(vchSig.ToList());
1884 bool fSuccess = true;
1885 while (fSuccess && nSigsCount > 0)
1887 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1888 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1891 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1901 // If there are more signatures left than keys left,
1902 // then too many signatures have failed
1903 if (nSigsCount > nKeysCount)
1911 popstack(ref stack);
1914 // A bug causes CHECKMULTISIG to consume one extra argument
1915 // whose contents were not checked in any way.
1917 // Unfortunately this is a potential source of mutability,
1918 // so optionally verify it is exactly equal to zero prior
1919 // to removing it from the stack.
1920 if (stack.Count() < 1)
1924 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1926 return false; // CHECKMULTISIG dummy argument not null
1928 popstack(ref stack);
1930 stack.Add(fSuccess ? trueBytes : falseBytes);
1932 if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1936 popstack(ref stack);
1951 if (stack.Count() + altStack.Count() > 1000)
1958 if (vfExec.Count() == 0)
1967 static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1969 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1972 if (pubKeyBytes.Count < 33)
1973 return false; // Non-canonical public key: too short
1974 if (pubKeyBytes[0] == 0x04)
1976 if (pubKeyBytes.Count != 65)
1977 return false; // Non-canonical public key: invalid length for uncompressed key
1979 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1981 if (pubKeyBytes.Count != 33)
1982 return false; // Non-canonical public key: invalid length for compressed key
1986 return false; // Non-canonical public key: compressed nor uncompressed
1991 static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1999 /// Check signature.
2001 /// <param name="sigBytes">Signature</param>
2002 /// <param name="pubkeyBytes">Public key</param>
2003 /// <param name="script">Spending script</param>
2004 /// <param name="txTo">CTransaction instance</param>
2005 /// <param name="nIn">Input number</param>
2006 /// <param name="nHashType">Hashing type flag</param>
2007 /// <param name="flags">Signature checking flags</param>
2008 /// <returns></returns>
2009 static bool CheckSig(IList<byte> sigBytes, IList<byte> pubkeyBytes, CScript script, CTransaction txTo, int nIn, int nHashType, int flags)
2015 // Trying to initialize the public key instance
2017 pubkey = new CPubKey(pubkeyBytes);
2021 // Exception occurred while initializing the public key
2026 if (!pubkey.IsValid)
2031 if (sigBytes.Count == 0)
2036 // Hash type is one byte tacked on to the end of the signature
2039 nHashType = sigBytes.Last();
2041 else if (nHashType != sigBytes.Last())
2047 sigBytes.RemoveAt(sigBytes.Count - 1);
2049 Hash256 sighash = SignatureHash(script, txTo, nIn, nHashType);
2051 if (!pubkey.VerifySignature(sighash, sigBytes))