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_PUBKEYHASH:
461 return "OP_PUBKEYHASH";
462 case instruction.OP_PUBKEY:
464 case instruction.OP_SMALLDATA:
465 return "OP_SMALLDATA";
467 case instruction.OP_INVALIDOPCODE:
468 return "OP_INVALIDOPCODE";
475 /// Get next opcode from passed list of bytes and extract push arguments if there are some.
477 /// <param name="codeBytes">ByteQueue reference.</param>
478 /// <param name="opcodeRet">Found opcode.</param>
479 /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
480 /// <returns>Result of operation</returns>
481 public static bool GetOp(ref ByteQueue codeBytes, out instruction opcodeRet, out IEnumerable<byte> bytesRet)
483 bytesRet = new List<byte>();
484 opcodeRet = instruction.OP_INVALIDOPCODE;
491 opcode = (instruction)codeBytes.Get();
493 catch (ByteQueueException)
495 // No instruction found there
500 if (opcode <= instruction.OP_PUSHDATA4)
502 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
506 if (opcode < instruction.OP_PUSHDATA1)
508 // Zero value opcodes (OP_0, OP_FALSE)
509 szBytes[3] = (byte)opcode;
511 else if (opcode == instruction.OP_PUSHDATA1)
513 // The next byte contains the number of bytes to be pushed onto the stack,
514 // i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
515 szBytes[3] = (byte)codeBytes.Get();
517 else if (opcode == instruction.OP_PUSHDATA2)
519 // The next two bytes contain the number of bytes to be pushed onto the stack,
520 // i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
521 codeBytes.Get(2).CopyTo(szBytes, 2);
523 else if (opcode == instruction.OP_PUSHDATA4)
525 // The next four bytes contain the number of bytes to be pushed onto the stack,
526 // OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
527 szBytes = codeBytes.Get(4);
530 catch (ByteQueueException)
532 // Unable to read operand length
536 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
540 // If nSize is greater than zero then there is some data available
543 // Read found number of bytes into list of OP_PUSHDATAn arguments.
544 bytesRet = codeBytes.GetEnumerable(nSize);
546 catch (ByteQueueException)
548 // Unable to read data
560 /// Convert value bytes into readable representation.
562 /// 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.
564 /// <param name="bytes">Collection of value bytes.</param>
565 /// <returns>Formatted value.</returns>
566 public static string ValueString(IEnumerable<byte> bytes)
568 StringBuilder sb = new StringBuilder();
570 if (bytes.Count() <= 4)
572 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
573 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
575 sb.Append(Interop.BEBytesToUInt32(valueBytes));
579 return Interop.ToHex(bytes);
582 return sb.ToString();
586 /// Convert list of stack items into human readable representation.
588 /// <param name="stackList">List of stack items.</param>
589 /// <returns>Formatted value.</returns>
590 public static string StackString(IList<IList<byte>> stackList)
592 StringBuilder sb = new StringBuilder();
593 foreach (IList<byte> bytesList in stackList)
595 sb.Append(ValueString(bytesList));
598 return sb.ToString();
602 /// Decode instruction to integer value
604 /// <param name="opcode">Small integer opcode (OP_1_NEGATE and OP_0 - OP_16)</param>
605 /// <returns>Small integer</returns>
606 public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
608 if (AllowNegate && opcode == instruction.OP_1NEGATE)
613 if (opcode == instruction.OP_0)
618 // Only OP_n opcodes are supported, throw exception otherwise.
619 if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
621 throw new Exception("Invalid integer instruction.");
624 return (int)opcode - (int)(instruction.OP_1 - 1);
628 /// Converts integer into instruction
630 /// <param name="n">Small integer from the range of -1 up to 16.</param>
631 /// <returns>Corresponding opcode.</returns>
632 public static instruction EncodeOP_N(int n, bool allowNegate = false)
634 if (allowNegate && n == -1)
636 return instruction.OP_1NEGATE;
641 return instruction.OP_0;
644 // The n value must be in the range of 0 to 16.
646 throw new Exception("Invalid integer value.");
647 return (instruction.OP_1 + n - 1);
650 public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
654 case txnouttype.TX_NONSTANDARD:
656 case txnouttype.TX_NULL_DATA:
658 case txnouttype.TX_PUBKEY:
660 case txnouttype.TX_PUBKEYHASH:
662 case txnouttype.TX_MULTISIG:
663 if (solutions.Count() < 1 || solutions.First().Count() < 1)
665 return solutions.First().First() + 1;
666 case txnouttype.TX_SCRIPTHASH:
667 return 1; // doesn't include args needed by the script
673 /// Is it a standart type of scriptPubKey?
675 /// <param name="scriptPubKey">CScript instance</param>
676 /// <param name="whichType">utut type</param>
677 /// <returns>Checking result</returns>
678 public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
680 IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
682 if (!Solver(scriptPubKey, out whichType, out solutions))
684 // No solutions found
688 if (whichType == txnouttype.TX_MULTISIG)
690 // Additional verification of OP_CHECKMULTISIG arguments
691 byte m = solutions.First().First();
692 byte n = solutions.Last().First();
694 // Support up to x-of-3 multisig txns as standard
705 return whichType != txnouttype.TX_NONSTANDARD;
709 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
711 /// <param name="scriptPubKey">CScript instance</param>
712 /// <param name="typeRet">Output type</param>
713 /// <param name="solutions">Set of solutions</param>
714 /// <returns>Result</returns>
715 public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<IEnumerable<byte>> solutions)
717 solutions = new List<IEnumerable<byte>>();
719 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
721 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
722 if (scriptPubKey.IsPayToScriptHash)
724 typeRet = txnouttype.TX_SCRIPTHASH;
726 // Take 20 bytes with offset of 2 bytes
727 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
728 solutions.Add(hashBytes);
733 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
734 if (scriptPubKey.IsPayToPubKeyHash)
736 typeRet = txnouttype.TX_PUBKEYHASH;
738 // Take 20 bytes with offset of 3 bytes
739 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
740 solutions.Add(hashBytes);
745 List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
747 // Sender provides pubkey, receiver adds signature
748 // [ECDSA public key] OP_CHECKSIG
750 new Tuple<txnouttype, IEnumerable<byte>>(
751 txnouttype.TX_PUBKEY,
753 (byte)instruction.OP_PUBKEY,
754 (byte)instruction.OP_CHECKSIG
758 // Sender provides N pubkeys, receivers provides M signatures
759 // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
760 // Where N and M are small integer opcodes (OP1 ... OP_16)
762 new Tuple<txnouttype, IEnumerable<byte>>(
763 txnouttype.TX_MULTISIG,
765 (byte)instruction.OP_SMALLINTEGER,
766 (byte)instruction.OP_PUBKEYS,
767 (byte)instruction.OP_SMALLINTEGER,
768 (byte)instruction.OP_CHECKMULTISIG
772 // Data-carrying output
773 // OP_RETURN [up to 80 bytes of data]
775 new Tuple<txnouttype, IEnumerable<byte>>(
776 txnouttype.TX_NULL_DATA,
778 (byte)instruction.OP_RETURN,
779 (byte)instruction.OP_SMALLDATA
783 // Nonstandard tx output
784 typeRet = txnouttype.TX_NONSTANDARD;
786 foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
788 CScript script1 = scriptPubKey;
789 CScript script2 = new CScript(templateTuple.Item2);
791 instruction opcode1, opcode2;
794 ByteQueue bq1 = script1.GetByteQUeue();
795 ByteQueue bq2 = script2.GetByteQUeue();
797 IEnumerable<byte> args1, args2;
799 byte last1 = script1.Bytes.Last();
800 byte last2 = script2.Bytes.Last();
804 if (bq1.GetCurrent() == last1 && bq2.GetCurrent() == last2)
807 typeRet = templateTuple.Item1;
808 if (typeRet == txnouttype.TX_MULTISIG)
810 // Additional checks for TX_MULTISIG:
811 byte m = solutions.First().First();
812 byte n = solutions.Last().First();
814 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
822 if (!GetOp(ref bq1, out opcode1, out args1))
826 if (!GetOp(ref bq2, out opcode2, out args2))
831 // Template matching opcodes:
832 if (opcode2 == instruction.OP_PUBKEYS)
834 while (args1.Count() >= 33 && args1.Count() <= 120)
836 solutions.Add(args1);
837 if (!GetOp(ref bq1, out opcode1, out args1))
842 if (!GetOp(ref bq2, out opcode2, out args2))
844 // Normal situation is to fall through
845 // to other if/else statements
847 if (opcode2 == instruction.OP_PUBKEY)
849 if (args1.Count() < 33 || args1.Count() > 120)
853 solutions.Add(args1);
855 else if (opcode2 == instruction.OP_PUBKEYHASH)
857 if (args1.Count() != 20) // hash160 size
861 solutions.Add(args1);
863 else if (opcode2 == instruction.OP_SMALLINTEGER)
865 // Single-byte small integer pushed onto solutions
866 if (opcode1 == instruction.OP_0 || (opcode1 >= instruction.OP_1 && opcode1 <= instruction.OP_16))
868 byte n = (byte)DecodeOP_N(opcode1);
869 solutions.Add(new byte[] { n });
876 else if (opcode2 == instruction.OP_SMALLDATA)
878 // small pushdata, <= 80 bytes
879 if (args1.Count() > 80)
884 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
886 // Others must match exactly
893 typeRet = txnouttype.TX_NONSTANDARD;
898 public static Hash256 SignatureHash(CScript scriptCode, CTransaction txTo, int nIn, int nHashType)
900 if (nIn >= txTo.vin.Length)
902 StringBuilder sb = new StringBuilder();
903 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
904 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
907 CTransaction txTmp = new CTransaction(txTo);
909 // In case concatenating two scripts ends up with two codeseparators,
910 // or an extra one at the end, this prevents all those possible incompatibilities.
911 scriptCode.RemovePattern(new byte[] { (byte)instruction.OP_CODESEPARATOR });
913 // Blank out other inputs' signatures
914 for (int i = 0; i < txTmp.vin.Length; i++)
916 txTmp.vin[i].scriptSig = new CScript();
918 txTmp.vin[nIn].scriptSig = scriptCode;
920 // Blank out some of the outputs
921 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
924 txTmp.vout = new CTxOut[0];
926 // Let the others update at will
927 for (int i = 0; i < txTmp.vin.Length; i++)
931 txTmp.vin[i].nSequence = 0;
935 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
937 // Only lock-in the txout payee at same index as txin
939 if (nOut >= txTmp.vout.Length)
941 StringBuilder sb = new StringBuilder();
942 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
943 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
945 Array.Resize(ref txTmp.vout, nOut + 1);
947 for (int i = 0; i < nOut; i++)
949 txTmp.vout[i] = new CTxOut();
952 // Let the others update at will
953 for (int i = 0; i < txTmp.vin.Length; i++)
957 txTmp.vin[i].nSequence = 0;
962 // Blank out other inputs completely, not recommended for open transactions
963 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
965 txTmp.vin[0] = txTmp.vin[nIn];
966 Array.Resize(ref txTmp.vin, 1);
969 // Serialize and hash
970 List<byte> b = new List<byte>();
971 b.AddRange(txTmp.Bytes);
972 b.AddRange(BitConverter.GetBytes(nHashType));
974 return Hash256.Compute256(b);
977 public class StackMachineException : Exception
979 public StackMachineException()
983 public StackMachineException(string message)
988 public StackMachineException(string message, Exception inner)
989 : base(message, inner)
996 // Script is a stack machine (like Forth) that evaluates a predicate
997 // returning a bool indicating valid or not. There are no loops.
1001 /// Remove last element from stack
1003 /// <param name="stack">Stack reference</param>
1004 static void popstack(ref List<IEnumerable<byte>> stack)
1006 int nCount = stack.Count;
1008 throw new StackMachineException("popstack() : stack empty");
1009 stack.RemoveAt(nCount - 1);
1013 /// Get element at specified stack depth
1015 /// <param name="stack">Stack reference</param>
1016 /// <param name="nDepth">Depth</param>
1017 /// <returns>Byte sequence</returns>
1018 static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
1020 int nStackElement = stack.Count + nDepth;
1024 StringBuilder sb = new StringBuilder();
1025 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
1027 throw new StackMachineException(sb.ToString());
1030 if (nStackElement < 0)
1032 StringBuilder sb = new StringBuilder();
1033 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
1035 throw new StackMachineException(sb.ToString());
1038 return stack[nStackElement];
1042 /// Cast argument to boolean value
1044 /// <param name="value">Some byte sequence</param>
1045 /// <returns></returns>
1046 private static bool CastToBool(IEnumerable<byte> arg)
1048 byte[] value = arg.ToArray();
1050 for (var i = 0; i < value.Length; i++)
1054 // Can be negative zero
1055 if (i == value.Length - 1 && value[i] == 0x80)
1068 /// Cast argument to integer value
1070 /// <param name="value"></param>
1071 /// <returns></returns>
1072 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
1074 if (value.Count() > 4)
1076 throw new StackMachineException("CastToBigInteger() : overflow");
1079 return new BigInteger(value.ToArray());
1082 static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
1086 ByteQueue CodeQueue = script.GetByteQUeue();
1088 List<bool> vfExec = new List<bool>();
1089 List<IEnumerable<byte>> altStack = new List<IEnumerable<byte>>();
1091 byte[] falseBytes = new byte[0];
1092 byte[] trueBytes = new byte[] { 0x01 };
1094 if (script.Bytes.Count() > 10000)
1096 return false; // Size limit failed
1100 int nCodeHashBegin = 0;
1102 IEnumerable<byte> pushArg;
1104 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
1106 bool fExec = vfExec.IndexOf(false) != -1;
1108 if (pushArg.Count() > 520)
1110 return false; // Script element size limit failed
1113 if (opcode > instruction.OP_16 && ++nOpCount > 201)
1118 if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
1120 stack.Add(pushArg); // Push argument to stack
1122 else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
1128 case instruction.OP_CAT:
1129 case instruction.OP_SUBSTR:
1130 case instruction.OP_LEFT:
1131 case instruction.OP_RIGHT:
1132 case instruction.OP_INVERT:
1133 case instruction.OP_AND:
1134 case instruction.OP_OR:
1135 case instruction.OP_XOR:
1136 case instruction.OP_2MUL:
1137 case instruction.OP_2DIV:
1138 case instruction.OP_MUL:
1139 case instruction.OP_DIV:
1140 case instruction.OP_MOD:
1141 case instruction.OP_LSHIFT:
1142 case instruction.OP_RSHIFT:
1146 // Push integer instructions
1148 case instruction.OP_1NEGATE:
1149 case instruction.OP_1:
1150 case instruction.OP_2:
1151 case instruction.OP_3:
1152 case instruction.OP_4:
1153 case instruction.OP_5:
1154 case instruction.OP_6:
1155 case instruction.OP_7:
1156 case instruction.OP_8:
1157 case instruction.OP_9:
1158 case instruction.OP_10:
1159 case instruction.OP_11:
1160 case instruction.OP_12:
1161 case instruction.OP_13:
1162 case instruction.OP_14:
1163 case instruction.OP_15:
1164 case instruction.OP_16:
1167 BigInteger bn = DecodeOP_N(opcode);
1168 stack.Add(bn.ToByteArray());
1175 case instruction.OP_NOP:
1176 case instruction.OP_NOP1:
1177 case instruction.OP_NOP2:
1178 case instruction.OP_NOP3:
1179 case instruction.OP_NOP4:
1180 case instruction.OP_NOP5:
1181 case instruction.OP_NOP6:
1182 case instruction.OP_NOP7:
1183 case instruction.OP_NOP8:
1184 case instruction.OP_NOP9:
1185 case instruction.OP_NOP10:
1194 case instruction.OP_IF:
1195 case instruction.OP_NOTIF:
1197 // <expression> if [statements] [else [statements]] endif
1198 bool fValue = false;
1201 if (stack.Count() < 1)
1205 IEnumerable<byte> vch = stacktop(ref stack, -1);
1206 fValue = CastToBool(vch);
1207 if (opcode == instruction.OP_NOTIF)
1211 popstack(ref stack);
1217 case instruction.OP_ELSE:
1219 int nExecCount = vfExec.Count();
1220 if (nExecCount == 0)
1224 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1228 case instruction.OP_ENDIF:
1230 int nExecCount = vfExec.Count();
1231 if (nExecCount == 0)
1235 vfExec.RemoveAt(nExecCount - 1);
1239 case instruction.OP_VERIFY:
1242 // (false -- false) and return
1243 if (stack.Count() < 1)
1248 bool fValue = CastToBool(stacktop(ref stack, -1));
1251 popstack(ref stack);
1260 case instruction.OP_RETURN:
1268 case instruction.OP_TOALTSTACK:
1270 if (stack.Count() < 1)
1274 altStack.Add(stacktop(ref stack, -1));
1275 popstack(ref stack);
1279 case instruction.OP_FROMALTSTACK:
1281 if (altStack.Count() < 1)
1285 stack.Add(stacktop(ref stack, -1));
1286 popstack(ref altStack);
1290 case instruction.OP_2DROP:
1293 if (stack.Count() < 2)
1297 popstack(ref stack);
1298 popstack(ref stack);
1302 case instruction.OP_2DUP:
1304 // (x1 x2 -- x1 x2 x1 x2)
1305 if (stack.Count() < 2)
1309 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1310 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1316 case instruction.OP_3DUP:
1318 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1319 if (stack.Count() < 3)
1323 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1324 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1325 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1332 case instruction.OP_2OVER:
1334 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1335 if (stack.Count() < 4)
1339 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1340 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1346 case instruction.OP_2ROT:
1348 int nStackDepth = stack.Count();
1349 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1350 if (nStackDepth < 6)
1354 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1355 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1356 stack.RemoveRange(nStackDepth - 6, 2);
1362 case instruction.OP_2SWAP:
1364 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1365 int nStackDepth = stack.Count();
1366 if (nStackDepth < 4)
1370 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1371 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1375 case instruction.OP_IFDUP:
1378 if (stack.Count() < 1)
1383 IEnumerable<byte> vch = stacktop(ref stack, -1);
1385 if (CastToBool(vch))
1392 case instruction.OP_DEPTH:
1395 BigInteger bn = new BigInteger((ushort)stack.Count());
1396 stack.Add(bn.ToByteArray());
1400 case instruction.OP_DROP:
1403 if (stack.Count() < 1)
1408 popstack(ref stack);
1412 case instruction.OP_DUP:
1415 if (stack.Count() < 1)
1420 IEnumerable<byte> vch = stacktop(ref stack, -1);
1425 case instruction.OP_NIP:
1428 int nStackDepth = stack.Count();
1429 if (nStackDepth < 2)
1434 stack.RemoveAt(nStackDepth - 2);
1438 case instruction.OP_OVER:
1440 // (x1 x2 -- x1 x2 x1)
1441 if (stack.Count() < 2)
1446 IEnumerable<byte> vch = stacktop(ref stack, -2);
1451 case instruction.OP_PICK:
1452 case instruction.OP_ROLL:
1454 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1455 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1457 int nStackDepth = stack.Count();
1458 if (nStackDepth < 2)
1463 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1464 popstack(ref stack);
1466 if (n < 0 || n >= stack.Count())
1471 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1472 if (opcode == instruction.OP_ROLL)
1474 stack.RemoveAt(nStackDepth - n - 1);
1481 case instruction.OP_ROT:
1483 // (x1 x2 x3 -- x2 x3 x1)
1484 // x2 x1 x3 after first swap
1485 // x2 x3 x1 after second swap
1486 int nStackDepth = stack.Count();
1487 if (nStackDepth < 3)
1491 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1492 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1497 case instruction.OP_SWAP:
1500 int nStackDepth = stack.Count();
1501 if (nStackDepth < 2)
1505 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1509 case instruction.OP_TUCK:
1511 // (x1 x2 -- x2 x1 x2)
1512 int nStackDepth = stack.Count();
1513 if (nStackDepth < 2)
1517 IEnumerable<byte> vch = stacktop(ref stack, -1);
1518 stack.Insert(nStackDepth - 2, vch);
1523 case instruction.OP_SIZE:
1526 if (stack.Count() < 1)
1531 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1532 stack.Add(bnSize.ToByteArray());
1540 case instruction.OP_EQUAL:
1541 case instruction.OP_EQUALVERIFY:
1542 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1545 if (stack.Count() < 2)
1550 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1551 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1552 bool fEqual = (vch1 == vch2);
1553 // OP_NOTEQUAL is disabled because it would be too easy to say
1554 // something like n != 1 and have some wiseguy pass in 1 with extra
1555 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1556 //if (opcode == instruction.OP_NOTEQUAL)
1557 // fEqual = !fEqual;
1558 popstack(ref stack);
1559 popstack(ref stack);
1560 stack.Add(fEqual ? trueBytes : falseBytes);
1562 if (opcode == instruction.OP_EQUALVERIFY)
1566 popstack(ref stack);
1580 case instruction.OP_1ADD:
1581 case instruction.OP_1SUB:
1582 case instruction.OP_NEGATE:
1583 case instruction.OP_ABS:
1584 case instruction.OP_NOT:
1585 case instruction.OP_0NOTEQUAL:
1588 if (stack.Count() < 1)
1593 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1596 case instruction.OP_1ADD:
1599 case instruction.OP_1SUB:
1602 case instruction.OP_NEGATE:
1605 case instruction.OP_ABS:
1606 bn = BigInteger.Abs(bn);
1608 case instruction.OP_NOT:
1609 bn = bn == 0 ? 1 : 0;
1611 case instruction.OP_0NOTEQUAL:
1612 bn = bn != 0 ? 1 : 0;
1616 throw new StackMachineException("invalid instruction");
1619 popstack(ref stack);
1620 stack.Add(bn.ToByteArray());
1624 case instruction.OP_ADD:
1625 case instruction.OP_SUB:
1626 case instruction.OP_BOOLAND:
1627 case instruction.OP_BOOLOR:
1628 case instruction.OP_NUMEQUAL:
1629 case instruction.OP_NUMEQUALVERIFY:
1630 case instruction.OP_NUMNOTEQUAL:
1631 case instruction.OP_LESSTHAN:
1632 case instruction.OP_GREATERTHAN:
1633 case instruction.OP_LESSTHANOREQUAL:
1634 case instruction.OP_GREATERTHANOREQUAL:
1635 case instruction.OP_MIN:
1636 case instruction.OP_MAX:
1639 if (stack.Count() < 2)
1644 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1645 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1650 case instruction.OP_ADD:
1653 case instruction.OP_SUB:
1656 case instruction.OP_BOOLAND:
1657 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1659 case instruction.OP_BOOLOR:
1660 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1662 case instruction.OP_NUMEQUAL:
1663 bn = (bn1 == bn2) ? 1 : 0;
1665 case instruction.OP_NUMEQUALVERIFY:
1666 bn = (bn1 == bn2) ? 1 : 0;
1668 case instruction.OP_NUMNOTEQUAL:
1669 bn = (bn1 != bn2) ? 1 : 0;
1671 case instruction.OP_LESSTHAN:
1672 bn = (bn1 < bn2) ? 1 : 0;
1674 case instruction.OP_GREATERTHAN:
1675 bn = (bn1 > bn2) ? 1 : 0;
1677 case instruction.OP_LESSTHANOREQUAL:
1678 bn = (bn1 <= bn2) ? 1 : 0;
1680 case instruction.OP_GREATERTHANOREQUAL:
1681 bn = (bn1 >= bn2) ? 1 : 0;
1683 case instruction.OP_MIN:
1684 bn = (bn1 < bn2 ? bn1 : bn2);
1686 case instruction.OP_MAX:
1687 bn = (bn1 > bn2 ? bn1 : bn2);
1691 throw new StackMachineException("invalid instruction");
1694 popstack(ref stack);
1695 popstack(ref stack);
1696 stack.Add(bn.ToByteArray());
1698 if (opcode == instruction.OP_NUMEQUALVERIFY)
1700 if (CastToBool(stacktop(ref stack, -1)))
1702 popstack(ref stack);
1712 case instruction.OP_WITHIN:
1714 // (x min max -- out)
1715 if (stack.Count() < 3)
1717 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1718 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1719 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1720 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1721 popstack(ref stack);
1722 popstack(ref stack);
1723 popstack(ref stack);
1724 stack.Add(fValue ? trueBytes : falseBytes);
1732 case instruction.OP_RIPEMD160:
1733 case instruction.OP_SHA1:
1734 case instruction.OP_SHA256:
1735 case instruction.OP_HASH160:
1736 case instruction.OP_HASH256:
1739 if (stack.Count() < 1)
1741 IEnumerable<byte> vch = stacktop(ref stack, -1);
1742 IEnumerable<byte> vchHash = null;
1743 if (opcode == instruction.OP_RIPEMD160)
1745 RIPEMD160 hash = RIPEMD160.Compute160(vch);
1746 vchHash = hash.hashBytes;
1748 else if (opcode == instruction.OP_SHA1)
1750 SHA1 hash = SHA1.Compute1(vch);
1751 vchHash = hash.hashBytes;
1753 else if (opcode == instruction.OP_SHA256)
1755 SHA256 hash = SHA256.Compute256(vch);
1756 vchHash = hash.hashBytes;
1758 else if (opcode == instruction.OP_HASH160)
1760 Hash160 hash = Hash160.Compute160(vch);
1761 vchHash = hash.hashBytes;
1763 else if (opcode == instruction.OP_HASH256)
1765 Hash256 hash = Hash256.Compute256(vch);
1766 vchHash = hash.hashBytes;
1768 popstack(ref stack);
1773 case instruction.OP_CODESEPARATOR:
1775 // Hash starts after the code separator
1776 nCodeHashBegin = CodeQueue.CurrentIndex;
1780 case instruction.OP_CHECKSIG:
1781 case instruction.OP_CHECKSIGVERIFY:
1783 // (sig pubkey -- bool)
1784 if (stack.Count() < 2)
1789 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1790 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1792 // Subset of script starting at the most recent codeseparator
1793 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1795 // There's no way for a signature to sign itself
1796 scriptCode.RemovePattern(sigBytes);
1798 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1800 popstack(ref stack);
1801 popstack(ref stack);
1802 stack.Add(fSuccess ? trueBytes : falseBytes);
1803 if (opcode == instruction.OP_CHECKSIGVERIFY)
1807 popstack(ref stack);
1817 case instruction.OP_CHECKMULTISIG:
1818 case instruction.OP_CHECKMULTISIGVERIFY:
1820 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1823 if (stack.Count() < i)
1828 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1829 if (nKeysCount < 0 || nKeysCount > 20)
1833 nOpCount += nKeysCount;
1840 if (stack.Count() < i)
1845 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1846 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1852 if (stack.Count() < i)
1857 // Subset of script starting at the most recent codeseparator
1858 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1860 // There is no way for a signature to sign itself, so we need to drop the signatures
1861 for (int k = 0; k < nSigsCount; k++)
1863 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1864 scriptCode.RemovePattern(vchSig.ToList());
1867 bool fSuccess = true;
1868 while (fSuccess && nSigsCount > 0)
1870 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1871 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1874 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1884 // If there are more signatures left than keys left,
1885 // then too many signatures have failed
1886 if (nSigsCount > nKeysCount)
1894 popstack(ref stack);
1897 // A bug causes CHECKMULTISIG to consume one extra argument
1898 // whose contents were not checked in any way.
1900 // Unfortunately this is a potential source of mutability,
1901 // so optionally verify it is exactly equal to zero prior
1902 // to removing it from the stack.
1903 if (stack.Count() < 1)
1907 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1909 return false; // CHECKMULTISIG dummy argument not null
1911 popstack(ref stack);
1913 stack.Add(fSuccess ? trueBytes : falseBytes);
1915 if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1919 popstack(ref stack);
1934 if (stack.Count() + altStack.Count() > 1000)
1941 if (vfExec.Count() == 0)
1950 static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1952 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1955 if (pubKeyBytes.Count() < 33)
1956 return false; // Non-canonical public key: too short
1957 if (pubKeyBytes[0] == 0x04)
1959 if (pubKeyBytes.Count() != 65)
1960 return false; // Non-canonical public key: invalid length for uncompressed key
1962 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1964 if (pubKeyBytes.Count() != 33)
1965 return false; // Non-canonical public key: invalid length for compressed key
1969 return false; // Non-canonical public key: compressed nor uncompressed
1974 static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1981 static bool CheckSig(IList<byte> vchSig, IList<byte> vchPubKey, CScript scriptCode, CTransaction txTo, int nIn, int nHashType, int flags)
1987 // Trying to initialize the public key instance
1989 pubkey = new CPubKey(vchPubKey);
1993 // Exception occurred while initializing the public key
1998 if (!pubkey.IsValid)
2003 if (vchSig.Count == 0)
2008 // Hash type is one byte tacked on to the end of the signature
2011 nHashType = vchSig.Last();
2013 else if (nHashType != vchSig.Last())
2019 vchSig.RemoveAt(vchSig.Count - 1);
2021 Hash256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType);
2023 if (!pubkey.VerifySignature(sighash, vchSig))