Ejemplo n.º 1
0
        public static bool Check()
        {
            Int256[] numbers_local = new Int256[K];
            for (int k = 0; k < K; k++)
            {
                Int256 no_local = 0;
                for (int d = 0; d < N; d++)
                {
                    no_local = no_local * 10 + Numbers[k][d];
                }
                numbers_local[k] = no_local;
            }
            Int256 sum = 0;

            for (int k = 0; k < K; k++)
            {
                sum += numbers_local[k];
            }
            Int256[] resLocal = new Int256[N + 1];
            int      t        = N + 1;

            while (sum > 0)
            {
                resLocal[--t] = sum % 10;
                sum          /= 10;
            }
            Console.WriteLine($"Local {String.Join("", resLocal)}");
            Console.WriteLine($"Global {String.Join("", Result)}");
            if (!String.Join("", Result).Equals(String.Join("", resLocal)))
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 2
0
        public override (object, int) Decode(byte[] data, int position, bool packed)
        {
            (BigInteger nominator, int newPosition) = Int256.DecodeInt(data, position, packed);
            BigRational rational = BigRational.FromBigInt(nominator) * BigRational.Reciprocal(BigRational.Pow(BigRational.FromInt(10), Precision));

            return(rational, newPosition);
        }
Ejemplo n.º 3
0
        private bool CheckNewNonceHash(Int256 newNonce, Int128 newNonceHash)
        {
            byte[] hash      = ComputeSHA1(newNonce.ToBytes());
            Int128 nonceHash = hash.ToInt128();

            return(nonceHash == newNonceHash);
        }
Ejemplo n.º 4
0
        private List <Solution> SearchFile(string fileName)
        {
            #if DEBUG
            checked {
            #endif

            List <Solution> solutionsFound = new List <Solution>();
            foreach (string line in File.ReadAllLines(fileName)) //For each line
            {
                string[] number = line.Split("\t");
                foreach (string numberString in number) //For each prime
                {
                    long prime = long.Parse(numberString);
                    primeCounter += 1;
                    primeSum     += (Int256)((Int128)prime * prime);

                    if (primeSum % primeCounter == 0)
                    {
                        solutionsFound.Add(new Solution()
                        {
                            numberOfPrimes = primeCounter,
                            sum            = primeSum,
                            lastPrime      = prime
                        });
                    }
                }
            }
            return(solutionsFound);

            #if DEBUG
        }
        #endif
        }
Ejemplo n.º 5
0
        void Simplify()
        {
            if (Value >= 1.0)
            {
                Int256 newExp   = Exp;
                double newValue = Value;

                while (newValue >= 1.0)
                {
                    newValue /= 10.0;
                    newExp++;
                }

                Value = newValue;
                Exp   = newExp;
            }
            else if (Value < 0.1 && Value >= 0.0)
            {
                Int256 newExp   = Exp;
                double newValue = Value;

                while (newValue < 0.1)
                {
                    newValue *= 10.0;
                    newExp--;
                }

                Value = newValue;
                Exp   = newExp;
            }
        }
Ejemplo n.º 6
0
 void Verify256Value(Int256 x, ulong a, ulong b, ulong c, ulong d)
 {
     Assert.AreEqual(a, x.A);
     Assert.AreEqual(b, x.B);
     Assert.AreEqual(c, x.C);
     Assert.AreEqual(d, x.D);
 }
Ejemplo n.º 7
0
    public void TestCompare()
    {
        Assert.AreEqual(0, new Int256(1).CompareTo(new Int256(1)));
        Assert.AreEqual(-1, new Int256(1).CompareTo(new Int256(2)));
        Assert.AreEqual(1, new Int256(2).CompareTo(new Int256(1)));
        Assert.AreEqual(0, new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4).CompareTo(new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4)));

        //public ulong[] ToUIn64Array()
        //public uint[] ToUIn32Array()

        var t1 = new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);

        ulong[] t2 = t1.ToUIn64Array();
        Assert.AreEqual(t2[0], 0xC2C4C6C8B1B2B3B4u);
        Assert.AreEqual(t2[1], 0xB2B4B6B8C1C2C3C4u);
        Assert.AreEqual(t2[2], 0xA2A4A6A8D1D2D3D4u);
        Assert.AreEqual(t2[3], 0x123456789ABCDEF0u);

        uint[] t3 = t1.ToUIn32Array();
        Assert.AreEqual(t3[0], 0xB1B2B3B4u);
        Assert.AreEqual(t3[1], 0xC2C4C6C8u);
        Assert.AreEqual(t3[2], 0xC1C2C3C4u);
        Assert.AreEqual(t3[3], 0xB2B4B6B8u);
        Assert.AreEqual(t3[4], 0xD1D2D3D4u);
        Assert.AreEqual(t3[5], 0xA2A4A6A8u);
        Assert.AreEqual(t3[6], 0x9ABCDEF0u);
        Assert.AreEqual(t3[7], 0x12345678u);

        //public static bool operator >(Int256 left, Int256 right)
        //public static bool operator <(Int256 left, Int256 right)
        //public static bool operator >=(Int256 left, Int256 right)
        //public static bool operator <=(Int256 left, Int256 right)
        //public static bool operator !=(Int256 left, Int256 right)
        //public static bool operator ==(Int256 left, Int256 right)

        Assert.AreEqual(true, new Int256(1) == new Int256(1));
        Assert.AreEqual(true, new Int256(10) == 10);
        Assert.AreEqual(true, new Int256(9) < 10);
        Assert.AreEqual(true, new Int256(11) > 10);
        Assert.AreEqual(true, new Int256(1) != new Int256(2));
        Assert.AreEqual(true, new Int256(0x123456789ABCDEFA) == 0x123456789ABCDEFA);

        var small1 = new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);
        var big1   = new Int256(0x223456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);
        var big1b  = new Int256(0x223456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);
        var small2 = new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);
        var big2   = new Int256(0x123456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B5);

        Assert.AreEqual(true, small1 < big1);
        Assert.AreEqual(true, small2 < big2);
        Assert.AreEqual(true, small1 <= big1);
        Assert.AreEqual(true, small2 <= big2);
        Assert.AreEqual(true, big1 > small1);
        Assert.AreEqual(true, big2 > small2);
        Assert.AreEqual(true, big1 >= small1);
        Assert.AreEqual(true, big2 >= small2);
        Assert.AreEqual(true, big1 >= big1b);
        Assert.AreEqual(true, big1 <= big1b);
    }
        /// <summary>
        ///     Converts an <see cref="Int256" /> value to an array of bytes.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="buffer">An array of bytes.</param>
        /// <param name="offset">The starting position within <paramref name="buffer" />.</param>
        /// <param name="asLittleEndian">Convert from little endian.</param>
        public static void ToBytes(this Int256 value, byte[] buffer, int offset = 0, bool?asLittleEndian = null)
        {
            bool ale = GetIsLittleEndian(asLittleEndian);

            value.D.ToBytes(buffer, ale ? offset : offset + 24, ale);
            value.C.ToBytes(buffer, ale ? offset + 8 : offset + 16, ale);
            value.B.ToBytes(buffer, ale ? offset + 16 : offset + 8, ale);
            value.A.ToBytes(buffer, ale ? offset + 24 : offset, ale);
        }
