Exemplo n.º 1
0
        protected override void ReadDataXML(XElement ele, ElderScrollsPlugin master)
        {
            XElement subEle;

            ReadUnusedXML(ele, master);

            if (ele.TryPathTo("ReferenceCount", false, out subEle))
            {
                ReferenceCount = subEle.ToUInt32();
            }

            if (ele.TryPathTo("CompiledSize", false, out subEle))
            {
                CompiledSize = subEle.ToUInt32();
            }

            if (ele.TryPathTo("VariableCount", false, out subEle))
            {
                VariableCount = subEle.ToUInt32();
            }

            if (ele.TryPathTo("Type", false, out subEle))
            {
                Type = subEle.ToEnum <ScriptType>();
            }

            if (ele.TryPathTo("Flags", false, out subEle))
            {
                Flags = subEle.ToEnum <ScriptFlags>();
            }
        }
Exemplo n.º 2
0
        ///////////////////////////////////////////////////////////////////////

        #region Public Constructors
        public Debugger(
            bool isolated,
            string culture,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            AppDomain appDomain,
            IHost host,
            string libraryPath,
            StringList autoPathList
            )
        {
            interpreter = isolated ? DebuggerOps.CreateInterpreter(
                culture, createFlags, initializeFlags, scriptFlags,
                interpreterFlags, appDomain, host, libraryPath,
                autoPathList) : null;

            ReturnCode code;
            Result     error = null;

            code = Initialize(ref error);

            if (code != ReturnCode.Ok)
            {
                DebugOps.Complain(interpreter, code, error);
            }
        }
Exemplo n.º 3
0
        static void Main()
        {
            // 準備
            {
                GyoMetsu.Config.MainConfig.Setup();
                var scriptFrags = new ScriptFlags();

                {
                    if (ActionSkillDatas.Instance == null)
                    {
                        new ActionSkillDatas();
                    }
                    var datas = ActionSkillDatas.Instance;

                    var files = System.IO.Directory.GetFiles("data/script/action_skill/", "*.cs");

                    foreach (var i in files)
                    {
                        datas.Load(i);
                    }
                }
            }

            var data   = new Data.DataCreater();
            var script = new Emugen.Script.Script <StartScript>("data/script/init.cs", new StartScript());

            script.Run();

            var runner = new Emugen.OpenTK.Runner(script.api.Title);

            foreach (var action in script.api._Actions)
            {
                action(runner);
            }
        }
Exemplo n.º 4
0
        ///////////////////////////////////////////////////////////////////////

        public static Interpreter CreateInterpreter(
            string culture,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            AppDomain appDomain,
            IHost host,
            string libraryPath,
            StringList autoPathList,
            ref Result result
            )
        {
            //
            // NOTE: First, mask off flags that we know to be invalid for all
            //       debugger interpreters.  Next, add flags to force a cloned
            //       interpreter host to be created and used.  Finally, create
            //       an isolated debugging interpreter with the right set of
            //       options.
            //
            createFlags &= ~CreateFlags.NonDebuggerUse;
            createFlags |= CreateFlags.CloneHost;

            return(Interpreter.Create(
                       culture, createFlags, initializeFlags, scriptFlags,
                       interpreterFlags, appDomain, host, libraryPath,
                       autoPathList, ref result));
        }
Exemplo n.º 5
0
        ///////////////////////////////////////////////////////////////////////

        public static IScript Create(
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
            DateTime timeStamp,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(PrivateCreate(
                       Guid.Empty, name, group, description, type, text, fileName,
                       startLine, endLine, viaSource,
#if XML
                       XmlBlockType.None, timeStamp, null, null,
#endif
                       engineMode, scriptFlags, engineFlags, substitutionFlags,
                       eventFlags, expressionFlags, clientData));
        }
Exemplo n.º 6
0
        ///////////////////////////////////////////////////////////////////////

        #region Debugger Interpreter Support Methods
#if DEBUGGER
        public static Interpreter CreateInterpreter(
            string culture,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            AppDomain appDomain,
            IHost host,
            string libraryPath,
            StringList autoPathList
            )
        {
            Result result = null;

            Interpreter interpreter = CreateInterpreter(
                culture, createFlags, initializeFlags, scriptFlags,
                interpreterFlags, appDomain, host, libraryPath,
                autoPathList, ref result);

            if (interpreter == null)
            {
                DebugOps.Complain(interpreter, ReturnCode.Error, result);
            }

            return(interpreter);
        }
