Exemplo n.º 1
0
 public ProgramPairResults(
     ProgramResult debugResult, ProgramResult releaseResult,
     ChecksumSite debugFirstUnmatch, ChecksumSite releaseFirstUnmatch)
 {
     DebugResult         = debugResult;
     ReleaseResult       = releaseResult;
     DebugFirstUnmatch   = debugFirstUnmatch;
     ReleaseFirstUnmatch = releaseFirstUnmatch;
 }
Exemplo n.º 2
0
        private static long GetEnergyFee(long Energy_usage, long energy_frozen, long energy_total)
        {
            if (energy_total <= 0)
            {
                return(0);
            }


            BigInteger result = new BigInteger(energy_frozen);

            result = BigInteger.Multiply(result, new BigInteger(Energy_usage));
            result = BigInteger.Divide(result, new BigInteger(energy_total));

            return((long)result);
        }
Exemplo n.º 3
0
        public TestResult RunTest(string name, IMachine machine, ITestResultBin bin, IDictionary <string, string> env)
        {
            ITestResource res = Repo.GetResource(name);

            TestResult tr = new TestResult();

            try
            {
                string winDirectory = TestPathPrefix + name + "\\" + DateTime.Now.Ticks + "\\";

                string targetFileName = winDirectory + name + ".bat";
                using (Stream s = res.Read())
                {
                    machine.PutFile(targetFileName, s);
                }

                ProgramResult result = machine.RunProgram(targetFileName, "", winDirectory, env);

                // Hoover up artifacts  *SLUURRRRRP*
                var artifacts = machine.ListFiles(winDirectory);
                foreach (var fileName in artifacts)
                {
                    string tempFile = Path.GetTempFileName();
                    using (FileStream fs = File.Create(tempFile))
                    {
                        machine.GetFile(fileName, fs);
                        fs.Seek(0, SeekOrigin.Begin);
                        bin.PutArtifact(new ArtifactInfo()
                        {
                            Name        = fileName,
                            Description = fileName,
                            FileName    = fileName
                        }, fs);
                    }
                    File.Delete(tempFile);
                }
                tr.Success = result.ExitCode == 0;
            } catch (Exception e)
            {
                tr.Success       = false;
                tr.StandardError = e.Message;
            }


            return(tr);
        }