Ejemplo n.º 9
0
 public Solver(SolverState state, FilePath FilePath, SaveStrategy Save)
 {
     this.FilePath = FilePath;
     this.Save     = Save;
     primeSum      = state.primeSum;
     primeCounter  = state.primeCounter;
     groupIndex    = state.groupIndex;
     part          = state.part;
 }
Ejemplo n.º 10
0
        public void Should_substruct_big_numbers_correctly(string x, string y, string z)
        {
            var i1 = Int256.Parse(x);
            var i2 = Int256.Parse(y);

            var i3 = i1 - i2;

            ("0x" + i3.ToString("X32")).Should().Be(z);
        }
Ejemplo n.º 11
0
        public void Should_multiply_big_numbers_correctly(string x, string y, string z)
        {
            var i1 = Int256.Parse(x);
            var i2 = Int256.Parse(y);

            var i3 = i1 * i2;

            ("0x" + i3.ToString("X")).Should().Be(z);
        }
Ejemplo n.º 12
0
        public void Should_sum_big_numbers_correctly(string x, string y, string z)
        {
            Int256 i1 = Int256.Parse(x);
            Int256 i2 = Int256.Parse(y);

            Int256 i3 = i1 + i2;

            ("0x" + i3.ToString("X32")).Should().Be(z);
        }
