Exemple #1
0
        public void AddNoise_ShouldAddNoise(double randomValue, double maxNoise, double expectedOffset)
        {
            var rand  = MockRandom.Get(randomValue);
            var input = new[] { 0.0, 0.2 };

            var expected = new[] { 0, 0.2 * (1 + expectedOffset) };
            var result   = input.AddRelativeNoise(maxNoise, rand);

            result.ShouldApproximatelyEqual(expected);
        }
Exemple #2
0
        public void RandomZero()
        {
            var mockRandom = new MockRandom();

            mockRandom.GetScalarResults.Add(Scalar.Zero);

            // Don't tolerate if the second zero scalar random is received.
            mockRandom.GetScalarResults.Add(Scalar.Zero);

            Assert.ThrowsAny <InvalidOperationException>(() => Prover.CreateProof(new KnowledgeOfDlogParams(Scalar.One, new Statement(Scalar.One * Generators.G, Generators.G)), mockRandom));
        }
Exemple #3
0
        public void RandomOverflow()
        {
            var mockRandom = new MockRandom();

            foreach (var scalar in CryptoHelpers.GetScalars(x => x.IsOverflow))
            {
                mockRandom.GetScalarResults.Add(scalar);

                Assert.ThrowsAny <InvalidOperationException>(() => Prover.CreateProof(new KnowledgeOfDlogParams(Scalar.One, new Statement(Scalar.One * Generators.G, Generators.G)), mockRandom));
            }
        }
Exemple #4
0
        public void SelectTest([Range(-1, 21, 1)] int selIdx)
        {
            var rn = new MockRandom();

            rn.IntValue = selIdx;
            var uList = SelectorTestsHelper.CreateRandomUtilityList(20);
            var s     = new RandomSelector(rn);

            var aIdx = s.Select(uList);
            var cIdx = selIdx.Clamp(0, 19);

            Assert.That(aIdx, Is.EqualTo(cIdx));
        }
Exemple #5
0
        public void End2EndVerificationSimple(uint scalarSeed)
        {
            var secret      = new Scalar(scalarSeed);
            var generator   = Generators.G;
            var publicPoint = secret * generator;
            var statement   = new Statement(publicPoint, generator);
            var random      = new MockRandom();

            random.GetBytesResults.Add(new byte[32]);
            var proof = ProofSystemHelpers.Prove(statement, secret, random);

            Assert.True(ProofSystemHelpers.Verify(statement, proof));
        }
Exemple #6
0
        public void SyntheticNoncesSecretDependenceTest()
        {
            var protocol = Encoding.UTF8.GetBytes("test TranscriptRng collisions");

            // if all synthetic nonce provider get the same randomness, nonce sequences
            // with different witnesses or commitments should still diverge
            var rnd = new MockRandom();

            rnd.GetBytesResults.Add(new byte[32]);
            rnd.GetBytesResults.Add(new byte[32]);
            rnd.GetBytesResults.Add(new byte[32]);
            rnd.GetBytesResults.Add(new byte[32]);

            var commitment1 = new[] { Generators.Gx0 };
            var commitment2 = new[] { Generators.Gx1 };
            var witness1    = new[] { Scalar.One };
            var witness2    = new[] { Scalar.Zero };

            var transcript1 = new Transcript(protocol);
            var transcript2 = new Transcript(protocol);
            var transcript3 = new Transcript(protocol);
            var transcript4 = new Transcript(protocol);

            transcript1.CommitPublicNonces(commitment1);
            transcript2.CommitPublicNonces(commitment2);
            transcript3.CommitPublicNonces(commitment2);
            transcript4.CommitPublicNonces(commitment2);

            var secretNonceGenerator1 = transcript1.CreateSyntheticSecretNonceProvider(witness1, rnd);
            var secretNonceGenerator2 = transcript2.CreateSyntheticSecretNonceProvider(witness1, rnd);
            var secretNonceGenerator3 = transcript3.CreateSyntheticSecretNonceProvider(witness2, rnd);
            var secretNonceGenerator4 = transcript4.CreateSyntheticSecretNonceProvider(witness2, rnd);

            Assert.Empty(rnd.GetBytesResults);

            var secretNonce1 = secretNonceGenerator1.GetScalar();
            var secretNonce2 = secretNonceGenerator2.GetScalar();
            var secretNonce3 = secretNonceGenerator3.GetScalar();
            var secretNonce4 = secretNonceGenerator4.GetScalar();

            Assert.NotEqual(secretNonce1, secretNonce2);
            Assert.NotEqual(secretNonce1, secretNonce3);
            Assert.NotEqual(secretNonce1, secretNonce4);

            Assert.NotEqual(secretNonce2, secretNonce3);
            Assert.NotEqual(secretNonce2, secretNonce4);

            // Since transcript3 and transcript4 share the same public inputs and
            // witness, with no randomness they should be identical
            Assert.Equal(secretNonce3, secretNonce4);
        }
