Exemplo n.º 1
0
        public static Int128 Int128Mul(long lhs, long rhs)
        {
            bool flag = lhs < 0 != rhs < 0;

            if (lhs < 0)
            {
                lhs = -lhs;
            }
            if (rhs < 0)
            {
                rhs = -rhs;
            }
            ulong num  = (ulong)lhs >> 32;
            ulong num2 = (ulong)(lhs & uint.MaxValue);
            ulong num3 = (ulong)rhs >> 32;
            ulong num4 = (ulong)(rhs & uint.MaxValue);
            ulong num5 = num * num3;
            ulong num6 = num2 * num4;
            ulong num7 = num * num4 + num2 * num3;
            long  num8 = (long)(num5 + (num7 >> 32));
            ulong num9 = (num7 << 32) + num6;

            if (num9 < num6)
            {
                num8++;
            }
            Int128 @int = new Int128(num8, num9);

            return((!flag) ? @int : (-@int));
        }
Exemplo n.º 2
0
        private bool CheckNewNonceHash(Int256 newNonce, Int128 newNonceHash)
        {
            byte[] hash      = ComputeSHA1(newNonce.ToBytes());
            Int128 nonceHash = hash.ToInt128();

            return(nonceHash == newNonceHash);
        }
Exemplo n.º 3
0
 private void CheckNonce(Int128 expectedNonce, Int128 actualNonce)
 {
     if (actualNonce != expectedNonce)
     {
         throw new InvalidResponseException(string.Format("Expected nonce {0:X16} differs from the actual nonce {1:X16}.", expectedNonce, actualNonce));
     }
 }
Exemplo n.º 4
0
        /// <summary>
        /// Gets a hash digest of the entropy which has been accumulated.
        /// Note: if no entropy has accumulated, the result is deterministic.
        /// </summary>
        public byte[] GetDigest()
        {
            byte[] result = null;

            // See above for hash algorithm mess.
#if (NETSTANDARD2_0 || NETSTANDARD1_3)
            if (_IncHash != null)
            {
                result = _IncHash.GetHashAndReset();
            }
#endif
#if (NETSTANDARD2_0 || NET452)
            if (_HashAlg != null)
            {
                // As the final block needs some input, we use part of the total entropy counter.
                _HashAlg.TransformFinalBlock(BitConverter.GetBytes(TotalEntropyBytes.Low), 0, 8);
                result = _HashAlg.Hash;
            }
#endif

            if (result == null)
            {
                ThrowGetDigestResultIsNull();
            }
            if (result.Length != _HashLengthInBytes)
            {
                ThrowDigestLengthIsWrong(result);
            }

            EntropyBytesSinceLastDigest = Int128.Zero;
            _CountOfBytesBySource.Clear();
            return(result);
        }
Exemplo n.º 5
0
 internal static Int128 ReverseEndianness(Int128 value)
 {
     return(new Int128(
                ReverseEndianness(value.Lower),
                ReverseEndianness(value.Upper)
                ));
 }
Exemplo n.º 6
0
        /// <summary>
        /// Convert the given value string to Int128 using the given radix
        /// </summary>
        internal override object FromString(string value, int radix)
        {
            Debug.Assert(radix == 16);
            Debug.Assert(value is not null);

            return(Int128.Parse(value, NumberStyles.HexNumber));
        }
Exemplo n.º 7
0
        internal void Add(byte[] entropy, IEntropySource source)
        {
            // Determine how much of the packet will be accepted.
            _CountOfBytesBySource.TryGetValue(source, out var countFromSource);
            var bytesToaccept = BytesToAcceptFromSource(entropy.Length, countFromSource);

            if (bytesToaccept <= 0)
            {
                // Ignoring this packet entirely.
                return;
            }

            // Accumulate the packer into the hash function.
            // Note that this may only incorporate part of the packet.
            AccumulateBlock(entropy, bytesToaccept);

            // Increment counters. Note that this may overflow for very long lived pools.
            if (_CountOfBytesBySource.Count <= MaxSourcesToCount && countFromSource < Int32.MaxValue)
            {
                try
                {
                    _CountOfBytesBySource[source] = countFromSource + bytesToaccept;
                }
                catch (OverflowException)
                {
                    _CountOfBytesBySource[source] = Int32.MaxValue;
                }
            }
            TotalEntropyBytes           = TotalEntropyBytes + bytesToaccept;
            EntropyBytesSinceLastDigest = EntropyBytesSinceLastDigest + bytesToaccept;
        }
Exemplo n.º 8
0
        public void Int128Equality()
        {
            // Reflexivity a = a
            // Symmetry a = b => b = a
            // Transitivity a = b & b = c => a = c

            Int128[] values = new Int128[] { Int128.MinValue, Int64.MinValue, Int32.MinValue, -Int128.One, Int128.Zero, Int128.One, Int64.MaxValue, Int128.MaxValue };

            foreach (Int128 x in values)
            {
                Assert.IsTrue(x.Equals(x));
                Assert.IsFalse(x.Equals(null));
                foreach (Int128 y in values)
                {
                    if (x == y)
                    {
                        Assert.IsTrue(y == x);
                        Assert.IsFalse(x != y);
                        Assert.IsTrue(y.Equals(x));
                        Assert.IsTrue(x.Equals((object)y));
                        Assert.IsTrue(x.GetHashCode() == y.GetHashCode());
                    }
                    else
                    {
                        Assert.IsTrue(x != y);
                        Assert.IsFalse(y.Equals(x));
                        Assert.IsFalse(x.Equals((object)y));
                    }
                }
            }
        }