Exemplo n.º 7
0
        ///////////////////////////////////////////////////////////////////////

        /* NOTE: For use by [test2] and CreateSlaveInterpreter ONLY. */
        internal static InterpreterHelper Create(
            AppDomain appDomain,
            IEnumerable <string> args,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            string text,
            string libraryPath,
            StringList autoPathList,
            ref Result result
            )
        {
            if (appDomain == null)
            {
                result = "invalid application domain";
                return(null);
            }

            if (assemblyName == null)
            {
                result = "invalid assembly name";
                return(null);
            }

            if (typeName == null)
            {
                result = "invalid type name";
                return(null);
            }

            try
            {
                object[] ctorArgs =
                {
                    args,             createFlags, initializeFlags, scriptFlags,
                    interpreterFlags, text,        libraryPath,     autoPathList,
                    result
                };

                InterpreterHelper interpreterHelper =
                    (InterpreterHelper)appDomain.CreateInstanceAndUnwrap(
                        assemblyName.ToString(), typeName, false,
                        MarshalOps.PrivateCreateInstanceBindingFlags,
                        null, ctorArgs, null, null, null);

                //
                // NOTE: Grab the result as it may have been modified.
                //
                result = ctorArgs[ctorArgs.Length - 1] as Result;

                return(interpreterHelper);
            }
            catch (Exception e)
            {
                result = e;
            }

            return(null);
        }
Exemplo n.º 8
0
 public ScriptData(Byte[] Unused, UInt32 ReferenceCount, UInt32 CompiledSize, UInt32 VariableCount, ScriptType Type, ScriptFlags Flags)
 {
     this.Unused         = Unused;
     this.ReferenceCount = ReferenceCount;
     this.CompiledSize   = CompiledSize;
     this.VariableCount  = VariableCount;
     this.Type           = Type;
     this.Flags          = Flags;
 }
Exemplo n.º 9
0
 public ScriptData(string Tag = null)
     : base(Tag)
 {
     Unused         = new byte[4];
     ReferenceCount = new UInt32();
     CompiledSize   = new UInt32();
     VariableCount  = new UInt32();
     Type           = new ScriptType();
     Flags          = new ScriptFlags();
 }
Exemplo n.º 10
0
 public ScriptData(ScriptData copyObject)
 {
     if (copyObject.Unused != null)
     {
         Unused = (Byte[])copyObject.Unused.Clone();
     }
     ReferenceCount = copyObject.ReferenceCount;
     CompiledSize   = copyObject.CompiledSize;
     VariableCount  = copyObject.VariableCount;
     Type           = copyObject.Type;
     Flags          = copyObject.Flags;
 }
Exemplo n.º 11
0
        private bool VerifyTransaction
        (
            PublicKey publicKey,
            VarType signature,
            Script subScript,
            Amount amount,
            ScriptFlags flags = ScriptFlags.ENABLE_SIGHASH_FORKID
        )
        {
            var hashType = new SignatureHashType(signature.LastByte);
            var sigHash  = ComputeSignatureHash(subScript, _tx, _index, hashType, amount, flags);

            return(publicKey.Verify(sigHash, signature));
        }
Exemplo n.º 12
0
        ///////////////////////////////////////////////////////////////////////

        public static bool HasFlags(
            ScriptFlags flags,
            ScriptFlags hasFlags,
            bool all
            )
        {
            if (all)
            {
                return((flags & hasFlags) == hasFlags);
            }
            else
            {
                return((flags & hasFlags) != ScriptFlags.None);
            }
        }
Exemplo n.º 13
0
        ///////////////////////////////////////////////////////////////////////

        public static IDebugger Create(
            bool isolated,
            string culture,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            AppDomain appDomain,
            IHost host,
            string libraryPath,
            StringList autoPathList
            )
        {
            return(new Debugger(
                       isolated, culture, createFlags, initializeFlags, scriptFlags,
                       interpreterFlags, appDomain, host, libraryPath, autoPathList));
        }