Ejemplo n.º 13
0
        public static async Task <Step3Res> Do(
            Some <ServerDhParams.OkTag> someServerDhParams,
            Int256 newNonce,
            Some <MtProtoPlainTransport> transport
            )
        {
            var dhParams        = someServerDhParams.Value;
            var key             = Aes.GenerateKeyDataFromNonces(dhParams.ServerNonce.ToBytes(true), newNonce.ToBytes(true));
            var plaintextAnswer = Aes.DecryptAES(key, dhParams.EncryptedAnswer.ToArrayUnsafe());
            var dh = plaintextAnswer.Apply(Deserialize(WithHashSumCheck(ServerDhInnerData.Deserialize)));

            Helpers.Assert(dh.Nonce == dhParams.Nonce, "auth step3: invalid nonce in encrypted answer");
            Helpers.Assert(dh.ServerNonce == dhParams.ServerNonce, "auth step3: invalid server nonce in encrypted answer");

            var currentEpochTime = Helpers.GetCurrentEpochTime();
            var timeOffset       = dh.ServerTime - currentEpochTime;

            var g       = dh.G;
            var dhPrime = new BigInteger(1, dh.DhPrime.ToArrayUnsafe());
            var ga      = new BigInteger(1, dh.Ga.ToArrayUnsafe());

            var b   = new BigInteger(Rnd.NextBytes(2048));
            var gb  = BigInteger.ValueOf(g).ModPow(b, dhPrime);
            var gab = ga.ModPow(b, dhPrime);

            var dhInnerData = new ClientDhInnerData(
                nonce: dh.Nonce,
                serverNonce: dh.ServerNonce,
                retryId: 0,
                gb: gb.ToByteArrayUnsigned().ToBytesUnsafe()
                );
            var dhInnerDataBts = Serialize(dhInnerData);

            var dhInnerDataHashedBts            = WithHashAndPadding(dhInnerDataBts);
            var dhInnerDataHashedEncryptedBytes = Aes.EncryptAES(key, dhInnerDataHashedBts);

            var resp = await transport.Value.Call(new SetClientDhParams(
                                                      nonce : dh.Nonce,
                                                      serverNonce : dh.ServerNonce,
                                                      encryptedData : dhInnerDataHashedEncryptedBytes.ToBytesUnsafe()
                                                      ));

            var res = resp.Match(
                dhGenOkTag: identity,
                dhGenFailTag: _ => throw Helpers.FailedAssertion("auth step3: dh_gen_fail"),
                dhGenRetryTag: _ => throw Helpers.FailedAssertion("auth step3: dh_gen_retry")
                );

            var authKey      = AuthKey.FromGab(gab);
            var newNonceHash = authKey.CalcNewNonceHash(newNonce.ToBytes(true), 1).ToInt128();

            Helpers.Assert(res.Nonce == dh.Nonce, "auth step3: invalid nonce");
            Helpers.Assert(res.ServerNonce == dh.ServerNonce, "auth step3: invalid server nonce");
            Helpers.Assert(res.NewNonceHash1 == newNonceHash, "auth step3: invalid new nonce hash");

            return(new Step3Res(authKey, timeOffset));
        }