Exemplo n.º 9
0
 public void Int128Comparison()
 {
     Int128[] orderedValues = new Int128[] { Int128.MinValue, Int64.MinValue, Int32.MinValue, -Int128.One, Int128.Zero, Int128.One, Int32.MaxValue, Int64.MaxValue, Int128.MaxValue };
     for (int i = 0; i < orderedValues.Length; i++)
     {
         for (int j = 0; j < orderedValues.Length; j++)
         {
             if (i < j)
             {
                 Assert.IsTrue(Int128.Compare(orderedValues[i], orderedValues[j]) == -1);
                 Assert.IsTrue(orderedValues[i].CompareTo(orderedValues[j]) == -1);
                 Assert.IsTrue(orderedValues[i] < orderedValues[j]);
                 Assert.IsFalse(orderedValues[i] >= orderedValues[j]);
             }
             else if (i == j)
             {
                 Assert.IsTrue(Int128.Compare(orderedValues[i], orderedValues[j]) == 0);
                 Assert.IsTrue(orderedValues[i].CompareTo(orderedValues[j]) == 0);
                 Assert.IsFalse(orderedValues[i] < orderedValues[j]);
                 Assert.IsFalse(orderedValues[i] > orderedValues[j]);
                 Assert.IsTrue(orderedValues[i] <= orderedValues[j]);
             }
             else
             {
                 Assert.IsTrue(Int128.Compare(orderedValues[i], orderedValues[j]) == +1);
                 Assert.IsTrue(orderedValues[i].CompareTo(orderedValues[j]) == +1);
                 Assert.IsTrue(orderedValues[i] > orderedValues[j]);
                 Assert.IsFalse(orderedValues[i] <= orderedValues[j]);
             }
         }
     }
 }
Exemplo n.º 10
0
        public void Int128ParseFailure()
        {
            Assert.IsFalse(Int128.TryParse(null, out _));
            Assert.ThrowsException <ArgumentNullException>(() => Int128.Parse(null));

            Assert.IsFalse(Int128.TryParse(String.Empty, out _));
            Assert.ThrowsException <FormatException>(() => Int128.Parse(String.Empty));

            Assert.IsFalse(Int128.TryParse("1x2", out _));
            Assert.ThrowsException <FormatException>(() => Int128.Parse("-1 2"));

            // Max is parsable, but one more isn't.
            Assert.IsTrue(Int128.TryParse(Int128.MaxValue.ToString(), out Int128 max));
            Assert.IsTrue(max == Int128.MaxValue);
            string oneOverMax = UInt128Test.MakeNumberOneBigger(Int128.MaxValue.ToString());

            Assert.IsFalse(Int128.TryParse(oneOverMax, out _));
            Assert.ThrowsException <OverflowException>(() => Int128.Parse(oneOverMax));

            // Min is parsable, but one less isn't.
            Assert.IsTrue(Int128.TryParse(Int128.MinValue.ToString(), out Int128 min));
            Assert.IsTrue(min == Int128.MinValue);
            string oneUnderMin = UInt128Test.MakeNumberOneBigger(Int128.MinValue.ToString());

            Assert.IsFalse(Int128.TryParse(oneUnderMin, out _));
            Assert.ThrowsException <OverflowException>(() => Int128.Parse(oneUnderMin));
        }
Exemplo n.º 11
0
        public void Int128Int64Agreement()
        {
            Random rng = new Random(12864);

            foreach (long u in GetRandomInt64(8, rng))
            {
                foreach (long v in GetRandomInt64(8, rng))
                {
                    Int128 sum  = ((Int128)u) + ((Int128)v);
                    long   sum1 = u + v;
                    Assert.IsTrue((long)sum == sum1);

                    Int128 difference  = ((Int128)u) - ((Int128)v);
                    long   difference1 = u - v;
                    Assert.IsTrue((long)difference == difference1);

                    Int128 product  = ((Int128)u) * ((Int128)v);
                    long   product1 = u * v;
                    Assert.IsTrue((long)product == product1);

                    Int128 quotient  = ((Int128)u) / ((Int128)v);
                    long   quotient1 = u / v;
                    Assert.IsTrue((long)quotient == quotient);
                }
            }
        }
Exemplo n.º 12
0
        public void Int128RandomArithmetic()
        {
            Random rng = new Random(314159);

            foreach (Int128 x in GetRandomInt128(8, rng))
            {
                // Relation of addition to multiplication
                Assert.IsTrue(-x == -1 * x);
                Assert.IsTrue(0 == 0 * x);
                Assert.IsTrue(x == 1 * x);
                Assert.IsTrue(x + x == 2 * x);
                Assert.IsTrue(x + x + x == 3 * x);

                foreach (Int128 y in GetRandomInt128(8, rng))
                {
                    // Subtraction and addition are inverses
                    Assert.IsTrue(y + (x - y) == x);

                    // Division methods agree
                    Int128 q = Int128.DivRem(x, y, out Int128 r);
                    Assert.IsTrue(q == x / y);
                    Assert.IsTrue(r == x % y);

                    // Division and multiplication are inverses
                    Assert.IsTrue(q * y + r == x);
                }
            }
        }
