public SendOrPostCallbackItem(SendOrPostCallback callback,
     object state, ExecutionType type)
 {
     _method = callback;
     _state = state;
     _exeType = type;
 }
 internal SendOrPostCallbackItem(SendOrPostCallback callback,
    object state, ExecutionType type)
 {
     mMethod = callback;
     mState = state;
     mExeType = type;
 }
		public bool ExecuteWrite (ExecutionType type, Transaction transaction)
		{
			if (type == ExecutionType.OnlyOnce) {
				return DoWrite(transaction.Isolateds, transaction.Action);
			} else {
				while (!DoWrite(transaction.Isolateds, transaction.Action));
			}
			
			return true;
		}
        public AndParallelExecution(ParallelExecutionContext executionContext)
        {
            _executionContext = executionContext;
            _executionContext.ExecutionCompleted += delegate
                {
                    if (ExecutionCompleted != null)
                        ExecutionCompleted();
                };

            ThenExecute = new ExecutionType(_executionContext);
        }
Example #5
0
        /// <summary>
        /// Prefered Constructor
        /// </summary>
        /// <param name="traceLine">The Line in the trace file containing the instruction</param>
        public Instruction(string traceLine)
        {
            string[] tokens = traceLine.Split(' ');

            this.address = int.Parse(tokens[0]);
            this.instruction = tokens[1];

            this.executionType = getExecutionType(tokens[1]);

            // Nop instructions have no arguments
            if (this.executionType != ExecutionType.Nop)
                this.setArguments(tokens[2]);
        }
Example #6
0
        public string ToString(ExecutionType execution)
        {
            StringBuilder builder = new StringBuilder();

            List<IModule> modules = ReferenceHelper.SortModulesByReference(Modules);
            for (int i = modules.Count - 1; i >= 0; i--)
            {
                if (EnumHelpers.ExecutionTypeMatchesRequirement(execution, modules[i].Execution))
                {
                    builder.AppendLine(IModuleToPrjLine(modules[i]));
                }
            }

            return builder.ToString();
        }
Example #7
0
 public static bool ExecutionTypeMatchesRequirement(ExecutionType requirement, ExecutionType current)
 {
     if (requirement == ExecutionType.All)
     {
         return true;
     }
     else if (requirement == ExecutionType.SimulationOnly && current == ExecutionType.SimulationOnly || current == ExecutionType.All)
     {
         return true;
     }
     else if (requirement == ExecutionType.SynthesisOnly && current == ExecutionType.SynthesisOnly || current == ExecutionType.All)
     {
         return true;
     }
     return false;
 }
Example #8
0
 public async ValueTask QueueAsync(Func <IServiceScopeFactory, CancellationToken, ValueTask> task, ExecutionType executionType = ExecutionType.Await)
 => await _queue.Writer.WriteAsync(new BackgroundTask(task, executionType));
 public void ReportAction(Int64 gas, UInt256 value, Address from, Address?to, ReadOnlyMemory <Byte> input, ExecutionType callType, Boolean isPrecompileCall = false)
 {
 }
Example #10
0
 public void ReportAction(long gas, UInt256 value, Address @from, Address to, byte[] input, ExecutionType callType, bool isPrecompileCall = false)
 {
     _currentTxTracer.ReportAction(gas, value, @from, to, input, callType, isPrecompileCall);
 }
Example #11
0
 private Task <object> ExecuteAsync(ExecutionType executionType, CommandType commandType, string commandText, IsolationLevel isolationLevel,
                                    SqlParameter[] parameters)
 {
     return(ExecuteAsync <object>(executionType, commandType, commandText, isolationLevel, parameters));
 }
Example #12
0
 public async Task <int> ExecuteNonQueryAsync(ExecutionType executionType, CommandType commandType, string commandText, IsolationLevel isolationLevel, params SqlParameter[] parameters)
 {
     return((int) await ExecuteAsync(executionType, commandType, commandText, isolationLevel, parameters).ConfigureAwait(false));
 }
 public void ReportAction(long gas, UInt256 value, Address @from, Address to, byte[] input, ExecutionType callType, bool isPrecompileCall = false)
 {
 }
Example #14
0
        private void ProcessArguments(string[] args)
        {
            for (int index = 0; index < args.Length; ++index)
            {
                var arg      = args[index];
                var moreArgs = index < args.Length - 1;

                if ((arg == "-a" || arg == "--assembly") && moreArgs)
                {
                    string assemblyName = args[++index];
                    _assemblies.Add(assemblyName);
                }
                else if ((arg == "-b" || arg == "--benchmark") && moreArgs)
                {
                    string benchmark = args[++index];
                    _benchmarks.Add(benchmark);
                }
                else if ((arg == "-p" || arg == "--param") && moreArgs)
                {
                    string param = args[++index];
                    int    pos   = param.IndexOf('=');
                    string key   = pos > 0 ? param.Substring(0, pos) : param;
                    string value = pos > 0 ? param.Substring(pos + 1) : null;
                    _parameters[param] = value;
                }
                else if ((arg == "-c" || arg == "--config") && moreArgs)
                {
                    _configurationFile = args[++index];
                }
                else if ((arg == "-r" || arg == "--report") && moreArgs)
                {
                    _reportFile = args[++index];
                }
                else if ((arg == "-d" || arg == "--duration") && moreArgs)
                {
                    _duration = Converter.StringToInteger(args[++index], 60);
                }
                else if ((arg == "-m" || arg == "--measure") && moreArgs)
                {
                    _measurementType = args[++index].ToLowerInvariant() == "nominal"
                        ? MeasurementType.Nominal : MeasurementType.Peak;
                }
                else if ((arg == "-e" || arg == "--execute") && moreArgs)
                {
                    var execution = args[++index].ToLowerInvariant();
                    _executionType = execution == "seq" || execution == "sequential"
                        ? ExecutionType.Sequential : ExecutionType.Proportional;
                }
                else if ((arg == "-n" || arg == "--nominal") && moreArgs)
                {
                    _nominalRate = Converter.StringToDouble(args[++index], 1);
                }
                else if (arg == "-f" || arg == "--force")
                {
                    _forceContinue = true;
                }
                else if (arg == "-h" || arg == "--help")
                {
                    _showHelp = true;
                }
                else if (arg == "-B" || arg == "--show-benchmarks")
                {
                    _showBenchmarks = true;
                }
                else if (arg == "-P" || arg == "--show-params")
                {
                    _showParameters = true;
                }
                else if (arg == "-e" || arg == "--environment")
                {
                    _benchmarkEnvironment = true;
                }
            }
        }
        public void ReportCall(long gas, UInt256 value, Address @from, Address to, byte[] input, ExecutionType callType)
        {
            ParityTraceAction action = new ParityTraceAction();

            action.From     = @from;
            action.To       = to;
            action.Value    = value;
            action.Input    = input;
            action.Gas      = gas;
            action.CallType = GetCallType(callType);

            PushCall(action);
        }
Example #16
0
 internal SendOrPostCallbackItem(SendOrPostCallback callback, object state, ExecutionType type)
 {
     _method        = callback;
     _state         = state;
     _executionType = type;
 }
Example #17
0
 public TransactionAction(Int64 gas, UInt256 value, Address from, Address?to, ReadOnlyMemory <Byte> input, ExecutionType callType, Boolean isPrecompileCall) => (this.Gas, this.Value, this.From, this.To, this.Input, this.CallType, this.IsPrecompileCall) = (gas, value, from, to, input.ToArray(), callType, isPrecompileCall);