Exemple #7
0
        public void Simple()
        {
            var r = new MockRandom();

            var key = new byte[54];

            r.Fill(new ArraySegment <byte>(key));

            var de = Default.CreateDecrypt(key);
            var en = Default.CreateEncrypt(key, r);

            const int maxSize = 1024 * 1024 * 16;
            var       input   = new byte[maxSize];

            r.Fill(new ArraySegment <byte>(input));
            var out1 = new byte[maxSize];
            var out2 = new byte[maxSize];
            var tmp  = new byte[maxSize];

            for (var i = 1; i < maxSize; i = 3 * i + 1)
            {
                Console.WriteLine(i);
                var inas     = new ArraySegment <byte>(input, 0, i);
                var enInfo   = en.Analyze(inas);
                var out1As   = new ArraySegment <byte>(out1, 0, enInfo.EncryptedMaxSize);
                var out2As   = new ArraySegment <byte>(out2, 0, enInfo.EncryptedMaxSize);
                var enCount1 = en.Encrypt(inas, out1As, enInfo);
                var enCount2 = en.Encrypt(inas, out2As, enInfo);

                Assert.AreEqual(enCount1, enCount2);
                Assert.False(AllSame(enCount1, out1, out2));

                {
                    var en1As    = new ArraySegment <byte>(out1, 0, enCount1);
                    var de1Info  = de.Analyze(en1As);
                    var tmpAs    = new ArraySegment <byte>(tmp, 0, de1Info.DecryptedMaxSize);
                    var deCount1 = de.Decrypt(en1As, tmpAs, de1Info);
                    Assert.AreEqual(i, deCount1);
                    Assert.True(AllSame(deCount1, input, tmp));
                }

                {
                    var en2As    = new ArraySegment <byte>(out2, 0, enCount2);
                    var de2Info  = de.Analyze(en2As);
                    var tmpAs    = new ArraySegment <byte>(tmp, 0, de2Info.DecryptedMaxSize);
                    var deCount2 = de.Decrypt(en2As, tmpAs, de2Info);
                    Assert.AreEqual(i, deCount2);
                    Assert.True(AllSame(deCount2, input, tmp));
                }
            }
        }
        public void End2EndVerificationSimple(uint scalarSeed1, uint scalarSeed2)
        {
            var secrets     = new ScalarVector(new Scalar(scalarSeed1), new Scalar(scalarSeed2));
            var generators  = new GroupElementVector(Generators.G, Generators.Ga);
            var publicPoint = secrets * generators;

            var statement = new Statement(publicPoint, generators);
            var random    = new MockRandom();

            random.GetBytesResults.Add(new byte[32]);
            var proof = ProofSystemHelpers.Prove(statement, secrets, random);

            Assert.True(ProofSystemHelpers.Verify(statement, proof));
        }
        public unsafe static void RandomShuffle(NonContiguousList <GameObjectStruct> l, Unity.Mathematics.Random r)
        {
            for (int i = 0; i < l.Length; i++)
            {
                var idx  = r.NextInt(0, l.Length);
                var tmp0 = l.mData[idx];
                var tmp1 = l.mData[i];
                tmp0->Random = new MockRandom((uint)i + 1);
                l.mData[i]   = tmp0;

                tmp1->Random = new MockRandom((uint)idx + 1);
                l.mData[idx] = tmp1;
            }
        }
Exemple #10
0
        public async Task SurrogatePairName()
        {
            MockRandom.Setup(x => x.Next(2)).Returns(0).Verifiable();
            await Target.RequestIntroductionAsync();

            await Target.SubmitContractAsync(new ContractPaper("𠮷田"));

            Assert.Collection(Target.Messages,
                              act => Assert.Equal("フン。", act.Value),
                              act => Assert.Equal("𠮷田というのかい。", act.Value),
                              act => Assert.Equal("贅沢な名だねぇ。", act.Value),
                              act => Assert.Equal("今からお前の名前は𠮷だ。", act.Value),
                              act => Assert.Equal("いいかい、𠮷だよ。", act.Value),
                              act => Assert.Equal("分かったら返事をするんだ、𠮷!!", act.Value));
            MockRandom.VerifyAll();
        }