Exemplo n.º 4
0
    private static ProgramPairResults RunPairAsync(AssemblyLoadContext alc, ProgramPair pair)
    {
        ProgramResult debugResult   = RunAndGetResultAsync(pair.Debug);
        ProgramResult releaseResult = RunAndGetResultAsync(pair.Release);
        ChecksumSite  unmatch1      = null;
        ChecksumSite  unmatch2      = null;

        if (debugResult.Checksum != releaseResult.Checksum && pair.TrackOutput)
        {
            int index;
            int count = Math.Min(debugResult.ChecksumSites.Count, releaseResult.ChecksumSites.Count);
            for (index = 0; index < count; index++)
            {
                ChecksumSite val1 = debugResult.ChecksumSites[index];
                ChecksumSite val2 = releaseResult.ChecksumSites[index];
                if (val1 != val2)
                {
                    break;
                }
            }

            if (index < debugResult.ChecksumSites.Count)
            {
                unmatch1 = debugResult.ChecksumSites[index];
            }
            if (index < releaseResult.ChecksumSites.Count)
            {
                unmatch2 = releaseResult.ChecksumSites[index];
            }
        }

        return(new ProgramPairResults(debugResult, releaseResult, unmatch1, unmatch2));

        ProgramResult RunAndGetResultAsync(byte[] bytes)
        {
            Assembly          asm            = alc.LoadFromStream(new MemoryStream(bytes));
            MethodInfo        mainMethodInfo = asm.GetType("Program").GetMethod("Main");
            Action <IRuntime> entryPoint     = (Action <IRuntime>)Delegate.CreateDelegate(typeof(Action <IRuntime>), mainMethodInfo);
            var runtime = new Runtime();

            List <ChecksumSite> TakeChecksumSites()
            {
                // A reference to the runtime stays in the loaded assembly and there may be a lot of checksum sites
                // so during reduction this can use a lot of memory.
                List <ChecksumSite> checksumSites = runtime.ChecksumSites;

                runtime.ChecksumSites = null;
                return(checksumSites);
            }

            if (pair.TrackOutput)
            {
                runtime.ChecksumSites = new List <ChecksumSite>();
            }

            int threadID = Environment.CurrentManagedThreadId;
            List <Exception> exceptions = null;

            void FirstChanceExceptionHandler(object sender, FirstChanceExceptionEventArgs args)
            {
                if (Environment.CurrentManagedThreadId == threadID)
                {
                    (exceptions ??= new List <Exception>()).Add(args.Exception);
                }
            }

            AppDomain.CurrentDomain.FirstChanceException += FirstChanceExceptionHandler;
            try
            {
                entryPoint(runtime);
            }
            catch
            {
                // We consider the innermost exception the root cause and only report it.
                // Otherwise we may be confusing the viewer about what the problem is.
                // Consider for example (adapted from a real example):
                // try
                // {
                //   value = -1;
                //   FunctionThatJitAssertsInDebug();
                //   value = 1;
                // }
                // finally
                // {
                //   int.MinValue / value;
                // }
                // We are interested in the JIT assert that was hit, and not the OverflowException
                // thrown because value = 1 did not get to run.
                Exception ex = exceptions[0];

                if (ex is InvalidProgramException && ex.Message.Contains("JIT assert failed"))
                {
                    return(new ProgramResult
                    {
                        Kind = ProgramResultKind.HitsJitAssert,
                        Checksum = runtime.FinishHashCode(),
                        ChecksumSites = TakeChecksumSites(),
                        JitAssertError = ex.Message,
                    });
                }

                return(new ProgramResult
                {
                    Kind = ProgramResultKind.ThrowsException,
                    Checksum = runtime.FinishHashCode(),
                    ChecksumSites = TakeChecksumSites(),
                    ExceptionType = ex.GetType().FullName,
                    ExceptionText = ex.ToString(),
                    ExceptionStackTrace = ex.StackTrace,
                });
            }
            finally
            {
                AppDomain.CurrentDomain.FirstChanceException -= FirstChanceExceptionHandler;
            }

            return(new ProgramResult
            {
                Kind = ProgramResultKind.RunsSuccessfully,
                Checksum = runtime.FinishHashCode(),
                ChecksumSites = TakeChecksumSites(),
            });
        }
    }
 private ProgramResult RunControllerSoftwareWithFeedback(int[] memory, ProgramResult state, Sys device, int input)
 {
     device.Write(input);
     return(state.Resume(memory));
 }