Example #18
0
        public async Task <HttpOperationResponse <ODataValueOfIEnumerableOfJobDto> > StartJob(string inputArgs, string jobNameSearchTerm, ExecutionType executionType = ExecutionType.Background)
        {
            await InitializeHeaders();

            var jobsStartJobsParameters = new Dictionary <long?, JobsStartJobsParameters>();

            switch (executionType)
            {
            case ExecutionType.Foreground:
                jobsStartJobsParameters = await BuildStartJobParameters(inputArgs, jobNameSearchTerm, "Personal", "KD2ME87R");

                break;

            case ExecutionType.Background:
                jobsStartJobsParameters = await BuildStartJobParameters(inputArgs, jobNameSearchTerm);

                break;

            default:
                jobsStartJobsParameters = await BuildStartJobParameters(inputArgs, jobNameSearchTerm);

                break;
            }

            // Start job
            return(await _uiPathWebApi110.Jobs.StartJobsWithHttpMessagesAsync(jobsStartJobsParameters.FirstOrDefault().Value, customHeaders : _headers, xUIPATHOrganizationUnitId : jobsStartJobsParameters.FirstOrDefault().Key));
        }
        private List<MethodInfo> GetExecutionMethods(Type testType, ExecutionType executionType)
        {
            List<MethodInfo> methods = new List<MethodInfo>();

            Type executionAttribute = null;

            switch (executionType)
            {
                case ExecutionType.PreHost:
                    executionAttribute = typeof(VsIdePreHostExecutionMethod);
                    break;
                case ExecutionType.PostHost:
                    executionAttribute = typeof(VsIdePostHostExecutionMethod);
                    break;
                default:
                    throw new ArgumentException("Unknow Execution Type.");
            }

            foreach (var m in testType.GetMethods())
            {
                bool hasCustomAttribute = m.GetCustomAttributes(executionAttribute, true).Length >= 1;
                
                if (hasCustomAttribute
                    && !m.IsAbstract
                    && m.IsStatic
                    && m.GetParameters().Length == 0)
                {
                    methods.Add(m);
                }
                else if (hasCustomAttribute)
                {
                    HostProcessErrorHandler(
                        String.Format("Method {0} is attributed with {1} but cannot be run Pre/Post Host. "
                                    + "Methods must be Static and have no parameters."
                                    , m.ToString()
                                    , executionType.ToString())
                        , TestOutcome.Warning
                        , false);
                }
            }

            return methods;
        }
        private void PrePostHostCodeExecution(ITestElement testElement, ITestContext testContext, ExecutionType executionType)
        {
            Assembly            testAssembly        = null;
            Type                testType            = null;
            List<MethodInfo>    preExecuteMethods   = null;
            String              currentMethod       = String.Empty;
            String              testClassName       = String.Empty;
            object              testObject          = null;
            object[]            parameters          = new object[] { };

            try
            {
                testAssembly        = Assembly.LoadFrom(testElement.Storage);
                testClassName       = GetTestClassName(testElement);
                testType            = testAssembly.GetType(testClassName);
                preExecuteMethods   = GetExecutionMethods(testType, executionType);

                if (preExecuteMethods.Count > 0)
                {
                    if (HostExists()) CleanupHostSide();

                    testObject = Activator.CreateInstance(testType);

                    foreach (var preExecuteMethod in preExecuteMethods)
                    {
                        currentMethod = preExecuteMethod.Name;
                        preExecuteMethod.Invoke(testObject, parameters);
                    }
                }
            }
            catch (Exception e)
            {
                String method = String.Empty;

                if (currentMethod != String.Empty)
                {
                    method = " in Method: " + currentMethod;
                }
                else
                {
                    method = "before method execution";
                }

                HostProcessErrorHandler(
                    String.Format("Pre-Host Code Execution Failed {0}. Error: {1}.", method, e.ToString())
                    , TestOutcome.Warning
                    , false);
            }

        }
Example #21
0
        /// <summary>
        /// Called to run/compile/check/prolint the current program
        /// </summary>
        public static void StartProgressExec(ExecutionType executionType)
        {
            CurrentOperation currentOperation;
            if (!Enum.TryParse(executionType.ToString(), true, out currentOperation))
                currentOperation = CurrentOperation.Run;

            // process already running?
            if (Plug.CurrentFileObject.CurrentOperation >= CurrentOperation.Prolint) {
                UserCommunication.NotifyUnique("KillExistingProcess", "This file is already being compiled, run or lint-ed.<br>Please wait the end of the previous action,<br>or click the link below to interrupt the previous action :<br><a href='#'>Click to kill the associated prowin process</a>", MessageImg.MsgRip, currentOperation.GetAttribute<CurrentOperationAttr>().Name, "Already being compiled/run", args => {
                    KillCurrentProcess();
                    StartProgressExec(executionType);
                    args.Handled = true;
                }, 5);
                return;
            }
            if (!Abl.IsCurrentProgressFile) {
                UserCommunication.Notify("Can only compile and run progress files!", MessageImg.MsgWarning, "Invalid file type", "Progress files only", 10);
                return;
            }
            if (string.IsNullOrEmpty(Plug.CurrentFilePath) || !File.Exists(Plug.CurrentFilePath)) {
                UserCommunication.Notify("Couldn't find the following file :<br>" + Plug.CurrentFilePath, MessageImg.MsgError, "Execution error", "File not found", 10);
                return;
            }
            if (!Config.Instance.CompileKnownExtension.Split(',').Contains(Path.GetExtension(Plug.CurrentFilePath))) {
                UserCommunication.Notify("Sorry, the file extension " + Path.GetExtension(Plug.CurrentFilePath).ProQuoter() + " isn't a valid extension for this action!<br><i>You can change the list of valid extensions in the settings window</i>", MessageImg.MsgWarning, "Invalid file extension", "Not an executable", 10);
                return;
            }

            // update function prototypes
            ProGenerateCode.UpdateFunctionPrototypesIfNeeded(true);

            // prolint? check that the StartProlint.p program is created, or do it
            if (executionType == ExecutionType.Prolint) {
                if (!File.Exists(Config.FileStartProlint))
                    if (!Utils.FileWriteAllBytes(Config.FileStartProlint, DataResources.StartProlint))
                        return;
            }

            // launch the compile process for the current file
            Plug.CurrentFileObject.ProgressExecution = new ProExecution {
                ListToCompile = new List<FileToCompile> {
                    new FileToCompile(Plug.CurrentFilePath)
                },
                OnExecutionEnd = OnSingleExecutionEnd,
                OnExecutionOk = OnSingleExecutionOk
            };
            if (!Plug.CurrentFileObject.ProgressExecution.Do(executionType))
                return;

            // change file object current operation, set flag
            Plug.CurrentFileObject.CurrentOperation |= currentOperation;
            FilesInfo.UpdateFileStatus();

            // clear current errors (updates the current file info)
            FilesInfo.ClearAllErrors(Plug.CurrentFilePath, true);
        }
Example #22
0
        internal object Execute(Context context, ExecutionType executionType)
        {
            var arguments = from child in Children select child.Execute(context, ExecutionType.Argument);

            return(Token.Execute(arguments, context, executionType));
        }
Example #23
0
        private static void SetSystem(ref IDictionary <int, SystemLayer> layers, EntitySystem system, int layer, ExecutionType executionType)
        {
            if (!layers.ContainsKey(layer))
            {
                layers[layer] = new SystemLayer();
            }

            var updateBag = layers[layer][executionType];

            if (!updateBag.Contains(system))
            {
                updateBag.Add(system);
            }
            //#if !FULLDOTNET
            //            layers = (from d in layers orderby d.Key ascending select d).ToDictionary(pair => pair.Key, pair => pair.Value);
            //#endif
        }
        private void RunImpl(Response response, dynamic args, ExecutionType executionType)
        {
            lock (_lock)
            {
                _attachMode = executionType == ExecutionType.Attach;

                SetExceptionBreakpoints(args.__exceptionOptions);

                SoftDebuggerRemoteArgs listenArgs;

                if (executionType == ExecutionType.Attach)
                {
                    // validate argument 'address'
                    string host = getString(args, "address");
                    if (host == null)
                    {
                        SendErrorResponse(response, 3007, "Property 'address' is missing or empty.");
                        return;
                    }

                    // validate argument 'port'
                    int port = getInt(args, "port", -1);
                    if (port == -1)
                    {
                        SendErrorResponse(response, 3008, "Property 'port' is missing.");
                        return;
                    }

                    IPAddress address = Utilities.ResolveIPAddress(host);
                    if (address == null)
                    {
                        SendErrorResponse(response, 3013, "Invalid address '{host}'.", new { host });
                        return;
                    }

                    listenArgs = new SoftDebuggerConnectArgs("Godot", IPAddress.Loopback, port);
                }
                else
                {
                    listenArgs = new SoftDebuggerListenArgs("Godot", IPAddress.Loopback, 0);
                }

                // ------

                _debuggeeKilled = false;

                string godotExecutablePath = (string)args.executable;

                string godotProjectDir = (string)args.godotProjectDir;

                var startInfo = new GodotDebuggerStartInfo(executionType, godotExecutablePath,
                                                           processOutputListener: this, listenArgs)
                {
                    WorkingDirectory = godotProjectDir
                };

                _session.Run(startInfo, _debuggerSessionOptions);

                _debuggeeExecuting = true;
            }
        }