Exemple #11
0
        public void Test3a()
        {
            // paths = 0123450
            var random = new MockRandom(new List <int>()
            {
                0, 0, 0, 1, 1, 1, 0
            });
            var paths = new Paths(new Complete2(random, 6));

            paths.Generate();
            var(n, m) = paths.Neighbours(0);
            Assert.AreEqual(1, n);
            Assert.AreEqual(5, m);
            (n, m) = paths.Neighbours(3);
            Assert.AreEqual(4, n);
            Assert.AreEqual(2, m);
        }
Exemple #12
0
        public void Test4a()
        {
            // paths = 5432105
            var random = new MockRandom(new List <int>()
            {
                5, 4, 3, 2, 1, 0, 0
            });
            var paths = new Paths(new Complete2(random, 6));

            paths.Generate();
            var(n, m) = paths.Neighbours(5);
            Assert.AreEqual(4, n);
            Assert.AreEqual(0, m);
            (n, m) = paths.Neighbours(2);
            Assert.AreEqual(1, n);
            Assert.AreEqual(3, m);
        }
Exemple #13
0
        public void ShouldStopWhenNoImprovement(int lastEpochOfImprovement,
                                                int maxEpochsWithoutImprovement,
                                                int epochsBetweenValidation,
                                                int expectedEvaluations)
        {
            _trainer.MaxEpochsWithoutImprovement = maxEpochsWithoutImprovement;
            _trainer.EpochsBetweenValidations    = epochsBetweenValidation;
            _trainer.NumEpochs = 100;

            var mockNeuralNet = GetMockNeuralNetwork();
            var nn            = mockNeuralNet.Object;

            _stepsOfImprovementRemaning = lastEpochOfImprovement / epochsBetweenValidation + 1;
            _trainer.Train(GetTrainingSet(), GetValidationSet(), MockRandom.Get(), nn);

            mockNeuralNet.Verify(n => n.FeedForward(It.IsAny <double[]>()), Times.Exactly(expectedEvaluations));
        }
Exemple #14
0
        public void Test2a()
        {
            // paths = 325013, 44
            var random = new MockRandom(new List <int>()
            {
                3, 2, 3, 0, 0, 0, 0
            });
            var paths = new Paths(new Complete2(random, 6));

            paths.Generate();
            var(n, m) = paths.Neighbours(5);
            Assert.AreEqual(0, n);
            Assert.AreEqual(2, m);
            (n, m) = paths.Neighbours(1);
            Assert.AreEqual(3, n);
            Assert.AreEqual(0, m);
            (n, m) = paths.Neighbours(4);
            Assert.AreEqual(4, n);
            Assert.AreEqual(4, m);
        }
Exemple #15
0
        public void Train_OneEpoch()
        {
            var mockNeuralNet = GetMockNeuralNetwork();
            var nn            = mockNeuralNet.Object;

            _trainer.Train(GetTrainingSet(), GetValidationSet(), MockRandom.Get(), nn);

            nn.Should().NotBeNull();
            var weights = nn.Weights;

            weights.Should().NotBeNullOrEmpty();
            weights.Should().HaveCount(2);

            var expected = new[] { new[] { 0.825, 1.65, 2.475 }, new[] { 0.425 } };

            for (var i = 0; i < weights.Length; i++)
            {
                weights[i].ShouldApproximatelyEqual(expected[i]);
            }
        }
Exemple #16
0
        public void ShouldReturnBestResultWhenStoppedEarly()
        {
            _trainer.MaxEpochsWithoutImprovement = 2;
            _trainer.NumEpochs = 5;

            var mockNeuralNet = GetMockNeuralNetwork();
            var nn            = mockNeuralNet.Object;

            _stepsOfImprovementRemaning = 2;
            _trainer.Train(GetTrainingSet(), GetValidationSet(), MockRandom.Get(), nn);

            // Should be same result as training for only 1 epoch.
            var weights  = nn.Weights;
            var expected = new[] { new[] { 0.825, 1.65, 2.475 }, new[] { 0.425 } };

            for (var i = 0; i < weights.Length; i++)
            {
                weights[i].ShouldApproximatelyEqual(expected[i]);
            }
        }
Exemple #17
0
        public void Test5a()
        {
            // paths = 02130, 454
            var random = new MockRandom(new List <int>()
            {
                0, 1, 0, 1, 0, 0, 0, 0
            });
            var paths = new Paths(new Complete2(random, 6));

            paths.Generate();
            var(n, m) = paths.Neighbours(0);
            Assert.AreEqual(2, n);
            Assert.AreEqual(3, m);
            (n, m) = paths.Neighbours(1);
            Assert.AreEqual(3, n);
            Assert.AreEqual(2, m);
            (n, m) = paths.Neighbours(4);
            Assert.AreEqual(5, n);
            Assert.AreEqual(5, m);
        }
