Exemplo n.º 1
0
        /// <summary>
        /// A wire that verifies each response.
        /// </summary>
        public Verified(IWire origin, IVerification verification) : base(request =>
        {
            var response =
                RuntimeInformation.OSDescription == "Browser"
                ?
                origin.Response(request).Result
                :
                AsyncContext.Run(() => origin.Response(request));

            verification.Verify(response);
            return(new TaskFactory().StartNew <IDictionary <string, string> >(() => response));
        })
        { }
        /// <summary>
        /// Check input data using verification method in interface variable and input kind of storage.
        /// </summary>
        /// <param name="inputData">
        /// Input password.
        /// </param>
        /// <param name="verification">
        /// Type of checking.
        /// </param>
        /// <param name="storage">
        /// Type of storage.
        /// </param>
        /// <returns>
        /// True if password is correct.
        /// </returns>
        public bool VerifyInputData(string inputData, IVerification verification, IRepository storage)
        {
            if (verification == null || storage == null)
            {
                throw new ArgumentNullException();
            }

            if (!verification.Verify(inputData))
            {
                return(false);
            }

            repository = storage;
            repository.Create(inputData);
            return(true);
        }
Exemplo n.º 3
0
        private async Task SubmitSolution(Challenge challenge, string program, bool save)
        {
            var code = program.ExtractYololCodeBlock();

            if (code == null)
            {
                await ReplyAsync(@"Failed to parse a yolol program from message - ensure you have enclosed your solution in triple backticks \`\`\`like this\`\`\`");

                return;
            }

            var(success, failure) = await _verification.Verify(challenge, code).ConfigureAwait(false);

            if (failure != null)
            {
                var message = failure.Type switch {
                    FailureType.ParseFailed => $"Code is not valid Yolol code:\n```{failure.Hint}```",
                    FailureType.RuntimeTooLongTicks => $"Program took too many ticks to produce a result. {failure.Hint}",
                    FailureType.RuntimeTooLongMilliseconds => $"Program took too long to produce a result. {failure.Hint}",
                    FailureType.IncorrectResult => $"Program produced an incorrect value! {failure.Hint}",
                    FailureType.ProgramTooLarge => "Program is too large - it must be 20 lines by 70 characters per line",
                    FailureType.InvalidProgramForChipType => $"Program used a feature which is not available on this level of Yolol chip. {failure.Hint}",
                    FailureType.ChallengeCodeFailed => $"Challenge code crashed! Please contact Martin#2468. {failure.Hint}",
                    FailureType.ChallengeForceFail => $"{failure.Hint}",
                    FailureType.Other => failure.Hint,
                    _ => throw new InvalidOperationException($"Unknown failure type: {failure.Type}")
                };

                await ReplyWithHint("Verification Failed!", message, failure.TestCase);

                return;
            }

            if (success == null)
            {
                throw new InvalidOperationException("Failed to verify solution (this is a bug, please contact @Martin#2468)");
            }

            await SubmitAndReply(success, new Solution(challenge.Id, Context.User.Id, success.Score, code), save);
        }
Exemplo n.º 4
0
 public void Verify(IVerification verification)
 {
     verification.Verify(this.ruleTree);
 }
Exemplo n.º 5
0
        public async Task SubmitSolution([Remainder] string input)
        {
            var code = input.ExtractYololCodeBlock();

            if (code == null)
            {
                await ReplyAsync(@"Failed to parse a yolol program from message - ensure you have enclosed your solution in triple backticks \`\`\`like this\`\`\`");

                return;
            }

            var challenge = await _challenges.GetCurrentChallenge();

            if (challenge == null)
            {
                await ReplyAsync("There is no currently running challenge!");

                return;
            }

            var(success, failure) = await _verification.Verify(challenge, code);

            if (failure != null)
            {
                var message = failure.Type switch {
                    FailureType.ParseFailed => $"Code is not valid Yolol code: {failure.Hint}",
                    FailureType.RuntimeTooLong => "Program took too long to produce a result",
                    FailureType.IncorrectResult => $"Program produced an incorrect value! {failure.Hint}",
                    FailureType.ProgramTooLarge => "Program is too large - it must be 20 lines by 70 characters per line",
                    _ => throw new ArgumentOutOfRangeException()
                };

                await ReplyAsync($"Verification failed! {message}.");
            }
            else if (success != null)
            {
                var solution = await _solutions.GetSolution(Context.User.Id, challenge.Id);

                if (solution.HasValue && success.Score < solution.Value.Score)
                {
                    await ReplyAsync($"Verification complete! You score {success.Score} points. Less than your current best of {solution.Value.Score}");
                }
                else
                {
                    // Get the current top solution
                    var topBefore = await _solutions.GetTopRank(challenge.Id).ToArrayAsync();

                    // Submit this solution
                    await _solutions.SetSolution(new Solution(challenge.Id, Context.User.Id, success.Score, code));

                    var rank = await _solutions.GetRank(challenge.Id, Context.User.Id);

                    var rankNum = uint.MaxValue;
                    if (rank.HasValue)
                    {
                        rankNum = rank.Value.Rank;
                    }
                    await ReplyAsync($"Verification complete! You scored {success.Score} points. You are currently rank {rankNum} for this challenge.");

                    // If this is the top ranking score, and there was a top ranking score before, and it wasn't this user: alert everyone
                    if (rankNum == 1 && topBefore.Length > 0 && topBefore.All(a => a.Solution.UserId != Context.User.Id))
                    {
                        var embed = new EmbedBuilder {
                            Title  = "Rank Alert",
                            Color  = Color.Gold,
                            Footer = new EmbedFooterBuilder().WithText("A Cylon Project")
                        };

                        var self = await _client.GetUserName(Context.User.Id);

                        var prev = (await topBefore.ToAsyncEnumerable().SelectAwait(async a => await _client.GetUserName(a.Solution.UserId)).ToArrayAsync()).Humanize("&");

                        embed.Description = success.Score == topBefore[0].Solution.Score
                            ? $"{self} ties for rank #1"
                            : $"{self} takes rank #1 from {prev}!";

                        await _broadcast.Broadcast(embed.Build());
                    }
                }
            }
            else
            {
                throw new InvalidOperationException("Failed to verify solution (this is a bug, please contact @Martin#2468)");
            }
        }
