2 * Novacoin classes library
3 * Copyright (C) 2015 Alex D. (balthazar.ad@gmail.com)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU Affero General Public License for more details.
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 using System.Collections.Generic;
22 using System.Numerics;
28 /// Script instructions
30 public enum instruction
72 OP_FROMALTSTACK = 0x6c,
104 OP_EQUALVERIFY = 0x88,
129 OP_NUMEQUALVERIFY = 0x9d,
130 OP_NUMNOTEQUAL = 0x9e,
132 OP_GREATERTHAN = 0xa0,
133 OP_LESSTHANOREQUAL = 0xa1,
134 OP_GREATERTHANOREQUAL = 0xa2,
146 OP_CODESEPARATOR = 0xab,
148 OP_CHECKSIGVERIFY = 0xad,
149 OP_CHECKMULTISIG = 0xae,
150 OP_CHECKMULTISIGVERIFY = 0xaf,
164 // template matching params
166 OP_SMALLINTEGER = 0xfa,
168 OP_PUBKEYHASH = 0xfd,
171 OP_INVALIDOPCODE = 0xff,
175 /// Transaction output types.
177 public enum txnouttype
181 // 'standard' transaction types:
190 /// Signature hash types/flags
197 SIGHASH_ANYONECANPAY = 0x80,
200 /** Script verification flags */
201 public enum scriptflag
203 SCRIPT_VERIFY_NONE = 0,
204 SCRIPT_VERIFY_P2SH = (1 << 0), // evaluate P2SH (BIP16) subscripts
205 SCRIPT_VERIFY_STRICTENC = (1 << 1), // enforce strict conformance to DER and SEC2 for signatures and pubkeys
206 SCRIPT_VERIFY_LOW_S = (1 << 2), // enforce low S values in signatures (depends on STRICTENC)
207 SCRIPT_VERIFY_NOCACHE = (1 << 3), // do not store results in signature cache (but do query it)
208 SCRIPT_VERIFY_NULLDUMMY = (1 << 4), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length
211 public static class ScriptCode
213 public static string GetTxnOutputType(txnouttype t)
217 case txnouttype.TX_NONSTANDARD: return "nonstandard";
218 case txnouttype.TX_PUBKEY: return "pubkey";
219 case txnouttype.TX_PUBKEYHASH: return "pubkeyhash";
220 case txnouttype.TX_SCRIPTHASH: return "scripthash";
221 case txnouttype.TX_MULTISIG: return "multisig";
222 case txnouttype.TX_NULL_DATA: return "nulldata";
228 /// Get the name of instruction
230 /// <param name="opcode">Instruction</param>
231 /// <returns>Instruction name</returns>
232 public static string GetOpName(instruction opcode)
234 if (opcode == instruction.OP_0) // OP_0 and OP_FALSE are synonyms
236 if (opcode == instruction.OP_1) // OP_1 and OP_TRUE are synonyms
239 return Enum.GetName(typeof(instruction), opcode);
243 /// Get next instruction from list of bytes and extract push arguments if there are some.
245 /// <param name="codeBytes">ByteQueue reference.</param>
246 /// <param name="opcodeRet">Found instruction.</param>
247 /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
248 /// <returns>Result of operation</returns>
249 public static bool GetOp(ref ByteQueue codeBytes, out instruction opcodeRet, out byte[] bytesRet)
251 bytesRet = new byte[0];
252 opcodeRet = instruction.OP_INVALIDOPCODE;
259 opcode = (instruction)codeBytes.Get();
261 catch (ByteQueueException)
263 // No instruction found there
268 if (opcode <= instruction.OP_PUSHDATA4)
270 var szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
274 if (opcode < instruction.OP_PUSHDATA1)
276 // Zero value instructions (OP_0, OP_FALSE)
277 szBytes[3] = (byte)opcode;
279 else if (opcode == instruction.OP_PUSHDATA1)
281 // The next byte contains the number of bytes to be pushed onto the stack,
282 // i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
283 szBytes[3] = codeBytes.Get();
285 else if (opcode == instruction.OP_PUSHDATA2)
287 // The next two bytes contain the number of bytes to be pushed onto the stack,
288 // i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
289 codeBytes.Get(2).CopyTo(szBytes, 2);
291 else if (opcode == instruction.OP_PUSHDATA4)
293 // The next four bytes contain the number of bytes to be pushed onto the stack,
294 // OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
295 szBytes = codeBytes.Get(4);
298 catch (ByteQueueException)
300 // Unable to read operand length
304 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
308 // If nSize is greater than zero then there is some data available
311 // Read found number of bytes into list of OP_PUSHDATAn arguments.
312 bytesRet = codeBytes.Get(nSize);
314 catch (ByteQueueException)
316 // Unable to read data
328 /// Convert value bytes into readable representation.
330 /// 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.
332 /// <param name="bytes">Collection of value bytes.</param>
333 /// <returns>Formatted value.</returns>
334 public static string ValueString(byte[] bytes)
336 var sb = new StringBuilder();
338 if (bytes.Length <= 4)
340 sb.Append(Interop.BEBytesToUInt32(bytes));
344 return Interop.ToHex(bytes);
347 return sb.ToString();
351 /// Convert list of stack items into human readable representation.
353 /// <param name="stackList">List of stack items.</param>
354 /// <returns>Formatted value.</returns>
355 public static string StackString(IList<byte[]> stackList)
357 var sb = new StringBuilder();
358 foreach (var bytes in stackList)
360 sb.Append(ValueString(bytes));
363 return sb.ToString();
367 /// Decode instruction to integer value
369 /// <param name="opcode">Small integer instruction (OP_1_NEGATE and OP_0 - OP_16)</param>
370 /// <returns>Small integer</returns>
371 public static int DecodeOP_N(instruction opcode, bool AllowNegate = false)
373 if (AllowNegate && opcode == instruction.OP_1NEGATE)
378 if (opcode == instruction.OP_0)
383 // Only OP_n instructions are supported, throw exception otherwise.
384 if (opcode < instruction.OP_1 || opcode > instruction.OP_16)
386 throw new ArgumentException("Invalid integer instruction.");
389 return (int)opcode - (int)(instruction.OP_1 - 1);
393 /// Converts integer into instruction
395 /// <param name="n">Small integer from the range of -1 up to 16.</param>
396 /// <returns>Corresponding instruction.</returns>
397 public static instruction EncodeOP_N(int n, bool allowNegate = false)
399 if (allowNegate && n == -1)
401 return instruction.OP_1NEGATE;
406 return instruction.OP_0;
409 // The n value must be in the range of 0 to 16.
411 throw new ArgumentException("Invalid integer value.");
412 return (instruction.OP_1 + n - 1);
415 public static int ScriptSigArgsExpected(txnouttype t, IList<byte[]> solutions)
419 case txnouttype.TX_NONSTANDARD:
421 case txnouttype.TX_NULL_DATA:
423 case txnouttype.TX_PUBKEY:
425 case txnouttype.TX_PUBKEYHASH:
427 case txnouttype.TX_MULTISIG:
428 if (solutions.Count < 1 || solutions.First().Length < 1)
430 return solutions.First()[0] + 1;
431 case txnouttype.TX_SCRIPTHASH:
432 return 1; // doesn't include args needed by the script
438 /// Is it a standart type of scriptPubKey?
440 /// <param name="scriptPubKey">CScript instance</param>
441 /// <param name="whichType">utut type</param>
442 /// <returns>Checking result</returns>
443 public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
445 IList<byte[]> solutions;
447 if (!Solver(scriptPubKey, out whichType, out solutions))
449 // No solutions found
453 if (whichType == txnouttype.TX_MULTISIG)
455 // Additional verification of OP_CHECKMULTISIG arguments
456 var m = solutions.First()[0];
457 var n = solutions.Last()[0];
459 // Support up to x-of-3 multisig txns as standard
470 return whichType != txnouttype.TX_NONSTANDARD;
474 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
476 /// <param name="scriptPubKey">CScript instance</param>
477 /// <param name="typeRet">Output type</param>
478 /// <param name="solutions">Set of solutions</param>
479 /// <returns>Result</returns>
480 public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<byte[]> solutions)
482 solutions = new List<byte[]>();
484 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types.
486 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
487 if (scriptPubKey.IsPayToScriptHash)
489 typeRet = txnouttype.TX_SCRIPTHASH;
491 // Take 20 bytes with offset of 2 bytes
492 var hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
493 solutions.Add(hashBytes.ToArray());
498 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
499 if (scriptPubKey.IsPayToPubKeyHash)
501 typeRet = txnouttype.TX_PUBKEYHASH;
503 // Take 20 bytes with offset of 3 bytes
504 var hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
505 solutions.Add(hashBytes.ToArray());
510 var templateTuples = new List<Tuple<txnouttype, byte[]>>();
512 // Sender provides pubkey, receiver adds signature
513 // [ECDSA public key] OP_CHECKSIG
515 new Tuple<txnouttype, byte[]>(
516 txnouttype.TX_PUBKEY,
518 (byte)instruction.OP_PUBKEY,
519 (byte)instruction.OP_CHECKSIG
523 // Sender provides N pubkeys, receivers provides M signatures
524 // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
525 // Where N and M are small integer instructions (OP1 ... OP_16)
527 new Tuple<txnouttype, byte[]>(
528 txnouttype.TX_MULTISIG,
530 (byte)instruction.OP_SMALLINTEGER,
531 (byte)instruction.OP_PUBKEYS,
532 (byte)instruction.OP_SMALLINTEGER,
533 (byte)instruction.OP_CHECKMULTISIG
537 // Data-carrying output
538 // OP_RETURN [up to 80 bytes of data]
540 new Tuple<txnouttype, byte[]>(
541 txnouttype.TX_NULL_DATA,
543 (byte)instruction.OP_RETURN,
544 (byte)instruction.OP_SMALLDATA
548 // Nonstandard tx output
549 typeRet = txnouttype.TX_NONSTANDARD;
551 foreach (var templateTuple in templateTuples)
553 var script1 = scriptPubKey;
554 var script2 = new CScript(templateTuple.Item2);
556 instruction opcode1, opcode2;
559 var bq1 = script1.GetByteQUeue();
560 var bq2 = script2.GetByteQUeue();
564 int last1 = script1.Bytes.Count() -1;
565 int last2 = script2.Bytes.Count() - 1;
569 if (bq1.CurrentIndex == last1 && bq2.CurrentIndex == last2)
572 typeRet = templateTuple.Item1;
573 if (typeRet == txnouttype.TX_MULTISIG)
575 // Additional checks for TX_MULTISIG:
576 var m = solutions.First().First();
577 var n = solutions.Last().First();
579 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
587 if (!GetOp(ref bq1, out opcode1, out args1))
591 if (!GetOp(ref bq2, out opcode2, out args2))
596 // Template matching instructions:
597 if (opcode2 == instruction.OP_PUBKEYS)
599 while (args1.Count() >= 33 && args1.Count() <= 120)
601 solutions.Add(args1);
602 if (!GetOp(ref bq1, out opcode1, out args1))
607 if (!GetOp(ref bq2, out opcode2, out args2))
611 // Normal situation is to fall through
612 // to other if/else statements
614 if (opcode2 == instruction.OP_PUBKEY)
616 int PubKeyLen = args1.Count();
617 if (PubKeyLen < 33 || PubKeyLen > 120)
621 solutions.Add(args1);
623 else if (opcode2 == instruction.OP_PUBKEYHASH)
625 if (args1.Count() != 20) // hash160 size
629 solutions.Add(args1);
631 else if (opcode2 == instruction.OP_SMALLINTEGER)
633 // Single-byte small integer pushed onto solutions
636 var n = (byte)DecodeOP_N(opcode1);
637 solutions.Add(new byte[] { n });
644 else if (opcode2 == instruction.OP_SMALLDATA)
646 // small pushdata, <= 80 bytes
647 if (args1.Length > 80)
652 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
654 // Others must match exactly
661 typeRet = txnouttype.TX_NONSTANDARD;
667 /// Generation of SignatureHash. This method is responsible for removal of transaction metadata. It's necessary signature can't sign itself.
669 /// <param name="script">Spending instructions</param>
670 /// <param name="txTo">Instance of transaction</param>
671 /// <param name="nIn">Input number</param>
672 /// <param name="nHashType">Hash type flag</param>
673 /// <returns></returns>
674 public static Hash256 SignatureHash(CScript script, CTransaction txTo, int nIn, int nHashType)
676 if (nIn >= txTo.vin.Length)
678 var sb = new StringBuilder();
679 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
680 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
683 // Init a copy of transaction
684 var txTmp = new CTransaction(txTo);
686 // In case concatenating two scripts ends up with two codeseparators,
687 // or an extra one at the end, this prevents all those possible incompatibilities.
688 script.RemoveInstruction(instruction.OP_CODESEPARATOR);
690 // Blank out other inputs' signatures
691 for (int i = 0; i < txTmp.vin.Length; i++)
693 txTmp.vin[i].scriptSig = new CScript();
695 txTmp.vin[nIn].scriptSig = script;
697 // Blank out some of the outputs
698 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
701 txTmp.vout = new CTxOut[0];
703 // Let the others update at will
704 for (int i = 0; i < txTmp.vin.Length; i++)
708 txTmp.vin[i].nSequence = 0;
712 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
714 // Only lock-in the txout payee at same index as txin
716 if (nOut >= txTmp.vout.Length)
718 StringBuilder sb = new StringBuilder();
719 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
720 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
722 Array.Resize(ref txTmp.vout, nOut + 1);
724 for (int i = 0; i < nOut; i++)
726 txTmp.vout[i] = new CTxOut();
729 // Let the others update at will
730 for (int i = 0; i < txTmp.vin.Length; i++)
734 txTmp.vin[i].nSequence = 0;
739 // Blank out other inputs completely, not recommended for open transactions
740 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
742 txTmp.vin[0] = txTmp.vin[nIn];
743 Array.Resize(ref txTmp.vin, 1);
746 // Concatenate and hash
747 var txBytes = txTmp.Bytes;
748 var nHashTypeBytes = BitConverter.GetBytes(nHashType);
750 return Hash256.Compute256(ref txBytes, ref nHashTypeBytes);
754 // Script is a stack machine (like Forth) that evaluates a predicate
755 // returning a bool indicating valid or not. There are no loops.
759 /// Script machine exception
761 public class StackMachineException : Exception
763 public StackMachineException()
767 public StackMachineException(string message)
772 public StackMachineException(string message, Exception inner)
773 : base(message, inner)
779 /// Remove last element from stack
781 /// <param name="stack">Stack reference</param>
782 private static void popstack(ref List<byte[]> stack)
784 int nCount = stack.Count;
786 throw new StackMachineException("popstack() : stack empty");
787 stack.RemoveAt(nCount - 1);
791 /// Get element at specified stack depth
793 /// <param name="stack">Stack reference</param>
794 /// <param name="nDepth">Depth</param>
795 /// <returns>Byte sequence</returns>
796 private static byte[] stacktop(ref List<byte[]> stack, int nDepth)
798 int nStackElement = stack.Count + nDepth;
802 StringBuilder sb = new StringBuilder();
803 sb.AppendFormat("stacktop() : positive depth ({0}) has no sense.", nDepth);
805 throw new StackMachineException(sb.ToString());
808 if (nStackElement < 0)
810 StringBuilder sb = new StringBuilder();
811 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth ({1})", nDepth, stack.Count);
813 throw new StackMachineException(sb.ToString());
816 return stack[nStackElement];
820 /// Cast argument to boolean value
822 /// <param name="value">Some byte sequence</param>
823 /// <returns></returns>
824 private static bool CastToBool(byte[] arg)
826 for (var i = 0; i < arg.Length; i++)
830 // Can be negative zero
831 if (i == arg.Length - 1 && arg[i] == 0x80)
844 /// Cast argument to integer value
846 /// <param name="value"></param>
847 /// <returns></returns>
848 private static BigInteger CastToBigInteger(byte[] value)
850 if (value.Length > 4)
852 throw new StackMachineException("CastToBigInteger() : overflow");
855 return new BigInteger(value);
859 /// Execution of script
861 /// <param name="stack"></param>
862 /// <param name="script">Script to execute</param>
863 /// <param name="txTo">Transaction instance</param>
864 /// <param name="nIn">Input number</param>
865 /// <param name="flags">Signature checking flags</param>
866 /// <param name="nHashType">Hash type flag</param>
867 /// <returns></returns>
868 public static bool EvalScript(ref List<byte[]> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
870 if (script.Bytes.Count() > 10000)
872 return false; // Size limit failed
875 var vfExec = new List<bool>();
878 int nCodeHashBegin = 0;
880 var falseBytes = new byte[0];
881 var trueBytes = new byte[] { 0x01 };
883 var CodeQueue = script.GetByteQUeue();
884 var altStack = new List<byte[]>();
891 while (GetOp(ref CodeQueue, out opcode, out pushArg)) // Read instructions
893 bool fExec = vfExec.IndexOf(false) == -1;
895 if (pushArg.Length > 520)
897 return false; // Script element size limit failed
900 if (opcode > instruction.OP_16 && ++nOpCount > 201)
905 if (fExec && 0 <= opcode && opcode <= instruction.OP_PUSHDATA4)
907 stack.Add(pushArg); // Push argument to stack
909 else if (fExec || (instruction.OP_IF <= opcode && opcode <= instruction.OP_ENDIF))
913 // Disabled instructions
915 case instruction.OP_CAT:
916 case instruction.OP_SUBSTR:
917 case instruction.OP_LEFT:
918 case instruction.OP_RIGHT:
919 case instruction.OP_INVERT:
920 case instruction.OP_AND:
921 case instruction.OP_OR:
922 case instruction.OP_XOR:
923 case instruction.OP_2MUL:
924 case instruction.OP_2DIV:
925 case instruction.OP_MUL:
926 case instruction.OP_DIV:
927 case instruction.OP_MOD:
928 case instruction.OP_LSHIFT:
929 case instruction.OP_RSHIFT:
933 // Push integer instructions
935 case instruction.OP_1NEGATE:
936 case instruction.OP_1:
937 case instruction.OP_2:
938 case instruction.OP_3:
939 case instruction.OP_4:
940 case instruction.OP_5:
941 case instruction.OP_6:
942 case instruction.OP_7:
943 case instruction.OP_8:
944 case instruction.OP_9:
945 case instruction.OP_10:
946 case instruction.OP_11:
947 case instruction.OP_12:
948 case instruction.OP_13:
949 case instruction.OP_14:
950 case instruction.OP_15:
951 case instruction.OP_16:
954 BigInteger bn = DecodeOP_N(opcode, true);
955 stack.Add(bn.ToByteArray());
962 case instruction.OP_NOP:
963 case instruction.OP_NOP1:
964 case instruction.OP_NOP2:
965 case instruction.OP_NOP3:
966 case instruction.OP_NOP4:
967 case instruction.OP_NOP5:
968 case instruction.OP_NOP6:
969 case instruction.OP_NOP7:
970 case instruction.OP_NOP8:
971 case instruction.OP_NOP9:
972 case instruction.OP_NOP10:
981 case instruction.OP_IF:
982 case instruction.OP_NOTIF:
984 // <expression> if [statements] [else [statements]] endif
988 if (stack.Count() < 1)
992 var vch = stacktop(ref stack, -1);
993 fValue = CastToBool(vch);
994 if (opcode == instruction.OP_NOTIF)
1004 case instruction.OP_ELSE:
1006 int nExecCount = vfExec.Count();
1007 if (nExecCount == 0)
1011 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1015 case instruction.OP_ENDIF:
1017 int nExecCount = vfExec.Count();
1018 if (nExecCount == 0)
1022 vfExec.RemoveAt(nExecCount - 1);
1026 case instruction.OP_VERIFY:
1029 // (false -- false) and return
1030 if (stack.Count() < 1)
1035 bool fValue = CastToBool(stacktop(ref stack, -1));
1038 popstack(ref stack);
1047 case instruction.OP_RETURN:
1055 case instruction.OP_TOALTSTACK:
1057 if (stack.Count() < 1)
1061 altStack.Add(stacktop(ref stack, -1));
1062 popstack(ref stack);
1066 case instruction.OP_FROMALTSTACK:
1068 if (altStack.Count() < 1)
1072 stack.Add(stacktop(ref stack, -1));
1073 popstack(ref altStack);
1077 case instruction.OP_2DROP:
1080 if (stack.Count() < 2)
1084 popstack(ref stack);
1085 popstack(ref stack);
1089 case instruction.OP_2DUP:
1091 // (x1 x2 -- x1 x2 x1 x2)
1092 if (stack.Count() < 2)
1096 var vch1 = stacktop(ref stack, -2);
1097 var vch2 = stacktop(ref stack, -1);
1103 case instruction.OP_3DUP:
1105 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1106 if (stack.Count() < 3)
1110 var vch1 = stacktop(ref stack, -3);
1111 var vch2 = stacktop(ref stack, -2);
1112 var vch3 = stacktop(ref stack, -1);
1119 case instruction.OP_2OVER:
1121 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1122 if (stack.Count() < 4)
1126 var vch1 = stacktop(ref stack, -4);
1127 var vch2 = stacktop(ref stack, -3);
1133 case instruction.OP_2ROT:
1135 int nStackDepth = stack.Count();
1136 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1137 if (nStackDepth < 6)
1141 var vch1 = stacktop(ref stack, -6);
1142 var vch2 = stacktop(ref stack, -5);
1143 stack.RemoveRange(nStackDepth - 6, 2);
1149 case instruction.OP_2SWAP:
1151 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1152 int nStackDepth = stack.Count;
1153 if (nStackDepth < 4)
1157 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1158 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1162 case instruction.OP_IFDUP:
1165 if (stack.Count() < 1)
1170 var vch = stacktop(ref stack, -1);
1172 if (CastToBool(vch))
1179 case instruction.OP_DEPTH:
1182 BigInteger bn = new BigInteger((ushort)stack.Count());
1183 stack.Add(bn.ToByteArray());
1187 case instruction.OP_DROP:
1190 if (stack.Count() < 1)
1195 popstack(ref stack);
1199 case instruction.OP_DUP:
1202 if (stack.Count() < 1)
1207 var vch = stacktop(ref stack, -1);
1212 case instruction.OP_NIP:
1215 int nStackDepth = stack.Count();
1216 if (nStackDepth < 2)
1221 stack.RemoveAt(nStackDepth - 2);
1225 case instruction.OP_OVER:
1227 // (x1 x2 -- x1 x2 x1)
1228 if (stack.Count() < 2)
1233 var vch = stacktop(ref stack, -2);
1238 case instruction.OP_PICK:
1239 case instruction.OP_ROLL:
1241 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1242 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1244 int nStackDepth = stack.Count();
1245 if (nStackDepth < 2)
1250 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1251 popstack(ref stack);
1253 if (n < 0 || n >= stack.Count())
1258 var vch = stacktop(ref stack, -n - 1);
1259 if (opcode == instruction.OP_ROLL)
1261 stack.RemoveAt(nStackDepth - n - 1);
1268 case instruction.OP_ROT:
1270 // (x1 x2 x3 -- x2 x3 x1)
1271 // x2 x1 x3 after first swap
1272 // x2 x3 x1 after second swap
1273 int nStackDepth = stack.Count();
1274 if (nStackDepth < 3)
1278 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1279 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1284 case instruction.OP_SWAP:
1287 int nStackDepth = stack.Count();
1288 if (nStackDepth < 2)
1292 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1296 case instruction.OP_TUCK:
1298 // (x1 x2 -- x2 x1 x2)
1299 int nStackDepth = stack.Count();
1300 if (nStackDepth < 2)
1304 var vch = stacktop(ref stack, -1);
1305 stack.Insert(nStackDepth - 2, vch);
1310 case instruction.OP_SIZE:
1313 if (stack.Count() < 1)
1318 var bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1319 stack.Add(bnSize.ToByteArray());
1327 case instruction.OP_EQUAL:
1328 case instruction.OP_EQUALVERIFY:
1329 //case instruction.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1332 if (stack.Count() < 2)
1337 var vch1 = stacktop(ref stack, -2);
1338 var vch2 = stacktop(ref stack, -1);
1339 bool fEqual = (vch1.SequenceEqual(vch2));
1340 // OP_NOTEQUAL is disabled because it would be too easy to say
1341 // something like n != 1 and have some wiseguy pass in 1 with extra
1342 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1343 //if (opcode == instruction.OP_NOTEQUAL)
1344 // fEqual = !fEqual;
1345 popstack(ref stack);
1346 popstack(ref stack);
1347 stack.Add(fEqual ? trueBytes : falseBytes);
1349 if (opcode == instruction.OP_EQUALVERIFY)
1353 popstack(ref stack);
1367 case instruction.OP_1ADD:
1368 case instruction.OP_1SUB:
1369 case instruction.OP_NEGATE:
1370 case instruction.OP_ABS:
1371 case instruction.OP_NOT:
1372 case instruction.OP_0NOTEQUAL:
1375 if (stack.Count() < 1)
1380 var bn = CastToBigInteger(stacktop(ref stack, -1));
1383 case instruction.OP_1ADD:
1386 case instruction.OP_1SUB:
1389 case instruction.OP_NEGATE:
1392 case instruction.OP_ABS:
1393 bn = BigInteger.Abs(bn);
1395 case instruction.OP_NOT:
1396 bn = bn == 0 ? 1 : 0;
1398 case instruction.OP_0NOTEQUAL:
1399 bn = bn != 0 ? 1 : 0;
1403 popstack(ref stack);
1404 stack.Add(bn.ToByteArray());
1408 case instruction.OP_ADD:
1409 case instruction.OP_SUB:
1410 case instruction.OP_BOOLAND:
1411 case instruction.OP_BOOLOR:
1412 case instruction.OP_NUMEQUAL:
1413 case instruction.OP_NUMEQUALVERIFY:
1414 case instruction.OP_NUMNOTEQUAL:
1415 case instruction.OP_LESSTHAN:
1416 case instruction.OP_GREATERTHAN:
1417 case instruction.OP_LESSTHANOREQUAL:
1418 case instruction.OP_GREATERTHANOREQUAL:
1419 case instruction.OP_MIN:
1420 case instruction.OP_MAX:
1423 if (stack.Count() < 2)
1428 var bn1 = CastToBigInteger(stacktop(ref stack, -2));
1429 var bn2 = CastToBigInteger(stacktop(ref stack, -1));
1434 case instruction.OP_ADD:
1437 case instruction.OP_SUB:
1440 case instruction.OP_BOOLAND:
1441 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1443 case instruction.OP_BOOLOR:
1444 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1446 case instruction.OP_NUMEQUAL:
1447 bn = (bn1 == bn2) ? 1 : 0;
1449 case instruction.OP_NUMEQUALVERIFY:
1450 bn = (bn1 == bn2) ? 1 : 0;
1452 case instruction.OP_NUMNOTEQUAL:
1453 bn = (bn1 != bn2) ? 1 : 0;
1455 case instruction.OP_LESSTHAN:
1456 bn = (bn1 < bn2) ? 1 : 0;
1458 case instruction.OP_GREATERTHAN:
1459 bn = (bn1 > bn2) ? 1 : 0;
1461 case instruction.OP_LESSTHANOREQUAL:
1462 bn = (bn1 <= bn2) ? 1 : 0;
1464 case instruction.OP_GREATERTHANOREQUAL:
1465 bn = (bn1 >= bn2) ? 1 : 0;
1467 case instruction.OP_MIN:
1468 bn = (bn1 < bn2 ? bn1 : bn2);
1470 case instruction.OP_MAX:
1471 bn = (bn1 > bn2 ? bn1 : bn2);
1475 popstack(ref stack);
1476 popstack(ref stack);
1477 stack.Add(bn.ToByteArray());
1479 if (opcode == instruction.OP_NUMEQUALVERIFY)
1481 if (CastToBool(stacktop(ref stack, -1)))
1483 popstack(ref stack);
1493 case instruction.OP_WITHIN:
1495 // (x min max -- out)
1496 if (stack.Count() < 3)
1501 var bn1 = CastToBigInteger(stacktop(ref stack, -3));
1502 var bn2 = CastToBigInteger(stacktop(ref stack, -2));
1503 var bn3 = CastToBigInteger(stacktop(ref stack, -1));
1505 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1507 popstack(ref stack);
1508 popstack(ref stack);
1509 popstack(ref stack);
1511 stack.Add(fValue ? trueBytes : falseBytes);
1518 case instruction.OP_RIPEMD160:
1519 case instruction.OP_SHA1:
1520 case instruction.OP_SHA256:
1521 case instruction.OP_HASH160:
1522 case instruction.OP_HASH256:
1525 if (stack.Count() < 1)
1530 var data = stacktop(ref stack, -1);
1534 case instruction.OP_HASH160:
1535 hash = Hash160.Compute160(data);
1537 case instruction.OP_HASH256:
1538 hash = Hash256.Compute256(data);
1540 case instruction.OP_SHA1:
1541 hash = SHA1.Compute1(data);
1543 case instruction.OP_SHA256:
1544 hash = SHA256.Compute256(data);
1546 case instruction.OP_RIPEMD160:
1547 hash = RIPEMD160.Compute160(data);
1550 popstack(ref stack);
1551 stack.Add(hash.hashBytes);
1555 case instruction.OP_CODESEPARATOR:
1557 // Hash starts after the code separator
1558 nCodeHashBegin = CodeQueue.CurrentIndex;
1562 case instruction.OP_CHECKSIG:
1563 case instruction.OP_CHECKSIGVERIFY:
1565 // (sig pubkey -- bool)
1566 if (stack.Count() < 2)
1571 var sigBytes = stacktop(ref stack, -2);
1572 var pubkeyBytes = stacktop(ref stack, -1);
1574 // Subset of script starting at the most recent codeseparator
1575 var scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin).ToArray());
1577 // There's no way for a signature to sign itself
1578 scriptCode.RemovePattern(sigBytes);
1580 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes, flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1582 popstack(ref stack);
1583 popstack(ref stack);
1585 stack.Add(fSuccess ? trueBytes : falseBytes);
1587 if (opcode == instruction.OP_CHECKSIGVERIFY)
1591 popstack(ref stack);
1601 case instruction.OP_CHECKMULTISIG:
1602 case instruction.OP_CHECKMULTISIGVERIFY:
1604 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1607 if (stack.Count() < i)
1612 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1613 if (nKeysCount < 0 || nKeysCount > 20)
1617 nOpCount += nKeysCount;
1624 if (stack.Count() < i)
1629 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1630 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1636 if (stack.Count() < i)
1641 // Subset of script starting at the most recent codeseparator
1642 var scriptCode = new CScript(script.Bytes.Skip(nCodeHashBegin).ToArray());
1644 // There is no way for a signature to sign itself, so we need to drop the signatures
1645 for (int k = 0; k < nSigsCount; k++)
1647 var vchSig = stacktop(ref stack, -isig - k);
1648 scriptCode.RemovePattern(vchSig);
1651 bool fSuccess = true;
1652 while (fSuccess && nSigsCount > 0)
1654 var sigBytes = stacktop(ref stack, -isig);
1655 var pubKeyBytes = stacktop(ref stack, -ikey);
1658 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes, flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1668 // If there are more signatures left than keys left,
1669 // then too many signatures have failed
1670 if (nSigsCount > nKeysCount)
1678 popstack(ref stack);
1681 // A bug causes CHECKMULTISIG to consume one extra argument
1682 // whose contents were not checked in any way.
1684 // Unfortunately this is a potential source of mutability,
1685 // so optionally verify it is exactly equal to zero prior
1686 // to removing it from the stack.
1687 if (stack.Count() < 1)
1691 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1693 return false; // CHECKMULTISIG dummy argument not null
1695 popstack(ref stack);
1697 stack.Add(fSuccess ? trueBytes : falseBytes);
1699 if (opcode == instruction.OP_CHECKMULTISIGVERIFY)
1703 popstack(ref stack);
1718 if (stack.Count() + altStack.Count() > 1000)
1726 // If there are any exceptions then just return false.
1730 if (vfExec.Count() != 0)
1732 // Something went wrong with conditional instructions.
1740 public static bool IsCanonicalPubKey(byte[] pubKeyBytes, int flags)
1742 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1745 if (pubKeyBytes.Length < 33)
1746 return false; // Non-canonical public key: too short
1747 if (pubKeyBytes[0] == 0x04)
1749 if (pubKeyBytes.Length != 65)
1750 return false; // Non-canonical public key: invalid length for uncompressed key
1752 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1754 if (pubKeyBytes.Length != 33)
1755 return false; // Non-canonical public key: invalid length for compressed key
1759 return false; // Non-canonical public key: compressed nor uncompressed
1764 public static bool IsCanonicalSignature(byte[] sigBytes, int flags)
1772 /// Check signature.
1774 /// <param name="sigBytes">Signature</param>
1775 /// <param name="pubkeyBytes">Public key</param>
1776 /// <param name="script">Spending script</param>
1777 /// <param name="txTo">CTransaction instance</param>
1778 /// <param name="nIn">Input number</param>
1779 /// <param name="nHashType">Hashing type flag</param>
1780 /// <param name="flags">Signature checking flags</param>
1781 /// <returns>Checking result</returns>
1782 public static bool CheckSig(byte[] sigBytes, byte[] pubkeyBytes, CScript script, CTransaction txTo, int nIn, int nHashType, int flags)
1788 // Trying to initialize the public key instance
1790 pubkey = new CPubKey(pubkeyBytes);
1794 // Exception occurred while initializing the public key
1799 if (!pubkey.IsValid)
1804 if (sigBytes.Length == 0)
1809 // Hash type is one byte tacked on to the end of the signature
1812 nHashType = sigBytes.Last();
1814 else if (nHashType != sigBytes.Last())
1820 Array.Resize(ref sigBytes, sigBytes.Length - 1);
1822 var sighash = SignatureHash(script, txTo, nIn, nHashType);
1824 if (!pubkey.VerifySignature(sighash, sigBytes))
1833 /// Evaluates the both scriptSig and scriptPubKey.
1835 /// <param name="scriptSig"></param>
1836 /// <param name="scriptPubKey"></param>
1837 /// <param name="txTo">Transaction</param>
1838 /// <param name="nIn">Input number</param>
1839 /// <param name="flags">Script validation flags</param>
1840 /// <param name="nHashType">Hash type flag</param>
1841 /// <returns></returns>
1842 public static bool VerifyScript(CScript scriptSig, CScript scriptPubKey, CTransaction txTo, int nIn, int flags, int nHashType)
1844 var stack = new List<byte[]>();
1845 List<byte[]> stackCopy = null;
1847 if (!EvalScript(ref stack, scriptSig, txTo, nIn, flags, nHashType))
1852 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0)
1854 stackCopy = new List<byte[]>(stack);
1857 if (!EvalScript(ref stack, scriptPubKey, txTo, nIn, flags, nHashType))
1862 if (stack.Count == 0 || CastToBool(stack.Last()) == false)
1867 // Additional validation for spend-to-script-hash transactions:
1868 if ((flags & (int)scriptflag.SCRIPT_VERIFY_P2SH) != 0 && scriptPubKey.IsPayToScriptHash)
1870 if (!scriptSig.IsPushOnly) // scriptSig must be literals-only
1875 // stackCopy cannot be empty here, because if it was the
1876 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
1877 // an empty stack and the EvalScript above would return false.
1879 if (stackCopy.Count == 0)
1881 throw new StackMachineException("Fatal script validation error.");
1884 var pubKey2 = new CScript(stackCopy.Last());
1885 popstack(ref stackCopy);
1887 if (!EvalScript(ref stackCopy, pubKey2, txTo, nIn, flags, nHashType))
1889 if (stackCopy.Count == 0)
1892 return CastToBool(stackCopy.Last());