Exemple #18
0
        public void Train_TwoEpochsWithMomentum()
        {
            var mockNeuralNet = GetMockNeuralNetwork();
            var nn            = mockNeuralNet.Object;

            _trainer.NumEpochs = 2;

            _trainer.Train(GetTrainingSet(), GetValidationSet(), MockRandom.Get(), nn);

            nn.Should().NotBeNull();
            var weights = nn.Weights;

            weights.Should().NotBeNullOrEmpty();
            weights.Should().HaveCount(2);

            var expected = new[] { new[] { 0.40875, 0.8175, 1.22625 }, new[] { -2.59625 } };

            for (var i = 0; i < weights.Length; i++)
            {
                weights[i].ShouldApproximatelyEqual(expected[i]);
            }
        }
    public void ScalarInternalTests()
    {
        using var mockRandom = new MockRandom();

        // The random should not overflow.
        mockRandom.GetBytesResults.Add(EC.N.ToBytes());

        // The random should not overflow.
        mockRandom.GetBytesResults.Add(new Scalar(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue).ToBytes());

        mockRandom.GetBytesResults.Add(Scalar.Zero.ToBytes());
        var one = new Scalar(1);

        mockRandom.GetBytesResults.Add(one.ToBytes());
        mockRandom.GetBytesResults.Add(one.ToBytes());
        var two = new Scalar(2);

        mockRandom.GetBytesResults.Add(two.ToBytes());
        var big = new Scalar(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue);

        mockRandom.GetBytesResults.Add(big.ToBytes());
        var biggest = EC.N + one.Negate();

        mockRandom.GetBytesResults.Add(biggest.ToBytes());

        var randomScalar = mockRandom.GetScalar();

        Assert.Equal(one, randomScalar);
        randomScalar = mockRandom.GetScalar();
        Assert.Equal(one, randomScalar);
        randomScalar = mockRandom.GetScalar();
        Assert.Equal(two, randomScalar);
        randomScalar = mockRandom.GetScalar();
        Assert.Equal(big, randomScalar);
        randomScalar = mockRandom.GetScalar();
        Assert.Equal(biggest, randomScalar);
    }
