3 * This program is free software: you can redistribute it and/or modify
4 * it under the terms of the GNU Affero General Public License as
5 * published by the Free Software Foundation, either version 3 of the
6 * License, or (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU Affero General Public License for more details.
13 * You should have received a copy of the GNU Affero General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 using System.Collections.Generic;
20 using System.Numerics;
28 public enum instruction
70 OP_FROMALTSTACK = 0x6c,
102 OP_EQUALVERIFY = 0x88,
127 OP_NUMEQUALVERIFY = 0x9d,
128 OP_NUMNOTEQUAL = 0x9e,
130 OP_GREATERTHAN = 0xa0,
131 OP_LESSTHANOREQUAL = 0xa1,
132 OP_GREATERTHANOREQUAL = 0xa2,
144 OP_CODESEPARATOR = 0xab,
146 OP_CHECKSIGVERIFY = 0xad,
147 OP_CHECKMULTISIG = 0xae,
148 OP_CHECKMULTISIGVERIFY = 0xaf,
162 // template matching params
164 OP_SMALLINTEGER = 0xfa,
166 OP_PUBKEYHASH = 0xfd,
169 OP_INVALIDOPCODE = 0xff,
173 /// Transaction output types.
175 public enum txnouttype
179 // 'standard' transaction types:
188 /// Signature hash types/flags
195 SIGHASH_ANYONECANPAY = 0x80,
198 /** Script verification flags */
199 public enum scriptflag
201 SCRIPT_VERIFY_NONE = 0,
202 SCRIPT_VERIFY_P2SH = (1 << 0), // evaluate P2SH (BIP16) subscripts
203 SCRIPT_VERIFY_STRICTENC = (1 << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
204 SCRIPT_VERIFY_LOW_S = (1 << 2), // enforce low S values in signatures (depends on STRICTENC)
205 SCRIPT_VERIFY_NOCACHE = (1 << 3), // do not store results in signature cache (but do query it)
206 SCRIPT_VERIFY_NULLDUMMY = (1 << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
209 public static class ScriptCode
211 public static string GetTxnOutputType(txnouttype t)
215 case txnouttype.TX_NONSTANDARD: return "nonstandard";
216 case txnouttype.TX_PUBKEY: return "pubkey";
217 case txnouttype.TX_PUBKEYHASH: return "pubkeyhash";
218 case txnouttype.TX_SCRIPTHASH: return "scripthash";
219 case txnouttype.TX_MULTISIG: return "multisig";
220 case txnouttype.TX_NULL_DATA: return "nulldata";
226 /// Get the name of supplied opcode
228 /// <param name="opcode">Opcode</param>
229 /// <returns>Opcode name</returns>
230 public static string GetOpName(instruction opcode)
232 if (opcode == instruction.OP_0) // OP_0 and OP_FALSE are synonyms
234 if (opcode == instruction.OP_1) // OP_1 and OP_TRUE are synonyms
237 return Enum.GetName(typeof(instruction), opcode);
241 /// Get next opcode from passed list of bytes and extract push arguments if there are some.
243 /// <param name="codeBytes">ByteQueue reference.</param>
244 /// <param name="opcodeRet">Found opcode.</param>
245 /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
246 /// <returns>Result of operation</returns>
247 public static bool GetOp(ref ByteQueue codeBytes, out instruction opcodeRet, out IEnumerable<byte> bytesRet)
249 bytesRet = new List<byte>();
250 opcodeRet = instruction.OP_INVALIDOPCODE;
257 opcode = (instruction)codeBytes.Get();
259 catch (ByteQueueException)
261 // No instruction found there
266 if (opcode <= instruction.OP_PUSHDATA4)
268 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
272 if (opcode < instruction.OP_PUSHDATA1)
274 // Zero value opcodes (OP_0, OP_FALSE)
275 szBytes[3] = (byte)opcode;
277 else if (opcode == instruction.OP_PUSHDATA1)
279 // The next byte contains the number of bytes to be pushed onto the stack,
280 // i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
281 szBytes[3] = codeBytes.Get();
283 else if (opcode == instruction.OP_PUSHDATA2)
285 // The next two bytes contain the number of bytes to be pushed onto the stack,
286 // i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
287 codeBytes.Get(2).CopyTo(szBytes, 2);
289 else if (opcode == instruction.OP_PUSHDATA4)
291 // The next four bytes contain the number of bytes to be pushed onto the stack,
292 // OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
293 szBytes = codeBytes.Get(4);
296 catch (ByteQueueException)
298 // Unable to read operand length
302 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
306 // If nSize is greater than zero then there is some data available
309 // Read found number of bytes into list of OP_PUSHDATAn arguments.
310 bytesRet = codeBytes.GetEnumerable(nSize);
312 catch (ByteQueueException)
314 // Unable to read data
326 /// Convert value bytes into readable representation.
328 /// If list lengh is equal or lesser than 4 bytes then bytes are interpreted as integer value. Otherwise you will get hex representation of supplied data.
330 /// <param name="bytes">Collection of value bytes.</param>
331 /// <returns>Formatted value.</returns>
332 public static string ValueString(IEnumerable<byte> bytes)
334 StringBuilder sb = new StringBuilder();
336 if (bytes.Count() <= 4)
338 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
339 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
341 sb.Append(Interop.BEBytesToUInt32(valueBytes));
345 return Interop.ToHex(bytes);
348 return sb.ToString();
352 /// Convert list of stack items into human readable representation.
354 /// <param name="stackList">List of stack items.</param>
355 /// <returns>Formatted value.</returns>
356 public static string StackString(IList<IList<byte>> stackList)
358 StringBuilder sb = new StringBuilder();
359 foreach (IList<byte> bytesList in stackList)
361 sb.Append(ValueString(bytesList));
364 return sb.ToString();
368 /// Decode instruction to integer value
370 /// <param name="opcode">Small integer opcode (OP_1_NEGATE and OP_0 - OP_16)</param>
371 /// <returns>Small integer</returns>
372 public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
374 if (AllowNegate && opcode == instruction.OP_1NEGATE)
379 if (opcode == instruction.OP_0)
384 // Only OP_n opcodes are supported, throw exception otherwise.
385 if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
387 throw new ArgumentException("Invalid integer instruction.");
390 return (int)opcode - (int)(instruction.OP_1 - 1);
394 /// Converts integer into instruction
396 /// <param name="n">Small integer from the range of -1 up to 16.</param>
397 /// <returns>Corresponding opcode.</returns>
398 public static instruction EncodeOP_N(int n, bool allowNegate = false)
400 if (allowNegate && n == -1)
402 return instruction.OP_1NEGATE;
407 return instruction.OP_0;
410 // The n value must be in the range of 0 to 16.
412 throw new ArgumentException("Invalid integer value.");
413 return (instruction.OP_1 + n - 1);
416 public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
420 case txnouttype.TX_NONSTANDARD:
422 case txnouttype.TX_NULL_DATA:
424 case txnouttype.TX_PUBKEY:
426 case txnouttype.TX_PUBKEYHASH:
428 case txnouttype.TX_MULTISIG:
429 if (solutions.Count() < 1 || solutions.First().Count() < 1)
431 return solutions.First().First() + 1;
432 case txnouttype.TX_SCRIPTHASH:
433 return 1; // doesn't include args needed by the script
439 /// Is it a standart type of scriptPubKey?
441 /// <param name="scriptPubKey">CScript instance</param>
442 /// <param name="whichType">utut type</param>
443 /// <returns>Checking result</returns>
444 public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
446 IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
448 if (!Solver(scriptPubKey, out whichType, out solutions))
450 // No solutions found
454 if (whichType == txnouttype.TX_MULTISIG)
456 // Additional verification of OP_CHECKMULTISIG arguments
457 byte m = solutions.First().First();
458 byte n = solutions.Last().First();
460 // Support up to x-of-3 multisig txns as standard
471 return whichType != txnouttype.TX_NONSTANDARD;
475 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
477 /// <param name="scriptPubKey">CScript instance</param>
478 /// <param name="typeRet">Output type</param>
479 /// <param name="solutions">Set of solutions</param>
480 /// <returns>Result</returns>
481 public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<IEnumerable<byte>> solutions)
483 solutions = new List<IEnumerable<byte>>();
485 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
487 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
488 if (scriptPubKey.IsPayToScriptHash)
490 typeRet = txnouttype.TX_SCRIPTHASH;
492 // Take 20 bytes with offset of 2 bytes
493 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
494 solutions.Add(hashBytes);
499 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
500 if (scriptPubKey.IsPayToPubKeyHash)
502 typeRet = txnouttype.TX_PUBKEYHASH;
504 // Take 20 bytes with offset of 3 bytes
505 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
506 solutions.Add(hashBytes);
511 List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
513 // Sender provides pubkey, receiver adds signature
514 // [ECDSA public key] OP_CHECKSIG
516 new Tuple<txnouttype, IEnumerable<byte>>(
517 txnouttype.TX_PUBKEY,
519 (byte)instruction.OP_PUBKEY,
520 (byte)instruction.OP_CHECKSIG
524 // Sender provides N pubkeys, receivers provides M signatures
525 // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
526 // Where N and M are small integer opcodes (OP1 ... OP_16)
528 new Tuple<txnouttype, IEnumerable<byte>>(
529 txnouttype.TX_MULTISIG,
531 (byte)instruction.OP_SMALLINTEGER,
532 (byte)instruction.OP_PUBKEYS,
533 (byte)instruction.OP_SMALLINTEGER,
534 (byte)instruction.OP_CHECKMULTISIG
538 // Data-carrying output
539 // OP_RETURN [up to 80 bytes of data]
541 new Tuple<txnouttype, IEnumerable<byte>>(
542 txnouttype.TX_NULL_DATA,
544 (byte)instruction.OP_RETURN,
545 (byte)instruction.OP_SMALLDATA
549 // Nonstandard tx output
550 typeRet = txnouttype.TX_NONSTANDARD;
552 foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
554 CScript script1 = scriptPubKey;
555 CScript script2 = new CScript(templateTuple.Item2);
557 instruction opcode1, opcode2;
560 ByteQueue bq1 = script1.GetByteQUeue();
561 ByteQueue bq2 = script2.GetByteQUeue();
563 IEnumerable<byte> args1, args2;
565 int last1 = script1.Bytes.Count() -1;
566 int last2 = script2.Bytes.Count() - 1;
570 if (bq1.CurrentIndex == last1 && bq2.CurrentIndex == last2)
573 typeRet = templateTuple.Item1;
574 if (typeRet == txnouttype.TX_MULTISIG)
576 // Additional checks for TX_MULTISIG:
577 byte m = solutions.First().First();
578 byte n = solutions.Last().First();
580 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
588 if (!GetOp(ref bq1, out opcode1, out args1))
592 if (!GetOp(ref bq2, out opcode2, out args2))
597 // Template matching opcodes:
598 if (opcode2 == instruction.OP_PUBKEYS)
600 while (args1.Count() >= 33 && args1.Count() <= 120)
602 solutions.Add(args1);
603 if (!GetOp(ref bq1, out opcode1, out args1))
608 if (!GetOp(ref bq2, out opcode2, out args2))
612 // Normal situation is to fall through
613 // to other if/else statements
615 if (opcode2 == instruction.OP_PUBKEY)
617 int PubKeyLen = args1.Count();
618 if (PubKeyLen < 33 || PubKeyLen > 120)
622 solutions.Add(args1);
624 else if (opcode2 == instruction.OP_PUBKEYHASH)
626 if (args1.Count() != 20) // hash160 size
630 solutions.Add(args1);
632 else if (opcode2 == instruction.OP_SMALLINTEGER)
634 // Single-byte small integer pushed onto solutions
637 byte n = (byte)DecodeOP_N(opcode1);
638 solutions.Add(new byte[] { n });
645 else if (opcode2 == instruction.OP_SMALLDATA)
647 // small pushdata, <= 80 bytes
648 if (args1.Count() > 80)
653 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
655 // Others must match exactly
662 typeRet = txnouttype.TX_NONSTANDARD;
668 /// Generation of SignatureHash. This method is responsible for removal of transaction metadata. It's necessary signature can't sign itself.
670 /// <param name="script">Spending instructions</param>
671 /// <param name="txTo">Instance of transaction</param>
672 /// <param name="nIn">Input number</param>
673 /// <param name="nHashType">Hash type flag</param>
674 /// <returns></returns>
675 public static Hash256 SignatureHash(CScript script, CTransaction txTo, int nIn, int nHashType)
677 if (nIn >= txTo.vin.Length)
679 StringBuilder sb = new StringBuilder();
680 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
681 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
684 // Init a copy of transaction
685 CTransaction txTmp = new CTransaction(txTo);
687 // In case concatenating two scripts ends up with two codeseparators,
688 // or an extra one at the end, this prevents all those possible incompatibilities.
689 script.RemovePattern(new byte[] { (byte)instruction.OP_CODESEPARATOR });
691 // Blank out other inputs' signatures
692 for (int i = 0; i < txTmp.vin.Length; i++)
694 txTmp.vin[i].scriptSig = new CScript();
696 txTmp.vin[nIn].scriptSig = script;
698 // Blank out some of the outputs
699 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
702 txTmp.vout = new CTxOut[0];
704 // Let the others update at will
705 for (int i = 0; i < txTmp.vin.Length; i++)
709 txTmp.vin[i].nSequence = 0;
713 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
715 // Only lock-in the txout payee at same index as txin
717 if (nOut >= txTmp.vout.Length)
719 StringBuilder sb = new StringBuilder();
720 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
721 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
723 Array.Resize(ref txTmp.vout, nOut + 1);
725 for (int i = 0; i < nOut; i++)
727 txTmp.vout[i] = new CTxOut();
730 // Let the others update at will
731 for (int i = 0; i < txTmp.vin.Length; i++)
735 txTmp.vin[i].nSequence = 0;
740 // Blank out other inputs completely, not recommended for open transactions
741 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
743 txTmp.vin[0] = txTmp.vin[nIn];
744 Array.Resize(ref txTmp.vin, 1);
747 // Serialize and hash
748 List<byte> b = new List<byte>();
749 b.AddRange(txTmp.Bytes);
750 b.AddRange(BitConverter.GetBytes(nHashType));
752 return Hash256.Compute256(b);
756 // Script is a stack machine (like Forth) that evaluates a predicate
757 // returning a bool indicating valid or not. There are no loops.
761 /// Script machine exception
763 public class StackMachineException : Exception
765 public StackMachineException()
769 public StackMachineException(string message)
774 public StackMachineException(string message, Exception inner)
775 : base(message, inner)
781 /// Remove last element from stack
783 /// <param name="stack">Stack reference</param>
784 private static void popstack(ref List<IEnumerable<byte>> stack)
786 int nCount = stack.Count;
788 throw new StackMachineException("popstack() : stack empty");
789 stack.RemoveAt(nCount - 1);
793 /// Get element at specified stack depth
795 /// <param name="stack">Stack reference</param>
796 /// <param name="nDepth">Depth</param>
797 /// <returns>Byte sequence</returns>
798 private static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
800 int nStackElement = stack.Count + nDepth;
804 StringBuilder sb = new StringBuilder();
805 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
807 throw new StackMachineException(sb.ToString());
810 if (nStackElement < 0)
812 StringBuilder sb = new StringBuilder();
813 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
815 throw new StackMachineException(sb.ToString());
818 return stack[nStackElement];
822 /// Cast argument to boolean value
824 /// <param name="value">Some byte sequence</param>
825 /// <returns></returns>
826 private static bool CastToBool(IEnumerable<byte> arg)
828 byte[] value = arg.ToArray();
830 for (var i = 0; i < value.Length; i++)
834 // Can be negative zero
835 if (i == value.Length - 1 && value[i] == 0x80)
848 /// Cast argument to integer value
850 /// <param name="value"></param>
851 /// <returns></returns>
852 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
854 if (value.Count() > 4)
856 throw new StackMachineException("CastToBigInteger() : overflow");
859 return new BigInteger(value.ToArray());
863 /// Execution of script
865 /// <param name="stack"></param>
866 /// <param name="script">Script to execute</param>
867 /// <param name="txTo">Transaction instance</param>
868 /// <param name="nIn">Input number</param>
869 /// <param name="flags">Signature checking flags</param>
870 /// <param name="nHashType">Hash type flag</param>
871 /// <returns></returns>
872 public static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
874 if (script.Bytes.Count() > 10000)
876 return false; // Size limit failed
879 List<bool> vfExec = new List<bool>();
882 int nCodeHashBegin = 0;
884 byte[] falseBytes = new byte[0];
885 byte[] trueBytes = new byte[] { 0x01 };
887 ByteQueue CodeQueue = script.GetByteQUeue();
888 List<IEnumerable<byte>> altStack = new List<IEnumerable<byte>>();
893 IEnumerable<byte> pushArg;
895 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
897 bool fExec = vfExec.IndexOf(false) == -1;
899 if (pushArg.Count() > 520)
901 return false; // Script element size limit failed
904 if (opcode > instruction.OP_16 && ++nOpCount > 201)
909 if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
911 stack.Add(pushArg); // Push argument to stack
913 else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
919 case instruction.OP_CAT:
920 case instruction.OP_SUBSTR:
921 case instruction.OP_LEFT:
922 case instruction.OP_RIGHT:
923 case instruction.OP_INVERT:
924 case instruction.OP_AND:
925 case instruction.OP_OR:
926 case instruction.OP_XOR:
927 case instruction.OP_2MUL:
928 case instruction.OP_2DIV:
929 case instruction.OP_MUL:
930 case instruction.OP_DIV:
931 case instruction.OP_MOD:
932 case instruction.OP_LSHIFT:
933 case instruction.OP_RSHIFT:
937 // Push integer instructions
939 case instruction.OP_1NEGATE:
940 case instruction.OP_1:
941 case instruction.OP_2:
942 case instruction.OP_3:
943 case instruction.OP_4:
944 case instruction.OP_5:
945 case instruction.OP_6:
946 case instruction.OP_7:
947 case instruction.OP_8:
948 case instruction.OP_9:
949 case instruction.OP_10:
950 case instruction.OP_11:
951 case instruction.OP_12:
952 case instruction.OP_13:
953 case instruction.OP_14:
954 case instruction.OP_15:
955 case instruction.OP_16:
958 BigInteger bn = DecodeOP_N(opcode, true);
959 stack.Add(bn.ToByteArray());
966 case instruction.OP_NOP:
967 case instruction.OP_NOP1:
968 case instruction.OP_NOP2:
969 case instruction.OP_NOP3:
970 case instruction.OP_NOP4:
971 case instruction.OP_NOP5:
972 case instruction.OP_NOP6:
973 case instruction.OP_NOP7:
974 case instruction.OP_NOP8:
975 case instruction.OP_NOP9:
976 case instruction.OP_NOP10:
985 case instruction.OP_IF:
986 case instruction.OP_NOTIF:
988 // <expression> if [statements] [else [statements]] endif
992 if (stack.Count() < 1)
996 IEnumerable<byte> vch = stacktop(ref stack, -1);
997 fValue = CastToBool(vch);
998 if (opcode == instruction.OP_NOTIF)
1002 popstack(ref stack);
1008 case instruction.OP_ELSE:
1010 int nExecCount = vfExec.Count();
1011 if (nExecCount == 0)
1015 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1019 case instruction.OP_ENDIF:
1021 int nExecCount = vfExec.Count();
1022 if (nExecCount == 0)
1026 vfExec.RemoveAt(nExecCount - 1);
1030 case instruction.OP_VERIFY:
1033 // (false -- false) and return
1034 if (stack.Count() < 1)
1039 bool fValue = CastToBool(stacktop(ref stack, -1));
1042 popstack(ref stack);
1051 case instruction.OP_RETURN:
1059 case instruction.OP_TOALTSTACK:
1061 if (stack.Count() < 1)
1065 altStack.Add(stacktop(ref stack, -1));
1066 popstack(ref stack);
1070 case instruction.OP_FROMALTSTACK:
1072 if (altStack.Count() < 1)
1076 stack.Add(stacktop(ref stack, -1));
1077 popstack(ref altStack);
1081 case instruction.OP_2DROP:
1084 if (stack.Count() < 2)
1088 popstack(ref stack);
1089 popstack(ref stack);
1093 case instruction.OP_2DUP:
1095 // (x1 x2 -- x1 x2 x1 x2)
1096 if (stack.Count() < 2)
1100 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1101 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1107 case instruction.OP_3DUP:
1109 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1110 if (stack.Count() < 3)
1114 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1115 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1116 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1123 case instruction.OP_2OVER:
1125 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1126 if (stack.Count() < 4)
1130 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1131 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1137 case instruction.OP_2ROT:
1139 int nStackDepth = stack.Count();
1140 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1141 if (nStackDepth < 6)
1145 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1146 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1147 stack.RemoveRange(nStackDepth - 6, 2);
1153 case instruction.OP_2SWAP:
1155 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1156 int nStackDepth = stack.Count();
1157 if (nStackDepth < 4)
1161 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1162 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1166 case instruction.OP_IFDUP:
1169 if (stack.Count() < 1)
1174 IEnumerable<byte> vch = stacktop(ref stack, -1);
1176 if (CastToBool(vch))
1183 case instruction.OP_DEPTH:
1186 BigInteger bn = new BigInteger((ushort)stack.Count());
1187 stack.Add(bn.ToByteArray());
1191 case instruction.OP_DROP:
1194 if (stack.Count() < 1)
1199 popstack(ref stack);
1203 case instruction.OP_DUP:
1206 if (stack.Count() < 1)
1211 IEnumerable<byte> vch = stacktop(ref stack, -1);
1216 case instruction.OP_NIP:
1219 int nStackDepth = stack.Count();
1220 if (nStackDepth < 2)
1225 stack.RemoveAt(nStackDepth - 2);
1229 case instruction.OP_OVER:
1231 // (x1 x2 -- x1 x2 x1)
1232 if (stack.Count() < 2)
1237 IEnumerable<byte> vch = stacktop(ref stack, -2);
1242 case instruction.OP_PICK:
1243 case instruction.OP_ROLL:
1245 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1246 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1248 int nStackDepth = stack.Count();
1249 if (nStackDepth < 2)
1254 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1255 popstack(ref stack);
1257 if (n < 0 || n >= stack.Count())
1262 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1263 if (opcode == instruction.OP_ROLL)
1265 stack.RemoveAt(nStackDepth - n - 1);
1272 case instruction.OP_ROT:
1274 // (x1 x2 x3 -- x2 x3 x1)
1275 // x2 x1 x3 after first swap
1276 // x2 x3 x1 after second swap
1277 int nStackDepth = stack.Count();
1278 if (nStackDepth < 3)
1282 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1283 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1288 case instruction.OP_SWAP:
1291 int nStackDepth = stack.Count();
1292 if (nStackDepth < 2)
1296 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1300 case instruction.OP_TUCK:
1302 // (x1 x2 -- x2 x1 x2)
1303 int nStackDepth = stack.Count();
1304 if (nStackDepth < 2)
1308 IEnumerable<byte> vch = stacktop(ref stack, -1);
1309 stack.Insert(nStackDepth - 2, vch);
1314 case instruction.OP_SIZE:
1317 if (stack.Count() < 1)
1322 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1323 stack.Add(bnSize.ToByteArray());
1331 case instruction.OP_EQUAL:
1332 case instruction.OP_EQUALVERIFY:
1333 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1336 if (stack.Count() < 2)
1341 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1342 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1343 bool fEqual = (vch1.SequenceEqual(vch2));
1344 // OP_NOTEQUAL is disabled because it would be too easy to say
1345 // something like n != 1 and have some wiseguy pass in 1 with extra
1346 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1347 //if (opcode == instruction.OP_NOTEQUAL)
1348 // fEqual = !fEqual;
1349 popstack(ref stack);
1350 popstack(ref stack);
1351 stack.Add(fEqual ? trueBytes : falseBytes);
1353 if (opcode == instruction.OP_EQUALVERIFY)
1357 popstack(ref stack);
1371 case instruction.OP_1ADD:
1372 case instruction.OP_1SUB:
1373 case instruction.OP_NEGATE:
1374 case instruction.OP_ABS:
1375 case instruction.OP_NOT:
1376 case instruction.OP_0NOTEQUAL:
1379 if (stack.Count() < 1)
1384 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1387 case instruction.OP_1ADD:
1390 case instruction.OP_1SUB:
1393 case instruction.OP_NEGATE:
1396 case instruction.OP_ABS:
1397 bn = BigInteger.Abs(bn);
1399 case instruction.OP_NOT:
1400 bn = bn == 0 ? 1 : 0;
1402 case instruction.OP_0NOTEQUAL:
1403 bn = bn != 0 ? 1 : 0;
1407 popstack(ref stack);
1408 stack.Add(bn.ToByteArray());
1412 case instruction.OP_ADD:
1413 case instruction.OP_SUB:
1414 case instruction.OP_BOOLAND:
1415 case instruction.OP_BOOLOR:
1416 case instruction.OP_NUMEQUAL:
1417 case instruction.OP_NUMEQUALVERIFY:
1418 case instruction.OP_NUMNOTEQUAL:
1419 case instruction.OP_LESSTHAN:
1420 case instruction.OP_GREATERTHAN:
1421 case instruction.OP_LESSTHANOREQUAL:
1422 case instruction.OP_GREATERTHANOREQUAL:
1423 case instruction.OP_MIN:
1424 case instruction.OP_MAX:
1427 if (stack.Count() < 2)
1432 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1433 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1438 case instruction.OP_ADD:
1441 case instruction.OP_SUB:
1444 case instruction.OP_BOOLAND:
1445 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1447 case instruction.OP_BOOLOR:
1448 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1450 case instruction.OP_NUMEQUAL:
1451 bn = (bn1 == bn2) ? 1 : 0;
1453 case instruction.OP_NUMEQUALVERIFY:
1454 bn = (bn1 == bn2) ? 1 : 0;
1456 case instruction.OP_NUMNOTEQUAL:
1457 bn = (bn1 != bn2) ? 1 : 0;
1459 case instruction.OP_LESSTHAN:
1460 bn = (bn1 < bn2) ? 1 : 0;
1462 case instruction.OP_GREATERTHAN:
1463 bn = (bn1 > bn2) ? 1 : 0;
1465 case instruction.OP_LESSTHANOREQUAL:
1466 bn = (bn1 <= bn2) ? 1 : 0;
1468 case instruction.OP_GREATERTHANOREQUAL:
1469 bn = (bn1 >= bn2) ? 1 : 0;
1471 case instruction.OP_MIN:
1472 bn = (bn1 < bn2 ? bn1 : bn2);
1474 case instruction.OP_MAX:
1475 bn = (bn1 > bn2 ? bn1 : bn2);
1479 popstack(ref stack);
1480 popstack(ref stack);
1481 stack.Add(bn.ToByteArray());
1483 if (opcode == instruction.OP_NUMEQUALVERIFY)
1485 if (CastToBool(stacktop(ref stack, -1)))
1487 popstack(ref stack);
1497 case instruction.OP_WITHIN:
1499 // (x min max -- out)
1500 if (stack.Count() < 3)
1505 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1506 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1507 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1509 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1511 popstack(ref stack);
1512 popstack(ref stack);
1513 popstack(ref stack);
1515 stack.Add(fValue ? trueBytes : falseBytes);
1522 case instruction.OP_RIPEMD160:
1523 case instruction.OP_SHA1:
1524 case instruction.OP_SHA256:
1525 case instruction.OP_HASH160:
1526 case instruction.OP_HASH256:
1529 if (stack.Count() < 1)
1534 IEnumerable<byte> data = stacktop(ref stack, -1);
1538 case instruction.OP_HASH160:
1539 hash = Hash160.Compute160(data);
1541 case instruction.OP_HASH256:
1542 hash = Hash256.Compute256(data);
1544 case instruction.OP_SHA1:
1545 hash = SHA1.Compute1(data);
1547 case instruction.OP_SHA256:
1548 hash = SHA256.Compute256(data);
1550 case instruction.OP_RIPEMD160:
1551 hash = RIPEMD160.Compute160(data);
1554 popstack(ref stack);
1555 stack.Add(hash.hashBytes);
1559 case instruction.OP_CODESEPARATOR:
1561 // Hash starts after the code separator
1562 nCodeHashBegin = CodeQueue.CurrentIndex;
1566 case instruction.OP_CHECKSIG:
1567 case instruction.OP_CHECKSIGVERIFY:
1569 // (sig pubkey -- bool)
1570 if (stack.Count() < 2)
1575 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1576 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1578 // Subset of script starting at the most recent codeseparator
1579 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1581 // There's no way for a signature to sign itself
1582 scriptCode.RemovePattern(sigBytes);
1584 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1586 popstack(ref stack);
1587 popstack(ref stack);
1589 stack.Add(fSuccess ? trueBytes : falseBytes);
1591 if (opcode == instruction.OP_CHECKSIGVERIFY)
1595 popstack(ref stack);
1605 case instruction.OP_CHECKMULTISIG:
1606 case instruction.OP_CHECKMULTISIGVERIFY:
1608 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1611 if (stack.Count() < i)
1616 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1617 if (nKeysCount < 0 || nKeysCount > 20)
1621 nOpCount += nKeysCount;
1628 if (stack.Count() < i)
1633 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1634 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1640 if (stack.Count() < i)
1645 // Subset of script starting at the most recent codeseparator
1646 CScript scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin));
1648 // There is no way for a signature to sign itself, so we need to drop the signatures
1649 for (int k = 0; k < nSigsCount; k++)
1651 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1652 scriptCode.RemovePattern(vchSig.ToList());
1655 bool fSuccess = true;
1656 while (fSuccess && nSigsCount > 0)
1658 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1659 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1662 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1672 // If there are more signatures left than keys left,
1673 // then too many signatures have failed
1674 if (nSigsCount > nKeysCount)
1682 popstack(ref stack);
1685 // A bug causes CHECKMULTISIG to consume one extra argument
1686 // whose contents were not checked in any way.
1688 // Unfortunately this is a potential source of mutability,
1689 // so optionally verify it is exactly equal to zero prior
1690 // to removing it from the stack.
1691 if (stack.Count() < 1)
1695 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1697 return false; // CHECKMULTISIG dummy argument not null
1699 popstack(ref stack);
1701 stack.Add(fSuccess ? trueBytes : falseBytes);
1703 if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1707 popstack(ref stack);
1722 if (stack.Count() + altStack.Count() > 1000)
1730 // If there are any exceptions then just return false.
1734 if (vfExec.Count() != 0)
1736 // Something went wrong with conditional instructions.
1744 public static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1746 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1749 if (pubKeyBytes.Count < 33)
1750 return false; // Non-canonical public key: too short
1751 if (pubKeyBytes[0] == 0x04)
1753 if (pubKeyBytes.Count != 65)
1754 return false; // Non-canonical public key: invalid length for uncompressed key
1756 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1758 if (pubKeyBytes.Count != 33)
1759 return false; // Non-canonical public key: invalid length for compressed key
1763 return false; // Non-canonical public key: compressed nor uncompressed
1768 public static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1776 /// Check signature.
1778 /// <param name="sigBytes">Signature</param>
1779 /// <param name="pubkeyBytes">Public key</param>
1780 /// <param name="script">Spending script</param>
1781 /// <param name="txTo">CTransaction instance</param>
1782 /// <param name="nIn">Input number</param>
1783 /// <param name="nHashType">Hashing type flag</param>
1784 /// <param name="flags">Signature checking flags</param>
1785 /// <returns>Checking result</returns>
1786 public static bool CheckSig(IList<byte> sigBytes, IList<byte> pubkeyBytes, CScript script, CTransaction txTo, int nIn, int nHashType, int flags)
1792 // Trying to initialize the public key instance
1794 pubkey = new CPubKey(pubkeyBytes);
1798 // Exception occurred while initializing the public key
1803 if (!pubkey.IsValid)
1808 if (sigBytes.Count == 0)
1813 // Hash type is one byte tacked on to the end of the signature
1816 nHashType = sigBytes.Last();
1818 else if (nHashType != sigBytes.Last())
1824 sigBytes.RemoveAt(sigBytes.Count - 1);
1826 Hash256 sighash = SignatureHash(script, txTo, nIn, nHashType);
1828 if (!pubkey.VerifySignature(sighash, sigBytes))
1837 /// Evaluates the both scriptSig and scriptPubKey.
1839 /// <param name="scriptSig"></param>
1840 /// <param name="scriptPubKey"></param>
1841 /// <param name="txTo">Transaction</param>
1842 /// <param name="nIn">Input number</param>
1843 /// <param name="flags">Script validation flags</param>
1844 /// <param name="nHashType">Hash type flag</param>
1845 /// <returns></returns>
1846 public static bool VerifyScript(CScript scriptSig, CScript scriptPubKey, CTransaction txTo, int nIn, int flags, int nHashType)
1848 List<IEnumerable<byte>> stack = new List<IEnumerable<byte>>();
1849 List<IEnumerable<byte>> stackCopy = null;
1851 if (!EvalScript(ref stack, scriptSig, txTo, nIn, flags, nHashType))
1856 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0)
1858 stackCopy = new List<IEnumerable<byte>> (stack);
1861 if (!EvalScript(ref stack, scriptPubKey, txTo, nIn, flags, nHashType))
1866 if (stack.Count == 0 || CastToBool(stack.Last()) == false)
1871 // Additional validation for spend-to-script-hash transactions:
1872 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0 && scriptPubKey.IsPayToScriptHash)
1874 if (!scriptSig.IsPushOnly) // scriptSig must be literals-only
1879 // stackCopy cannot be empty here, because if it was the
1880 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1881 // an empty stack and the EvalScript above would return false.
1883 if (stackCopy.Count == 0)
1885 throw new StackMachineException("Fatal script validation error.");
1888 CScript pubKey2 = new CScript(stackCopy.Last());
1889 popstack(ref stackCopy);
1891 if (!EvalScript(ref stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1893 if (stackCopy.Count == 0)
1896 return CastToBool(stackCopy.Last());