Example #25
0
        private EntitySystem SetSystem(Type systemType, EntitySystem system, GameLoopType gameLoopType, int layer = 0, ExecutionType executionType = ExecutionType.Synchronous)
        {
            system.EntityWorld = _entityWorld;

            if (_systems.ContainsKey(systemType))
            {
                _systems[systemType].Add(system);
            }
            else
            {
                var genericType = typeof(List <>);
                var listType    = genericType.MakeGenericType(systemType);
                _systems[systemType] = (IList)Activator.CreateInstance(listType);
                _systems[systemType].Add(system);
            }

            switch (gameLoopType)
            {
            case GameLoopType.Draw:
            {
                SetSystem(ref _drawLayers, system, layer, executionType);
            }

            break;

            case GameLoopType.Update:
            {
                SetSystem(ref _updateLayers, system, layer, executionType);
            }

            break;
            }

            if (!_mergedBag.Contains(system))
            {
                _mergedBag.Add(system);
            }

            system.Bit = _systemBitManager.GetBitFor(system);

            return(system);
        }
Example #26
0
 public async Task <IEnumerable <T> > ExecuteReaderAsync <T>(ExecutionType executionType, CommandType commandType, string commandText, IsolationLevel isolationLevel,
                                                             Func <IDataReader, T> callback, params SqlParameter[] parameters)
 {
     return((IEnumerable <T>) await ExecuteAsync(executionType, commandType, commandText, isolationLevel, parameters, callback).ConfigureAwait(false));
 }
Example #27
0
 public T SetSystem <T>(T system, GameLoopType gameLoopType, int layer = 0, ExecutionType executionType = ExecutionType.Synchronous) where T : EntitySystem
 {
     return((T)SetSystem(system.GetType(), system, gameLoopType, layer, executionType));
 }
Example #28
0
 public Task <object> ExecuteScalarAsync(ExecutionType executionType, CommandType commandType, string commandText, IsolationLevel isolationLevel, params SqlParameter[] parameters)
 {
     return(ExecuteAsync(executionType, commandType, commandText, isolationLevel, parameters));
 }
Example #29
0
        public TransactionReceipt Execute(
            Transaction transaction,
            BlockHeader block)
        {
            TransactionTrace trace = null;

            if (_tracer.IsTracingEnabled)
            {
                trace = new TransactionTrace();
            }

            IReleaseSpec spec      = _specProvider.GetSpec(block.Number);
            Address      recipient = transaction.To;
            UInt256      value     = transaction.Value;
            UInt256      gasPrice  = transaction.GasPrice;
            long         gasLimit  = (long)transaction.GasLimit;

            byte[] machineCode = transaction.Init;
            byte[] data        = transaction.Data ?? Bytes.Empty;

            Address sender = transaction.SenderAddress;

            if (_logger.IsTrace)
            {
                _logger.Trace($"SPEC: {spec.GetType().Name}");
                _logger.Trace("HASH: " + transaction.Hash);
                _logger.Trace("IS_CONTRACT_CREATION: " + transaction.IsContractCreation);
                _logger.Trace("IS_MESSAGE_CALL: " + transaction.IsMessageCall);
                _logger.Trace("IS_TRANSFER: " + transaction.IsTransfer);
                _logger.Trace("SENDER: " + sender);
                _logger.Trace("TO: " + transaction.To);
                _logger.Trace("GAS LIMIT: " + transaction.GasLimit);
                _logger.Trace("GAS PRICE: " + transaction.GasPrice);
                _logger.Trace("VALUE: " + transaction.Value);
                _logger.Trace("DATA_LENGTH: " + (transaction.Data?.Length ?? 0));
                _logger.Trace("NONCE: " + transaction.Nonce);
            }

            if (sender == null)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"SENDER_NOT_SPECIFIED");
                }

                return(GetNullReceipt(block, 0L));
            }

            long intrinsicGas = _intrinsicGasCalculator.Calculate(transaction, spec);

            if (_logger.IsTrace)
            {
                _logger.Trace("INTRINSIC GAS: " + intrinsicGas);
            }

            if (gasLimit < intrinsicGas)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"GAS_LIMIT_BELOW_INTRINSIC_GAS {gasLimit} < {intrinsicGas}");
                }

                return(GetNullReceipt(block, 0L));
            }

            if (gasLimit > block.GasLimit - block.GasUsed)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"BLOCK_GAS_LIMIT_EXCEEDED {gasLimit} > {block.GasLimit} - {block.GasUsed}");
                }

                return(GetNullReceipt(block, 0L));
            }

            if (!_stateProvider.AccountExists(sender))
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"SENDER_ACCOUNT_DOES_NOT_EXIST {sender}");
                }

                _stateProvider.CreateAccount(sender, 0);
            }

            UInt256 senderBalance = _stateProvider.GetBalance(sender);

            if ((ulong)intrinsicGas * gasPrice + value > senderBalance)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"INSUFFICIENT_SENDER_BALANCE: ({sender})b = {senderBalance}");
                }

                return(GetNullReceipt(block, 0L));
            }

            if (transaction.Nonce != _stateProvider.GetNonce(sender))
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"WRONG_TRANSACTION_NONCE: {transaction.Nonce} (expected {_stateProvider.GetNonce(sender)})");
                }

                return(GetNullReceipt(block, 0L));
            }

            _stateProvider.IncrementNonce(sender);
            _stateProvider.SubtractFromBalance(sender, (ulong)gasLimit * gasPrice, spec);
            _stateProvider.Commit(spec);

            long            unspentGas = gasLimit - intrinsicGas;
            long            spentGas   = gasLimit;
            List <LogEntry> logEntries = new List <LogEntry>();

            if (transaction.IsContractCreation)
            {
                Rlp addressBaseRlp = Rlp.Encode(
                    Rlp.Encode(sender),
                    Rlp.Encode(_stateProvider.GetNonce(sender) - 1));
                Keccak addressBaseKeccak = Keccak.Compute(addressBaseRlp);
                recipient = new Address(addressBaseKeccak);
            }

            int snapshot        = _stateProvider.TakeSnapshot();
            int storageSnapshot = _storageProvider.TakeSnapshot();

            _stateProvider.SubtractFromBalance(sender, value, spec);
            byte statusCode = StatusCode.Failure;

            HashSet <Address> destroyedAccounts = new HashSet <Address>();

            try
            {
                if (transaction.IsContractCreation)
                {
                    // TODO: review tests around it as it fails on Ropsten 230881 when we throw an exception
                    if (_stateProvider.AccountExists(recipient) && !_stateProvider.IsEmptyAccount(recipient))
                    {
                        // TODO: review
//                        throw new TransactionCollisionException();
                    }
                }

                if (transaction.IsTransfer) // TODO: this is never called and wrong, to be removed
                {
                    _stateProvider.SubtractFromBalance(sender, value, spec);
                    _stateProvider.AddToBalance(recipient, value, spec);
                    statusCode = StatusCode.Success;
                }
                else
                {
                    bool isPrecompile = recipient.IsPrecompiled(spec);

                    ExecutionEnvironment env = new ExecutionEnvironment();
                    env.Value            = value;
                    env.TransferValue    = value;
                    env.Sender           = sender;
                    env.ExecutingAccount = recipient;
                    env.CurrentBlock     = block;
                    env.GasPrice         = gasPrice;
                    env.InputData        = data ?? new byte[0];
                    env.CodeInfo         = isPrecompile ? new CodeInfo(recipient) : machineCode == null?_virtualMachine.GetCachedCodeInfo(recipient) : new CodeInfo(machineCode);

                    env.Originator = sender;

                    ExecutionType executionType = isPrecompile
                        ? ExecutionType.DirectPrecompile
                        : transaction.IsContractCreation
                            ? ExecutionType.DirectCreate
                            : ExecutionType.Transaction;

                    TransactionSubstate substate;
                    byte[] output;
                    using (EvmState state = new EvmState(unspentGas, env, executionType, false))
                    {
                        (output, substate) = _virtualMachine.Run(state, spec, trace);
                        unspentGas         = state.GasAvailable;
                    }

                    if (substate.ShouldRevert)
                    {
                        if (_logger.IsTrace)
                        {
                            _logger.Trace("REVERTING");
                        }

                        logEntries.Clear();
                        destroyedAccounts.Clear();
                        _stateProvider.Restore(snapshot);
                        _storageProvider.Restore(storageSnapshot);
                    }
                    else
                    {
                        if (transaction.IsContractCreation)
                        {
                            long codeDepositGasCost = output.Length * GasCostOf.CodeDeposit;
                            if (spec.IsEip170Enabled && output.Length > 0x6000)
                            {
                                codeDepositGasCost = long.MaxValue;
                            }

                            if (unspentGas < codeDepositGasCost && spec.IsEip2Enabled)
                            {
                                throw new OutOfGasException();
                            }

                            if (unspentGas >= codeDepositGasCost)
                            {
                                Keccak codeHash = _stateProvider.UpdateCode(output);
                                _stateProvider.UpdateCodeHash(recipient, codeHash, spec);
                                unspentGas -= codeDepositGasCost;
                            }
                        }

                        logEntries.AddRange(substate.Logs);
                        foreach (Address toBeDestroyed in substate.DestroyList)
                        {
                            destroyedAccounts.Add(toBeDestroyed);
                        }

                        statusCode = StatusCode.Success;
                    }

                    spentGas = Refund(gasLimit, unspentGas, substate, sender, gasPrice, spec);
                }
            }
            catch (Exception ex) when(ex is EvmException || ex is OverflowException)  // TODO: OverflowException? still needed? hope not
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"EVM EXCEPTION: {ex.GetType().Name}");
                }

                logEntries.Clear();
                destroyedAccounts.Clear();
                _stateProvider.Restore(snapshot);
                _storageProvider.Restore(storageSnapshot);
            }

            foreach (Address toBeDestroyed in destroyedAccounts)
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"DESTROYING: {toBeDestroyed}");
                }
                _stateProvider.DeleteAccount(toBeDestroyed);
            }

            if (_logger.IsTrace)
            {
                _logger.Trace("GAS SPENT: " + spentGas);
            }

            if (!destroyedAccounts.Contains(block.Beneficiary))
            {
                if (!_stateProvider.AccountExists(block.Beneficiary))
                {
                    _stateProvider.CreateAccount(block.Beneficiary, (ulong)spentGas * gasPrice);
                }
                else
                {
                    _stateProvider.AddToBalance(block.Beneficiary, (ulong)spentGas * gasPrice, spec);
                }
            }

            _storageProvider.Commit(spec);
            _stateProvider.Commit(spec);

            block.GasUsed += spentGas;

            if (_tracer.IsTracingEnabled)
            {
                trace.Gas = spentGas;
                _tracer.SaveTrace(Transaction.CalculateHash(transaction), trace);
            }

            return(BuildTransactionReceipt(block, statusCode, logEntries.Any() ? logEntries.ToArray() : LogEntry.EmptyLogs, recipient));
        }