Ejemplo n.º 14
0
 public override void DeserializeBody(BinaryReader br)
 {
     pq           = StringUtil.Deserialize(br);
     p            = StringUtil.Deserialize(br);
     q            = StringUtil.Deserialize(br);
     nonce        = (Int128)ObjectUtils.DeserializeObject(br);
     server_nonce = (Int128)ObjectUtils.DeserializeObject(br);
     new_nonce    = (Int256)ObjectUtils.DeserializeObject(br);
     Type         = TLAbsP_Q_inner_dataTypes.TLP_q_inner_data;
 }
Ejemplo n.º 15
0
        public void Should_multiply_correctly(int x, int y, int z)
        {
            var i1 = (Int256)x;
            var i2 = (Int256)y;

            Int256 i3 = i1 * i2;

            ((int)i3).Should().Be(z);
            i3.ToString().Should().Be(z.ToString(CultureInfo.InvariantCulture));
        }
Ejemplo n.º 16
0
        private ReqDHParamsArgs CreateReqDhParamsArgs(ResPQ resPQ, out PQInnerData pqInnerData)
        {
            Int256 pq = resPQ.Pq.ToInt256(asLittleEndian: false);
            Int256 p, q;

            pq.GetPrimeMultipliers(out p, out q);

            Int256 newNonce = _nonceGenerator.GetNonce(32).ToInt256();

            pqInnerData = new PQInnerData
            {
                Pq          = resPQ.Pq,
                P           = p.ToBytes(false, true),
                Q           = q.ToBytes(false, true),
                Nonce       = resPQ.Nonce,
                ServerNonce = resPQ.ServerNonce,
                NewNonce    = newNonce
            };

            byte[] data     = _tlRig.Serialize(pqInnerData);
            byte[] dataHash = ComputeSHA1(data);

            Debug.Assert((dataHash.Length + data.Length) <= 255);

            // data_with_hash := SHA1(data) + data + (any random bytes); such that the length equal 255 bytes;
            var dataWithHash = new byte[255];

            using (var streamer = new TLStreamer(dataWithHash))
            {
                streamer.Write(dataHash);
                streamer.Write(data);
                streamer.WriteRandomDataTillEnd();
            }

            PublicKey publicKey = _keyChain.GetFirst(resPQ.ServerPublicKeyFingerprints);

            if (publicKey == null)
            {
                throw new PublicKeyNotFoundException(resPQ.ServerPublicKeyFingerprints);
            }

            byte[] encryptedData = _encryptionServices.RSAEncrypt(dataWithHash, publicKey);

            var reqDhParamsArgs = new ReqDHParamsArgs
            {
                Nonce                = pqInnerData.Nonce,
                ServerNonce          = pqInnerData.ServerNonce,
                P                    = pqInnerData.P,
                Q                    = pqInnerData.Q,
                PublicKeyFingerprint = publicKey.Fingerprint,
                EncryptedData        = encryptedData
            };

            return(reqDhParamsArgs);
        }