Exemplo n.º 13
0
        public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, Int128 expected)
        {
            Int128 result;

            // Default style and provider
            if ((style == NumberStyles.Integer) && (provider is null))
            {
                Assert.True(Int128.TryParse(value, out result));
                Assert.Equal(expected, result);
                Assert.Equal(expected, Int128.Parse(value));
            }

            // Default provider
            if (provider is null)
            {
                Assert.Equal(expected, Int128.Parse(value, style));

                // Substitute default NumberFormatInfo
                Assert.True(Int128.TryParse(value, style, new NumberFormatInfo(), out result));
                Assert.Equal(expected, result);
                Assert.Equal(expected, Int128.Parse(value, style, new NumberFormatInfo()));
            }

            // Default style
            if (style == NumberStyles.Integer)
            {
                Assert.Equal(expected, Int128.Parse(value, provider));
            }

            // Full overloads
            Assert.True(Int128.TryParse(value, style, provider, out result));
            Assert.Equal(expected, result);
            Assert.Equal(expected, Int128.Parse(value, style, provider));
        }
Exemplo n.º 14
0
        public static void ToString_InvalidFormat_ThrowsFormatException()
        {
            Int128 i = 123;

            Assert.Throws <FormatException>(() => i.ToString("Y"));       // Invalid format
            Assert.Throws <FormatException>(() => i.ToString("Y", null)); // Invalid format
        }
Exemplo n.º 15
0
        public static async Task <ResPq> Do(Int128 nonce, MtProtoPlainTransport transport)
        {
            var res = await transport.Call(new ReqPq(nonce)).ConfigureAwait(false);

            Helpers.Assert(res.Nonce == nonce, "auth step1: invalid nonce");
            return(res);
        }
Exemplo n.º 16
0
        /// <summary>
        ///     Converts an <see cref="Int128" /> 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 Int128 value, byte[] buffer, int offset = 0, bool?asLittleEndian = null)
        {
            bool ale = GetIsLittleEndian(asLittleEndian);

            value.Low.ToBytes(buffer, ale ? offset : offset + 8, ale);
            value.High.ToBytes(buffer, ale ? offset + 8 : offset, ale);
        }
Exemplo n.º 17
0
        public static Int128 Int128Mul(long lhs, long rhs)
        {
            bool num = lhs < 0 != rhs < 0;

            if (lhs < 0)
            {
                lhs = -lhs;
            }
            if (rhs < 0)
            {
                rhs = -rhs;
            }
            ulong num2  = (ulong)lhs >> 32;
            ulong num3  = (ulong)(lhs & uint.MaxValue);
            ulong num4  = (ulong)rhs >> 32;
            ulong num5  = (ulong)(rhs & uint.MaxValue);
            ulong num6  = num2 * num4;
            ulong num7  = num3 * num5;
            ulong num8  = num2 * num5 + num3 * num4;
            long  num9  = (long)(num6 + (num8 >> 32));
            ulong num10 = (num8 << 32) + num7;

            if (num10 < num7)
            {
                num9++;
            }
            Int128 @int = new Int128(num9, num10);

            if (!num)
            {
                return(@int);
            }
            return(-@int);
        }
Exemplo n.º 18
0
        public static void ToStringTest(Int128 i, string format, IFormatProvider provider, string expected)
        {
            // Format is case insensitive
            string upperFormat = format.ToUpperInvariant();
            string lowerFormat = format.ToLowerInvariant();

            string upperExpected = expected.ToUpperInvariant();
            string lowerExpected = expected.ToLowerInvariant();

            bool isDefaultProvider = (provider is null) || (provider == NumberFormatInfo.CurrentInfo);

            if (string.IsNullOrEmpty(format) || (format.ToUpperInvariant() is "G" or "R"))
            {
                if (isDefaultProvider)
                {
                    Assert.Equal(upperExpected, i.ToString());
                    Assert.Equal(upperExpected, i.ToString((IFormatProvider)null));
                }
                Assert.Equal(upperExpected, i.ToString(provider));
            }

            if (isDefaultProvider)
            {
                Assert.Equal(upperExpected, i.ToString(upperFormat));
                Assert.Equal(lowerExpected, i.ToString(lowerFormat));
                Assert.Equal(upperExpected, i.ToString(upperFormat, null));
                Assert.Equal(lowerExpected, i.ToString(lowerFormat, null));
            }

            Assert.Equal(upperExpected, i.ToString(upperFormat, provider));
            Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider));
        }
Exemplo n.º 19
0
        public void JaegerActivityConverterTest_ConvertActivityToJaegerSpan_NoAttributes()
        {
            var activity         = CreateTestActivity(setAttributes: false);
            var traceIdAsInt     = new Int128(activity.Context.TraceId);
            var spanIdAsInt      = new Int128(activity.Context.SpanId);
            var linkTraceIdAsInt = new Int128(activity.Links.Single().Context.TraceId);
            var linkSpanIdAsInt  = new Int128(activity.Links.Single().Context.SpanId);

            var jaegerSpan = activity.ToJaegerSpan();

            Assert.Equal("Name", jaegerSpan.OperationName);
            Assert.Equal(2, jaegerSpan.Logs.Count);

            Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
            Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
            Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
            Assert.Equal(new Int128(activity.ParentSpanId).Low, jaegerSpan.ParentSpanId);

            Assert.Equal(activity.Links.Count(), jaegerSpan.References.Count);
            var references = jaegerSpan.References.ToArray();
            var jaegerRef  = references[0];

            Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
            Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
            Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);

            Assert.Equal(0x1, jaegerSpan.Flags);

            Assert.Equal(activity.StartTimeUtc.ToEpochMicroseconds(), jaegerSpan.StartTime);
            Assert.Equal((long)(activity.Duration.TotalMilliseconds * 1000), jaegerSpan.Duration);

            // 2 tags: span.kind & library.name.
            Assert.Equal(2, jaegerSpan.Tags.Count);

            var logs      = jaegerSpan.Logs.ToArray();
            var jaegerLog = logs[0];

            Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
            Assert.Equal(2, jaegerLog.Fields.Count());
            var eventFields = jaegerLog.Fields.ToArray();
            var eventField  = eventFields[0];

            Assert.Equal("key", eventField.Key);
            Assert.Equal("value", eventField.VStr);
            eventField = eventFields[1];
            Assert.Equal("message", eventField.Key);
            Assert.Equal("Event1", eventField.VStr);

            Assert.Equal(activity.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);

            jaegerLog = logs[1];
            Assert.Equal(2, jaegerLog.Fields.Count());
            eventFields = jaegerLog.Fields.ToArray();
            eventField  = eventFields[0];
            Assert.Equal("key", eventField.Key);
            Assert.Equal("value", eventField.VStr);
            eventField = eventFields[1];
            Assert.Equal("message", eventField.Key);
            Assert.Equal("Event2", eventField.VStr);
        }