Example #30
0
 public void ReportAction(long gas, UInt256 value, Address @from, Address to, byte[] input, ExecutionType callType, bool isPrecompileCall = false) => throw new InvalidOperationException(ErrorMessage);
Example #31
0
        /// <summary>
        /// allows to prepare the execution environnement by creating a unique temp folder
        /// and copying every critical files into it
        /// Then execute the progress program
        /// </summary>
        /// <returns></returns>
        public bool Do(ExecutionType executionType)
        {
            if (ListToCompile == null)
                ListToCompile = new List<FileToCompile>();

            ExecutionType = executionType;

            // check prowin32.exe
            if (!File.Exists(ProEnv.ProwinPath)) {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The file path to Prowin.exe is incorrect : <div class='ToolTipcodeSnippet'>" + ProEnv.ProwinPath + "</div>You must provide a valid path before executing this action<br><i>You can change this path in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return false;
            }

            // check compilation dir
            if (executionType == ExecutionType.Compile && !ProEnv.CompileLocally && (!Path.IsPathRooted(ProEnv.BaseCompilationPath))) {
                UserCommunication.NotifyUnique("ProExecutionChecks", "The path for the compilation base directory is incorrect : <div class='ToolTipcodeSnippet'>" + (string.IsNullOrEmpty(ProEnv.BaseCompilationPath) ? "it's empty!" : ProEnv.BaseCompilationPath) + "</div>You must provide a valid path before executing this action :<br><br><i>1. Either change the compilation directory<br>2. Or toggle the option to compile next to the source file!<br><br>The options are configurable in the <a href='go'>set environment page</a></i>", MessageImg.MsgWarning, "Execution error", "Invalid file path", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProExecutionChecks");
                    args.Handled = true;
                }, 10);
                return false;
            }

            // create a unique temporary folder
            LocalTempDir = Path.Combine(Config.FolderTemp, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
            if (!Utils.CreateDirectory(LocalTempDir))
                return false;

            // for each file of the list
            var filesListPath = Path.Combine(LocalTempDir, "files.list");
            StringBuilder filesListcontent = new StringBuilder();
            var count = 1;
            foreach (var fileToCompile in ListToCompile) {

                if (!File.Exists(fileToCompile.InputPath)) {
                    UserCommunication.Notify("Couldn't find the following file :<br>" + fileToCompile.InputPath, MessageImg.MsgError, "Execution error", "File not found", 10);
                    return false;
                }

                // if current file and the file has unsaved modif, we copy the content to a temp file, otherwise we just use the input path (also use the input path for .cls files!)
                if (fileToCompile.InputPath.Equals(Plug.CurrentFilePath) &&
                    (Npp.GetModify || (fileToCompile.BaseFileName ?? "").StartsWith("_")) &&
                    !Path.GetExtension(fileToCompile.InputPath).Equals(".cls")) {
                    fileToCompile.CompInputPath = Path.Combine(LocalTempDir, "tmp_" + DateTime.Now.ToString("yyMMdd_HHmmssfff_") + count + Path.GetExtension(fileToCompile.InputPath));
                    Utils.FileWriteAllText(fileToCompile.CompInputPath, Npp.Text, Encoding.Default);
                } else {
                    fileToCompile.CompInputPath = fileToCompile.InputPath;
                }

                if (executionType != ExecutionType.Compile)
                    continue;

                // we set where the *.lst and *.r files will be generated by the COMPILE command
                var baseFileName = Path.GetFileNameWithoutExtension(fileToCompile.CompInputPath);
                var lastDeployment = ProEnv.Deployer.GetTargetDirsNeededForFile(fileToCompile.InputPath, 0).Last();

                // for *.cls files, as many *.r files are generated, we need to compile in a temp directory
                // we need to know which *.r files were generated for each input file
                // so each file gets his own sub tempDir
                if ((lastDeployment.DeployType != DeployType.Move) ||
                    Config.Instance.CompileForceUseOfTemp ||
                    Path.GetExtension(fileToCompile.InputPath).Equals(".cls")
                    ) {

                    var subTempDir = Path.Combine(LocalTempDir, count.ToString());

                    // if the deployment dir is not on the same disk as the temp folder, we create a temp dir
                    // as close to the final deployment as possible (= in the deployment base dir!)
                    if (lastDeployment.DeployType != DeployType.Ftp && !string.IsNullOrEmpty(DistantRootTempDir) && DistantRootTempDir.Length > 2 && !DistantRootTempDir.Substring(0, 2).EqualsCi(LocalTempDir.Substring(0, 2))) {

                        if (Utils.CreateDirectory(DistantRootTempDir, FileAttributes.Hidden))
                            DistantTempDir = Path.Combine(DistantRootTempDir, _proExecutionCounter + "-" + DateTime.Now.ToString("yyMMdd_HHmmssfff"));
                        else
                            DistantTempDir = LocalTempDir;

                        subTempDir = Path.Combine(DistantTempDir, count.ToString());
                    }

                    if (!Utils.CreateDirectory(subTempDir))
                        return false;

                    fileToCompile.CompOutputDir = subTempDir;
                    fileToCompile.CompOutputLst = Path.Combine(subTempDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR = Path.Combine(subTempDir, baseFileName + ".r");

                } else {

                    // if we want to move the r-code somewhere during the deployment, then we will compile the r-code
                    // directly there, because it's faster than generating it in a temp folder and moving it afterward
                    fileToCompile.CompOutputDir = lastDeployment.TargetDir;
                    if (!Utils.CreateDirectory(fileToCompile.CompOutputDir))
                        return false;

                    fileToCompile.CompOutputLst = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".lst");
                    fileToCompile.CompOutputR = Path.Combine(fileToCompile.CompOutputDir, baseFileName + ".r");
                }

                // feed files list
                filesListcontent.AppendLine(fileToCompile.CompInputPath.ProQuoter() + " " + fileToCompile.CompOutputDir.ProQuoter() + " " + fileToCompile.CompOutputLst.ProQuoter());

                count++;
            }
            Utils.FileWriteAllText(filesListPath, filesListcontent.ToString(), Encoding.Default);

            // when running a procedure, check that a .r is not hiding the program, if that's the case we warn the user
            if (executionType == ExecutionType.Run && !_dontWarnAboutRCode && ListToCompile.Count >= 1) {
                if (File.Exists(Path.ChangeExtension(ListToCompile.First().InputPath, ".r"))) {
                    UserCommunication.NotifyUnique("rcodehide", "Friendly warning, an <b>r-code</b> <i>(i.e. *.r file)</i> is hiding the current program<br>If you modified it since the last compilation you might not have the expected behavior...<br><br><i>" + "stop".ToHtmlLink("Click here to not show this message again for this session") + "</i>", MessageImg.MsgWarning, "Execution warning", "An Rcode hides the program", args => {
                        _dontWarnAboutRCode = true;
                        UserCommunication.CloseUniqueNotif("rcodehide");
                    }, 5);
                }
            }

            // Move ini file into the execution dir
            var baseIniPath = "";
            if (File.Exists(ProEnv.IniPath)) {
                baseIniPath = Path.Combine(LocalTempDir, "base.ini");
                // we need to copy the .ini but we must delete the PROPATH= part, as stupid as it sounds, if we leave a huge PROPATH
                // in this file, it increases the compilation time by a stupid amount... unbelievable i know, but trust me, it does...
                var encoding = TextEncodingDetect.GetFileEncoding(ProEnv.IniPath);
                var fileContent = Utils.ReadAllText(ProEnv.IniPath, encoding);
                var regex = new Regex("^PROPATH=.*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                var matches = regex.Match(fileContent);
                if (matches.Success)
                    fileContent = regex.Replace(fileContent, @"PROPATH=");
                Utils.FileWriteAllText(baseIniPath, fileContent, encoding);
            }

            // Move pf file into the execution dir
            var basePfPath = "";
            if (File.Exists(ProEnv.GetPfPath())) {
                basePfPath = Path.Combine(LocalTempDir, "base.pf");
                File.Copy(ProEnv.GetPfPath(), basePfPath);
            }

            // set common info on the execution
            LogPath = Path.Combine(LocalTempDir, "run.log");
            ProcessStartDir = executionType == ExecutionType.Run ? Path.GetDirectoryName(ListToCompile.First().InputPath) ?? LocalTempDir : LocalTempDir;
            ProgressWin32 = ProEnv.ProwinPath;
            if (executionType == ExecutionType.Database)
                ExtractDbOutputPath = Path.Combine(LocalTempDir, ExtractDbOutputPath);
            ProgressionFilePath = Path.Combine(LocalTempDir, "compile.progression");
            DatabaseConnectionLog = Path.Combine(LocalTempDir, "db.ko");
            NotificationOutputPath = Path.Combine(LocalTempDir, "postExecution.notif");
            var propathToUse = string.Join(",", ProEnv.GetProPathDirList);
            string fileToExecute = "";

            if (executionType == ExecutionType.Appbuilder) {
                fileToExecute = ListToCompile.First().InputPath;

            } else if (executionType == ExecutionType.Database) {

                // for database extraction, we need to copy the DumpDatabase program
                fileToExecute = "db_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                if (!Utils.FileWriteAllBytes(Path.Combine(LocalTempDir, fileToExecute), DataResources.DumpDatabase))
                    return false;

            } else if (executionType == ExecutionType.Prolint) {

                // prolint, we need to copy the StartProlint program
                fileToExecute = "prolint_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                ProlintOutputPath = Path.Combine(LocalTempDir, "prolint.log");
                StringBuilder prolintProgram = new StringBuilder();
                prolintProgram.AppendLine("&SCOPED-DEFINE PathFileToProlint " + ListToCompile.First().CompInputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathProlintOutputFile " + ProlintOutputPath.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathToStartProlintProgram " + Config.FileStartProlint.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE UserName " + Config.Instance.UserName.ProQuoter());
                prolintProgram.AppendLine("&SCOPED-DEFINE PathActualFilePath " + ListToCompile.First().InputPath.ProQuoter());
                var filename = Path.GetFileName(Plug.CurrentFilePath);
                if (FileTag.Contains(filename)) {
                    var fileInfo = FileTag.GetLastFileTag(filename);
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationName " + fileInfo.ApplicationName.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileApplicationVersion " + fileInfo.ApplicationVersion.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileWorkPackage " + fileInfo.WorkPackage.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileBugID " + fileInfo.BugId.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileCorrectionNumber " + fileInfo.CorrectionNumber.ProQuoter());
                    prolintProgram.AppendLine("&SCOPED-DEFINE FileDate " + fileInfo.CorrectionDate.ProQuoter());
                }
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileStartProlint);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileStartProlint, encoding).Replace(@"/*<inserted_3P_values>*/", prolintProgram.ToString()), encoding);

            } else if (executionType == ExecutionType.DeploymentHook) {

                fileToExecute = "hook_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p";
                StringBuilder hookProc = new StringBuilder();
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationName " + ProEnv.Name.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE ApplicationSuffix " + ProEnv.Suffix.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE StepNumber " + DeploymentStep);
                hookProc.AppendLine("&SCOPED-DEFINE SourceDirectory " + DeploymentSourcePath.ProQuoter());
                hookProc.AppendLine("&SCOPED-DEFINE DeploymentDirectory " + ProEnv.BaseCompilationPath.ProQuoter());
                var encoding = TextEncodingDetect.GetFileEncoding(Config.FileDeploymentHook);
                Utils.FileWriteAllText(Path.Combine(LocalTempDir, fileToExecute), Utils.ReadAllText(Config.FileDeploymentHook, encoding).Replace(@"/*<inserted_3P_values>*/", hookProc.ToString()), encoding);

            } else if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader) {
                // need to init datadigger?
                if (!File.Exists(Path.Combine(Config.FolderDataDigger, "DataDigger.p"))) {
                    if (!Utils.FileWriteAllBytes(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), DataResources.DataDigger))
                        return false;
                    if (!Utils.ExtractAll(Path.Combine(Config.FolderDataDigger, "DataDigger.zip"), Config.FolderDataDigger))
                        return false;
                }
                // add the datadigger folder to the propath
                propathToUse = Config.FolderDataDigger + "," + propathToUse;

            } else {

                if (ListToCompile.Count == 1)
                    fileToExecute = ListToCompile.First().CompInputPath;
            }

            // prepare the .p runner
            var runnerPath = Path.Combine(LocalTempDir, "run_" + DateTime.Now.ToString("yyMMdd_HHmmssfff") + ".p");
            StringBuilder runnerProgram = new StringBuilder();
            runnerProgram.AppendLine("&SCOPED-DEFINE ExecutionType " + executionType.ToString().ToUpper().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ToExecute " + fileToExecute.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE LogFile " + LogPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtractDbOutputPath " + ExtractDbOutputPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE propathToUse " + (LocalTempDir + "," + propathToUse).ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE ExtraPf " + ProEnv.ExtraPf.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE BasePfPath " + basePfPath.Trim().ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileWithLst " + ProEnv.CompileWithListing);
            runnerProgram.AppendLine("&SCOPED-DEFINE ToCompileListFile " + filesListPath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CreateFileIfConnectFails " + DatabaseConnectionLog.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE CompileProgressionFile " + ProgressionFilePath.ProQuoter());
            runnerProgram.AppendLine("&SCOPED-DEFINE DbConnectionMandatory " + NeedDatabaseConnection);
            runnerProgram.AppendLine("&SCOPED-DEFINE NotificationOutputPath " + NotificationOutputPath.ProQuoter());
            runnerProgram.Append(Encoding.Default.GetString(DataResources.ProgressRun));
            Utils.FileWriteAllText(runnerPath, runnerProgram.ToString(), Encoding.Default);

            // preferably, we use the batch mode because it's faster than the client mode
            var batchMode = (executionType == ExecutionType.CheckSyntax || executionType == ExecutionType.Compile || executionType == ExecutionType.Database);

            // no batch mode option?
            batchMode = batchMode && !Config.Instance.NeverUseProwinInBatchMode;

            // multiple compilation, we don't want to show all those Prowin in the task bar...
            batchMode = batchMode && !NoBatch;

            // Parameters
            StringBuilder Params = new StringBuilder();

            if (executionType == ExecutionType.DataDigger || executionType == ExecutionType.DataReader)
                Params.Append(" -s 10000 -d dmy -E -rereadnolock -h 255 -Bt 4000 -tmpbsize 8");
            if (executionType != ExecutionType.Run)
                Params.Append(" -T " + LocalTempDir.Trim('\\').ProQuoter());
            if (!string.IsNullOrEmpty(baseIniPath))
                Params.Append(" -ini " + baseIniPath.ProQuoter());
            if (batchMode)
                Params.Append(" -b");
            Params.Append(" -p " + runnerPath.ProQuoter());
            if (!string.IsNullOrWhiteSpace(ProEnv.CmdLineParameters))
                Params.Append(" " + ProEnv.CmdLineParameters.Trim());
            ExeParameters = Params.ToString();

            // we supress the splashscreen
            if (!batchMode)
                MoveSplashScreenNoError(Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen.bmp"), Path.Combine(Path.GetDirectoryName(ProgressWin32) ?? "", "splashscreen-3p-disabled.bmp"));

            // Start a process
            var pInfo = new ProcessStartInfo {
                FileName = ProEnv.ProwinPath,
                Arguments = ExeParameters,
                WorkingDirectory = ProcessStartDir
            };
            if (batchMode) {
                pInfo.WindowStyle = ProcessWindowStyle.Hidden;
                pInfo.CreateNoWindow = true;
            }
            Process = new Process {
                StartInfo = pInfo,
                EnableRaisingEvents = true
            };
            Process.Exited += ProcessOnExited;
            try {
                Process.Start();
            } catch (Exception e) {
                UserCommunication.NotifyUnique("ProwinFailed", "Couldn't start a new prowin process!<br>Please check that the file path to prowin32.exe is correct in the <a href='go'>set environment page</a>.<br><br>Below is the technical error that occured :<br><div class='ToolTipcodeSnippet'>" + e.Message + "</div>", MessageImg.MsgError, "Execution error", "Can't start a prowin process", args => {
                    Appli.Appli.GoToPage(PageNames.SetEnvironment);
                    UserCommunication.CloseUniqueNotif("ProwinFailed");
                    args.Handled = true;
                }, 10);
            }

            //UserCommunication.Notify("New process starting...<br><br><b>FileName :</b><br>" + ProEnv.ProwinPath + "<br><br><b>Parameters :</b><br>" + ExeParameters + "<br><br><b>Temporary directory :</b><br><a href='" + TempDir + "'>" + TempDir + "</a>");

            return true;
        }
 public EstimateGasTracerTests(bool useCreates)
 {
     _executionType = useCreates ? ExecutionType.Create : ExecutionType.Call;
 }
        public void Execute(Transaction transaction, BlockHeader block, ITxTracer txTracer, bool readOnly)
        {
            IReleaseSpec spec      = _specProvider.GetSpec(block.Number);
            Address      recipient = transaction.To;
            UInt256      value     = transaction.Value;
            UInt256      gasPrice  = transaction.GasPrice;
            long         gasLimit  = (long)transaction.GasLimit;

            byte[] machineCode = transaction.Init;
            byte[] data        = transaction.Data ?? Bytes.Empty;

            Address sender = transaction.SenderAddress;

            if (_logger.IsTrace)
            {
                _logger.Trace($"Executing tx {transaction.Hash}");
            }

            if (sender == null)
            {
                TraceLogInvalidTx(transaction, "SENDER_NOT_SPECIFIED");
                if (txTracer.IsTracingReceipt)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                return;
            }

            long intrinsicGas = _intrinsicGasCalculator.Calculate(transaction, spec);

            if (_logger.IsTrace)
            {
                _logger.Trace($"Intrinsic gas calculated for {transaction.Hash}: " + intrinsicGas);
            }

            if (gasLimit < intrinsicGas)
            {
                TraceLogInvalidTx(transaction, $"GAS_LIMIT_BELOW_INTRINSIC_GAS {gasLimit} < {intrinsicGas}");
                if (txTracer.IsTracingReceipt)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                return;
            }

            if (gasLimit > block.GasLimit - block.GasUsed)
            {
                TraceLogInvalidTx(transaction, $"BLOCK_GAS_LIMIT_EXCEEDED {gasLimit} > {block.GasLimit} - {block.GasUsed}");
                if (txTracer.IsTracingReceipt)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                return;
            }

            if (!_stateProvider.AccountExists(sender))
            {
                TraceLogInvalidTx(transaction, $"SENDER_ACCOUNT_DOES_NOT_EXIST {sender}");
                if (gasPrice == UInt256.Zero)
                {
                    _stateProvider.CreateAccount(sender, UInt256.Zero);
                }
            }

            UInt256 senderBalance = _stateProvider.GetBalance(sender);

            if ((ulong)intrinsicGas * gasPrice + value > senderBalance)
            {
                TraceLogInvalidTx(transaction, $"INSUFFICIENT_SENDER_BALANCE: ({sender})_BALANCE = {senderBalance}");
                if (txTracer.IsTracingReceipt)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                return;
            }

            if (transaction.Nonce != _stateProvider.GetNonce(sender))
            {
                TraceLogInvalidTx(transaction, $"WRONG_TRANSACTION_NONCE: {transaction.Nonce} (expected {_stateProvider.GetNonce(sender)})");
                if (txTracer.IsTracingReceipt)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                return;
            }

            _stateProvider.IncrementNonce(sender);
            _stateProvider.SubtractFromBalance(sender, (ulong)gasLimit * gasPrice, spec);

            // TODO: I think we can skip this commit and decrease the tree operations this way
            _stateProvider.Commit(_specProvider.GetSpec(block.Number), txTracer.IsTracingState ? txTracer : null);

            long unspentGas = gasLimit - intrinsicGas;
            long spentGas   = gasLimit;

            int stateSnapshot   = _stateProvider.TakeSnapshot();
            int storageSnapshot = _storageProvider.TakeSnapshot();

            _stateProvider.SubtractFromBalance(sender, value, spec);
            byte statusCode = StatusCode.Failure;
            TransactionSubstate substate = null;

            try
            {
                if (transaction.IsContractCreation)
                {
                    recipient = Address.OfContract(sender, _stateProvider.GetNonce(sender) - 1);
                    if (_stateProvider.AccountExists(recipient))
                    {
                        if ((_virtualMachine.GetCachedCodeInfo(recipient)?.MachineCode?.Length ?? 0) != 0 || _stateProvider.GetNonce(recipient) != 0)
                        {
                            if (_logger.IsTrace)
                            {
                                _logger.Trace($"Contract collision at {recipient}"); // the account already owns the contract with the code
                            }

                            throw new TransactionCollisionException();
                        }

                        _stateProvider.UpdateStorageRoot(recipient, Keccak.EmptyTreeHash);
                    }
                }

                bool isPrecompile = recipient.IsPrecompiled(spec);

                ExecutionEnvironment env = new ExecutionEnvironment();
                env.Value            = value;
                env.TransferValue    = value;
                env.Sender           = sender;
                env.ExecutingAccount = recipient;
                env.CurrentBlock     = block;
                env.GasPrice         = gasPrice;
                env.InputData        = data ?? new byte[0];
                env.CodeInfo         = isPrecompile ? new CodeInfo(recipient) : machineCode == null?_virtualMachine.GetCachedCodeInfo(recipient) : new CodeInfo(machineCode);

                env.Originator = sender;

                ExecutionType executionType = transaction.IsContractCreation ? ExecutionType.Create : ExecutionType.Call;
                using (EvmState state = new EvmState(unspentGas, env, executionType, isPrecompile, true, false))
                {
                    substate   = _virtualMachine.Run(state, spec, txTracer);
                    unspentGas = state.GasAvailable;
                }

                if (substate.ShouldRevert || substate.IsError)
                {
                    if (_logger.IsTrace)
                    {
                        _logger.Trace("Restoring state from before transaction");
                    }
                    _stateProvider.Restore(stateSnapshot);
                    _storageProvider.Restore(storageSnapshot);
                }
                else
                {
                    // tks: there is similar code fo contract creation from init and from CREATE
                    // this may lead to inconsistencies (however it is tested extensively in blockchain tests)
                    if (transaction.IsContractCreation)
                    {
                        long codeDepositGasCost = substate.Output.Length * GasCostOf.CodeDeposit;
                        if (spec.IsEip170Enabled && substate.Output.Length > 0x6000)
                        {
                            codeDepositGasCost = long.MaxValue;
                        }

                        if (unspentGas < codeDepositGasCost && spec.IsEip2Enabled)
                        {
                            throw new OutOfGasException();
                        }

                        if (unspentGas >= codeDepositGasCost)
                        {
                            Keccak codeHash = _stateProvider.UpdateCode(substate.Output);
                            _stateProvider.UpdateCodeHash(recipient, codeHash, spec);
                            unspentGas -= codeDepositGasCost;
                        }
                    }

                    foreach (Address toBeDestroyed in substate.DestroyList)
                    {
                        if (_logger.IsTrace)
                        {
                            _logger.Trace($"Destroying account {toBeDestroyed}");
                        }
                        _stateProvider.DeleteAccount(toBeDestroyed);
                    }

                    statusCode = StatusCode.Success;
                }

                spentGas = Refund(gasLimit, unspentGas, substate, sender, gasPrice, spec);
            }
            catch (Exception ex) when(ex is EvmException || ex is OverflowException)  // TODO: OverflowException? still needed? hope not
            {
                if (_logger.IsTrace)
                {
                    _logger.Trace($"EVM EXCEPTION: {ex.GetType().Name}");
                }
                _stateProvider.Restore(stateSnapshot);
                _storageProvider.Restore(storageSnapshot);
            }

            if (_logger.IsTrace)
            {
                _logger.Trace("Gas spent: " + spentGas);
            }

            Address gasBeneficiary = block.GasBeneficiary;

            if (statusCode == StatusCode.Failure || !(substate?.DestroyList.Contains(gasBeneficiary) ?? false))
            {
                if (!_stateProvider.AccountExists(gasBeneficiary))
                {
                    _stateProvider.CreateAccount(gasBeneficiary, (ulong)spentGas * gasPrice);
                }
                else
                {
                    _stateProvider.AddToBalance(gasBeneficiary, (ulong)spentGas * gasPrice, spec);
                }
            }

            if (!readOnly)
            {
                _storageProvider.Commit(txTracer.IsTracingState ? txTracer : null);
                _stateProvider.Commit(spec, txTracer.IsTracingState ? txTracer : null);
            }
            else
            {
                _storageProvider.Reset();
                _stateProvider.Reset();
            }

            if (!readOnly)
            {
                block.GasUsed += spentGas;
            }

            if (txTracer.IsTracingReceipt)
            {
                if (statusCode == StatusCode.Failure)
                {
                    txTracer.MarkAsFailed(recipient, (long)transaction.GasLimit);
                }
                else
                {
                    txTracer.MarkAsSuccess(recipient, spentGas, substate.Output, substate.Logs.Any() ? substate.Logs.ToArray() : LogEntry.EmptyLogs);
                }
            }
        }
 internal void setExecutionLevel(ExecutionType executionType)
 {
     ExecutionLevel = executionType;
 }
Example #35
0
 public ExecutionObject(ExecutionType executionType)
 {
     ExecutionType = executionType;
 }
Example #36
0
        private void SetData_ExecuteCode(object sender, EventArgs e)
        {
            string approversName = string.Empty;

            var approvers = GetApprovers(this.ApprovalData);
            approversName = String.Join(",", approvers.ToArray());
            Approvers = approvers.Select(p => new TaskInfo()
               {
               Approver = p,
               MessageTitle = this.ApprovalData.MessageTitle,
               Message = this.ApprovalData.Message,
               MailEnable = this.ApprovalData.EnableEmail,
               TaskContentType = this.ApprovalData.TaskContenType,
               TaskTitle = this.ApprovalData.TaskTitle,
               AppendTitle = this.ApprovalData.AppendTitle,
               TaskInstruction = this.ApprovalData.TaskInstruction,
               DueDate = this.ApprovalData.DueDate,
               TaskDuration = this.ApprovalData.DurationPerTask,
               UpdatedProperties = this.ApprovalData.UpdatedProperties,
               TaskEvents = this.ApprovalData.TaskEvents,
               }).ToList();
            MultiTaskReplicator_ExecutionType = (ExecutionType)Enum.Parse(typeof(ExecutionType), this.ApprovalData.TaskSequenceType);
            workflowProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.WorkflowComment, "Begin approval level: " + ApprovalData.LevelName , MultiTaskReplicator_ExecutionType.ToString());
            workflowProperties.LogToWorkflowHistory(SPWorkflowHistoryEventType.WorkflowComment, "Tasks was created and sent to : " + approversName, string.Empty);
        }
        private static XElement CreateFileElement(string path, string type, string library, ExecutionType assoc)
        {
            XElement element = new XElement(xm + "file");
            element.SetAttributeValue(xm + "name", path);
            element.SetAttributeValue(xm + "type", type);
            if (!string.IsNullOrEmpty(library))
            {
                element.Add(new XElement(xm + "library",
                    new XAttribute(xm + "name", library)));
            }

            // Determine Association for sim/synthesis
            if (EnumHelpers.ExecutionTypeMatchesRequirement(ExecutionType.SimulationOnly, assoc))
            {
                XElement childAssociation = new XElement(xm + "association");
                childAssociation.SetAttributeValue(xm + "name", "BehavioralSimulation");
                element.Add(childAssociation);
            }
            if (EnumHelpers.ExecutionTypeMatchesRequirement(ExecutionType.SynthesisOnly, assoc))
            {
                XElement childAssociation = new XElement(xm + "association");
                childAssociation.SetAttributeValue(xm + "name", "Implementation");
                element.Add(childAssociation);
            }
            return element;
        }