Ejemplo n.º 17
0
    public void TestPlusMinusOps()
    {
        //public static Int256 operator +(Int256 value)
        //public static Int256 operator -(Int256 value)
        //public static Int256 operator +(Int256 left, Int256 right)
        //public static Int256 operator -(Int256 left, Int256 right)

        Verify256Value(new Int256(1) + new Int256(1), 0, 0, 0, 2);
        var t1 = new Int256(1);

        t1++;
        Verify256Value(t1, 0, 0, 0, 2);

        Verify256Value(new Int256(5) - new Int256(3), 0, 0, 0, 2);
        var t2 = new Int256(3);

        t2--;
        Verify256Value(t2, 0, 0, 0, 2);

        var big1 = new Int256(0x223456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);

        Verify256Value(big1 + new Int256(1), 0x223456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B5);
        Verify256Value(big1 + new Int256(1, 0, 0, 0), 0x223456789ABCDEF1, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);
        Verify256Value(big1 - new Int256(1), 0x223456789ABCDEF0, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B3);
        Verify256Value(big1 - new Int256(1, 0, 0, 0), 0x223456789ABCDEEF, 0xA2A4A6A8D1D2D3D4, 0xB2B4B6B8C1C2C3C4, 0xC2C4C6C8B1B2B3B4);

        var bigWrap1a = new Int256(0xFFFFFFFFFFFFFFFF, 0, 0, 0);
        var bigWrap1b = new Int256(0, 0xFFFFFFFFFFFFFFFF, 0, 0);
        var bigWrap1c = new Int256(0, 0, 0xFFFFFFFFFFFFFFFF, 0);
        var bigWrap1d = new Int256(0, 0, 0, 0xFFFFFFFFFFFFFFFF);

        Verify256Value(bigWrap1a + new Int256(1, 0, 0, 0), 0, 0, 0, 0);
        Verify256Value(bigWrap1b + new Int256(0, 1, 0, 0), 1, 0, 0, 0);
        Verify256Value(bigWrap1c + new Int256(0, 0, 1, 0), 0, 1, 0, 0);
        Verify256Value(bigWrap1d + new Int256(1), 0, 0, 1, 0);
        var bigWrap2a = new Int256(1, 0, 0, 0);
        var bigWrap2b = new Int256(0, 1, 0, 0);
        var bigWrap2c = new Int256(0, 0, 1, 0);
        var bigWrap2d = new Int256(0, 0, 0, 0);

        Verify256Value(bigWrap2a - new Int256(1), 0, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF);
        Verify256Value(bigWrap2b - new Int256(1), 0, 0, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF);
        Verify256Value(bigWrap2c - new Int256(1), 0, 0, 0, 0xFFFFFFFFFFFFFFFF);
        Verify256Value(bigWrap2d - new Int256(1), 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF);

        //public static Int256 operator ++(Int256 value)
        //public static Int256 operator --(Int256 value)

        bigWrap2d--;
        Assert.AreEqual(true, bigWrap2d == -1);
        bigWrap2d++;
        Assert.AreEqual(true, bigWrap2d == 0);
        bigWrap2d++;
        Assert.AreEqual(true, bigWrap2d == 1);
    }
Ejemplo n.º 18
0
        public void Should_rightShift_correctly(string x, string y, string z)
        {
            //
            // X >> Y should = z
            //
            var i1       = Int256.Parse(x);
            var shifthBy = int.Parse(y);
            var i3       = i1 >> shifthBy;

            ("0x" + i3.ToString("X32")).Should().Be(z);
        }
Ejemplo n.º 19
0
        public void Should_leftShift_correctly(string x, string y, string z)
        {
            //
            // X >> Y should = z
            //
            Int256 i1       = Int256.Parse(x);
            int    shifthBy = int.Parse(y);
            Int256 i3       = i1 << shifthBy;

            ("0x" + i3.ToString("X32")).Should().Be(z);
        }
Ejemplo n.º 20
0
 public static void GetPrimeMultipliers(this Int256 pq, out Int256 p, out Int256 q)
 {
     p = PollardRho(pq);
     q = pq / p;
     if (p > q)
     {
         Int256 t = p;
         p = q;
         q = t;
     }
 }
Ejemplo n.º 21
0
        //[TestCase("2852213850458175921094913949697", "51539607551", "55340232221128654847")]
        //[TestCase("2253601067072664030639173111353", "2932031007403", "768614336404564651")]
        //[TestCase("154866286100907105216716400854538488352313", "768614336404564651", "201487636602438195784363")]
        //[TestCase("170277282318432095373149951383568233665261047797485113", "201487636602438195784363", "845100400152152934331135470251")]
        //[TestCase("47928794074934470746074693488053803551576675688093033978263006055993", "845100400152152934331135470251", "56713727820156410577229101238628035243")]
        public void Should_get_prime_multipliers_for_Int256(string pqS, string expectedPs, string expectedQs)
        {
            Int256 pq = Int256.Parse(pqS);
            Int256 expectedP = Int256.Parse(expectedPs);
            Int256 expectedQ = Int256.Parse(expectedQs);
            Int256 p, q;

            pq.GetPrimeMultipliers(out p, out q);

            p.Should().Be(expectedP);
            q.Should().Be(expectedQ);
        }