Exemplo n.º 6
0
        public void Go()
        {
            try
            {
                if (this.vm != null)
                {
                    TransactionCapsule tx = new TransactionCapsule(this.transaction);
                    if (null != this.block &&
                        this.block.IsGenerateMyself &&
                        tx.ContractResult != contractResult.Unknown &&
                        tx.ContractResult == contractResult.OutOfTime)
                    {
                        this.result = this.program.Result;
                        this.program.SpendAllEnergy();

                        OutOfTimeException e = VMExceptions.AlreadyTimeOut();
                        this.runtime_error    = e.Message;
                        this.result.Exception = e;
                        throw e;
                    }

                    vm.Play(program);
                    this.result = this.program.Result;

                    if (this.is_static_call)
                    {
                        long call_value       = TransactionCapsule.GetCallValue(this.transaction.RawData.Contract[0]);
                        long call_token_value = TransactionCapsule.GetCallTokenValue(this.transaction.RawData.Contract[0]);
                        if (call_value > 0 || call_token_value > 0)
                        {
                            this.runtime_error = "constant cannot set call value or call token value.";
                            this.result.RejectInternalTransaction();
                        }

                        return;
                    }

                    if (this.transaction_type == TransactionType.TX_CONTRACT_CREATION_TYPE &&
                        !this.result.IsRevert)
                    {
                        byte[] code             = this.program.Result.HReturn;
                        long   save_code_energy = (long)code.Length * EnergyCost.CREATE_DATA;
                        long   after_Spend      = this.program.EnergyLimitLeft.ToLong() - save_code_energy;
                        if (after_Spend < 0)
                        {
                            if (this.result.Exception == null)
                            {
                                this.result.Exception = VMExceptions.NotEnoughSpendEnergy(
                                    "save just created contract code",
                                    save_code_energy,
                                    this.program.EnergyLimitLeft.ToLong());
                            }
                        }
                        else
                        {
                            this.result.SpendEnergy(save_code_energy);
                            if (VMConfig.AllowTvmConstantinople)
                            {
                                this.deposit.SaveCode(this.program.ContractAddress.GetNoLeadZeroesData(), code);
                            }
                        }
                    }

                    if (this.result.Exception != null || this.result.IsRevert)
                    {
                        this.result.DeleteAccount.Clear();
                        this.result.LogInfos.Clear();
                        this.result.ResetFutureRefund();
                        this.result.RejectInternalTransaction();

                        if (this.result.Exception != null)
                        {
                            if (!(this.result.Exception is TransferException))
                            {
                                this.program.SpendAllEnergy();
                            }
                            this.runtime_error = this.result.Exception.Message;
                            throw this.result.Exception;
                        }
                        else
                        {
                            this.runtime_error = "REVERT opcode executed";
                        }
                    }
                    else
                    {
                        this.deposit.Commit();

                        if (this.log_info_parser != null)
                        {
                            List <ContractTrigger> triggers = this.log_info_parser.ParseLogInfos(this.program.Result.LogInfos, this.deposit);
                            this.program.Result.Triggers = triggers;
                        }
                    }
                }
                else
                {
                    this.deposit.Commit();
                }
            }
            catch (VMStackOverFlowException e)
            {
                this.program.SpendAllEnergy();
                this.result           = this.program.Result;
                this.result.Exception = e;
                this.result.RejectInternalTransaction();
                this.runtime_error = this.result.Exception.Message;
                Logger.Info("JVMStackOverFlowException : " + this.result.Exception.Message);
            }
            catch (OutOfTimeException e)
            {
                this.program.SpendAllEnergy();
                this.result           = this.program.Result;
                this.result.Exception = e;
                this.result.RejectInternalTransaction();
                this.runtime_error = result.Exception.Message;
                Logger.Info("timeout : " + this.result.Exception.Message);
            }
            catch (System.Exception e)
            {
                if (!(e is TransferException))
                {
                    this.program.SpendAllEnergy();
                }
                this.result = this.program.Result;
                this.result.RejectInternalTransaction();
                if (this.result.Exception == null)
                {
                    Logger.Error(e.Message);
                    this.result.Exception = new System.Exception("Unknown exception");
                }

                if (this.runtime_error == null || this.runtime_error.Length == 0)
                {
                    this.runtime_error = this.result.Exception.Message;
                }
                Logger.Info("runtime result is : " + this.result.Exception.Message);
            }

            this.trace.SetBill(this.result.EnergyUsed);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Result(int id, string filePath)
        {
            Problem problem = await dbContext.Problems.Include(m => m.Tests).FirstOrDefaultAsync(p => p.ProblemID == id);

            if (problem == null)
            {
                return(RedirectToAction(nameof(List)));
            }

            if (!System.IO.File.Exists(filePath))
            {
                return(RedirectToAction(nameof(Solve), new { id }));
            }

            string parentFolderPath = Directory.GetParent(filePath).FullName;

            ResultViewModel viewModel = new ResultViewModel()
            {
                ProblemID           = problem.ProblemID,
                Name                = problem.Name,
                ShowFailedTestCases = problem.ShowFailedTestCases
            };
            UserProgram userProgram = new UserProgram();

            var result = userProgram.SetSource(filePath);

            viewModel.CompilationResult = result;

            if (result.Status == UserProgram.Result.StatusType.Failed)
            {
                Directory.Delete(parentFolderPath, true);

                return(View(viewModel));
            }

            result = userProgram.Compile();
            viewModel.CompilationResult = result;

            if (result.Status == UserProgram.Result.StatusType.Failed)
            {
                Directory.Delete(parentFolderPath, true);

                viewModel.CompilationResult = result;
                return(View(viewModel));
            }

            int passed = 0;

            foreach (Test t in problem.Tests)
            {
                result = userProgram.Execute(t.GivenInput);
                ResultViewModel.TestResult testResult = new ResultViewModel.TestResult()
                {
                    Test = t, ExecutionResult = result
                };

                if (result.Status == UserProgram.Result.StatusType.Successful)
                {
                    // Format expected output lines
                    string[] expectedOutputLines = t.ExpectedOutput.Split('\n');
                    for (int i = 0; i < expectedOutputLines.Length; i++)
                    {
                        expectedOutputLines[i] = expectedOutputLines[i].Trim('\u202c').Trim();
                    }

                    result = userProgram.EvaluateAndGetResultIfFailed(expectedOutputLines);

                    if (result.Status == UserProgram.Result.StatusType.Successful)
                    {
                        passed++;
                    }

                    testResult.EvaluationResult = result;
                    viewModel.TestResults.Add(testResult);
                }
                else
                {
                    viewModel.TestResults.Add(testResult);
                }
            }

            viewModel.PassedTests = passed;

            try
            {
                Directory.Delete(parentFolderPath, true);
            }
            catch (UnauthorizedAccessException) // Sometimes the process isn't killed fast enough
            {
                Thread.Sleep(100);
                Directory.Delete(parentFolderPath, true);
            }

            ApplicationUser partialUser = await userManager.GetUserAsync(User);

            ApplicationUser currentUser = await userManager.Users
                                          .Include(u => u.ProblemResults)
                                          .ThenInclude(r => r.FirstResult)
                                          .Include(u => u.ProblemResults)
                                          .ThenInclude(r => r.BestResult)
                                          .FirstOrDefaultAsync(u => u == partialUser);

            if (currentUser != null)
            {
                bool hasProblem           = currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID);
                bool gotPerfectPercentage = false;
                if (hasProblem)
                {
                    ProblemResult problemResult  = currentUser.ProblemResults.Where(r => r.ProblemID == problem.ProblemID).First();
                    int           bestPercentage = problemResult.BestResult.PercentageResult;
                    gotPerfectPercentage = bestPercentage < 100;
                }

                bool isAdmin = await userManager.IsInRoleAsync(currentUser, "Admin");

                // A unique user solved the problem and is not an Admin
                if (passed == problem.Tests.Count && (!hasProblem || (hasProblem && gotPerfectPercentage)) && !isAdmin)
                {
                    problem.TimesSolved++;

                    if (await TryUpdateModelAsync(problem))
                    {
                        try
                        {
                            await dbContext.SaveChangesAsync();
                        }
                        catch (DbUpdateException)
                        {
                            return(View(viewModel));
                        }
                    }
                }

                ProgramResult programResult = viewModel.GetProgramResult();
                if (currentUser.ProblemResults.Exists(r => r.ProblemID == problem.ProblemID))
                {
                    // Tried to solve the problem again
                    ProblemResult problemResult = currentUser.ProblemResults.First(r => r.ProblemID == problem.ProblemID);
                    if (programResult.PercentageResult > problemResult.BestResult.PercentageResult)
                    {
                        if (problemResult.BestResult != problemResult.FirstResult)
                        {
                            dbContext.Remove(problemResult.BestResult);
                        }
                        problemResult.BestResult = programResult;
                    }
                }
                else
                {
                    // Solved this problem for the first time
                    ProblemResult problemResult = new ProblemResult()
                    {
                        ProblemID   = problem.ProblemID,
                        FirstResult = programResult,
                        BestResult  = programResult
                    };
                    currentUser.ProblemResults.Add(problemResult);
                }

                await userManager.UpdateAsync(currentUser);
            }

            return(View(viewModel));
        }
