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}) has no sense.", 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 ({1})", nDepth, stack.Count);
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)
1039 /// Cast argument to integer value
1041 /// <param name="value"></param>
1042 /// <returns></returns>
1043 private static BigInteger CastToBigInteger(IEnumerable<byte> value)
1045 if (value.Count() > 4)
1047 throw new StackMachineException("CastToBigInteger() : overflow");
1050 return new BigInteger(value.ToArray());
1053 static bool EvalScript(ref List<IEnumerable<byte>> stack, CScript script, CTransaction txTo, int nIn, int flags, int nHashType)
1055 ByteQueue pc = script.GetByteQUeue();
1057 ByteQueue pbegincodehash = script.GetByteQUeue();
1061 List<bool> vfExec = new List<bool>();
1062 List<IEnumerable<byte>> altstack = new List<IEnumerable<byte>>();
1064 byte[] vchFalse = new byte[0];
1065 byte[] vchTrue = new byte[] { 0x01 };
1067 if (script.Bytes.Count() > 10000)
1077 foreach (bool fValue in vfExec)
1089 IEnumerable<byte> pushArg;
1090 if (!GetOp(ref pc, out opcode, out pushArg))
1095 if (pushArg.Count() > 520) // Check against MAX_SCRIPT_ELEMENT_SIZE
1100 if (opcode > opcodetype.OP_16 && ++nOpCount > 201)
1105 if (fExec && 0 <= opcode && opcode <= opcodetype.OP_PUSHDATA4)
1107 // Push argument to stack
1110 else if (fExec || (opcodetype.OP_IF <= opcode && opcode <= opcodetype.OP_ENDIF))
1116 case opcodetype.OP_CAT:
1117 case opcodetype.OP_SUBSTR:
1118 case opcodetype.OP_LEFT:
1119 case opcodetype.OP_RIGHT:
1120 case opcodetype.OP_INVERT:
1121 case opcodetype.OP_AND:
1122 case opcodetype.OP_OR:
1123 case opcodetype.OP_XOR:
1124 case opcodetype.OP_2MUL:
1125 case opcodetype.OP_2DIV:
1126 case opcodetype.OP_MUL:
1127 case opcodetype.OP_DIV:
1128 case opcodetype.OP_MOD:
1129 case opcodetype.OP_LSHIFT:
1130 case opcodetype.OP_RSHIFT:
1136 case opcodetype.OP_1NEGATE:
1137 case opcodetype.OP_1:
1138 case opcodetype.OP_2:
1139 case opcodetype.OP_3:
1140 case opcodetype.OP_4:
1141 case opcodetype.OP_5:
1142 case opcodetype.OP_6:
1143 case opcodetype.OP_7:
1144 case opcodetype.OP_8:
1145 case opcodetype.OP_9:
1146 case opcodetype.OP_10:
1147 case opcodetype.OP_11:
1148 case opcodetype.OP_12:
1149 case opcodetype.OP_13:
1150 case opcodetype.OP_14:
1151 case opcodetype.OP_15:
1152 case opcodetype.OP_16:
1155 BigInteger bn = new BigInteger((int)opcode - (int)(opcodetype.OP_1 - 1));
1156 stack.Add(bn.ToByteArray());
1164 case opcodetype.OP_NOP:
1165 case opcodetype.OP_NOP1:
1166 case opcodetype.OP_NOP2:
1167 case opcodetype.OP_NOP3:
1168 case opcodetype.OP_NOP4:
1169 case opcodetype.OP_NOP5:
1170 case opcodetype.OP_NOP6:
1171 case opcodetype.OP_NOP7:
1172 case opcodetype.OP_NOP8:
1173 case opcodetype.OP_NOP9:
1174 case opcodetype.OP_NOP10:
1177 case opcodetype.OP_IF:
1178 case opcodetype.OP_NOTIF:
1180 // <expression> if [statements] [else [statements]] endif
1181 bool fValue = false;
1184 if (stack.Count() < 1)
1188 IEnumerable<byte> vch = stacktop(ref stack, -1);
1189 fValue = CastToBool(vch);
1190 if (opcode == opcodetype.OP_NOTIF)
1194 popstack(ref stack);
1200 case opcodetype.OP_ELSE:
1202 int nExecCount = vfExec.Count();
1203 if (nExecCount == 0)
1207 vfExec[nExecCount - 1] = !vfExec[nExecCount - 1];
1211 case opcodetype.OP_ENDIF:
1213 int nExecCount = vfExec.Count();
1214 if (nExecCount == 0)
1218 vfExec.RemoveAt(nExecCount - 1);
1222 case opcodetype.OP_VERIFY:
1225 // (false -- false) and return
1226 if (stack.Count() < 1)
1231 bool fValue = CastToBool(stacktop(ref stack, -1));
1234 popstack(ref stack);
1243 case opcodetype.OP_RETURN:
1248 case opcodetype.OP_TOALTSTACK:
1250 if (stack.Count() < 1)
1254 altstack.Add(stacktop(ref stack, -1));
1255 popstack(ref stack);
1259 case opcodetype.OP_FROMALTSTACK:
1261 if (altstack.Count() < 1)
1265 stack.Add(stacktop(ref stack, -1));
1266 popstack(ref altstack);
1270 case opcodetype.OP_2DROP:
1273 if (stack.Count() < 2)
1277 popstack(ref stack);
1278 popstack(ref stack);
1282 case opcodetype.OP_2DUP:
1284 // (x1 x2 -- x1 x2 x1 x2)
1285 if (stack.Count() < 2)
1289 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1290 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1296 case opcodetype.OP_3DUP:
1298 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
1299 if (stack.Count() < 3)
1303 IEnumerable<byte> vch1 = stacktop(ref stack, -3);
1304 IEnumerable<byte> vch2 = stacktop(ref stack, -2);
1305 IEnumerable<byte> vch3 = stacktop(ref stack, -1);
1312 case opcodetype.OP_2OVER:
1314 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
1315 if (stack.Count() < 4)
1319 IEnumerable<byte> vch1 = stacktop(ref stack, -4);
1320 IEnumerable<byte> vch2 = stacktop(ref stack, -3);
1326 case opcodetype.OP_2ROT:
1328 int nStackDepth = stack.Count();
1329 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
1330 if (nStackDepth < 6)
1334 IEnumerable<byte> vch1 = stacktop(ref stack, -6);
1335 IEnumerable<byte> vch2 = stacktop(ref stack, -5);
1336 stack.RemoveRange(nStackDepth - 6, 2);
1342 case opcodetype.OP_2SWAP:
1344 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
1345 int nStackDepth = stack.Count();
1346 if (nStackDepth < 4)
1350 stack.Swap(nStackDepth - 4, nStackDepth - 2);
1351 stack.Swap(nStackDepth - 3, nStackDepth - 1);
1355 case opcodetype.OP_IFDUP:
1358 if (stack.Count() < 1)
1363 IEnumerable<byte> vch = stacktop(ref stack, -1);
1365 if (CastToBool(vch))
1372 case opcodetype.OP_DEPTH:
1375 BigInteger bn = new BigInteger((ushort)stack.Count());
1376 stack.Add(bn.ToByteArray());
1380 case opcodetype.OP_DROP:
1383 if (stack.Count() < 1)
1388 popstack(ref stack);
1392 case opcodetype.OP_DUP:
1395 if (stack.Count() < 1)
1400 IEnumerable<byte> vch = stacktop(ref stack, -1);
1405 case opcodetype.OP_NIP:
1408 int nStackDepth = stack.Count();
1409 if (nStackDepth < 2)
1414 stack.RemoveAt(nStackDepth - 2);
1418 case opcodetype.OP_OVER:
1420 // (x1 x2 -- x1 x2 x1)
1421 if (stack.Count() < 2)
1426 IEnumerable<byte> vch = stacktop(ref stack, -2);
1431 case opcodetype.OP_PICK:
1432 case opcodetype.OP_ROLL:
1434 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
1435 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
1437 int nStackDepth = stack.Count();
1438 if (nStackDepth < 2)
1443 int n = (int)CastToBigInteger(stacktop(ref stack, -1));
1444 popstack(ref stack);
1446 if (n < 0 || n >= stack.Count())
1451 IEnumerable<byte> vch = stacktop(ref stack, -n - 1);
1452 if (opcode == opcodetype.OP_ROLL)
1454 stack.RemoveAt(nStackDepth - n - 1);
1461 case opcodetype.OP_ROT:
1463 // (x1 x2 x3 -- x2 x3 x1)
1464 // x2 x1 x3 after first swap
1465 // x2 x3 x1 after second swap
1466 int nStackDepth = stack.Count();
1467 if (nStackDepth < 3)
1471 stack.Swap(nStackDepth - 3, nStackDepth - 2);
1472 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1477 case opcodetype.OP_SWAP:
1480 int nStackDepth = stack.Count();
1481 if (nStackDepth < 2)
1485 stack.Swap(nStackDepth - 2, nStackDepth - 1);
1489 case opcodetype.OP_TUCK:
1491 // (x1 x2 -- x2 x1 x2)
1492 int nStackDepth = stack.Count();
1493 if (nStackDepth < 2)
1497 IEnumerable<byte> vch = stacktop(ref stack, -1);
1498 stack.Insert(nStackDepth - 2, vch);
1503 case opcodetype.OP_SIZE:
1506 if (stack.Count() < 1)
1511 BigInteger bnSize = new BigInteger((ushort)stacktop(ref stack, -1).Count());
1512 stack.Add(bnSize.ToByteArray());
1520 case opcodetype.OP_EQUAL:
1521 case opcodetype.OP_EQUALVERIFY:
1522 //case opcodetype.OP_NOTEQUAL: // use OP_NUMNOTEQUAL
1525 if (stack.Count() < 2)
1530 IEnumerable<byte> vch1 = stacktop(ref stack, -2);
1531 IEnumerable<byte> vch2 = stacktop(ref stack, -1);
1532 bool fEqual = (vch1 == vch2);
1533 // OP_NOTEQUAL is disabled because it would be too easy to say
1534 // something like n != 1 and have some wiseguy pass in 1 with extra
1535 // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001)
1536 //if (opcode == opcodetype.OP_NOTEQUAL)
1537 // fEqual = !fEqual;
1538 popstack(ref stack);
1539 popstack(ref stack);
1540 stack.Add(fEqual ? vchTrue : vchFalse);
1542 if (opcode == opcodetype.OP_EQUALVERIFY)
1546 popstack(ref stack);
1560 case opcodetype.OP_1ADD:
1561 case opcodetype.OP_1SUB:
1562 case opcodetype.OP_NEGATE:
1563 case opcodetype.OP_ABS:
1564 case opcodetype.OP_NOT:
1565 case opcodetype.OP_0NOTEQUAL:
1568 if (stack.Count() < 1)
1573 BigInteger bn = CastToBigInteger(stacktop(ref stack, -1));
1576 case opcodetype.OP_1ADD:
1579 case opcodetype.OP_1SUB:
1582 case opcodetype.OP_NEGATE:
1585 case opcodetype.OP_ABS:
1586 bn = BigInteger.Abs(bn);
1588 case opcodetype.OP_NOT:
1589 bn = bn == 0 ? 1 : 0;
1591 case opcodetype.OP_0NOTEQUAL:
1592 bn = bn != 0 ? 1 : 0;
1596 throw new StackMachineException("invalid opcode");
1600 popstack(ref stack);
1601 stack.Add(bn.ToByteArray());
1605 case opcodetype.OP_ADD:
1606 case opcodetype.OP_SUB:
1607 case opcodetype.OP_BOOLAND:
1608 case opcodetype.OP_BOOLOR:
1609 case opcodetype.OP_NUMEQUAL:
1610 case opcodetype.OP_NUMEQUALVERIFY:
1611 case opcodetype.OP_NUMNOTEQUAL:
1612 case opcodetype.OP_LESSTHAN:
1613 case opcodetype.OP_GREATERTHAN:
1614 case opcodetype.OP_LESSTHANOREQUAL:
1615 case opcodetype.OP_GREATERTHANOREQUAL:
1616 case opcodetype.OP_MIN:
1617 case opcodetype.OP_MAX:
1620 if (stack.Count() < 2)
1625 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -2));
1626 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -1));
1631 case opcodetype.OP_ADD:
1634 case opcodetype.OP_SUB:
1637 case opcodetype.OP_BOOLAND:
1638 bn = (bn1 != 0 && bn2 != 0) ? 1 : 0;
1640 case opcodetype.OP_BOOLOR:
1641 bn = (bn1 != 0 || bn2 != 0) ? 1 : 0;
1643 case opcodetype.OP_NUMEQUAL:
1644 bn = (bn1 == bn2) ? 1 : 0;
1646 case opcodetype.OP_NUMEQUALVERIFY:
1647 bn = (bn1 == bn2) ? 1 : 0;
1649 case opcodetype.OP_NUMNOTEQUAL:
1650 bn = (bn1 != bn2) ? 1 : 0;
1652 case opcodetype.OP_LESSTHAN:
1653 bn = (bn1 < bn2) ? 1 : 0;
1655 case opcodetype.OP_GREATERTHAN:
1656 bn = (bn1 > bn2) ? 1 : 0;
1658 case opcodetype.OP_LESSTHANOREQUAL:
1659 bn = (bn1 <= bn2) ? 1 : 0;
1661 case opcodetype.OP_GREATERTHANOREQUAL:
1662 bn = (bn1 >= bn2) ? 1 : 0;
1664 case opcodetype.OP_MIN:
1665 bn = (bn1 < bn2 ? bn1 : bn2);
1667 case opcodetype.OP_MAX:
1668 bn = (bn1 > bn2 ? bn1 : bn2);
1672 throw new StackMachineException("invalid opcode");
1676 popstack(ref stack);
1677 popstack(ref stack);
1678 stack.Add(bn.ToByteArray());
1680 if (opcode == opcodetype.OP_NUMEQUALVERIFY)
1682 if (CastToBool(stacktop(ref stack, -1)))
1684 popstack(ref stack);
1694 case opcodetype.OP_WITHIN:
1696 // (x min max -- out)
1697 if (stack.Count() < 3)
1699 BigInteger bn1 = CastToBigInteger(stacktop(ref stack, -3));
1700 BigInteger bn2 = CastToBigInteger(stacktop(ref stack, -2));
1701 BigInteger bn3 = CastToBigInteger(stacktop(ref stack, -1));
1702 bool fValue = (bn2 <= bn1 && bn1 < bn3);
1703 popstack(ref stack);
1704 popstack(ref stack);
1705 popstack(ref stack);
1706 stack.Add(fValue ? vchTrue : vchFalse);
1714 case opcodetype.OP_RIPEMD160:
1715 case opcodetype.OP_SHA1:
1716 case opcodetype.OP_SHA256:
1717 case opcodetype.OP_HASH160:
1718 case opcodetype.OP_HASH256:
1721 if (stack.Count() < 1)
1723 IEnumerable<byte> vch = stacktop(ref stack, -1);
1724 IEnumerable<byte> vchHash = null;
1725 if (opcode == opcodetype.OP_RIPEMD160)
1727 RIPEMD160 hash = RIPEMD160.Compute160(vch);
1728 vchHash = hash.hashBytes;
1730 else if (opcode == opcodetype.OP_SHA1)
1732 SHA1 hash = SHA1.Compute1(vch);
1733 vchHash = hash.hashBytes;
1735 else if (opcode == opcodetype.OP_SHA256)
1737 SHA256 hash = SHA256.Compute256(vch);
1738 vchHash = hash.hashBytes;
1740 else if (opcode == opcodetype.OP_HASH160)
1742 Hash160 hash = Hash160.Compute160(vch);
1743 vchHash = hash.hashBytes;
1745 else if (opcode == opcodetype.OP_HASH256)
1747 Hash256 hash = Hash256.Compute256(vch);
1748 vchHash = hash.hashBytes;
1750 popstack(ref stack);
1755 case opcodetype.OP_CODESEPARATOR:
1757 // Hash starts after the code separator
1758 pbegincodehash = pc;
1762 case opcodetype.OP_CHECKSIG:
1763 case opcodetype.OP_CHECKSIGVERIFY:
1765 // (sig pubkey -- bool)
1766 if (stack.Count() < 2)
1771 IList<byte> sigBytes = stacktop(ref stack, -2).ToList();
1772 IList<byte> pubkeyBytes = stacktop(ref stack, -1).ToList();
1774 // Subset of script starting at the most recent codeseparator
1775 CScript scriptCode = new CScript(script.Bytes.Skip(pbegincodehash.CurrentIndex));
1777 // There's no way for a signature to sign itself
1778 scriptCode.RemovePattern(sigBytes);
1780 bool fSuccess = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubkeyBytes.ToList(), flags) && CheckSig(sigBytes, pubkeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1782 popstack(ref stack);
1783 popstack(ref stack);
1784 stack.Add(fSuccess ? vchTrue : vchFalse);
1785 if (opcode == opcodetype.OP_CHECKSIGVERIFY)
1789 popstack(ref stack);
1799 case opcodetype.OP_CHECKMULTISIG:
1800 case opcodetype.OP_CHECKMULTISIGVERIFY:
1802 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
1805 if (stack.Count() < i)
1810 int nKeysCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1811 if (nKeysCount < 0 || nKeysCount > 20)
1815 nOpCount += nKeysCount;
1822 if (stack.Count() < i)
1827 int nSigsCount = (int)CastToBigInteger(stacktop(ref stack, -i));
1828 if (nSigsCount < 0 || nSigsCount > nKeysCount)
1834 if (stack.Count() < i)
1839 // Subset of script starting at the most recent codeseparator
1840 CScript scriptCode = new CScript(script.Bytes.Skip(pbegincodehash.CurrentIndex));
1842 // There is no way for a signature to sign itself, so we need to drop the signatures
1843 for (int k = 0; k < nSigsCount; k++)
1845 IEnumerable<byte> vchSig = stacktop(ref stack, -isig - k);
1846 scriptCode.RemovePattern(vchSig.ToList());
1849 bool fSuccess = true;
1850 while (fSuccess && nSigsCount > 0)
1852 IList<byte> sigBytes = stacktop(ref stack, -isig).ToList();
1853 IList<byte> pubKeyBytes = stacktop(ref stack, -ikey).ToList();
1856 bool fOk = IsCanonicalSignature(sigBytes, flags) && IsCanonicalPubKey(pubKeyBytes.ToList(), flags) && CheckSig(sigBytes, pubKeyBytes, scriptCode, txTo, nIn, nHashType, flags);
1866 // If there are more signatures left than keys left,
1867 // then too many signatures have failed
1868 if (nSigsCount > nKeysCount)
1876 popstack(ref stack);
1879 // A bug causes CHECKMULTISIG to consume one extra argument
1880 // whose contents were not checked in any way.
1882 // Unfortunately this is a potential source of mutability,
1883 // so optionally verify it is exactly equal to zero prior
1884 // to removing it from the stack.
1885 if (stack.Count() < 1)
1889 if ((flags & (int)scriptflag.SCRIPT_VERIFY_NULLDUMMY) != 0 && stacktop(ref stack, -1).Count() != 0)
1891 return false; // CHECKMULTISIG dummy argument not null
1893 popstack(ref stack);
1895 stack.Add(fSuccess ? vchTrue : vchFalse);
1897 if (opcode == opcodetype.OP_CHECKMULTISIGVERIFY)
1901 popstack(ref stack);
1916 if (stack.Count() + altstack.Count() > 1000)
1923 if (vfExec.Count() == 0)
1932 static bool IsCanonicalPubKey(IList<byte> pubKeyBytes, int flags)
1934 if ((flags & (int)scriptflag.SCRIPT_VERIFY_STRICTENC) == 0)
1937 if (pubKeyBytes.Count() < 33)
1938 return false; // Non-canonical public key: too short
1939 if (pubKeyBytes[0] == 0x04)
1941 if (pubKeyBytes.Count() != 65)
1942 return false; // Non-canonical public key: invalid length for uncompressed key
1944 else if (pubKeyBytes[0] == 0x02 || pubKeyBytes[0] == 0x03)
1946 if (pubKeyBytes.Count() != 33)
1947 return false; // Non-canonical public key: invalid length for compressed key
1951 return false; // Non-canonical public key: compressed nor uncompressed
1956 static bool IsCanonicalSignature(IList<byte> sigBytes, int flags)
1964 static bool CheckSig(IList<byte> sigBytes, IList<byte> pubKeyBytes, CScript scriptCode, CTransaction txTo, int nIn, int nHashType, int flags)