Exemplo n.º 20
0
        /// <summary>
        /// Gets the circumference of a closed polygon.
        /// </summary>
        /// <param name="closedPolygon">The closed polygon.</param>
        /// <returns>The circumference of the given closed polygon.</returns>
        public static double GetClosedPolygonCircumference(IEnumerable <IntPoint> closedPolygon)
        {
            IntPoint firstPoint = default;
            IntPoint previous   = default;

            double sum            = 0.0;
            var    numberOfPoints = 0;

            foreach (var pt in closedPolygon)
            {
                if (0 == numberOfPoints)
                {
                    firstPoint = pt;
                }
                else
                {
                    sum += Math.Sqrt((double)(Int128.Int128Mul(pt.X - previous.X, pt.X - previous.X) + Int128.Int128Mul(pt.Y - previous.Y, pt.Y - previous.Y)));
                }

                previous = pt;
                ++numberOfPoints;
            }

            if (numberOfPoints == 0)
            {
                throw new ArgumentException("Polygon is empty (has no point at all)", nameof(closedPolygon));
            }
            else
            {
                var pt = firstPoint;
                sum += Math.Sqrt((double)(Int128.Int128Mul(pt.X - previous.X, pt.X - previous.X) + Int128.Int128Mul(pt.Y - previous.Y, pt.Y - previous.Y)));
                return(sum);
            }
        }
Exemplo n.º 21
0
 public override void DeserializeBody(BinaryReader br)
 {
     nonce          = (Int128)ObjectUtils.DeserializeObject(br);
     server_nonce   = (Int128)ObjectUtils.DeserializeObject(br);
     new_nonce_hash = (Int128)ObjectUtils.DeserializeObject(br);
     Type           = TLAbsServer_DH_ParamsTypes.TLServer_DH_params_fail;
 }
Exemplo n.º 22
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Immediate"/> class.
 /// </summary>
 /// <param name="constant">A constant.</param>
 /// <param name="size">The size of the resulting value.</param>
 public Immediate(Int128 constant, DataSize size)
     : this(c => new SimpleExpression(constant), size)
 {
     #region Contract
     Contract.Requires <InvalidEnumArgumentException>(Enum.IsDefined(typeof(DataSize), size));
     #endregion
 }
Exemplo n.º 23
0
        public void JaegerSpanConverterTest_ConvertSpanToJaegerSpan_NoEvents()
        {
            var span             = CreateTestSpan(addEvents: false);
            var traceIdAsInt     = new Int128(span.Context.TraceId);
            var spanIdAsInt      = new Int128(span.Context.SpanId);
            var linkTraceIdAsInt = new Int128(span.Links.Single().Context.TraceId);
            var linkSpanIdAsInt  = new Int128(span.Links.Single().Context.SpanId);

            var jaegerSpan = span.ToJaegerSpan();

            Assert.Equal("Name", jaegerSpan.OperationName);
            Assert.Empty(jaegerSpan.Logs);

            Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
            Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
            Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
            Assert.Equal(new Int128(span.ParentSpanId).Low, jaegerSpan.ParentSpanId);

            Assert.Equal(span.Links.Count(), jaegerSpan.References.Count);
            var references = jaegerSpan.References.ToArray();
            var jaegerRef  = references[0];

            Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
            Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
            Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);

            Assert.Equal(0x1, jaegerSpan.Flags);

            Assert.Equal(span.StartTimestamp.ToEpochMicroseconds(), jaegerSpan.StartTime);
            Assert.Equal(
                span.EndTimestamp.ToEpochMicroseconds()
                - span.StartTimestamp.ToEpochMicroseconds(), jaegerSpan.Duration);

            var tags = jaegerSpan.Tags.ToArray();
            var tag  = tags[0];

            Assert.Equal(JaegerTagType.STRING, tag.VType);
            Assert.Equal("stringKey", tag.Key);
            Assert.Equal("value", tag.VStr);
            tag = tags[1];
            Assert.Equal(JaegerTagType.LONG, tag.VType);
            Assert.Equal("longKey", tag.Key);
            Assert.Equal(1, tag.VLong);
            tag = tags[2];
            Assert.Equal(JaegerTagType.LONG, tag.VType);
            Assert.Equal("longKey2", tag.Key);
            Assert.Equal(1, tag.VLong);
            tag = tags[3];
            Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
            Assert.Equal("doubleKey", tag.Key);
            Assert.Equal(1, tag.VDouble);
            tag = tags[4];
            Assert.Equal(JaegerTagType.DOUBLE, tag.VType);
            Assert.Equal("doubleKey2", tag.Key);
            Assert.Equal(1, tag.VDouble);
            tag = tags[5];
            Assert.Equal(JaegerTagType.BOOL, tag.VType);
            Assert.Equal("boolKey", tag.Key);
            Assert.Equal(true, tag.VBool);
        }