Ejemplo n.º 22
0
    public void TestMathOps()
    {
        //public static Int256 operator /(Int256 dividend, Int256 divisor)
        //public static Int256 operator *(Int256 left, Int256 right)

        var m1 = new Int256(0, 0, 0, 2);

        m1 /= 2;
        Verify256Value(m1, 0, 0, 0, 1);

        var m2 = new Int256(0, 0, 1, 0);

        m2 /= 2;
        Verify256Value(m2, 0, 0, 0, 0x8000000000000000);
        m2 /= 2;
        Verify256Value(m2, 0, 0, 0, 0x4000000000000000);
        m2 *= 2;
        Verify256Value(m2, 0, 0, 0, 0x8000000000000000);
        m2 *= 2;
        Verify256Value(m2, 0, 0, 1, 0);
        m2 *= 2;
        Verify256Value(m2, 0, 0, 2, 0);

        //public static Int256 operator %(Int256 dividend, Int256 divisor)
        var m3 = new Int256(0, 0, 0, 13);

        Assert.AreEqual(3, m3 % 10);

        //public static Int256 operator >>(Int256 value, int shift)
        //public static Int256 operator <<(Int256 value, int shift)
        var m4 = new Int256(0, 0, 1, 0);

        m4 >>= 2;
        Verify256Value(m4, 0, 0, 0, 0x4000000000000000);
        m4 <<= 3;
        Verify256Value(m4, 0, 0, 2, 0);

        //public static Int256 operator |(Int256 left, Int256 right)
        //public static Int256 operator &(Int256 left, Int256 right)
        var m5a = new Int256(0, 0, 1, 0);
        var m5b = new Int256(2, 2, 2, 2);

        m5a |= m5b;
        Verify256Value(m5a, 2, 2, 3, 2);

        var m6a = new Int256(0, 0, 1, 0);
        var m6b = new Int256(2, 2, 3, 2);

        m6a &= m6b;
        Verify256Value(m6a, 0, 0, 1, 0);

        //public static Int256 operator ~(Int256 value)
    }
        /// <summary>
        ///     Converts an <see cref="Int256" /> value to a byte array.
        /// </summary>
        /// <param name="value">Value.</param>
        /// <param name="asLittleEndian">Convert from little endian.</param>
        /// <param name="trimZeros">Trim zero bytes from left or right, depending on endian.</param>
        /// <returns>Array of bytes.</returns>
        public static byte[] ToBytes(this Int256 value, bool?asLittleEndian = null, bool trimZeros = false)
        {
            var buffer = new byte[32];

            value.ToBytes(buffer, 0, asLittleEndian);

            if (trimZeros)
            {
                buffer = buffer.TrimZeros(asLittleEndian);
            }

            return(buffer);
        }
Ejemplo n.º 24
0
 public static Int256 GCD(this Int256 a, Int256 b)
 {
     while (true)
     {
         if (b == 0)
         {
             return(a);
         }
         Int256 a1 = a;
         a = b;
         b = a1 % b;
     }
 }
Ejemplo n.º 25
0
        void ConvertFromDouble(double d)
        {
            Int256 newExp   = 0;
            double newValue = d;

            while (newValue >= 1.0)
            {
                newValue /= 10.0;
                newExp++;
            }

            Value = newValue;
            Exp   = newExp;
        }
Ejemplo n.º 26
0
        public void Should_compare_big_numbers_correctly(string x, string y, bool?z)
        {
            // z == null means that numbers are equal.

            Int256 i1 = Int256.Parse(x);
            Int256 i2 = Int256.Parse(y);

            bool value = z.HasValue && z.Value;

            (i1 > i2).Should().Be(value);
            (i1 < i2).Should().Be(z.HasValue && !value);
            (i1 == i2).Should().Be(!z.HasValue);
            (i1 != i2).Should().Be(z.HasValue);
        }