Exemple #20
0
        public void GenerateCoordinatorParameters()
        {
            // Coordinator key is (0, 0, 0, 0, 0)
            var rnd = new MockRandom();

            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.Zero, 5));
            var key = new CoordinatorSecretKey(rnd);
            var ex  = Assert.Throws <ArgumentException>(key.ComputeCoordinatorParameters);

            Assert.StartsWith("Point at infinity is not a valid value.", ex.Message);

            // Coordinator key is (0, 0, 1, 1, 1)
            rnd = new MockRandom();
            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.Zero, 2));
            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.One, 3));
            key = new CoordinatorSecretKey(rnd);
            ex  = Assert.Throws <ArgumentException>(key.ComputeCoordinatorParameters);
            Assert.StartsWith("Point at infinity is not a valid value.", ex.Message);

            // Coordinator key is (1, 1, 0, 0, 0)
            rnd = new MockRandom();
            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.One, 2));
            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.Zero, 3));
            key = new CoordinatorSecretKey(rnd);
            var iparams = key.ComputeCoordinatorParameters();

            Assert.Equal(Generators.GV, iparams.I);

            // Coordinator key is (1, 1, 1, 1, 1)
            rnd = new MockRandom();
            rnd.GetScalarResults.AddRange(Enumerable.Repeat(Scalar.One, 5));
            key     = new CoordinatorSecretKey(rnd);
            iparams = key.ComputeCoordinatorParameters();
            Assert.Equal(Generators.Gw + Generators.Gwp, iparams.Cw);
            Assert.Equal(Generators.GV - Generators.Gx0 - Generators.Gx1 - Generators.Ga, iparams.I);
        }
        public void FiatShamirComposition()
        {
            var rnd = new MockRandom();

            rnd.GetBytesResults.Add(new byte[32]);
            rnd.GetBytesResults.Add(new byte[32]);

            var witness1 = new ScalarVector(Scalar.One);
            var witness2 = new ScalarVector(Scalar.One + Scalar.One);

            var g = new GroupElementVector(Generators.G);

            var publicPoint1 = witness1 * g;
            var publicPoint2 = witness2 * g;

            var statement1 = new Statement(new Equation(publicPoint1, g));
            var statement2 = new Statement(new Equation(publicPoint2, g));

            var prover1 = new Prover(new Knowledge(statement1, witness1));
            var prover2 = new Prover(new Knowledge(statement2, witness2));

            var proverTranscript   = new WalletWasabi.Crypto.ZeroKnowledge.Transcript(new byte[0]);
            var verifierTranscript = proverTranscript.MakeCopy();

            var prover1Nonces = prover1.CommitToStatements(proverTranscript);
            var prover2Nonces = prover2.CommitToStatements(proverTranscript);

            var prover1Respond = prover1Nonces(rnd);
            var prover2Respond = prover2Nonces(rnd);

            var proof1 = prover1Respond();
            var proof2 = prover2Respond();

            var verifier1 = new Verifier(statement1);
            var verifier2 = new Verifier(statement2);

            // First, verify as a compound proof
            var correctVerifierTranscript = verifierTranscript.MakeCopy();
            var correctVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var correctVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var correctVerifier1Verify    = correctVerifier1Nonces(proof1);
            var correctVerifier2Verify    = correctVerifier2Nonces(proof2);

            Assert.True(correctVerifier1Verify());
            Assert.True(correctVerifier2Verify());

            // If the verifiers are not run interleaved, they should reject.
            var notInterleavedVerifierTranscript = verifierTranscript.MakeCopy();
            var notInterleavedVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var notInterleavedVerifier1Verify    = notInterleavedVerifier1Nonces(proof1);

            Assert.False(notInterleavedVerifier1Verify());
            var notInterleavedVerifier2Nonces = verifier2.CommitToStatements(correctVerifierTranscript);
            var notInterleavedVerifier2Verify = notInterleavedVerifier2Nonces(proof2);

            Assert.False(notInterleavedVerifier2Verify());

            // If the verifiers are run independently (without sharing a transcript),
            // they should reject.
            var incompleteTranscript1 = verifierTranscript.MakeCopy();
            var incompleteTranscript2 = verifierTranscript.MakeCopy();
            var incompleteTranscriptVerifier1Nonces = verifier1.CommitToStatements(incompleteTranscript1);
            var incompleteTranscriptVerifier2Nonces = verifier2.CommitToStatements(incompleteTranscript2);
            var incompleteTranscriptVerifier1Verify = incompleteTranscriptVerifier1Nonces(proof1);
            var incompleteTranscriptVerifier2Verify = incompleteTranscriptVerifier2Nonces(proof2);

            Assert.False(incompleteTranscriptVerifier1Verify());
            Assert.False(incompleteTranscriptVerifier2Verify());

            // If the sub-proofs are swapped between the verifiers, they should reject.
            var incorrectProofVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectProofVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectProofVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectProofVerifier1Verify    = incorrectProofVerifier1Nonces(proof2);
            var incorrectProofVerifier2Verify    = incorrectProofVerifier2Nonces(proof1);

            Assert.False(incorrectProofVerifier1Verify());
            Assert.False(incorrectProofVerifier2Verify());

            // If the order of the verifiers is changed, they should reject.
            var incorrectOrderVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectOrderVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderVerifier2Verify    = incorrectOrderVerifier2Nonces(proof2);
            var incorrectOrderVerifier1Verify    = incorrectOrderVerifier1Nonces(proof1);

            Assert.False(incorrectOrderVerifier1Verify());
            Assert.False(incorrectOrderVerifier2Verify());

            // If the proofs are committed to the transcript in the right order but
            // with the wrong verifier (combination of previous two cases) they should
            // reject.
            var incorrectOrderAndProofVerifierTranscript = verifierTranscript.MakeCopy();
            var incorrectOrderAndProofVerifier1Nonces    = verifier1.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderAndProofVerifier2Nonces    = verifier2.CommitToStatements(correctVerifierTranscript);
            var incorrectOrderAndProofVerifier2Verify    = incorrectOrderAndProofVerifier2Nonces(proof1);
            var incorrectOrderAndProofVerifier1Verify    = incorrectOrderAndProofVerifier1Nonces(proof2);

            Assert.False(incorrectOrderAndProofVerifier2Verify());
            Assert.False(incorrectOrderAndProofVerifier1Verify());
        }
Exemple #22
0
 public TestDuoApi(string ikey, string skey, string host, string user_agent, MockSleeper sleeper, MockRandom random)
     : base(ikey, skey, host, user_agent, "http", sleeper, random)
 {
     this.sleeper = sleeper;
     this.random  = random;
 }
Exemple #23
0
 public void Dispose()
 {
     MockRandom.Dispose();
 }