Exemplo n.º 14
0
        ///////////////////////////////////////////////////////////////////////

        //
        // NOTE: For use by the associated InterpreterHelper.Create method
        //       overload ONLY.
        //
        private InterpreterHelper(
            IEnumerable <string> args,
            CreateFlags createFlags,
            InitializeFlags initializeFlags,
            ScriptFlags scriptFlags,
            InterpreterFlags interpreterFlags,
            string text,
            string libraryPath,
            StringList autoPathList,
            ref Result result
            )
        {
            interpreter = Interpreter.Create(
                args, createFlags, initializeFlags, scriptFlags,
                interpreterFlags, text, libraryPath, autoPathList,
                ref result);
        }
Exemplo n.º 15
0
            public TV2(params string[] args)
            {
                sig   = args[0];
                pub   = args[1];
                flags = args[2];
                error = args[3];

                scriptSig   = ScriptBuilder.ParseTestScript(sig).ToScript();
                scriptPub   = ScriptBuilder.ParseTestScript(pub).ToScript();
                scriptFlags = ScriptInterpreter.ParseFlags(flags);
                scriptError = ToScriptError(error);

                opcodes = scriptSig.Decode().Select(o => o.Code)
                          .Concat(scriptPub.Decode().Select(o => o.Code))
                          .Distinct()
                          .OrderBy(o => o).ToArray();

                keyopcode = opcodes.Length == 0 ? (Opcode?)null : opcodes.Last();
            }
Exemplo n.º 16
0
 protected override void ReadData(ESPReader reader)
 {
     using (MemoryStream stream = new MemoryStream(reader.ReadBytes(size)))
         using (ESPReader subReader = new ESPReader(stream, reader.Plugin))
         {
             try
             {
                 Unused         = subReader.ReadBytes(4);
                 ReferenceCount = subReader.ReadUInt32();
                 CompiledSize   = subReader.ReadUInt32();
                 VariableCount  = subReader.ReadUInt32();
                 Type           = subReader.ReadEnum <ScriptType>();
                 Flags          = subReader.ReadEnum <ScriptFlags>();
             }
             catch
             {
                 return;
             }
         }
 }
Exemplo n.º 17
0
        ///////////////////////////////////////////////////////////////////////

        private static IScript PrivateCreate(
            Guid id,
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
#if XML
            XmlBlockType blockType,
            DateTime timeStamp,
            string publicKeyToken,
            byte[] signature,
#endif
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(new Script(
                       id, name, group, description, type, text, fileName,
                       startLine, endLine, viaSource,
#if XML
                       blockType, timeStamp, publicKeyToken, signature,
#endif
#if CAS_POLICY
                       DefaultEvidence,
                       DefaultHashValue,
                       DefaultHashAlgorithm,
#endif
                       engineMode, scriptFlags, engineFlags, substitutionFlags,
                       eventFlags, expressionFlags, clientData));
        }