Ejemplo n.º 27
0
        public override byte[] Encode(object arg, bool packed)
        {
            if (arg is BigRational input)
            {
                if (_denominator != input.Denominator)
                {
                    throw new AbiException(AbiEncodingExceptionMessage);
                }

                return(Int256.Encode(input.Numerator, packed));
            }

            throw new AbiException(AbiEncodingExceptionMessage);
        }
Ejemplo n.º 28
0
        static void Main(string[] args)
        {
            string[] values  = File.ReadAllLines(@"/Users/alexandraneamtu/Documents/An3-sem1/crypto/Lab2/Lab2Crypto/test.txt");
            string[] results = new string[100];
            foreach (var line in values)
            {
                string[] s = line.Split(',');

                /*
                 * long a, b;
                 *
                 * bool aResult = Int64.TryParse(s[0], out a);
                 * bool bResult = Int64.TryParse(s[1], out b);
                 *
                 * if (aResult && bResult)
                 * {
                 *
                 *  Console.WriteLine("a: " + a + " b: " + b);
                 *  var time1 = Stopwatch.StartNew();
                 *  var result1 = GCDAlgorithms.Alg1(a, b);
                 *  time1.Stop();
                 *  Console.WriteLine("Alg1 Result: " + result1);
                 *  Console.WriteLine(time1.Elapsed.TotalMilliseconds * 1000000 + " nanoseconds\n");
                 *
                 *
                 *  Console.WriteLine("a: " + a + " b: " + b);
                 *  var time2 = Stopwatch.StartNew();
                 *  var result2 = GCDAlgorithms.Alg2(a, b);
                 *  time2.Stop();
                 *  Console.WriteLine("Alg2 Result: " + result2);
                 *  Console.WriteLine(time2.Elapsed.TotalMilliseconds * 1000000 + " nanoseconds\n");
                 * }
                 */

                Int256 aBig, bBig;
                bool   aBigResult = Int256.TryParse(s[0], out aBig);
                bool   bBigResult = Int256.TryParse(s[1], out bBig);
                if (aBigResult && bBigResult)
                {
                    Console.WriteLine("a: " + aBig + " b: " + bBig);
                    var time3   = Stopwatch.StartNew();
                    var result3 = GCDAlgorithms.Alg3(aBig, bBig);
                    time3.Stop();
                    Console.WriteLine("Alg3 Result: " + result3);
                    Console.WriteLine(time3.Elapsed.TotalMilliseconds * 1000000
                                      + " nanoseconds\n");
                }
            }
            Console.ReadLine();
        }
Ejemplo n.º 29
0
        public static Int256 PollardRho(Int256 number)
        {
            var func = new Func <Int256, Int256, Int256>((param, mod) => ((param * param + 1) % mod));

            Int256 x = 2, y = 2, z;

            do
            {
                x = func(x, number);
                y = func(func(y, number), number);
                z = GCD(x > y ? x - y : y - x, number);
            } while (z <= 1);
            return(z);
        }
Ejemplo n.º 30
0
        private Int128 ComputeNewNonceHash(Int256 newNonce, byte num, byte[] authKeyAuxHash)
        {
            var arr = new byte[33 + authKeyAuxHash.Length];

            using (var streamer = new TLStreamer(arr))
            {
                streamer.WriteInt256(newNonce);
                streamer.WriteByte(num);
                streamer.Write(authKeyAuxHash);
            }
            byte[] hash   = ComputeSHA1(arr);
            Int128 result = hash.ToInt128(HashLength - 16);

            return(result);
        }
Ejemplo n.º 31
0
 public override void WriteInt256(Int256 value)
 {
     lock (_streamer)
         _streamer.WriteInt256(value);
 }
Ejemplo n.º 32
0
 public static void GetPrimeMultipliers(this Int256 pq, out Int256 p, out Int256 q)
 {
     p = PollardRho(pq);
     q = pq/p;
     if (p > q)
     {
         Int256 t = p;
         p = q;
         q = t;
     }
 }