Exemplo n.º 6
0
        public async Task Rescore(string id)
        {
            var uid = BalderHash.BalderHash32.Parse(id);

            if (!uid.HasValue)
            {
                await ReplyAsync($"Cannot parse `{id}` as a challenge ID");

                return;
            }

            var challenges = await _challenges.GetChallenges(id : uid.Value.Value, includeUnstarted : true).ToArrayAsync();

            if (challenges.Length == 0)
            {
                await ReplyAsync("Cannot find challenge with given ID");

                return;
            }

            if (challenges.Length > 1)
            {
                await ReplyAsync("Found more than one challenge, please disambiguate:");

                foreach (var challenge in challenges)
                {
                    await ReplyAsync($" - {challenge.Name} (`{((uint)challenge.Id).BalderHash()}`)");

                    await Task.Delay(10);
                }
                return;
            }

            var c = challenges.Single();

            await ReplyAsync($" - {c.Name} (`{((uint)c.Id).BalderHash()}`)");

            await ReplyAsync("Rescore this challenge (yes/no)?");

            var confirm = (await NextMessageAsync(timeout: TimeSpan.FromMilliseconds(-1))).Content;

            if (!confirm.Equals("yes", StringComparison.OrdinalIgnoreCase))
            {
                await ReplyAsync("Not rescoring anything");

                return;
            }

            var solutions = await _solutions.GetSolutions(c.Id, uint.MaxValue).ToArrayAsync();

            const string pbarHeader = "Rescoring: ";
            var          progress   = await ReplyAsync(pbarHeader);

            var totalTicks = 0l;
            var failures   = 0;
            var results    = new List <RescoreItem>(solutions.Length);

            for (var i = 0; i < solutions.Length; i++)
            {
                await progress.ModifyAsync(a => a.Content = $"{pbarHeader} {i}/{solutions.Length}");

                var s = solutions[i];
                var(success, failure) = await _verification.Verify(c, s.Solution.Yolol);

                if (success != null)
                {
                    totalTicks += success.Iterations;
                    results.Add(new RescoreItem(
                                    s.Solution,
                                    new Solution(s.Solution.ChallengeId, s.Solution.UserId, success.Score, s.Solution.Yolol)
                                    ));
                }
                else if (failure != null)
                {
                    failures++;
                    results.Add(new RescoreItem(
                                    s.Solution,
                                    new Solution(s.Solution.ChallengeId, s.Solution.UserId, s.Solution.Score, s.Solution.Yolol),
                                    failure.Hint
                                    ));
                }
                else
                {
                    throw new InvalidOperationException("Verification did not return success or failure");
                }

                await Task.Delay(100);
            }

            await progress.ModifyAsync(a => a.Content = $"Completed rescoring ({totalTicks} total ticks)");

            if (failures > 0)
            {
                await ReplyAsync($"{failures} solutions failed to verify");
            }

            var report = new StringBuilder();

            report.AppendLine($"Rescoring `{c.Name}`");
            foreach (var rescore in results)
            {
                report.AppendLine($"{await UserName(rescore.Before.UserId)}: {rescore.Before.Score} => {rescore.After.Score}");
            }
            await ReplyAsync(report.ToString());

            await ReplyAsync("Apply rescoring to this challenge (yes/no)?");

            var confirm2 = (await NextMessageAsync(timeout: TimeSpan.FromMilliseconds(-1))).Content;

            if (!confirm2.Equals("yes", StringComparison.OrdinalIgnoreCase))
            {
                await ReplyAsync("Not applying rescoring");

                return;
            }

            foreach (var rescore in results)
            {
                await _solutions.SetSolution(rescore.After);
            }

            await ReplyAsync("Done.");
        }