2 using System.Collections.Generic;
8 // using Org.BouncyCastle.Math;
15 public enum opcodetype
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(opcodetype opcode)
222 case opcodetype.OP_0:
224 case opcodetype.OP_PUSHDATA1:
225 return "OP_PUSHDATA1";
226 case opcodetype.OP_PUSHDATA2:
227 return "OP_PUSHDATA2";
228 case opcodetype.OP_PUSHDATA4:
229 return "OP_PUSHDATA4";
230 case opcodetype.OP_1NEGATE:
232 case opcodetype.OP_RESERVED:
233 return "OP_RESERVED";
234 case opcodetype.OP_1:
236 case opcodetype.OP_2:
238 case opcodetype.OP_3:
240 case opcodetype.OP_4:
242 case opcodetype.OP_5:
244 case opcodetype.OP_6:
246 case opcodetype.OP_7:
248 case opcodetype.OP_8:
250 case opcodetype.OP_9:
252 case opcodetype.OP_10:
254 case opcodetype.OP_11:
256 case opcodetype.OP_12:
258 case opcodetype.OP_13:
260 case opcodetype.OP_14:
262 case opcodetype.OP_15:
264 case opcodetype.OP_16:
268 case opcodetype.OP_NOP:
270 case opcodetype.OP_VER:
272 case opcodetype.OP_IF:
274 case opcodetype.OP_NOTIF:
276 case opcodetype.OP_VERIF:
278 case opcodetype.OP_VERNOTIF:
279 return "OP_VERNOTIF";
280 case opcodetype.OP_ELSE:
282 case opcodetype.OP_ENDIF:
284 case opcodetype.OP_VERIFY:
286 case opcodetype.OP_RETURN:
290 case opcodetype.OP_TOALTSTACK:
291 return "OP_TOALTSTACK";
292 case opcodetype.OP_FROMALTSTACK:
293 return "OP_FROMALTSTACK";
294 case opcodetype.OP_2DROP:
296 case opcodetype.OP_2DUP:
298 case opcodetype.OP_3DUP:
300 case opcodetype.OP_2OVER:
302 case opcodetype.OP_2ROT:
304 case opcodetype.OP_2SWAP:
306 case opcodetype.OP_IFDUP:
308 case opcodetype.OP_DEPTH:
310 case opcodetype.OP_DROP:
312 case opcodetype.OP_DUP:
314 case opcodetype.OP_NIP:
316 case opcodetype.OP_OVER:
318 case opcodetype.OP_PICK:
320 case opcodetype.OP_ROLL:
322 case opcodetype.OP_ROT:
324 case opcodetype.OP_SWAP:
326 case opcodetype.OP_TUCK:
330 case opcodetype.OP_CAT:
332 case opcodetype.OP_SUBSTR:
334 case opcodetype.OP_LEFT:
336 case opcodetype.OP_RIGHT:
338 case opcodetype.OP_SIZE:
342 case opcodetype.OP_INVERT:
344 case opcodetype.OP_AND:
346 case opcodetype.OP_OR:
348 case opcodetype.OP_XOR:
350 case opcodetype.OP_EQUAL:
352 case opcodetype.OP_EQUALVERIFY:
353 return "OP_EQUALVERIFY";
354 case opcodetype.OP_RESERVED1:
355 return "OP_RESERVED1";
356 case opcodetype.OP_RESERVED2:
357 return "OP_RESERVED2";
360 case opcodetype.OP_1ADD:
362 case opcodetype.OP_1SUB:
364 case opcodetype.OP_2MUL:
366 case opcodetype.OP_2DIV:
368 case opcodetype.OP_NEGATE:
370 case opcodetype.OP_ABS:
372 case opcodetype.OP_NOT:
374 case opcodetype.OP_0NOTEQUAL:
375 return "OP_0NOTEQUAL";
376 case opcodetype.OP_ADD:
378 case opcodetype.OP_SUB:
380 case opcodetype.OP_MUL:
382 case opcodetype.OP_DIV:
384 case opcodetype.OP_MOD:
386 case opcodetype.OP_LSHIFT:
388 case opcodetype.OP_RSHIFT:
390 case opcodetype.OP_BOOLAND:
392 case opcodetype.OP_BOOLOR:
394 case opcodetype.OP_NUMEQUAL:
395 return "OP_NUMEQUAL";
396 case opcodetype.OP_NUMEQUALVERIFY:
397 return "OP_NUMEQUALVERIFY";
398 case opcodetype.OP_NUMNOTEQUAL:
399 return "OP_NUMNOTEQUAL";
400 case opcodetype.OP_LESSTHAN:
401 return "OP_LESSTHAN";
402 case opcodetype.OP_GREATERTHAN:
403 return "OP_GREATERTHAN";
404 case opcodetype.OP_LESSTHANOREQUAL:
405 return "OP_LESSTHANOREQUAL";
406 case opcodetype.OP_GREATERTHANOREQUAL:
407 return "OP_GREATERTHANOREQUAL";
408 case opcodetype.OP_MIN:
410 case opcodetype.OP_MAX:
412 case opcodetype.OP_WITHIN:
416 case opcodetype.OP_RIPEMD160:
417 return "OP_RIPEMD160";
418 case opcodetype.OP_SHA1:
420 case opcodetype.OP_SHA256:
422 case opcodetype.OP_HASH160:
424 case opcodetype.OP_HASH256:
426 case opcodetype.OP_CODESEPARATOR:
427 return "OP_CODESEPARATOR";
428 case opcodetype.OP_CHECKSIG:
429 return "OP_CHECKSIG";
430 case opcodetype.OP_CHECKSIGVERIFY:
431 return "OP_CHECKSIGVERIFY";
432 case opcodetype.OP_CHECKMULTISIG:
433 return "OP_CHECKMULTISIG";
434 case opcodetype.OP_CHECKMULTISIGVERIFY:
435 return "OP_CHECKMULTISIGVERIFY";
438 case opcodetype.OP_NOP1:
440 case opcodetype.OP_NOP2:
442 case opcodetype.OP_NOP3:
444 case opcodetype.OP_NOP4:
446 case opcodetype.OP_NOP5:
448 case opcodetype.OP_NOP6:
450 case opcodetype.OP_NOP7:
452 case opcodetype.OP_NOP8:
454 case opcodetype.OP_NOP9:
456 case opcodetype.OP_NOP10:
459 // template matching params
460 case opcodetype.OP_PUBKEYHASH:
461 return "OP_PUBKEYHASH";
462 case opcodetype.OP_PUBKEY:
464 case opcodetype.OP_SMALLDATA:
465 return "OP_SMALLDATA";
467 case opcodetype.OP_INVALIDOPCODE:
468 return "OP_INVALIDOPCODE";
475 /// Get next opcode from passed list of bytes and extract push arguments if there are some.
477 /// <param name="codeBytes">ByteQueue reference.</param>
478 /// <param name="opcodeRet">Found opcode.</param>
479 /// <param name="bytesRet">IEnumerable out param which is used to get the push arguments.</param>
480 /// <returns>Result of operation</returns>
481 public static bool GetOp(ref ByteQueue codeBytes, out opcodetype opcodeRet, out IEnumerable<byte> bytesRet)
483 bytesRet = new List<byte>();
484 opcodeRet = opcodetype.OP_INVALIDOPCODE;
491 opcode = (opcodetype)codeBytes.Get();
493 catch (ByteQueueException)
495 // No instruction found there
500 if (opcode <= opcodetype.OP_PUSHDATA4)
502 byte[] szBytes = new byte[4] { 0, 0, 0, 0 }; // Zero length
506 if (opcode < opcodetype.OP_PUSHDATA1)
508 // Zero value opcodes (OP_0, OP_FALSE)
509 szBytes[3] = (byte)opcode;
511 else if (opcode == opcodetype.OP_PUSHDATA1)
513 // The next byte contains the number of bytes to be pushed onto the stack,
514 // i.e. you have something like OP_PUSHDATA1 0x01 [0x5a]
515 szBytes[3] = (byte)codeBytes.Get();
517 else if (opcode == opcodetype.OP_PUSHDATA2)
519 // The next two bytes contain the number of bytes to be pushed onto the stack,
520 // i.e. now your operation will seem like this: OP_PUSHDATA2 0x00 0x01 [0x5a]
521 codeBytes.Get(2).CopyTo(szBytes, 2);
523 else if (opcode == opcodetype.OP_PUSHDATA4)
525 // The next four bytes contain the number of bytes to be pushed onto the stack,
526 // OP_PUSHDATA4 0x00 0x00 0x00 0x01 [0x5a]
527 szBytes = codeBytes.Get(4);
530 catch (ByteQueueException)
532 // Unable to read operand length
536 int nSize = (int)Interop.BEBytesToUInt32(szBytes);
540 // If nSize is greater than zero then there is some data available
543 // Read found number of bytes into list of OP_PUSHDATAn arguments.
544 bytesRet = codeBytes.GetEnumerable(nSize);
546 catch (ByteQueueException)
548 // Unable to read data
560 /// Convert value bytes into readable representation.
562 /// If list lengh is equal or lesser than 4 bytes then bytes are interpreted as integer value. Otherwise you will get hex representation of supplied data.
564 /// <param name="bytes">Collection of value bytes.</param>
565 /// <returns>Formatted value.</returns>
566 public static string ValueString(IEnumerable<byte> bytes)
568 StringBuilder sb = new StringBuilder();
570 if (bytes.Count() <= 4)
572 byte[] valueBytes = new byte[4] { 0, 0, 0, 0 };
573 bytes.ToArray().CopyTo(valueBytes, valueBytes.Length - bytes.Count());
575 sb.Append(Interop.BEBytesToUInt32(valueBytes));
579 return Interop.ToHex(bytes);
582 return sb.ToString();
586 /// Convert list of stack items into human readable representation.
588 /// <param name="stackList">List of stack items.</param>
589 /// <returns>Formatted value.</returns>
590 public static string StackString(IList<IList<byte>> stackList)
592 StringBuilder sb = new StringBuilder();
593 foreach (IList<byte> bytesList in stackList)
595 sb.Append(ValueString(bytesList));
598 return sb.ToString();
602 /// Decode small integer
604 /// <param name="opcode">Small integer opcode (OP_0 - OP_16)</param>
605 /// <returns>Small integer</returns>
606 public static int DecodeOP_N(opcodetype opcode)
608 if (opcode == opcodetype.OP_0)
611 // Only OP_n opcodes are supported, throw exception otherwise.
612 if (opcode < opcodetype.OP_1 || opcode > opcodetype.OP_16)
613 throw new Exception("Invalid small integer opcode.");
614 return (int)opcode - (int)(opcodetype.OP_1 - 1);
618 /// Converts small integer into opcode
620 /// <param name="n">Small integer from the range of 0 up to 16.</param>
621 /// <returns>Corresponding opcode.</returns>
622 public static opcodetype EncodeOP_N(int n)
624 // The n value must be in the range of 0 to 16.
626 throw new Exception("Invalid small integer value.");
628 return opcodetype.OP_0;
629 return (opcodetype)(opcodetype.OP_1 + n - 1);
632 public static int ScriptSigArgsExpected(txnouttype t, IList<IEnumerable<byte>> solutions)
636 case txnouttype.TX_NONSTANDARD:
638 case txnouttype.TX_NULL_DATA:
640 case txnouttype.TX_PUBKEY:
642 case txnouttype.TX_PUBKEYHASH:
644 case txnouttype.TX_MULTISIG:
645 if (solutions.Count() < 1 || solutions.First().Count() < 1)
647 return solutions.First().First() + 1;
648 case txnouttype.TX_SCRIPTHASH:
649 return 1; // doesn't include args needed by the script
655 /// Is it a standart type of scriptPubKey?
657 /// <param name="scriptPubKey">CScript instance</param>
658 /// <param name="whichType">utut type</param>
659 /// <returns>Checking result</returns>
660 public static bool IsStandard(CScript scriptPubKey, out txnouttype whichType)
662 IList<IEnumerable<byte>> solutions = new List<IEnumerable<byte>>();
664 if (!Solver(scriptPubKey, out whichType, out solutions))
666 // No solutions found
670 if (whichType == txnouttype.TX_MULTISIG)
672 // Additional verification of OP_CHECKMULTISIG arguments
673 byte m = solutions.First().First();
674 byte n = solutions.Last().First();
676 // Support up to x-of-3 multisig txns as standard
687 return whichType != txnouttype.TX_NONSTANDARD;
691 /// Return public keys or hashes from scriptPubKey, for 'standard' transaction types.
693 /// <param name="scriptPubKey">CScript instance</param>
694 /// <param name="typeRet">Output type</param>
695 /// <param name="solutions">Set of solutions</param>
696 /// <returns>Result</returns>
697 public static bool Solver(CScript scriptPubKey, out txnouttype typeRet, out IList<IEnumerable<byte>> solutions)
699 solutions = new List<IEnumerable<byte>>();
701 // There are shortcuts for pay-to-script-hash and pay-to-pubkey-hash, which are more constrained than the other types:
703 // It is always OP_HASH160 20 [20 byte hash] OP_EQUAL
704 if (scriptPubKey.IsPayToScriptHash)
706 typeRet = txnouttype.TX_SCRIPTHASH;
708 // Take 20 bytes with offset of 2 bytes
709 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(2).Take(20);
710 solutions.Add(hashBytes);
715 // It is always OP_DUP OP_HASH160 20 [20 byte hash] OP_EQUALVERIFY OP_CHECKSIG
716 if (scriptPubKey.IsPayToPubKeyHash)
718 typeRet = txnouttype.TX_PUBKEYHASH;
720 // Take 20 bytes with offset of 3 bytes
721 IEnumerable<byte> hashBytes = scriptPubKey.Bytes.Skip(3).Take(20);
722 solutions.Add(hashBytes);
727 List<Tuple<txnouttype, IEnumerable<byte>>> templateTuples = new List<Tuple<txnouttype, IEnumerable<byte>>>();
729 // Sender provides pubkey, receiver adds signature
730 // [ECDSA public key] OP_CHECKSIG
732 new Tuple<txnouttype, IEnumerable<byte>>(
733 txnouttype.TX_PUBKEY,
734 new byte[] { (byte)opcodetype.OP_PUBKEY, (byte)opcodetype.OP_CHECKSIG })
737 // Sender provides N pubkeys, receivers provides M signatures
738 // N [pubkey1] [pubkey2] ... [pubkeyN] M OP_CHECKMULTISIG
739 // Where N and M are small integer opcodes (OP1 ... OP_16)
741 new Tuple<txnouttype, IEnumerable<byte>>(
742 txnouttype.TX_MULTISIG,
743 new byte[] { (byte)opcodetype.OP_SMALLINTEGER, (byte)opcodetype.OP_PUBKEYS, (byte)opcodetype.OP_SMALLINTEGER, (byte)opcodetype.OP_CHECKMULTISIG })
746 // Data-carrying output
747 // OP_RETURN [up to 80 bytes of data]
749 new Tuple<txnouttype, IEnumerable<byte>>(
750 txnouttype.TX_NULL_DATA,
751 new byte[] { (byte)opcodetype.OP_RETURN, (byte)opcodetype.OP_SMALLDATA })
754 // Nonstandard tx output
755 typeRet = txnouttype.TX_NONSTANDARD;
757 foreach (Tuple<txnouttype, IEnumerable<byte>> templateTuple in templateTuples)
759 CScript script1 = scriptPubKey;
760 CScript script2 = new CScript(templateTuple.Item2);
762 opcodetype opcode1, opcode2;
765 ByteQueue wl1 = script1.GetByteQUeue();
766 ByteQueue wl2 = script2.GetByteQUeue();
768 IEnumerable<byte> args1, args2;
770 byte last1 = script1.Bytes.Last();
771 byte last2 = script2.Bytes.Last();
775 if (wl1.GetCurrent() == last1 && wl2.GetCurrent() == last2)
778 typeRet = templateTuple.Item1;
779 if (typeRet == txnouttype.TX_MULTISIG)
781 // Additional checks for TX_MULTISIG:
782 byte m = solutions.First().First();
783 byte n = solutions.Last().First();
785 if (m < 1 || n < 1 || m > n || solutions.Count - 2 != n)
793 if (!GetOp(ref wl1, out opcode1, out args1))
797 if (!GetOp(ref wl2, out opcode2, out args2))
802 // Template matching opcodes:
803 if (opcode2 == opcodetype.OP_PUBKEYS)
805 while (args1.Count() >= 33 && args1.Count() <= 120)
807 solutions.Add(args1);
808 if (!GetOp(ref wl1, out opcode1, out args1))
813 if (!GetOp(ref wl2, out opcode2, out args2))
815 // Normal situation is to fall through
816 // to other if/else statements
818 if (opcode2 == opcodetype.OP_PUBKEY)
820 if (args1.Count() < 33 || args1.Count() > 120)
824 solutions.Add(args1);
826 else if (opcode2 == opcodetype.OP_PUBKEYHASH)
828 if (args1.Count() != 20) // hash160 size
832 solutions.Add(args1);
834 else if (opcode2 == opcodetype.OP_SMALLINTEGER)
836 // Single-byte small integer pushed onto solutions
837 if (opcode1 == opcodetype.OP_0 || (opcode1 >= opcodetype.OP_1 && opcode1 <= opcodetype.OP_16))
839 byte n = (byte)DecodeOP_N(opcode1);
840 solutions.Add(new byte[] { n });
847 else if (opcode2 == opcodetype.OP_SMALLDATA)
849 // small pushdata, <= 80 bytes
850 if (args1.Count() > 80)
855 else if (opcode1 != opcode2 || !args1.SequenceEqual(args2))
857 // Others must match exactly
864 typeRet = txnouttype.TX_NONSTANDARD;
869 public static Hash256 SignatureHash(CScript scriptCode, CTransaction txTo, int nIn, int nHashType)
871 if (nIn >= txTo.vin.Length)
873 StringBuilder sb = new StringBuilder();
874 sb.AppendFormat("ERROR: SignatureHash() : nIn={0} out of range\n", nIn);
875 throw new ArgumentOutOfRangeException("nIn", sb.ToString());
878 CTransaction txTmp = new CTransaction(txTo);
880 // In case concatenating two scripts ends up with two codeseparators,
881 // or an extra one at the end, this prevents all those possible incompatibilities.
882 scriptCode.RemovePattern(new byte[] { (byte)opcodetype.OP_CODESEPARATOR });
884 // Blank out other inputs' signatures
885 for (int i = 0; i < txTmp.vin.Length; i++)
887 txTmp.vin[i].scriptSig = new CScript();
889 txTmp.vin[nIn].scriptSig = scriptCode;
891 // Blank out some of the outputs
892 if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_NONE)
895 txTmp.vout = new CTxOut[0];
897 // Let the others update at will
898 for (int i = 0; i < txTmp.vin.Length; i++)
902 txTmp.vin[i].nSequence = 0;
906 else if ((nHashType & 0x1f) == (int)sigflag.SIGHASH_SINGLE)
908 // Only lock-in the txout payee at same index as txin
910 if (nOut >= txTmp.vout.Length)
912 StringBuilder sb = new StringBuilder();
913 sb.AppendFormat("ERROR: SignatureHash() : nOut={0} out of range\n", nOut);
914 throw new ArgumentOutOfRangeException("nOut", sb.ToString());
916 Array.Resize(ref txTmp.vout, nOut + 1);
918 for (int i = 0; i < nOut; i++)
920 txTmp.vout[i] = new CTxOut();
923 // Let the others update at will
924 for (int i = 0; i < txTmp.vin.Length; i++)
928 txTmp.vin[i].nSequence = 0;
933 // Blank out other inputs completely, not recommended for open transactions
934 if ((nHashType & (int)sigflag.SIGHASH_ANYONECANPAY) != 0)
936 txTmp.vin[0] = txTmp.vin[nIn];
937 Array.Resize(ref txTmp.vin, 1);
940 // Serialize and hash
941 List<byte> b = new List<byte>();
942 b.AddRange(txTmp.Bytes);
943 b.AddRange(BitConverter.GetBytes(nHashType));
945 return Hash256.Compute256(b);
948 public class StackMachineException : Exception
950 public StackMachineException()
954 public StackMachineException(string message)
959 public StackMachineException(string message, Exception inner)
960 : base(message, inner)
967 // Script is a stack machine (like Forth) that evaluates a predicate
968 // returning a bool indicating valid or not. There are no loops.
972 /// Remove last element from stack
974 /// <param name="stack">Stack reference</param>
975 static void popstack(ref List<IEnumerable<byte>> stack)
977 int nCount = stack.Count;
979 throw new StackMachineException("popstack() : stack empty");
980 stack.RemoveAt(nCount - 1);
984 /// Get element at specified stack depth
986 /// <param name="stack">Stack reference</param>
987 /// <param name="nDepth">Depth</param>
988 /// <returns>Byte sequence</returns>
989 static IEnumerable<byte> stacktop(ref List<IEnumerable<byte>> stack, int nDepth)
991 int nStackElement = stack.Count + nDepth;
995 StringBuilder sb = new StringBuilder();
996 sb.AppendFormat("stacktop() : positive depth ({0})", nDepth);
998 throw new StackMachineException(sb.ToString());
1001 if (nStackElement < 0)
1003 StringBuilder sb = new StringBuilder();
1004 sb.AppendFormat("stacktop() : nDepth={0} exceeds real stack depth", nDepth);
1006 throw new StackMachineException(sb.ToString());
1009 return stack[nStackElement];
1013 /// Cast argument to boolean value
1015 /// <param name="value">Some byte sequence</param>
1016 /// <returns></returns>
1017 private static bool CastToBool(IEnumerable<byte> arg)
1019 byte[] value = arg.ToArray();
1021 for (var i = 0; i < value.Length; i++)
1025 // Can be negative zero
1026 if (i == value.Length - 1 && value[i] == 0x80)
1037 /// Cast argument to integer value
1039 /// <param name="value"></param>
1040 /// <returns></returns>
1041 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
1043 if (value.Count() > 4)
1045 throw new StackMachineException("CastToBigInteger() : overflow");
1048 return new BigInteger(value.ToArray());
1051 static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
1053 ByteQueue pc = script.GetByteQUeue();
1055 ByteQueue pbegincodehash = script.GetByteQUeue();
1058 IEnumerable<byte> vchPushValue;
1060 List<bool> vfExec = new List<bool>();
1061 List<IEnumerable<byte>> altstack = new List<IEnumerable<byte>>();
1063 byte[] vchFalse = new byte[0];
1064 byte[] vchTrue = new byte[] { 0x01 };
1066 if (script.Bytes.Count() > 10000)
1076 foreach (bool fValue in vfExec)
1088 if (!GetOp(ref pc, out opcode, out vchPushValue))
1090 if (vchPushValue.Count() > 520) // Check against MAX_SCRIPT_ELEMENT_SIZE
1092 if (opcode > opcodetype.OP_16 && ++nOpCount > 201)
1095 if (opcode == opcodetype.OP_CAT ||
1096 opcode == opcodetype.OP_SUBSTR ||
1097 opcode == opcodetype.OP_LEFT ||
1098 opcode == opcodetype.OP_RIGHT ||
1099 opcode == opcodetype.OP_INVERT ||
1100 opcode == opcodetype.OP_AND ||
1101 opcode == opcodetype.OP_OR ||
1102 opcode == opcodetype.OP_XOR ||
1103 opcode == opcodetype.OP_2MUL ||
1104 opcode == opcodetype.OP_2DIV ||
1105 opcode == opcodetype.OP_MUL ||
1106 opcode == opcodetype.OP_DIV ||
1107 opcode == opcodetype.OP_MOD ||
1108 opcode == opcodetype.OP_LSHIFT ||
1109 opcode == opcodetype.OP_RSHIFT)
1110 return false; // Disabled opcodes.
1112 if (fExec && 0 <= opcode && opcode <= opcodetype.OP_PUSHDATA4)
1114 stack.Add(vchPushValue);
1116 else if (fExec || (opcodetype.OP_IF <= opcode && opcode <= opcodetype.OP_ENDIF))
1122 case opcodetype.OP_1NEGATE:
1123 case opcodetype.OP_1:
1124 case opcodetype.OP_2:
1125 case opcodetype.OP_3:
1126 case opcodetype.OP_4:
1127 case opcodetype.OP_5:
1128 case opcodetype.OP_6:
1129 case opcodetype.OP_7:
1130 case opcodetype.OP_8:
1131 case opcodetype.OP_9:
1132 case opcodetype.OP_10:
1133 case opcodetype.OP_11:
1134 case opcodetype.OP_12:
1135 case opcodetype.OP_13:
1136 case opcodetype.OP_14:
1137 case opcodetype.OP_15:
1138 case opcodetype.OP_16:
1141 BigInteger bn = new BigInteger((int)opcode - (int)(opcodetype.OP_1 - 1));
1142 stack.Add(bn.ToByteArray());
1150 case opcodetype.OP_NOP:
1151 case opcodetype.OP_NOP1:
1152 case opcodetype.OP_NOP2:
1153 case opcodetype.OP_NOP3:
1154 case opcodetype.OP_NOP4:
1155 case opcodetype.OP_NOP5:
1156 case opcodetype.OP_NOP6:
1157 case opcodetype.OP_NOP7:
1158 case opcodetype.OP_NOP8:
1159 case opcodetype.OP_NOP9:
1160 case opcodetype.OP_NOP10:
1163 case opcodetype.OP_IF:
1164 case opcodetype.OP_NOTIF:
1166 // <expression> if [statements] [else [statements]] endif
1167 bool fValue = false;
1170 if (stack.Count() < 1)
1174 IEnumerable<byte> vch = stacktop(ref stack, -1);
1175 fValue = CastToBool(vch);
1176 if (opcode == opcodetype.OP_NOTIF)
1180 popstack(ref stack);
1186 case opcodetype.OP_ELSE:
1188 int nExecCount = vfExec.Count();
1189 if (nExecCount == 0)
1193 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1197 case opcodetype.OP_ENDIF:
1199 int nExecCount = vfExec.Count();
1200 if (nExecCount == 0)
1204 vfExec.RemoveAt(nExecCount - 1);
1208 case opcodetype.OP_VERIFY:
1211 // (false -- false) and return
1212 if (stack.Count() < 1)
1217 bool fValue = CastToBool(stacktop(ref stack, -1));
1220 popstack(ref stack);
1229 case opcodetype.OP_RETURN:
1234 case opcodetype.OP_TOALTSTACK:
1236 if (stack.Count() < 1)
1240 altstack.Add(stacktop(ref stack, -1));
1241 popstack(ref stack);
1245 case opcodetype.OP_FROMALTSTACK:
1247 if (altstack.Count() < 1)
1251 stack.Add(stacktop(ref stack, -1));
1252 popstack(ref altstack);
1256 case opcodetype.OP_2DROP:
1259 if (stack.Count() < 2)
1263 popstack(ref stack);
1264 popstack(ref stack);
1268 case opcodetype.OP_2DUP:
1270 // (x1 x2 -- x1 x2 x1 x2)
1271 if (stack.Count() < 2)
1275 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1276 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1282 case opcodetype.OP_3DUP:
1284 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1285 if (stack.Count() < 3)
1289 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1290 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1291 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1298 case opcodetype.OP_2OVER:
1300 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1301 if (stack.Count() < 4)
1305 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1306 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1312 case opcodetype.OP_2ROT:
1314 int nStackDepth = stack.Count();
1315 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1316 if (nStackDepth < 6)
1320 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1321 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1322 stack.RemoveRange(nStackDepth - 6, 2);
1328 case opcodetype.OP_2SWAP:
1330 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1331 int nStackDepth = stack.Count();
1332 if (nStackDepth < 4)
1336 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1337 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1341 case opcodetype.OP_IFDUP:
1344 if (stack.Count() < 1)
1349 IEnumerable<byte> vch = stacktop(ref stack, -1);
1351 if (CastToBool(vch))
1358 case opcodetype.OP_DEPTH:
1361 BigInteger bn = new BigInteger((ushort)stack.Count());
1362 stack.Add(bn.ToByteArray());
1366 case opcodetype.OP_DROP:
1369 if (stack.Count() < 1)
1374 popstack(ref stack);
1378 case opcodetype.OP_DUP:
1381 if (stack.Count() < 1)
1386 IEnumerable<byte> vch = stacktop(ref stack, -1);
1391 case opcodetype.OP_NIP:
1394 int nStackDepth = stack.Count();
1395 if (nStackDepth < 2)
1400 stack.RemoveAt(nStackDepth - 2);
1404 case opcodetype.OP_OVER:
1406 // (x1 x2 -- x1 x2 x1)
1407 if (stack.Count() < 2)
1412 IEnumerable<byte> vch = stacktop(ref stack, -2);
1417 case opcodetype.OP_PICK:
1418 case opcodetype.OP_ROLL:
1420 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1421 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1423 int nStackDepth = stack.Count();
1424 if (nStackDepth < 2)
1429 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1430 popstack(ref stack);
1432 if (n < 0 || n >= stack.Count())
1437 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1438 if (opcode == opcodetype.OP_ROLL)
1440 stack.RemoveAt(nStackDepth - n - 1);
1447 case opcodetype.OP_ROT:
1449 // (x1 x2 x3 -- x2 x3 x1)
1450 // x2 x1 x3 after first swap
1451 // x2 x3 x1 after second swap
1452 int nStackDepth = stack.Count();
1453 if (nStackDepth < 3)
1457 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1458 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1463 case opcodetype.OP_SWAP:
1466 int nStackDepth = stack.Count();
1467 if (nStackDepth < 2)
1471 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1475 case opcodetype.OP_TUCK:
1477 // (x1 x2 -- x2 x1 x2)
1478 int nStackDepth = stack.Count();
1479 if (nStackDepth < 2)
1483 IEnumerable<byte> vch = stacktop(ref stack, -1);
1484 stack.Insert(nStackDepth - 2, vch);
1489 case opcodetype.OP_SIZE:
1492 if (stack.Count() < 1)
1497 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1498 stack.Add(bnSize.ToByteArray());
1506 case opcodetype.OP_EQUAL:
1507 case opcodetype.OP_EQUALVERIFY:
1508 //case opcodetype.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1511 if (stack.Count() < 2)
1516 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1517 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1518 bool fEqual = (vch1 == vch2);
1519 // OP_NOTEQUAL is disabled because it would be too easy to say
1520 // something like n != 1 and have some wiseguy pass in 1 with extra
1521 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1522 //if (opcode == opcodetype.OP_NOTEQUAL)
1523 // fEqual = !fEqual;
1524 popstack(ref stack);
1525 popstack(ref stack);
1526 stack.Add(fEqual ? vchTrue : vchFalse);
1528 if (opcode == opcodetype.OP_EQUALVERIFY)
1532 popstack(ref stack);
1546 case opcodetype.OP_1ADD:
1547 case opcodetype.OP_1SUB:
1548 case opcodetype.OP_NEGATE:
1549 case opcodetype.OP_ABS:
1550 case opcodetype.OP_NOT:
1551 case opcodetype.OP_0NOTEQUAL:
1554 if (stack.Count() < 1)
1559 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1562 case opcodetype.OP_1ADD:
1565 case opcodetype.OP_1SUB:
1568 case opcodetype.OP_NEGATE:
1571 case opcodetype.OP_ABS:
1572 bn = BigInteger.Abs(bn);
1574 case opcodetype.OP_NOT:
1575 bn = bn == 0 ? 1 : 0;
1577 case opcodetype.OP_0NOTEQUAL:
1578 bn = bn != 0 ? 1 : 0;
1582 throw new StackMachineException("invalid opcode");
1586 popstack(ref stack);
1587 stack.Add(bn.ToByteArray());
1591 case opcodetype.OP_ADD:
1592 case opcodetype.OP_SUB:
1593 case opcodetype.OP_BOOLAND:
1594 case opcodetype.OP_BOOLOR:
1595 case opcodetype.OP_NUMEQUAL:
1596 case opcodetype.OP_NUMEQUALVERIFY:
1597 case opcodetype.OP_NUMNOTEQUAL:
1598 case opcodetype.OP_LESSTHAN:
1599 case opcodetype.OP_GREATERTHAN:
1600 case opcodetype.OP_LESSTHANOREQUAL:
1601 case opcodetype.OP_GREATERTHANOREQUAL:
1602 case opcodetype.OP_MIN:
1603 case opcodetype.OP_MAX:
1606 if (stack.Count() < 2)
1611 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1612 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1617 case opcodetype.OP_ADD:
1620 case opcodetype.OP_SUB:
1623 case opcodetype.OP_BOOLAND:
1624 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1626 case opcodetype.OP_BOOLOR:
1627 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1629 case opcodetype.OP_NUMEQUAL:
1630 bn = (bn1 == bn2) ? 1 : 0;
1632 case opcodetype.OP_NUMEQUALVERIFY:
1633 bn = (bn1 == bn2) ? 1 : 0;
1635 case opcodetype.OP_NUMNOTEQUAL:
1636 bn = (bn1 != bn2) ? 1 : 0;
1638 case opcodetype.OP_LESSTHAN:
1639 bn = (bn1 < bn2) ? 1 : 0;
1641 case opcodetype.OP_GREATERTHAN:
1642 bn = (bn1 > bn2) ? 1 : 0;
1644 case opcodetype.OP_LESSTHANOREQUAL:
1645 bn = (bn1 <= bn2) ? 1 : 0;
1647 case opcodetype.OP_GREATERTHANOREQUAL:
1648 bn = (bn1 >= bn2) ? 1 : 0;
1650 case opcodetype.OP_MIN:
1651 bn = (bn1 < bn2 ? bn1 : bn2);
1653 case opcodetype.OP_MAX:
1654 bn = (bn1 > bn2 ? bn1 : bn2);
1658 throw new StackMachineException("invalid opcode");
1662 popstack(ref stack);
1663 popstack(ref stack);
1664 stack.Add(bn.ToByteArray());
1666 if (opcode == opcodetype.OP_NUMEQUALVERIFY)
1668 if (CastToBool(stacktop(ref stack, -1)))
1670 popstack(ref stack);
1680 case opcodetype.OP_WITHIN:
1682 // (x min max -- out)
1683 if (stack.Count() < 3)
1685 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1686 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1687 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1688 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1689 popstack(ref stack);
1690 popstack(ref stack);
1691 popstack(ref stack);
1692 stack.Add(fValue ? vchTrue : vchFalse);
1700 case opcodetype.OP_RIPEMD160:
1701 case opcodetype.OP_SHA1:
1702 case opcodetype.OP_SHA256:
1703 case opcodetype.OP_HASH160:
1704 case opcodetype.OP_HASH256:
1707 if (stack.Count() < 1)
1709 IEnumerable<byte> vch = stacktop(ref stack, -1);
1710 IEnumerable<byte> vchHash = null;
1711 if (opcode == opcodetype.OP_RIPEMD160)
1713 RIPEMD160 hash = RIPEMD160.Compute160(vch);
1714 vchHash = hash.hashBytes;
1716 else if (opcode == opcodetype.OP_SHA1)
1718 SHA1 hash = SHA1.Compute1(vch);
1719 vchHash = hash.hashBytes;
1721 else if (opcode == opcodetype.OP_SHA256)
1723 SHA256 hash = SHA256.Compute256(vch);
1724 vchHash = hash.hashBytes;
1726 else if (opcode == opcodetype.OP_HASH160)
1728 Hash160 hash = Hash160.Compute160(vch);
1729 vchHash = hash.hashBytes;
1731 else if (opcode == opcodetype.OP_HASH256)
1733 Hash256 hash = Hash256.Compute256(vch);
1734 vchHash = hash.hashBytes;
1736 popstack(ref stack);
1741 case opcodetype.OP_CODESEPARATOR:
1743 // Hash starts after the code separator
1744 pbegincodehash = pc;
1748 case opcodetype.OP_CHECKSIG:
1749 case opcodetype.OP_CHECKSIGVERIFY:
1751 // (sig pubkey -- bool)
1752 if (stack.Count() < 2)
1757 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1758 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1760 // Subset of script starting at the most recent codeseparator
1761 CScript scriptCode = new CScript(script.Bytes.Skip(pbegincodehash.CurrentIndex));
1763 // There's no way for a signature to sign itself
1764 scriptCode.RemovePattern(sigBytes);
1766 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1768 popstack(ref stack);
1769 popstack(ref stack);
1770 stack.Add(fSuccess ? vchTrue : vchFalse);
1771 if (opcode == opcodetype.OP_CHECKSIGVERIFY)
1775 popstack(ref stack);
1785 case opcodetype.OP_CHECKMULTISIG:
1786 case opcodetype.OP_CHECKMULTISIGVERIFY:
1788 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1791 if (stack.Count() < i)
1796 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1797 if (nKeysCount < 0 || nKeysCount > 20)
1801 nOpCount += nKeysCount;
1808 if (stack.Count() < i)
1813 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1814 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1820 if (stack.Count() < i)
1825 // Subset of script starting at the most recent codeseparator
1826 CScript scriptCode = new CScript(script.Bytes.Skip(pbegincodehash.CurrentIndex));
1828 // There is no way for a signature to sign itself, so we need to drop the signatures
1829 for (int k = 0; k < nSigsCount; k++)
1831 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1832 scriptCode.RemovePattern(vchSig.ToList());
1835 bool fSuccess = true;
1836 while (fSuccess && nSigsCount > 0)
1838 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1839 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1842 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1852 // If there are more signatures left than keys left,
1853 // then too many signatures have failed
1854 if (nSigsCount > nKeysCount)
1862 popstack(ref stack);
1865 // A bug causes CHECKMULTISIG to consume one extra argument
1866 // whose contents were not checked in any way.
1868 // Unfortunately this is a potential source of mutability,
1869 // so optionally verify it is exactly equal to zero prior
1870 // to removing it from the stack.
1871 if (stack.Count() < 1)
1875 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1877 return false; // CHECKMULTISIG dummy argument not null
1879 popstack(ref stack);
1881 stack.Add(fSuccess ? vchTrue : vchFalse);
1883 if (opcode == opcodetype.OP_CHECKMULTISIGVERIFY)
1887 popstack(ref stack);
1902 if (stack.Count() + altstack.Count() > 1000)
1909 if (vfExec.Count() == 0)
1918 static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1920 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1923 if (pubKeyBytes.Count() < 33)
1924 return false; // Non-canonical public key: too short
1925 if (pubKeyBytes[0] == 0x04)
1927 if (pubKeyBytes.Count() != 65)
1928 return false; // Non-canonical public key: invalid length for uncompressed key
1930 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1932 if (pubKeyBytes.Count() != 33)
1933 return false; // Non-canonical public key: invalid length for compressed key
1937 return false; // Non-canonical public key: compressed nor uncompressed
1942 static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1950 static bool CheckSig(IList<byte> sigBytes, IList<byte> pubKeyBytes, CScript scriptCode, CTransaction txTo, int nIn, int nHashType, int flags)