Ejemplo n.º 33
0
 /// <summary>
 ///     Writes a 256-bit signed integer.
 /// </summary>
 public virtual void WriteInt256(Int256 value)
 {
     value.ToBytes(_buffer, 0, _streamAsLittleEndianInternal);
     Write(_buffer, 0, 32);
 }
Ejemplo n.º 34
0
 private Int128 ComputeNewNonceHash(Int256 newNonce, byte num, byte[] authKeyAuxHash)
 {
     var arr = new byte[33 + authKeyAuxHash.Length];
     using (var streamer = new TLStreamer(arr))
     {
         streamer.WriteInt256(newNonce);
         streamer.WriteByte(num);
         streamer.Write(authKeyAuxHash);
     }
     byte[] hash = ComputeSHA1(arr);
     Int128 result = hash.ToInt128(HashLength - 16);
     return result;
 }
Ejemplo n.º 35
0
 public static void Serialize(Int256 src, BinaryWriter writer)
 {
     writer.Write(src.ToBytes(true));
 }
Ejemplo n.º 36
0
 public static Int256 GCD(this Int256 a, Int256 b)
 {
     while (true)
     {
         if (b == 0)
         {
             return a;
         }
         Int256 a1 = a;
         a = b;
         b = a1%b;
     }
 }
Ejemplo n.º 37
0
 private bool CheckNewNonceHash(Int256 newNonce, Int128 newNonceHash)
 {
     byte[] hash = ComputeSHA1(newNonce.ToBytes());
     Int128 nonceHash = hash.ToInt128();
     return nonceHash == newNonceHash;
 }
Ejemplo n.º 38
0
        public static void GetPrimeMultipliers(this Int256 pq, out Int256 p, out Int256 q)
        {
            // new prime generation algorithm.
            ulong what = (ulong)pq.ToType(typeof(ulong), null, false);
            int it = 0, i, j;
            ulong g = 0;

            for (i = 0; i < 3 || it < 1000; i++)
            {
                ulong t = ((GenerateLongRand() & 15) + 17) % what;
                ulong x = GenerateLongRand() % (what - 1) + 1, y = x;
                int lim = 1 << (i + 18);
                for (j = 1; j < lim; j++)
                {
                    ++it;
                    ulong a = x, b = x, c = t;
                    while (b != 0)
                    {
                        if ((b & 1) != 0)
                        {
                            c += a;
                            if (c >= what)
                            {
                                c -= what;
                            }
                        }
                        a += a;
                        if (a >= what)
                        {
                            a -= what;
                        }
                        b >>= 1;
                    }
                    x = c;
                    ulong z = x < y ? what + x - y : x - y;
                    g = GCD(z, what);
                    if (g != 1)
                    {
                        break;
                    }
                    if ((j & (j - 1)) == 0)
                    {
                        y = x;
                    }
                }
                if (g > 1 && g < what)
                {
                    break;
                }
            }

            if (g > 1 && g < what)
            {
                p = g;
                q = what / g;
                if (p > q)
                {
                    var tmp = p;
                    p = q;
                    q = tmp;
                }
            }
            else
            {
                p = 0;
                q = 0;
            }
            // Old algorithm, can be removed in later versions
            //p = PollardRho(pq);
            //q = pq / p;
            //if (p > q)
            //{
            //    Int256 t = p;
            //    p = q;
            //    q = t;
            //}
            Console.WriteLine("p {0} q {1}", p, q);
        }
Ejemplo n.º 39
0
        public static Int256 PollardRho(Int256 number)
        {
            var func = new Func<Int256, Int256, Int256>((param, mod) => ((param*param + 1)%mod));

            Int256 x = 2, y = 2, z;
            do
            {
                x = func(x, number);
                y = func(func(y, number), number);
                z = GCD(x > y ? x - y : y - x, number);
            } while (z <= 1);
            return z;
        }