Exemplo n.º 8
0
        public static TransactionInfoCapsule BuildInstance(TransactionCapsule transaction, BlockCapsule block, TransactionTrace trace)
        {
            TransactionInfo result  = new TransactionInfo();
            ReceiptCapsule  receipt = trace.Receipt;

            result.Result = TransactionInfo.Types.code.Sucess;
            if (trace.RuntimeError.IsNotNullOrEmpty() ||
                trace.Result.Exception != null)
            {
                result.Result     = TransactionInfo.Types.code.Failed;
                result.ResMessage = ByteString.CopyFromUtf8(trace.RuntimeError);
            }

            result.Id = ByteString.CopyFrom(transaction.Id.Hash);
            ProgramResult program_result = trace.Result;

            long fee = program_result.TransactionResult.Fee
                       + receipt.EnergyFee
                       + receipt.NetFee
                       + receipt.MultiSignFee;


            result.Fee = fee;
            result.ContractResult.Add(ByteString.CopyFrom(program_result.HReturn));
            result.ContractAddress               = ByteString.CopyFrom(program_result.ContractAddress);
            result.UnfreezeAmount                = program_result.TransactionResult.UnfreezeAmount;
            result.AssetIssueID                  = program_result.TransactionResult.AssetIssueID;
            result.ExchangeId                    = program_result.TransactionResult.ExchangeId;
            result.WithdrawAmount                = program_result.TransactionResult.WithdrawAmount;
            result.ExchangeReceivedAmount        = program_result.TransactionResult.ExchangeReceivedAmount;
            result.ExchangeInjectAnotherAmount   = program_result.TransactionResult.ExchangeInjectAnotherAmount;
            result.ExchangeWithdrawAnotherAmount = program_result.TransactionResult.ExchangeWithdrawAnotherAmount;

            List <TransactionInfo.Types.Log> logs = new List <TransactionInfo.Types.Log>();

            program_result.LogInfos.ForEach(info => logs.Add(LogInfo.BuildLog(info)));
            result.Log.AddRange(logs);

            if (block != null)
            {
                result.BlockNumber    = block.Instance.BlockHeader.RawData.Number;
                result.BlockTimeStamp = block.Instance.BlockHeader.RawData.Timestamp;
            }

            result.Receipt = receipt.Receipt;

            if (Args.Instance.VM.SaveInternalTx == true && program_result.InternalTransactions != null)
            {
                foreach (var tx in program_result.InternalTransactions)
                {
                    Protocol.InternalTransaction internal_transaction = new Protocol.InternalTransaction();
                    internal_transaction.Hash              = ByteString.CopyFrom(tx.Hash);
                    internal_transaction.CallerAddress     = ByteString.CopyFrom(tx.SendAddress);
                    internal_transaction.TransferToAddress = ByteString.CopyFrom(tx.TransferToAddress);

                    CallValueInfo call_value_info = new CallValueInfo();
                    call_value_info.CallValue = tx.Value;
                    internal_transaction.CallValueInfo.Add(call_value_info);

                    foreach (var token_info in tx.TokenInfo)
                    {
                        call_value_info           = new CallValueInfo();
                        call_value_info.TokenId   = token_info.Key;
                        call_value_info.CallValue = token_info.Value;
                        internal_transaction.CallValueInfo.Add(call_value_info);
                    }

                    internal_transaction.Note     = ByteString.CopyFrom(Encoding.UTF8.GetBytes(tx.Note));
                    internal_transaction.Rejected = tx.IsReject;
                    result.InternalTransactions.Add(internal_transaction);
                }
            }

            return(new TransactionInfoCapsule(result));
        }