Exemplo n.º 18
0
        ///////////////////////////////////////////////////////////////////////

        public static IScript Create(
            string name,
            string group,
            string description,
            string type,
            string text,
            DateTime timeStamp,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            return(Create(
                       name, group, description, type, text, null, Parser.UnknownLine,
                       Parser.UnknownLine, false, timeStamp, engineMode, scriptFlags,
                       engineFlags, substitutionFlags, eventFlags, expressionFlags,
                       clientData));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Modeled on Bitcoin-SV interpreter.cpp 0.1.1 lines 1866-1945
        /// </summary>
        /// <param name="scriptSig"></param>
        /// <param name="scriptPub"></param>
        /// <param name="flags"></param>
        /// <param name="checker"></param>
        /// <param name="error"></param>
        /// <returns></returns>
        public static bool VerifyScript(Script scriptSig, Script scriptPub, ScriptFlags flags, SignatureCheckerBase checker, out ScriptError error)
        {
            SetError(out error, ScriptError.UNKNOWN_ERROR);

            if ((flags & ScriptFlags.ENABLE_SIGHASH_FORKID) != 0)
            {
                flags |= ScriptFlags.VERIFY_STRICTENC;
            }

            if ((flags & ScriptFlags.VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly())
            {
                return(SetError(out error, ScriptError.SIG_PUSHONLY));
            }

            var evaluator = new ScriptEvaluator();

            return(evaluator switch
            {
                _ when !evaluator.EvalScript(scriptSig, flags, checker, out error) => false,
                _ when !evaluator.EvalScript(scriptPub, flags, checker, out error) => false,
                _ when evaluator.Count == 0 => SetError(out error, ScriptError.EVAL_FALSE),
                _ when !evaluator.Peek() => SetError(out error, ScriptError.EVAL_FALSE),
                _ => SetSuccess(out error)
            });
Exemplo n.º 20
0
        public bool TryImportScript(string scriptText, UPath scriptPath, IDynamicObject scriptObject, ScriptFlags flags, out object result, TemplateContext context = null)
        {
            if (scriptText == null)
            {
                throw new ArgumentNullException(nameof(scriptText));
            }
            if (scriptPath == null)
            {
                throw new ArgumentNullException(nameof(scriptPath));
            }
            if (scriptObject == null)
            {
                throw new ArgumentNullException(nameof(scriptObject));
            }

            result  = null;
            context = context ?? new TemplateContext(Builtins);

            var scriptResult = ParseScript(scriptText, scriptPath.FullName, ScriptMode.ScriptOnly);

            if (!scriptResult.HasErrors)
            {
                if ((flags & ScriptFlags.AllowSiteFunctions) != 0)
                {
                    context.PushGlobal(SiteFunctions);
                }

                context.PushGlobal((ScriptObject)scriptObject);
                context.PushSourceFile(scriptPath.FullName);
                context.EnableOutput   = false;
                context.TemplateLoader = (flags & ScriptFlags.AllowSiteFunctions) != 0 ? unauthorizedTemplateLoader : new TemplateLoaderFromIncludes(Site);

                try
                {
                    result = scriptResult.Template.Evaluate(context);
                }
                catch (ScriptRuntimeException exception)
                {
                    LogException(exception);
                    return(false);
                }
                finally
                {
                    context.PopSourceFile();
                    context.PopGlobal();
                    if ((flags & ScriptFlags.AllowSiteFunctions) != 0)
                    {
                        context.PopGlobal();
                    }
                }
                return(true);
            }
            return(false);
        }
Exemplo n.º 21
0
        ///////////////////////////////////////////////////////////////////////

        #region Private Constructors
        private Script(
            Guid id,
            string name,
            string group,
            string description,
            string type,
            string text,
            string fileName,
            int startLine,
            int endLine,
            bool viaSource,
#if XML
            XmlBlockType blockType,
            DateTime timeStamp,
            string publicKeyToken,
            byte[] signature,
#endif
#if CAS_POLICY
            Evidence evidence,
            byte[] hashValue,
            HashAlgorithm hashAlgorithm,
#endif
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData
            )
        {
            this.kind        = IdentifierKind.Script;
            this.id          = id;
            this.name        = name;
            this.group       = group;
            this.description = description;
            this.type        = type;
            this.parts       = null; /* TODO: If we ever support scripts with multiple
                                      *       parts, change this to be a formal argument
                                      *       to this constructor and remove text? */
            this.text        = text;
            this.fileName    = fileName;
            this.startLine   = startLine;
            this.endLine     = endLine;
            this.viaSource   = viaSource;

#if XML
            this.blockType      = blockType;
            this.timeStamp      = timeStamp;
            this.publicKeyToken = publicKeyToken;
            this.signature      = signature;
#endif

#if CAS_POLICY
            this.evidence      = evidence;
            this.hashValue     = hashValue;
            this.hashAlgorithm = hashAlgorithm;
#endif

            this.engineMode        = engineMode;
            this.scriptFlags       = scriptFlags;
            this.engineFlags       = engineFlags;
            this.substitutionFlags = substitutionFlags;
            this.expressionFlags   = expressionFlags;
            this.eventFlags        = eventFlags;
            this.clientData        = clientData;
        }
Exemplo n.º 22
0
        ///////////////////////////////////////////////////////////////////////

#if XML
        /* INTERNAL STATIC OK */
        internal static IScript CreateFromXmlNode( /* NOTE: Engine use only. */
            string type,
            XmlNode node,
            EngineMode engineMode,
            ScriptFlags scriptFlags,
            EngineFlags engineFlags,
            SubstitutionFlags substitutionFlags,
            EventFlags eventFlags,
            ExpressionFlags expressionFlags,
            IClientData clientData,
            ref Result error
            )
        {
            try
            {
                XmlElement element = node as XmlElement;

                if (element != null)
                {
                    foreach (string attribute in _XmlAttribute.RequiredList)
                    {
                        if ((attribute != null) && !element.HasAttribute(attribute))
                        {
                            error = String.Format(
                                "missing required attribute \"{0}\"",
                                attribute);

                            return(null);
                        }
                    }

                    /* REQUIRED */
                    Guid id = element.HasAttribute(_XmlAttribute.Id) ?
                              new Guid(element.GetAttribute(_XmlAttribute.Id)) : Guid.Empty;

                    /* REQUIRED */
                    XmlBlockType blockType = element.HasAttribute(_XmlAttribute.Type) ?
                                             (XmlBlockType)Enum.Parse(typeof(XmlBlockType),
                                                                      element.GetAttribute(_XmlAttribute.Type), true) :
                                             XmlBlockType.None;

                    /* REQUIRED */
                    string text = element.InnerText;

                    /* OPTIONAL */
                    string name = element.HasAttribute(_XmlAttribute.Name) ?
                                  element.GetAttribute(_XmlAttribute.Name) : null;

                    /* OPTIONAL */
                    string group = element.HasAttribute(_XmlAttribute.Group) ?
                                   element.GetAttribute(_XmlAttribute.Group) : null;

                    /* OPTIONAL */
                    string description = element.HasAttribute(_XmlAttribute.Description) ?
                                         element.GetAttribute(_XmlAttribute.Description) : null;

                    /* OPTIONAL */
                    DateTime timeStamp = element.HasAttribute(_XmlAttribute.TimeStamp) ?
                                         DateTime.Parse(element.GetAttribute(_XmlAttribute.TimeStamp)).ToUniversalTime() :
                                         DateTime.MinValue;

                    /* OPTIONAL */
                    string publicKeyToken = element.HasAttribute(_XmlAttribute.PublicKeyToken) ?
                                            element.GetAttribute(_XmlAttribute.PublicKeyToken) : null;

                    /* OPTIONAL */
                    byte[] signature = element.HasAttribute(_XmlAttribute.Signature) ?
                                       Convert.FromBase64String(
                        element.GetAttribute(_XmlAttribute.Signature)) : null;

                    //
                    // NOTE: Create the script using the values extracted from the XML element.
                    //
                    return(PrivateCreate(
                               id, name, group, description, type, text, null, Parser.UnknownLine,
                               Parser.UnknownLine, false, blockType, timeStamp, publicKeyToken,
                               signature, engineMode, scriptFlags, engineFlags, substitutionFlags,
                               eventFlags, expressionFlags, clientData));
                }
                else
                {
                    error = "xml node is not an element";
                }
            }
            catch (Exception e)
            {
                error = e;
            }

            return(null);
        }
Exemplo n.º 23
0
 public XenkoScriptAttribute(ScriptFlags flags = ScriptFlags.None)
 {
     this.Flags = flags;
 }
Exemplo n.º 24
0
        public bool TryImportScriptFromFile(FileEntry scriptPath, IDynamicObject scriptObject, ScriptFlags flags, out object result, TemplateContext context = null)
        {
            if (scriptPath == null)
            {
                throw new ArgumentNullException(nameof(scriptPath));
            }
            if (scriptObject == null)
            {
                throw new ArgumentNullException(nameof(scriptObject));
            }
            result = null;

            var scriptExist = scriptPath.Exists;

            if ((flags & ScriptFlags.Expect) != 0)
            {
                if (!scriptExist)
                {
                    Site.Error($"Config file [{scriptPath}] does not exist");
                    return(false);
                }
            }

            if (scriptExist)
            {
                var configAsText = scriptPath.ReadAllText();
                return(TryImportScript(configAsText, scriptPath.Path, scriptObject, flags, out result, context));
            }
            return(true);
        }
Exemplo n.º 25
0
 public bool TryImportScriptStatement(string scriptStatement, IDynamicObject scriptObject, ScriptFlags flags, out object result, TemplateContext context = null)
 {
     if (scriptStatement == null)
     {
         throw new ArgumentNullException(nameof(scriptStatement));
     }
     if (scriptObject == null)
     {
         throw new ArgumentNullException(nameof(scriptObject));
     }
     return(TryImportScript(scriptStatement, "__script__", scriptObject, flags, out result, context));
 }
Exemplo n.º 26
0
 public XenkoScriptAttribute(ScriptFlags flags = ScriptFlags.None)
 {
     this.Flags = flags;
 }
Exemplo n.º 27
0
 public ParadoxScriptAttribute(ScriptFlags flags = ScriptFlags.None)
 {
     this.Flags = flags;
 }
Exemplo n.º 28
0
        ///////////////////////////////////////////////////////////////////////

        #region Control Event Handlers
        private void btnRun_Click(
            object sender,
            EventArgs e
            )
        {
            EnableControls(false);

            ReturnCode code;

            ScriptFlags scriptFlags = ScriptFlags.UserRequiredFile;
            IClientData clientData  = ClientData.Empty;

            Result result = null;

            code = interpreter.GetScript(
                CommonOps.ProgressScriptName, ref scriptFlags, ref clientData,
                ref result);

            if (code == ReturnCode.Ok)
            {
                string text = result;

                if (Utility.HasFlags(scriptFlags, ScriptFlags.File, true))
                {
                    code = Engine.ReadScriptFile(
                        interpreter, text, ref text, ref result);
                }

                if (code == ReturnCode.Ok)
                {
                    code = interpreter.SetArguments(
                        new StringList(arguments), ref result);

                    if (code == ReturnCode.Ok)
                    {
                        code = interpreter.QueueScript(
                            Utility.GetUtcNow(), text, ref result);

                        if (code == ReturnCode.Ok)
                        {
                            //
                            // NOTE: Set the internal script (for tracking
                            //       purposes) to the script we just queued.
                            //
                            script = result;

#if !DAEMON
                            //
                            // NOTE: Start asynchronously processing queued
                            //       events in the interpreter until the queue
                            //       is empty if we are already processing
                            //       events due to being in dedicated daemon
                            //       mode (i.e. if DAEMON is defined).
                            //
                            /* IGNORED */
                            Engine.QueueWorkItem(
                                interpreter, AsyncProcessEvents, false);
#endif
                        }
                    }
                }
            }

            if (code != ReturnCode.Ok)
            {
                CommonOps.Complain(code, result);
            }
        }
Exemplo n.º 29
0
 public virtual bool CheckSignature(VarType scriptSig, VarType vchPubKey, Script script, ScriptFlags flags) => false;
Exemplo n.º 30
0
        public static UInt256 ComputeSignatureHash
        (
            Script scriptCode,
            Transaction txTo,
            int nIn,
            SignatureHashType sigHashType,
            Amount amount,
            ScriptFlags flags = ScriptFlags.ENABLE_SIGHASH_FORKID
        )
        {
            if (sigHashType.HasForkId && (flags & ScriptFlags.ENABLE_SIGHASH_FORKID) != 0)
            {
                var hashPrevOuts = new UInt256();
                var hashSequence = new UInt256();
                var hashOutputs  = new UInt256();

                if (!sigHashType.HasAnyoneCanPay)
                {
                    hashPrevOuts = GetPrevOutHash(txTo);
                }

                var baseNotSingleOrNone =
                    (sigHashType.GetBaseType() != BaseSignatureHashEnum.Single) &&
                    (sigHashType.GetBaseType() != BaseSignatureHashEnum.None);

                if (!sigHashType.HasAnyoneCanPay && baseNotSingleOrNone)
                {
                    hashSequence = GetSequenceHash(txTo);
                }

                if (baseNotSingleOrNone)
                {
                    hashOutputs = GetOutputsHash(txTo);
                }
                else if (sigHashType.GetBaseType() == BaseSignatureHashEnum.Single && nIn < txTo.Outputs.Length)
                {
                    using var hw = new HashWriter();
                    hw.Add(txTo.Outputs[nIn]);
                    hashOutputs = hw.GetHashFinal();
                }

                using var writer = new HashWriter();
                writer
                // Version
                .Add(txTo.Version)
                // Input prevouts/nSequence (none/all, depending on flags)
                .Add(hashPrevOuts)
                .Add(hashSequence)
                // The input being signed (replacing the scriptSig with scriptCode +
                // amount). The prevout may already be contained in hashPrevout, and the
                // nSequence may already be contain in hashSequence.
                .Add(txTo.Inputs[nIn].PrevOut)
                .Add(scriptCode)
                .Add(amount)
                .Add(txTo.Inputs[nIn].Sequence)
                // Outputs (none/one/all, depending on flags)
                .Add(hashOutputs)
                // Locktime
                .Add(txTo.LockTime)
                // Sighash type
                .Add(sigHashType.RawSigHashType);

                return(writer.GetHashFinal());
            }

            if (nIn >= txTo.Inputs.Length)
            {
                //  nIn out of range
                return(UInt256.One);
            }

            // Check for invalid use of SIGHASH_SINGLE
            if (sigHashType.GetBaseType() == BaseSignatureHashEnum.Single && nIn >= txTo.Outputs.Length)
            {
                //  nOut out of range
                return(UInt256.One);
            }

            {
                // Original digest algorithm...
                var hasAnyoneCanPay = sigHashType.HasAnyoneCanPay;
                // ReSharper disable once UnusedVariable
                var numberOfInputs = hasAnyoneCanPay ? 1 : txTo.Inputs.Length;
                using var writer = new HashWriter();
                // Start with the version...
                writer.Add(txTo.Version);
                // Add Input(s)...
                if (hasAnyoneCanPay)
                {
                    // AnyoneCanPay serializes only the input being signed.
                    var i = txTo.Inputs[nIn];
                    writer
                    .Add((byte)1)
                    .Add(i.PrevOut)
                    .Add(scriptCode, true)
                    .Add(i.Sequence);
                }
                else
                {
                    // Non-AnyoneCanPay case. Process all inputs but handle input being signed in its own way.
                    var isSingleOrNone = sigHashType.IsBaseSingle || sigHashType.IsBaseNone;
                    writer.Add(txTo.Inputs.Length.AsVarIntBytes());
                    for (var nInput = 0; nInput < txTo.Inputs.Length; nInput++)
                    {
                        var i = txTo.Inputs[nInput];
                        writer.Add(i.PrevOut);
                        if (nInput != nIn)
                        {
                            writer.Add(Script.None);
                        }
                        else
                        {
                            writer.Add(scriptCode, true);
                        }
                        if (nInput != nIn && isSingleOrNone)
                        {
                            writer.Add(0);
                        }
                        else
                        {
                            writer.Add(i.Sequence);
                        }
                    }
                }
                // Add Output(s)...
                var nOutputs = sigHashType.IsBaseNone ? 0 : sigHashType.IsBaseSingle ? nIn + 1 : txTo.Outputs.Length;
                writer.Add(nOutputs.AsVarIntBytes());
                for (var nOutput = 0; nOutput < nOutputs; nOutput++)
                {
                    if (sigHashType.IsBaseSingle && nOutput != nIn)
                    {
                        writer.Add(TxOut.Null);
                    }
                    else
                    {
                        writer.Add(txTo.Outputs[nOutput]);
                    }
                }
                // Finish up...
                writer
                .Add(txTo.LockTime)
                .Add(sigHashType.RawSigHashType)
                ;
                return(writer.GetHashFinal());
            }
        }
Exemplo n.º 31
0
        public override bool CheckSignature(VarType scriptSig, VarType vchPubKey, Script script, ScriptFlags flags)
        {
            if (scriptSig?.IsEmpty ?? false)
            {
                return(false);
            }
            if (vchPubKey?.IsEmpty ?? false)
            {
                return(false);
            }
            var publicKey = new PublicKey(vchPubKey);

            return(publicKey.IsValid && VerifyTransaction(publicKey, scriptSig, script, _amount));
        }
Exemplo n.º 32
0
 public StrideScriptAttribute(ScriptFlags flags = ScriptFlags.None)
 {
     this.Flags = flags;
 }