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)
219 if (opcode == instruction.OP_0) // OP_0 and OP_FALSE are synonyms
221 if (opcode == instruction.OP_1) // OP_1 and OP_TRUE are synonyms
224 return Enum.GetName(typeof(instruction), opcode);
228 /// Get next opcode from passed list of bytes and extract push arguments if there are some.
230 /// <param name="codeBytes">ByteQueue reference.</param>
231 /// <param name="opcodeRet">Found opcode.</param>
232 /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
233 /// <returns>Result of operation</returns>
234 public static bool GetOp(ref ByteQueue codeBytes, out instruction opcodeRet, out IEnumerable<byte> bytesRet)
236 bytesRet = new List<byte>();
237 opcodeRet = instruction.OP_INVALIDOPCODE;
244 opcode = (instruction)codeBytes.Get();
246 catch (ByteQueueException)
248 // No instruction found there
253 if (opcode <= instruction.OP_PUSHDATA4)
255 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
259 if (opcode < instruction.OP_PUSHDATA1)
261 // Zero value opcodes (OP_0, OP_FALSE)
262 szBytes[3] = (byte)opcode;
264 else if (opcode == instruction.OP_PUSHDATA1)
266 // The next byte contains the number of bytes to be pushed onto the stack,
267 // i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
268 szBytes[3] = (byte)codeBytes.Get();
270 else if (opcode == instruction.OP_PUSHDATA2)
272 // The next two bytes contain the number of bytes to be pushed onto the stack,
273 // i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
274 codeBytes.Get(2).CopyTo(szBytes, 2);
276 else if (opcode == instruction.OP_PUSHDATA4)
278 // The next four bytes contain the number of bytes to be pushed onto the stack,
279 // OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
280 szBytes = codeBytes.Get(4);
283 catch (ByteQueueException)
285 // Unable to read operand length
289 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
293 // If nSize is greater than zero then there is some data available
296 // Read found number of bytes into list of OP_PUSHDATAn arguments.
297 bytesRet = codeBytes.GetEnumerable(nSize);
299 catch (ByteQueueException)
301 // Unable to read data
313 /// Convert value bytes into readable representation.
315 /// 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.
317 /// <param name="bytes">Collection of value bytes.</param>
318 /// <returns>Formatted value.</returns>
319 public static string ValueString(IEnumerable<byte> bytes)
321 StringBuilder sb = new StringBuilder();
323 if (bytes.Count() <= 4)
325 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
326 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
328 sb.Append(Interop.BEBytesToUInt32(valueBytes));
332 return Interop.ToHex(bytes);
335 return sb.ToString();
339 /// Convert list of stack items into human readable representation.
341 /// <param name="stackList">List of stack items.</param>
342 /// <returns>Formatted value.</returns>
343 public static string StackString(IList<IList<byte>> stackList)
345 StringBuilder sb = new StringBuilder();
346 foreach (IList<byte> bytesList in stackList)
348 sb.Append(ValueString(bytesList));
351 return sb.ToString();
355 /// Decode instruction to integer value
357 /// <param name="opcode">Small integer opcode (OP_1_NEGATE and OP_0 - OP_16)</param>
358 /// <returns>Small integer</returns>
359 public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
361 if (AllowNegate && opcode == instruction.OP_1NEGATE)
366 if (opcode == instruction.OP_0)
371 // Only OP_n opcodes are supported, throw exception otherwise.
372 if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
374 throw new ArgumentException("Invalid integer instruction.");
377 return (int)opcode - (int)(instruction.OP_1 - 1);
381 /// Converts integer into instruction
383 /// <param name="n">Small integer from the range of -1 up to 16.</param>
384 /// <returns>Corresponding opcode.</returns>
385 public static instruction EncodeOP_N(int n, bool allowNegate = false)
387 if (allowNegate && n == -1)
389 return instruction.OP_1NEGATE;
394 return instruction.OP_0;
397 // The n value must be in the range of 0 to 16.
399 throw new ArgumentException("Invalid integer value.");
400 return (instruction.OP_1 + n - 1);
403 public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
407 case txnouttype.TX_NONSTANDARD:
409 case txnouttype.TX_NULL_DATA:
411 case txnouttype.TX_PUBKEY:
413 case txnouttype.TX_PUBKEYHASH:
415 case txnouttype.TX_MULTISIG:
416 if (solutions.Count() < 1 || solutions.First().Count() < 1)
418 return solutions.First().First() + 1;
419 case txnouttype.TX_SCRIPTHASH:
420 return 1; // doesn't include args needed by the script
426 /// Is it a standart type of scriptPubKey?
428 /// <param name="scriptPubKey">CScript instance</param>
429 /// <param name="whichType">utut type</param>
430 /// <returns>Checking result</returns>
431 public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
433 IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
435 if (!Solver(scriptPubKey, out whichType, out solutions))
437 // No solutions found
441 if (whichType == txnouttype.TX_MULTISIG)
443 // Additional verification of OP_CHECKMULTISIG arguments
444 byte m = solutions.First().First();
445 byte n = solutions.Last().First();
447 // Support up to x-of-3 multisig txns as standard
458 return whichType != txnouttype.TX_NONSTANDARD;
462 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
464 /// <param name="scriptPubKey">CScript instance</param>
465 /// <param name="typeRet">Output type</param>
466 /// <param name="solutions">Set of solutions</param>
467 /// <returns>Result</returns>
468 public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<IEnumerable<byte>> solutions)
470 solutions = new List<IEnumerable<byte>>();
472 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
474 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
475 if (scriptPubKey.IsPayToScriptHash)
477 typeRet = txnouttype.TX_SCRIPTHASH;
479 // Take 20 bytes with offset of 2 bytes
480 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
481 solutions.Add(hashBytes);
486 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
487 if (scriptPubKey.IsPayToPubKeyHash)
489 typeRet = txnouttype.TX_PUBKEYHASH;
491 // Take 20 bytes with offset of 3 bytes
492 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
493 solutions.Add(hashBytes);
498 List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
500 // Sender provides pubkey, receiver adds signature
501 // [ECDSA public key] OP_CHECKSIG
503 new Tuple<txnouttype, IEnumerable<byte>>(
504 txnouttype.TX_PUBKEY,
506 (byte)instruction.OP_PUBKEY,
507 (byte)instruction.OP_CHECKSIG
511 // Sender provides N pubkeys, receivers provides M signatures
512 // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
513 // Where N and M are small integer opcodes (OP1 ... OP_16)
515 new Tuple<txnouttype, IEnumerable<byte>>(
516 txnouttype.TX_MULTISIG,
518 (byte)instruction.OP_SMALLINTEGER,
519 (byte)instruction.OP_PUBKEYS,
520 (byte)instruction.OP_SMALLINTEGER,
521 (byte)instruction.OP_CHECKMULTISIG
525 // Data-carrying output
526 // OP_RETURN [up to 80 bytes of data]
528 new Tuple<txnouttype, IEnumerable<byte>>(
529 txnouttype.TX_NULL_DATA,
531 (byte)instruction.OP_RETURN,
532 (byte)instruction.OP_SMALLDATA
536 // Nonstandard tx output
537 typeRet = txnouttype.TX_NONSTANDARD;
539 foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
541 CScript script1 = scriptPubKey;
542 CScript script2 = new CScript(templateTuple.Item2);
544 instruction opcode1, opcode2;
547 ByteQueue bq1 = script1.GetByteQUeue();
548 ByteQueue bq2 = script2.GetByteQUeue();
550 IEnumerable<byte> args1, args2;
552 int last1 = script1.Bytes.Count() -1;
553 int last2 = script2.Bytes.Count() - 1;
557 if (bq1.CurrentIndex == last1 && bq2.CurrentIndex == last2)
560 typeRet = templateTuple.Item1;
561 if (typeRet == txnouttype.TX_MULTISIG)
563 // Additional checks for TX_MULTISIG:
564 byte m = solutions.First().First();
565 byte n = solutions.Last().First();
567 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
575 if (!GetOp(ref bq1, out opcode1, out args1))
579 if (!GetOp(ref bq2, out opcode2, out args2))
584 // Template matching opcodes:
585 if (opcode2 == instruction.OP_PUBKEYS)
587 while (args1.Count() >= 33 && args1.Count() <= 120)
589 solutions.Add(args1);
590 if (!GetOp(ref bq1, out opcode1, out args1))
595 if (!GetOp(ref bq2, out opcode2, out args2))
599 // Normal situation is to fall through
600 // to other if/else statements
602 if (opcode2 == instruction.OP_PUBKEY)
604 int PubKeyLen = args1.Count();
605 if (PubKeyLen < 33 || PubKeyLen > 120)
609 solutions.Add(args1);
611 else if (opcode2 == instruction.OP_PUBKEYHASH)
613 if (args1.Count() != 20) // hash160 size
617 solutions.Add(args1);
619 else if (opcode2 == instruction.OP_SMALLINTEGER)
621 // Single-byte small integer pushed onto solutions
624 byte n = (byte)DecodeOP_N(opcode1);
625 solutions.Add(new byte[] { n });
632 else if (opcode2 == instruction.OP_SMALLDATA)
634 // small pushdata, <= 80 bytes
635 if (args1.Count() > 80)
640 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
642 // Others must match exactly
649 typeRet = txnouttype.TX_NONSTANDARD;
655 /// Generation of SignatureHash. This method is responsible for removal of transaction metadata. It's necessary signature can't sign itself.
657 /// <param name="script">Spending instructions</param>
658 /// <param name="txTo">Instance of transaction</param>
659 /// <param name="nIn">Input number</param>
660 /// <param name="nHashType">Hash type flag</param>
661 /// <returns></returns>
662 public static Hash256 SignatureHash(CScript script, CTransaction txTo, int nIn, int nHashType)
664 if (nIn >= txTo.vin.Length)
666 StringBuilder sb = new StringBuilder();
667 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
668 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
671 // Init a copy of transaction
672 CTransaction txTmp = new CTransaction(txTo);
674 // In case concatenating two scripts ends up with two codeseparators,
675 // or an extra one at the end, this prevents all those possible incompatibilities.
676 script.RemovePattern(new byte[] { (byte)instruction.OP_CODESEPARATOR });
678 // Blank out other inputs' signatures
679 for (int i = 0; i < txTmp.vin.Length; i++)
681 txTmp.vin[i].scriptSig = new CScript();
683 txTmp.vin[nIn].scriptSig = script;
685 // Blank out some of the outputs
686 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
689 txTmp.vout = new CTxOut[0];
691 // Let the others update at will
692 for (int i = 0; i < txTmp.vin.Length; i++)
696 txTmp.vin[i].nSequence = 0;
700 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
702 // Only lock-in the txout payee at same index as txin
704 if (nOut >= txTmp.vout.Length)
706 StringBuilder sb = new StringBuilder();
707 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
708 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
710 Array.Resize(ref txTmp.vout, nOut + 1);
712 for (int i = 0; i < nOut; i++)
714 txTmp.vout[i] = new CTxOut();
717 // Let the others update at will
718 for (int i = 0; i < txTmp.vin.Length; i++)
722 txTmp.vin[i].nSequence = 0;
727 // Blank out other inputs completely, not recommended for open transactions
728 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
730 txTmp.vin[0] = txTmp.vin[nIn];
731 Array.Resize(ref txTmp.vin, 1);
734 // Serialize and hash
735 List<byte> b = new List<byte>();
736 b.AddRange(txTmp.Bytes);
737 b.AddRange(BitConverter.GetBytes(nHashType));
739 return Hash256.Compute256(b);
743 // Script is a stack machine (like Forth) that evaluates a predicate
744 // returning a bool indicating valid or not. There are no loops.
748 /// Script machine exception
750 public class StackMachineException : Exception
752 public StackMachineException()
756 public StackMachineException(string message)
761 public StackMachineException(string message, Exception inner)
762 : base(message, inner)
768 /// Remove last element from stack
770 /// <param name="stack">Stack reference</param>
771 private static void popstack(ref List<IEnumerable<byte>> stack)
773 int nCount = stack.Count;
775 throw new StackMachineException("popstack() : stack empty");
776 stack.RemoveAt(nCount - 1);
780 /// Get element at specified stack depth
782 /// <param name="stack">Stack reference</param>
783 /// <param name="nDepth">Depth</param>
784 /// <returns>Byte sequence</returns>
785 private static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
787 int nStackElement = stack.Count + nDepth;
791 StringBuilder sb = new StringBuilder();
792 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
794 throw new StackMachineException(sb.ToString());
797 if (nStackElement < 0)
799 StringBuilder sb = new StringBuilder();
800 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
802 throw new StackMachineException(sb.ToString());
805 return stack[nStackElement];
809 /// Cast argument to boolean value
811 /// <param name="value">Some byte sequence</param>
812 /// <returns></returns>
813 private static bool CastToBool(IEnumerable<byte> arg)
815 byte[] value = arg.ToArray();
817 for (var i = 0; i < value.Length; i++)
821 // Can be negative zero
822 if (i == value.Length - 1 && value[i] == 0x80)
835 /// Cast argument to integer value
837 /// <param name="value"></param>
838 /// <returns></returns>
839 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
841 if (value.Count() > 4)
843 throw new StackMachineException("CastToBigInteger() : overflow");
846 return new BigInteger(value.ToArray());
850 /// Execution of script
852 /// <param name="stack"></param>
853 /// <param name="script">Script to execute</param>
854 /// <param name="txTo">Transaction instance</param>
855 /// <param name="nIn">Input number</param>
856 /// <param name="flags">Signature checking flags</param>
857 /// <param name="nHashType">Hash type flag</param>
858 /// <returns></returns>
859 public static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
861 if (script.Bytes.Count() > 10000)
863 return false; // Size limit failed
866 List<bool> vfExec = new List<bool>();
869 int nCodeHashBegin = 0;
871 byte[] falseBytes = new byte[0];
872 byte[] trueBytes = new byte[] { 0x01 };
874 ByteQueue CodeQueue = script.GetByteQUeue();
875 List<IEnumerable<byte>> altStack = new List<IEnumerable<byte>>();
880 IEnumerable<byte> pushArg;
882 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
884 bool fExec = vfExec.IndexOf(false) == -1;
886 if (pushArg.Count() > 520)
888 return false; // Script element size limit failed
891 if (opcode > instruction.OP_16 && ++nOpCount > 201)
896 if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
898 stack.Add(pushArg); // Push argument to stack
900 else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
906 case instruction.OP_CAT:
907 case instruction.OP_SUBSTR:
908 case instruction.OP_LEFT:
909 case instruction.OP_RIGHT:
910 case instruction.OP_INVERT:
911 case instruction.OP_AND:
912 case instruction.OP_OR:
913 case instruction.OP_XOR:
914 case instruction.OP_2MUL:
915 case instruction.OP_2DIV:
916 case instruction.OP_MUL:
917 case instruction.OP_DIV:
918 case instruction.OP_MOD:
919 case instruction.OP_LSHIFT:
920 case instruction.OP_RSHIFT:
924 // Push integer instructions
926 case instruction.OP_1NEGATE:
927 case instruction.OP_1:
928 case instruction.OP_2:
929 case instruction.OP_3:
930 case instruction.OP_4:
931 case instruction.OP_5:
932 case instruction.OP_6:
933 case instruction.OP_7:
934 case instruction.OP_8:
935 case instruction.OP_9:
936 case instruction.OP_10:
937 case instruction.OP_11:
938 case instruction.OP_12:
939 case instruction.OP_13:
940 case instruction.OP_14:
941 case instruction.OP_15:
942 case instruction.OP_16:
945 BigInteger bn = DecodeOP_N(opcode, true);
946 stack.Add(bn.ToByteArray());
953 case instruction.OP_NOP:
954 case instruction.OP_NOP1:
955 case instruction.OP_NOP2:
956 case instruction.OP_NOP3:
957 case instruction.OP_NOP4:
958 case instruction.OP_NOP5:
959 case instruction.OP_NOP6:
960 case instruction.OP_NOP7:
961 case instruction.OP_NOP8:
962 case instruction.OP_NOP9:
963 case instruction.OP_NOP10:
972 case instruction.OP_IF:
973 case instruction.OP_NOTIF:
975 // <expression> if [statements] [else [statements]] endif
979 if (stack.Count() < 1)
983 IEnumerable<byte> vch = stacktop(ref stack, -1);
984 fValue = CastToBool(vch);
985 if (opcode == instruction.OP_NOTIF)
995 case instruction.OP_ELSE:
997 int nExecCount = vfExec.Count();
1002 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1006 case instruction.OP_ENDIF:
1008 int nExecCount = vfExec.Count();
1009 if (nExecCount == 0)
1013 vfExec.RemoveAt(nExecCount - 1);
1017 case instruction.OP_VERIFY:
1020 // (false -- false) and return
1021 if (stack.Count() < 1)
1026 bool fValue = CastToBool(stacktop(ref stack, -1));
1029 popstack(ref stack);
1038 case instruction.OP_RETURN:
1046 case instruction.OP_TOALTSTACK:
1048 if (stack.Count() < 1)
1052 altStack.Add(stacktop(ref stack, -1));
1053 popstack(ref stack);
1057 case instruction.OP_FROMALTSTACK:
1059 if (altStack.Count() < 1)
1063 stack.Add(stacktop(ref stack, -1));
1064 popstack(ref altStack);
1068 case instruction.OP_2DROP:
1071 if (stack.Count() < 2)
1075 popstack(ref stack);
1076 popstack(ref stack);
1080 case instruction.OP_2DUP:
1082 // (x1 x2 -- x1 x2 x1 x2)
1083 if (stack.Count() < 2)
1087 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1088 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1094 case instruction.OP_3DUP:
1096 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1097 if (stack.Count() < 3)
1101 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1102 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1103 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1110 case instruction.OP_2OVER:
1112 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1113 if (stack.Count() < 4)
1117 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1118 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1124 case instruction.OP_2ROT:
1126 int nStackDepth = stack.Count();
1127 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1128 if (nStackDepth < 6)
1132 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1133 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1134 stack.RemoveRange(nStackDepth - 6, 2);
1140 case instruction.OP_2SWAP:
1142 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1143 int nStackDepth = stack.Count();
1144 if (nStackDepth < 4)
1148 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1149 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1153 case instruction.OP_IFDUP:
1156 if (stack.Count() < 1)
1161 IEnumerable<byte> vch = stacktop(ref stack, -1);
1163 if (CastToBool(vch))
1170 case instruction.OP_DEPTH:
1173 BigInteger bn = new BigInteger((ushort)stack.Count());
1174 stack.Add(bn.ToByteArray());
1178 case instruction.OP_DROP:
1181 if (stack.Count() < 1)
1186 popstack(ref stack);
1190 case instruction.OP_DUP:
1193 if (stack.Count() < 1)
1198 IEnumerable<byte> vch = stacktop(ref stack, -1);
1203 case instruction.OP_NIP:
1206 int nStackDepth = stack.Count();
1207 if (nStackDepth < 2)
1212 stack.RemoveAt(nStackDepth - 2);
1216 case instruction.OP_OVER:
1218 // (x1 x2 -- x1 x2 x1)
1219 if (stack.Count() < 2)
1224 IEnumerable<byte> vch = stacktop(ref stack, -2);
1229 case instruction.OP_PICK:
1230 case instruction.OP_ROLL:
1232 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1233 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1235 int nStackDepth = stack.Count();
1236 if (nStackDepth < 2)
1241 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1242 popstack(ref stack);
1244 if (n < 0 || n >= stack.Count())
1249 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1250 if (opcode == instruction.OP_ROLL)
1252 stack.RemoveAt(nStackDepth - n - 1);
1259 case instruction.OP_ROT:
1261 // (x1 x2 x3 -- x2 x3 x1)
1262 // x2 x1 x3 after first swap
1263 // x2 x3 x1 after second swap
1264 int nStackDepth = stack.Count();
1265 if (nStackDepth < 3)
1269 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1270 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1275 case instruction.OP_SWAP:
1278 int nStackDepth = stack.Count();
1279 if (nStackDepth < 2)
1283 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1287 case instruction.OP_TUCK:
1289 // (x1 x2 -- x2 x1 x2)
1290 int nStackDepth = stack.Count();
1291 if (nStackDepth < 2)
1295 IEnumerable<byte> vch = stacktop(ref stack, -1);
1296 stack.Insert(nStackDepth - 2, vch);
1301 case instruction.OP_SIZE:
1304 if (stack.Count() < 1)
1309 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1310 stack.Add(bnSize.ToByteArray());
1318 case instruction.OP_EQUAL:
1319 case instruction.OP_EQUALVERIFY:
1320 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1323 if (stack.Count() < 2)
1328 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1329 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1330 bool fEqual = (vch1 == vch2);
1331 // OP_NOTEQUAL is disabled because it would be too easy to say
1332 // something like n != 1 and have some wiseguy pass in 1 with extra
1333 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1334 //if (opcode == instruction.OP_NOTEQUAL)
1335 // fEqual = !fEqual;
1336 popstack(ref stack);
1337 popstack(ref stack);
1338 stack.Add(fEqual ? trueBytes : falseBytes);
1340 if (opcode == instruction.OP_EQUALVERIFY)
1344 popstack(ref stack);
1358 case instruction.OP_1ADD:
1359 case instruction.OP_1SUB:
1360 case instruction.OP_NEGATE:
1361 case instruction.OP_ABS:
1362 case instruction.OP_NOT:
1363 case instruction.OP_0NOTEQUAL:
1366 if (stack.Count() < 1)
1371 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1374 case instruction.OP_1ADD:
1377 case instruction.OP_1SUB:
1380 case instruction.OP_NEGATE:
1383 case instruction.OP_ABS:
1384 bn = BigInteger.Abs(bn);
1386 case instruction.OP_NOT:
1387 bn = bn == 0 ? 1 : 0;
1389 case instruction.OP_0NOTEQUAL:
1390 bn = bn != 0 ? 1 : 0;
1394 popstack(ref stack);
1395 stack.Add(bn.ToByteArray());
1399 case instruction.OP_ADD:
1400 case instruction.OP_SUB:
1401 case instruction.OP_BOOLAND:
1402 case instruction.OP_BOOLOR:
1403 case instruction.OP_NUMEQUAL:
1404 case instruction.OP_NUMEQUALVERIFY:
1405 case instruction.OP_NUMNOTEQUAL:
1406 case instruction.OP_LESSTHAN:
1407 case instruction.OP_GREATERTHAN:
1408 case instruction.OP_LESSTHANOREQUAL:
1409 case instruction.OP_GREATERTHANOREQUAL:
1410 case instruction.OP_MIN:
1411 case instruction.OP_MAX:
1414 if (stack.Count() < 2)
1419 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1420 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1425 case instruction.OP_ADD:
1428 case instruction.OP_SUB:
1431 case instruction.OP_BOOLAND:
1432 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1434 case instruction.OP_BOOLOR:
1435 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1437 case instruction.OP_NUMEQUAL:
1438 bn = (bn1 == bn2) ? 1 : 0;
1440 case instruction.OP_NUMEQUALVERIFY:
1441 bn = (bn1 == bn2) ? 1 : 0;
1443 case instruction.OP_NUMNOTEQUAL:
1444 bn = (bn1 != bn2) ? 1 : 0;
1446 case instruction.OP_LESSTHAN:
1447 bn = (bn1 < bn2) ? 1 : 0;
1449 case instruction.OP_GREATERTHAN:
1450 bn = (bn1 > bn2) ? 1 : 0;
1452 case instruction.OP_LESSTHANOREQUAL:
1453 bn = (bn1 <= bn2) ? 1 : 0;
1455 case instruction.OP_GREATERTHANOREQUAL:
1456 bn = (bn1 >= bn2) ? 1 : 0;
1458 case instruction.OP_MIN:
1459 bn = (bn1 < bn2 ? bn1 : bn2);
1461 case instruction.OP_MAX:
1462 bn = (bn1 > bn2 ? bn1 : bn2);
1466 popstack(ref stack);
1467 popstack(ref stack);
1468 stack.Add(bn.ToByteArray());
1470 if (opcode == instruction.OP_NUMEQUALVERIFY)
1472 if (CastToBool(stacktop(ref stack, -1)))
1474 popstack(ref stack);
1484 case instruction.OP_WITHIN:
1486 // (x min max -- out)
1487 if (stack.Count() < 3)
1492 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1493 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1494 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1496 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1498 popstack(ref stack);
1499 popstack(ref stack);
1500 popstack(ref stack);
1502 stack.Add(fValue ? trueBytes : falseBytes);
1509 case instruction.OP_RIPEMD160:
1510 case instruction.OP_SHA1:
1511 case instruction.OP_SHA256:
1512 case instruction.OP_HASH160:
1513 case instruction.OP_HASH256:
1516 if (stack.Count() < 1)
1521 IEnumerable<byte> data = stacktop(ref stack, -1);
1525 case instruction.OP_HASH160:
1526 hash = Hash160.Compute160(data);
1528 case instruction.OP_HASH256:
1529 hash = Hash256.Compute256(data);
1531 case instruction.OP_SHA1:
1532 hash = SHA1.Compute1(data);
1534 case instruction.OP_SHA256:
1535 hash = SHA256.Compute256(data);
1537 case instruction.OP_RIPEMD160:
1538 hash = RIPEMD160.Compute160(data);
1541 popstack(ref stack);
1542 stack.Add(hash.hashBytes);
1546 case instruction.OP_CODESEPARATOR:
1548 // Hash starts after the code separator
1549 nCodeHashBegin = CodeQueue.CurrentIndex;
1553 case instruction.OP_CHECKSIG:
1554 case instruction.OP_CHECKSIGVERIFY:
1556 // (sig pubkey -- bool)
1557 if (stack.Count() < 2)
1562 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1563 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1565 // Subset of script starting at the most recent codeseparator
1566 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1568 // There's no way for a signature to sign itself
1569 scriptCode.RemovePattern(sigBytes);
1571 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1573 popstack(ref stack);
1574 popstack(ref stack);
1576 stack.Add(fSuccess ? trueBytes : falseBytes);
1578 if (opcode == instruction.OP_CHECKSIGVERIFY)
1582 popstack(ref stack);
1592 case instruction.OP_CHECKMULTISIG:
1593 case instruction.OP_CHECKMULTISIGVERIFY:
1595 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1598 if (stack.Count() < i)
1603 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1604 if (nKeysCount < 0 || nKeysCount > 20)
1608 nOpCount += nKeysCount;
1615 if (stack.Count() < i)
1620 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1621 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1627 if (stack.Count() < i)
1632 // Subset of script starting at the most recent codeseparator
1633 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1635 // There is no way for a signature to sign itself, so we need to drop the signatures
1636 for (int k = 0; k < nSigsCount; k++)
1638 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1639 scriptCode.RemovePattern(vchSig.ToList());
1642 bool fSuccess = true;
1643 while (fSuccess && nSigsCount > 0)
1645 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1646 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1649 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1659 // If there are more signatures left than keys left,
1660 // then too many signatures have failed
1661 if (nSigsCount > nKeysCount)
1669 popstack(ref stack);
1672 // A bug causes CHECKMULTISIG to consume one extra argument
1673 // whose contents were not checked in any way.
1675 // Unfortunately this is a potential source of mutability,
1676 // so optionally verify it is exactly equal to zero prior
1677 // to removing it from the stack.
1678 if (stack.Count() < 1)
1682 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1684 return false; // CHECKMULTISIG dummy argument not null
1686 popstack(ref stack);
1688 stack.Add(fSuccess ? trueBytes : falseBytes);
1690 if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1694 popstack(ref stack);
1709 if (stack.Count() + altStack.Count() > 1000)
1717 // If there are any exceptions then just return false.
1721 if (vfExec.Count() != 0)
1723 // Something went wrong with conditional instructions.
1731 public static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1733 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1736 if (pubKeyBytes.Count < 33)
1737 return false; // Non-canonical public key: too short
1738 if (pubKeyBytes[0] == 0x04)
1740 if (pubKeyBytes.Count != 65)
1741 return false; // Non-canonical public key: invalid length for uncompressed key
1743 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1745 if (pubKeyBytes.Count != 33)
1746 return false; // Non-canonical public key: invalid length for compressed key
1750 return false; // Non-canonical public key: compressed nor uncompressed
1755 public static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1763 /// Check signature.
1765 /// <param name="sigBytes">Signature</param>
1766 /// <param name="pubkeyBytes">Public key</param>
1767 /// <param name="script">Spending script</param>
1768 /// <param name="txTo">CTransaction instance</param>
1769 /// <param name="nIn">Input number</param>
1770 /// <param name="nHashType">Hashing type flag</param>
1771 /// <param name="flags">Signature checking flags</param>
1772 /// <returns>Checking result</returns>
1773 public static bool CheckSig(IList<byte> sigBytes, IList<byte> pubkeyBytes, CScript script, CTransaction txTo, int nIn, int nHashType, int flags)
1779 // Trying to initialize the public key instance
1781 pubkey = new CPubKey(pubkeyBytes);
1785 // Exception occurred while initializing the public key
1790 if (!pubkey.IsValid)
1795 if (sigBytes.Count == 0)
1800 // Hash type is one byte tacked on to the end of the signature
1803 nHashType = sigBytes.Last();
1805 else if (nHashType != sigBytes.Last())
1811 sigBytes.RemoveAt(sigBytes.Count - 1);
1813 Hash256 sighash = SignatureHash(script, txTo, nIn, nHashType);
1815 if (!pubkey.VerifySignature(sighash, sigBytes))
1824 /// Evaluates the both scriptSig and scriptPubKey.
1826 /// <param name="scriptSig"></param>
1827 /// <param name="scriptPubKey"></param>
1828 /// <param name="txTo">Transaction</param>
1829 /// <param name="nIn">Input number</param>
1830 /// <param name="flags">Script validation flags</param>
1831 /// <param name="nHashType">Hash type flag</param>
1832 /// <returns></returns>
1833 public static bool VerifyScript(CScript scriptSig, CScript scriptPubKey, CTransaction txTo, int nIn, int flags, int nHashType)
1835 List<IEnumerable<byte>> stack = new List<IEnumerable<byte>>();
1836 List<IEnumerable<byte>> stackCopy = null;
1838 if (!EvalScript(ref stack, scriptSig, txTo, nIn, flags, nHashType))
1843 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0)
1845 stackCopy = new List<IEnumerable<byte>> (stack);
1848 if (!EvalScript(ref stack, scriptPubKey, txTo, nIn, flags, nHashType))
1853 if (stack.Count == 0 || CastToBool(stack.Last()) == false)
1858 // Additional validation for spend-to-script-hash transactions:
1859 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0 && scriptPubKey.IsPayToScriptHash)
1861 if (!scriptSig.IsPushOnly) // scriptSig must be literals-only
1866 // stackCopy cannot be empty here, because if it was the
1867 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1868 // an empty stack and the EvalScript above would return false.
1870 if (stackCopy.Count == 0)
1872 throw new StackMachineException("Fatal script validation error.");
1875 CScript pubKey2 = new CScript(stackCopy.Last());
1876 popstack(ref stackCopy);
1878 if (!EvalScript(ref stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1880 if (stackCopy.Count == 0)
1883 return CastToBool(stackCopy.Last());