Example #38
0
 public override object Execute(IEnumerable <object> args, Context context, ExecutionType executionType) =>
 SystemCallInvoker.Execute(Representation, args.ToArray());
Example #39
0
 public bool Equals(BrowserConfiguration other) => ExecutionType.Equals(other?.ExecutionType) &&
 BrowserType.Equals(other?.BrowserType) &&
 ShouldCaptureHttpTraffic.Equals(other?.ShouldCaptureHttpTraffic) &&
 Size.Equals(other?.Size) &&
 ShouldAutomaticallyScrollToVisible.Equals(other?.ShouldAutomaticallyScrollToVisible);
 public void ReportAction(long gas, UInt256 value, Address @from, Address to, ReadOnlyMemory <byte> input, ExecutionType callType, bool isPrecompileCall = false) => throw new OperationCanceledException(ErrorMessage);
Example #41
0
 public EvmState(long gasAvailable, ExecutionEnvironment env, ExecutionType executionType, bool isPrecompile, bool isTopLevel, bool isContinuation)
     : this(gasAvailable, env, executionType, isPrecompile, isTopLevel, -1, -1, 0L, 0L, false, isContinuation)
 {
     GasAvailable = gasAvailable;
     Env          = env;
 }
        public JsonNetResult CategoryTree(bool includeHidden = false, bool includeImages = false)
        {
            ExecutionType executionType = ExecutionType.local;
            Stopwatch     stopWatch     = new Stopwatch();

            stopWatch.Start();

            //Get the subdomain (if exists) for the api call
            string accountNameKey = Common.GetSubDomain(Request.Url);

            if (String.IsNullOrEmpty(accountNameKey))
            {
                return(new JsonNetResult {
                    Data = "Not found"
                });                                              //return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            List <CategoryTreeModel> categoryTree     = null;
            CategoryTreeJson         categoryTreeJson = null;

            string localCacheKey = accountNameKey + ":categorytree:" + includeHidden + ":" + includeImages;

            #region (Plan A) Get json from local cache

            try
            {
                categoryTreeJson = (CategoryTreeJson)HttpRuntime.Cache[localCacheKey];
            }
            catch (Exception e)
            {
                var error = e.Message;
                //TODO: Log: error message for local cache call
            }

            #endregion

            if (categoryTreeJson == null)
            {
                #region (Plan B) Get Public json from second layer of Redis Cache

                IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                string pathAndQuery = Common.GetApiPathAndQuery(Request.Url);

                string hashApiKey   = accountNameKey + ":apicache";
                string hashApiField = pathAndQuery;

                try
                {
                    var redisApiValue = cache.HashGet(hashApiKey, hashApiField);

                    if (redisApiValue.HasValue)
                    {
                        categoryTreeJson = JsonConvert.DeserializeObject <CategoryTreeJson>(redisApiValue);
                        executionType    = ExecutionType.redis_secondary;
                    }
                }
                catch
                {
                }

                #endregion

                if (categoryTreeJson == null)
                {
                    #region (Plan C) Get category data from Redis Cache and rebuild

                    try
                    {
                        //IDatabase cache = CoreServices.RedisConnectionMultiplexers.RedisMultiplexer.GetDatabase();

                        string hashMainKey   = accountNameKey + ":categories";
                        string hashMainField = "tree:public";

                        if (includeHidden == true)
                        {
                            hashMainField = "tree:private";
                        }

                        try
                        {
                            var redisValue = cache.HashGet(hashMainKey, hashMainField);

                            if (redisValue.HasValue)
                            {
                                categoryTree  = JsonConvert.DeserializeObject <List <ApplicationCategorizationService.CategoryTreeModel> >(redisValue);
                                executionType = ExecutionType.redis_main;
                            }
                        }
                        catch
                        {
                        }
                    }
                    catch (Exception e)
                    {
                        var error = e.Message;
                        //TODO: Log: error message for Redis call
                    }

                    #endregion

                    if (categoryTree == null)
                    {
                        #region (Plan D) Get data from WCF

                        var applicationCategorizationServiceClient = new ApplicationCategorizationService.ApplicationCategorizationServiceClient();

                        try
                        {
                            applicationCategorizationServiceClient.Open();

                            categoryTree = applicationCategorizationServiceClient.GetCategoryTree(accountNameKey, includeHidden, Common.SharedClientKey).ToList();

                            executionType = ExecutionType.wcf;

                            WCFManager.CloseConnection(applicationCategorizationServiceClient);
                        }
                        catch (Exception e)
                        {
                            #region Manage Exception

                            string exceptionMessage = e.Message.ToString();

                            var    currentMethod       = System.Reflection.MethodBase.GetCurrentMethod();
                            string currentMethodString = currentMethod.DeclaringType.FullName + "." + currentMethod.Name;

                            // Abort the connection & manage the exception
                            WCFManager.CloseConnection(applicationCategorizationServiceClient, exceptionMessage, currentMethodString);

                            #endregion
                        }

                        #endregion
                    }
                }

                #region Transform into json object, add images & cache locally or locally and radisAPI layer

                if (categoryTreeJson != null)
                {
                    //Just cache locally (we got json from the api redis layer)
                    HttpRuntime.Cache.Insert(localCacheKey, categoryTreeJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                }
                else if (categoryTree != null)
                {
                    //Transform categories into JSON and cache BOTH locally AND into redis
                    categoryTreeJson = Transforms.Json.CategorizationTransforms.CategoryTree(accountNameKey, categoryTree, includeImages);
                    HttpRuntime.Cache.Insert(localCacheKey, categoryTreeJson, null, DateTime.Now.AddMinutes(Common.CategorizationCacheTimeInMinutes), TimeSpan.Zero);
                    try
                    {
                        cache.HashSet(hashApiKey, hashApiField, JsonConvert.SerializeObject(categoryTreeJson), When.Always, CommandFlags.FireAndForget);
                    }
                    catch
                    {
                    }
                }

                #endregion
            }

            if (categoryTreeJson != null)
            {
                //Add execution data
                stopWatch.Stop();
                categoryTreeJson.executionType = "test";
                categoryTreeJson.executionType = executionType.ToString();
                categoryTreeJson.executionTime = stopWatch.Elapsed.TotalMilliseconds + "ms";
            }

            JsonNetResult jsonNetResult = new JsonNetResult();
            jsonNetResult.Formatting = Newtonsoft.Json.Formatting.Indented;
            jsonNetResult.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local; //<-- Convert UTC times to LocalTime
            jsonNetResult.Data = categoryTreeJson;

            return(jsonNetResult);
        }
 public GasEstimationTests(bool useCreates)
 {
     _executionType = useCreates ? ExecutionType.Create : ExecutionType.Call;
 }
Example #44
0
 public void ReportCall(long gas, UInt256 value, Address @from, Address to, byte[] input, ExecutionType callType)
 {
     _currentTxTracer.ReportCall(gas, value, @from, to, input, callType);
 }
 public void setExecutionType(ExecutionType executionType)
 {
     this.executionType = executionType;
 }