Exemplo n.º 24
0
        public static Int128 Power(Int128 value, Int128 exponent)
        {
            Int128 result;

            Int128.Pow(out result, ref value, (int)exponent);
            return(result);
        }
Exemplo n.º 25
0
        public IMessage DecodeEncryptedMessage(byte[] messageBytes, byte[] authKey, Sender sender, out UInt64 salt, out UInt64 sessionId)
        {
            Argument.IsNotNull(() => authKey);
            Argument.IsNotNull(() => messageBytes);

            ulong providedAuthKeyId = ComputeAuthKeyId(authKey);

            var encryptedData = new byte[messageBytes.Length - EncryptedOuterHeaderLength];

            Int128 msgKey;

            using (var streamer = new TLStreamer(messageBytes))
            {
                // Reading header.
                ulong authKeyId = streamer.ReadUInt64();
                if (authKeyId != providedAuthKeyId)
                {
                    throw new InvalidAuthKey(string.Format("Message encrypted with auth key with id={0}, but auth key provided for decryption with id={1}.", authKeyId,
                                                           providedAuthKeyId));
                }
                msgKey = streamer.ReadInt128();

                // Reading encrypted data.
                streamer.Read(encryptedData, 0, encryptedData.Length);
            }

            // Decrypting.
            byte[] aesKey, aesIV;
            ComputeAesKeyAndIV(authKey, msgKey, out aesKey, out aesIV, sender);
            byte[] innerDataWithPadding = _encryptionServices.Aes256IgeDecrypt(encryptedData, aesKey, aesIV);

            Int32  msgDataLength;
            UInt64 msgId;
            UInt32 seqno;
            Object body;

            using (var streamer = new TLStreamer(innerDataWithPadding))
            {
                salt          = streamer.ReadUInt64();
                sessionId     = streamer.ReadUInt64();
                msgId         = streamer.ReadUInt64();
                seqno         = streamer.ReadUInt32();
                msgDataLength = streamer.ReadInt32();
                body          = _tlRig.Deserialize(streamer);
            }

            int innerDataLength = EncryptedInnerHeaderLength + msgDataLength;

            // When an encrypted message is received, it must be checked that
            // msg_key is in fact equal to the 128 lower-order bits
            // of the SHA1 hash of the previously encrypted portion.
            Int128 expectedMsgKey = ComputeMsgKey(new ArraySegment <byte>(innerDataWithPadding, 0, innerDataLength));

            if (msgKey != expectedMsgKey)
            {
                throw new InvalidMessageException(string.Format("Expected message key to be {0}, but actual is {1}.", expectedMsgKey, msgKey));
            }

            return(new Message(msgId, seqno, body));
        }
        public void JaegerSpanConverterTest_ConvertSpanToJaegerSpan_NoAttributes()
        {
            var span             = CreateTestSpan(setAttributes: false);
            var traceIdAsInt     = new Int128(span.Context.TraceId);
            var spanIdAsInt      = new Int128(span.Context.SpanId);
            var linkTraceIdAsInt = new Int128(span.Links.Single().Context.TraceId);
            var linkSpanIdAsInt  = new Int128(span.Links.Single().Context.SpanId);

            var jaegerSpan = span.ToJaegerSpan();

            Assert.Equal("Name", jaegerSpan.OperationName);
            Assert.Equal(2, jaegerSpan.Logs.Count());

            Assert.Equal(traceIdAsInt.High, jaegerSpan.TraceIdHigh);
            Assert.Equal(traceIdAsInt.Low, jaegerSpan.TraceIdLow);
            Assert.Equal(spanIdAsInt.Low, jaegerSpan.SpanId);
            Assert.Equal(new Int128(span.ParentSpanId).Low, jaegerSpan.ParentSpanId);

            Assert.Equal(span.Links.Count(), jaegerSpan.References.Count());
            var references = jaegerSpan.References.ToArray();
            var jaegerRef  = references[0];

            Assert.Equal(linkTraceIdAsInt.High, jaegerRef.TraceIdHigh);
            Assert.Equal(linkTraceIdAsInt.Low, jaegerRef.TraceIdLow);
            Assert.Equal(linkSpanIdAsInt.Low, jaegerRef.SpanId);

            Assert.Equal(0x1, jaegerSpan.Flags);

            Assert.Equal(span.StartTimestamp.ToEpochMicroseconds(), jaegerSpan.StartTime);
            Assert.Equal((long)((span.EndTimestamp - span.StartTimestamp).TotalMilliseconds * 1000), jaegerSpan.Duration);

            // A single tag representing the span.kind
            Assert.Single(jaegerSpan.JaegerTags);

            var logs      = jaegerSpan.Logs.ToArray();
            var jaegerLog = logs[0];

            Assert.Equal(span.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);
            Assert.Equal(2, jaegerLog.Fields.Count());
            var eventFields = jaegerLog.Fields.ToArray();
            var eventField  = eventFields[0];

            Assert.Equal("key", eventField.Key);
            Assert.Equal("value", eventField.VStr);
            eventField = eventFields[1];
            Assert.Equal("message", eventField.Key);
            Assert.Equal("Event1", eventField.VStr);

            Assert.Equal(span.Events.First().Timestamp.ToEpochMicroseconds(), jaegerLog.Timestamp);

            jaegerLog = logs[1];
            Assert.Equal(2, jaegerLog.Fields.Count());
            eventFields = jaegerLog.Fields.ToArray();
            eventField  = eventFields[0];
            Assert.Equal("key", eventField.Key);
            Assert.Equal("value", eventField.VStr);
            eventField = eventFields[1];
            Assert.Equal("message", eventField.Key);
            Assert.Equal("Event2", eventField.VStr);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Immediate"/> class.
 /// </summary>
 /// <param name="constant">A constant.</param>
 /// <param name="size">The size of the resulting value.</param>
 public Immediate(Int128 constant, DataSize size)
     : this(c => new SimpleExpression(constant), size)
 {
     #region Contract
     Contract.Requires<InvalidEnumArgumentException>(Enum.IsDefined(typeof(DataSize), size));
     #endregion
 }
Exemplo n.º 28
0
 public override void DeserializeBody(BinaryReader br)
 {
     nonce           = (Int128)ObjectUtils.DeserializeObject(br);
     server_nonce    = (Int128)ObjectUtils.DeserializeObject(br);
     new_nonce_hash2 = (Int128)ObjectUtils.DeserializeObject(br);
     Type            = TLAbsSet_client_DH_params_answerTypes.TLDh_gen_retry;
 }
Exemplo n.º 29
0
        // nb: Constructing two new Int128 objects every time we want to multiply longs
        // is slow. So, although calling the Int128Mul method doesn't look as clean, the
        // code runs significantly faster than if we'd used the * operator.

        public static Int128 Int128Mul(long lhs, long rhs)
        {
            var negate = lhs < 0 != rhs < 0;

            if (lhs < 0)
            {
                lhs = -lhs;
            }
            if (rhs < 0)
            {
                rhs = -rhs;
            }
            var int1Hi = (ulong)lhs >> 32;
            var int1Lo = (ulong)lhs & 0xFFFFFFFF;
            var int2Hi = (ulong)rhs >> 32;
            var int2Lo = (ulong)rhs & 0xFFFFFFFF;

            // nb: see comments in clipper.pas
            var a = int1Hi * int2Hi;
            var b = int1Lo * int2Lo;
            var c = int1Hi * int2Lo + int1Lo * int2Hi;

            ulong lo;
            var   hi = (long)(a + (c >> 32));

            unchecked { lo = (c << 32) + b; }
            if (lo < b)
            {
                hi++;
            }
            var result = new Int128(hi, lo);

            return(negate ? -result : result);
        }
Exemplo n.º 30
0
        public static Int128 operator +(Int128 val1, int val2)
        {
            if (val1 == 0)
            {
                return(new Int128((uint)val2));
            }
            if (val2 == 0)
            {
                return(val1);
            }
            Int128 ret = new Int128(0);
            ulong  sum = 0;

            sum     = val1._x0 + (ulong)val2 + sum;
            ret._x0 = (uint)sum;
            sum   >>= 32;
            sum     = val1._x1 + sum;
            ret._x1 = (uint)sum;
            sum   >>= 32;
            sum     = val1._x2 + sum;
            ret._x2 = (uint)sum;
            sum   >>= 32;
            sum     = val1._x3 + sum;
            ret._x3 = (uint)sum;
            return(ret);
        }
Exemplo n.º 31
0
        private static void TestMul6464(long a, long b, ulong highExpected, ulong lowExpected)
        {
            Int128 product = Int128.Mul(a, b);

            Assert.AreEqual(highExpected, product.High);
            Assert.AreEqual(lowExpected, product.Low);
        }
Exemplo n.º 32
0
 public static Int128 Align(Int128 value, int boundary)
 {
     #region Contract
     Contract.Requires<ArgumentOutOfRangeException>(boundary >= 1);
     Contract.Requires<ArgumentException>(IsPowerOfTwo(boundary));
     Contract.Ensures(Contract.Result<Int128>() >= value);
     #endregion
     return (boundary + ((value - 1) & ~(boundary - 1)));
 }
Exemplo n.º 33
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Relocation"/> class.
        /// </summary>
        /// <param name="symbol">The target symbol.</param>
        /// <param name="section">The section in which the storage unit to be relocated resides.</param>
        /// <param name="offset">The offset relative to the start of <paramref name="section"/> at which the storage
        /// unit to be relocated resides.</param>
        /// <param name="addend">The constant used to compute the value of the relocatable field.</param>
        /// <param name="type">The type of relocation compution to perform.</param>
        public Relocation(Symbol symbol, Section section, Int128 offset, Int128 addend, RelocationType type)
        {
            #region Contract
            Contract.Requires<ArgumentNullException>(symbol != null);
            Contract.Requires<ArgumentNullException>(section != null);
            #endregion

            this.targetSymbol = symbol;
            this.section = section;
            this.offset = offset;
            this.addend = addend;
            this.type = type;
        }
        /// <summary>
        /// Writes a 128-bit value to the <see cref="BinaryWriter"/>.
        /// </summary>
        /// <param name="writer">The <see cref="BinaryWriter"/> to write to.</param>
        /// <param name="value">The value to write.</param>
        public static void Write(this BinaryWriter writer, Int128 value)
        {
            #region Contract
            Contract.Requires<ArgumentNullException>(writer != null);
            #endregion

            // We maintain the same byte ordering as the BinaryWriter.
            if (BitConverter.IsLittleEndian)
            {
                writer.Write((ulong)value.Low);
                writer.Write((ulong)value.High);
            }
            else
            {
                writer.Write((ulong)value.High);
                writer.Write((ulong)value.Low);
            }
        }
Exemplo n.º 35
0
 public static void Serialize(Int128 src, BinaryWriter writer)
 {
     writer.Write(src.ToBytes(true));
 }
Exemplo n.º 36
0
 void StartFight(Int128 guid)
 {
     Thread.Sleep(100);
     var t = new Thread(StartFightNewThead) {Name = "StartFightNewThead(object guid)"};
     t.Start(guid);
     Thread.Sleep(1000);
 }
Exemplo n.º 37
0
 public Guid(Int128 guid)
 {
     _mGuid = guid;
 }
Exemplo n.º 38
0
 public static void GetPrimeMultipliers(this Int128 pq, out Int128 p, out Int128 q)
 {
     var pq256 = (Int256) pq;
     Int256 p256, q256;
     pq256.GetPrimeMultipliers(out p256, out q256);
     p = (Int128) p256;
     q = (Int128) q256;
 }
Exemplo n.º 39
0
 public static Int128 Square(Int128 a)
 {
     return Int128.Square(a);
 }
Exemplo n.º 40
0
 /// <summary>
 /// Resets this context without clearing the symbol or relocation tables.
 /// </summary>
 /// <remarks>
 /// The context's address is reset to zero, the curent section is set to <see langword="null"/>. Derived
 /// classes may override this method and reset other fields and properties. The symbol and relocation tables
 /// are never cleared.
 /// </remarks>
 public virtual void Reset()
 {
     this.address = 0;
     this.section = null;
 }
Exemplo n.º 41
0
 public static DataSize GetSizeOfValue(Int128 value)
 {
     #region Contract
     Contract.Ensures(Enum.IsDefined(typeof(DataSize), Contract.Result<DataSize>()));
     #endregion
     return GetSizeOfValue(value, true);
 }
Exemplo n.º 42
0
 public static bool IsPowerOfTwo(Int128 a)
 {
     return a.IsPowerOfTwo;
 }
Exemplo n.º 43
0
 public WowGuid(Int128 guid)
 {
     m_guid = guid;
 }
Exemplo n.º 44
0
 public static Int128 Max(Int128 a, Int128 b)
 {
     return Int128.Max(a, b);
 }
Exemplo n.º 45
0
 public static Int128 Min(Int128 a, Int128 b)
 {
     return Int128.Min(a, b);
 }
Exemplo n.º 46
0
 public static Int128 TwosComplement(Int128 a)
 {
     return -a;
 }
Exemplo n.º 47
0
 public static Int128 CalculatePadding(Int128 value, int boundary)
 {
     #region Contract
     Contract.Requires<ArgumentOutOfRangeException>(boundary >= 1);
     Contract.Requires<ArgumentException>(IsPowerOfTwo(boundary));
     Contract.Ensures(Contract.Result<Int128>() >= 0);
     #endregion
     return Align(value, boundary) - value;
 }
Exemplo n.º 48
0
        public List<CrawlTaskDetail> List = new List<CrawlTaskDetail>(); //任务列表

        #endregion Fields

        #region Constructors

        public CrawlTask()
        {
            ID = new Int128(Guid.NewGuid().ToByteArray());
            CreateDt = DateTime.Now;
            WorkTimeSpan = 60;
        }
Exemplo n.º 49
0
        public static DataSize GetSizeOfValue(Int128 value, bool signed)
        {
            #region Contract
            Contract.Ensures(Enum.IsDefined(typeof(DataSize), Contract.Result<DataSize>()));
            #endregion

            if (signed && value < 0)
                value = -value;

            if (value.High != 0) return DataSize.Bit128;
            if ((value.Low & 0xFFFFFFFF00000000) != 0) return DataSize.Bit64;
            if ((value.Low & 0x00000000FFFF0000) != 0) return DataSize.Bit32;
            if ((value.Low & 0x000000000000FF00) != 0) return DataSize.Bit16;
            return DataSize.Bit8;
        }
Exemplo n.º 50
0
 /// <summary>
 /// Defines the symbol by setting its value and adding it to the symbol table.
 /// </summary>
 /// <param name="context">The current <see cref="Context"/>.</param>
 /// <param name="value">The value of the symbol.</param>
 public void Define(Context context, Int128 value)
 {
     #region Contract
     Contract.Requires<ArgumentNullException>(context != null);
     #endregion
     this.Value = value;
     this.DefiningSection = context.Section;
     this.DefiningFile = context.Section.Parent;
     context.SymbolTable.Add(this);
 }
Exemplo n.º 51
0
 public static Int128 GCD(this Int128 a, Int128 b)
 {
     while (true)
     {
         if (b == 0)
         {
             return a;
         }
         Int128 a1 = a;
         a = b;
         b = a1%b;
     }
 }
Exemplo n.º 52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Immediate"/> class.
 /// </summary>
 /// <param name="constant">A constant.</param>
 public Immediate(Int128 constant)
     : this(constant, DataSize.None)
 {
 }
Exemplo n.º 53
0
 public static Int128 Power(Int128 value, Int128 exponent)
 {
     Int128 result;
     Int128.Pow(out result, ref value, (int)exponent);
     return result;
 }
Exemplo n.º 54
0
        private void ComputeAesKeyAndIV(byte[] authKey, Int128 msgKey, out byte[] aesKey, out byte[] aesIV, Sender sender)
        {
            // x = 0 for messages from client to server and x = 8 for those from server to client.
            int x;
            switch (sender)
            {
                case Sender.Client:
                    x = 0;
                    break;
                case Sender.Server:
                    x = 8;
                    break;
                default:
                    throw new ArgumentOutOfRangeException("sender");
            }

            byte[] msgKeyBytes = msgKey.ToBytes();

            byte[] buffer = _aesKeyAndIVComputationBuffer ?? (_aesKeyAndIVComputationBuffer = new byte[32 + MsgKeyLength]);

            // sha1_a = SHA1 (msg_key + substr (auth_key, x, 32));
            Buffer.BlockCopy(msgKeyBytes, 0, buffer, 0, MsgKeyLength);
            Buffer.BlockCopy(authKey, x, buffer, MsgKeyLength, 32);
            byte[] sha1A = _hashServices.ComputeSHA1(buffer);

            // sha1_b = SHA1 (substr (auth_key, 32+x, 16) + msg_key + substr (auth_key, 48+x, 16));
            Buffer.BlockCopy(authKey, 32 + x, buffer, 0, 16);
            Buffer.BlockCopy(msgKeyBytes, 0, buffer, 16, MsgKeyLength);
            Buffer.BlockCopy(authKey, 48 + x, buffer, 16 + MsgKeyLength, 16);
            byte[] sha1B = _hashServices.ComputeSHA1(buffer);

            // sha1_с = SHA1 (substr (auth_key, 64+x, 32) + msg_key);
            Buffer.BlockCopy(authKey, 64 + x, buffer, 0, 32);
            Buffer.BlockCopy(msgKeyBytes, 0, buffer, 32, MsgKeyLength);
            byte[] sha1C = _hashServices.ComputeSHA1(buffer);

            // sha1_d = SHA1 (msg_key + substr (auth_key, 96+x, 32));
            Buffer.BlockCopy(msgKeyBytes, 0, buffer, 0, MsgKeyLength);
            Buffer.BlockCopy(authKey, 96 + x, buffer, MsgKeyLength, 32);
            byte[] sha1D = _hashServices.ComputeSHA1(buffer);

            // aes_key = substr (sha1_a, 0, 8) + substr (sha1_b, 8, 12) + substr (sha1_c, 4, 12);
            aesKey = new byte[32];
            Buffer.BlockCopy(sha1A, 0, aesKey, 0, 8);
            Buffer.BlockCopy(sha1B, 8, aesKey, 8, 12);
            Buffer.BlockCopy(sha1C, 4, aesKey, 20, 12);

            // aes_iv = substr (sha1_a, 8, 12) + substr (sha1_b, 0, 8) + substr (sha1_c, 16, 4) + substr (sha1_d, 0, 8);
            aesIV = new byte[32];
            Buffer.BlockCopy(sha1A, 8, aesIV, 0, 12);
            Buffer.BlockCopy(sha1B, 0, aesIV, 12, 8);
            Buffer.BlockCopy(sha1C, 16, aesIV, 20, 4);
            Buffer.BlockCopy(sha1D, 0, aesIV, 24, 8);
        }
        /// <summary>
        /// Writes a value to the <see cref="BinaryWriter"/> as a value with the specified size.
        /// </summary>
        /// <param name="writer">The <see cref="BinaryWriter"/> to write to.</param>
        /// <param name="value">The value to write.</param>
        /// <param name="size">The size of the value to write.</param>
        /// <returns>The number of written bytes.</returns>
        public static int Write(this BinaryWriter writer, Int128 value, DataSize size)
        {
            #region Contract
            Contract.Requires<ArgumentNullException>(writer != null);
            Contract.Requires<InvalidEnumArgumentException>(Enum.IsDefined(typeof(DataSize), size));
            Contract.Requires<ArgumentException>(size != DataSize.None);
            Contract.Ensures(Contract.Result<int>() >= 0);
            #endregion

            switch (size)
            {
                case DataSize.Bit8:
                case DataSize.Bit16:
                case DataSize.Bit32:
                case DataSize.Bit64:
                case DataSize.Bit80:
                    writer.Write((ulong)value, size);
                    break;
                case DataSize.Bit128:
                    writer.Write(value);
                    break;
                case DataSize.Bit256:
                    // We maintain the same byte ordering as the BinaryWriter.
                    if (BitConverter.IsLittleEndian)
                    {
                        writer.Write(value);
                        writer.Write((Int128)0);
                    }
                    else
                    {
                        writer.Write((Int128)0);
                        writer.Write(value);
                    }
                    break;
                default:
                    throw new NotSupportedException();
            }

            return (int)size;
        }
Exemplo n.º 56
0
 private bool CheckNewNonceHash(Int256 newNonce, Int128 newNonceHash)
 {
     byte[] hash = ComputeSHA1(newNonce.ToBytes());
     Int128 nonceHash = hash.ToInt128();
     return nonceHash == newNonceHash;
 }
Exemplo n.º 57
0
 public override void WriteInt128(Int128 value)
 {
     lock (_streamer)
         _streamer.WriteInt128(value);
 }
Exemplo n.º 58
0
 private void CheckNonce(Int128 expectedNonce, Int128 actualNonce)
 {
     if (actualNonce != expectedNonce)
     {
         throw new InvalidResponseException(string.Format("Expected nonce {0:X16} differs from the actual nonce {1:X16}.", expectedNonce, actualNonce));
     }
 }
Exemplo n.º 59
0
 public static Int128 Modulus(Int128 n, Int128 p)
 {
     var result = n % p;
     if (result < 0)
         result += p;
     return result;
 }
Exemplo n.º 60
0
 public static Int128 Abs(Int128 a)
 {
     return a.IsNegative ? -a : a;
 }