コード例 #1
0
        public void GetMatchingTest()
        {
            int defaultsectorsize = 1024;

            using (Stream dest = new MemoryStream())
            {
                using (Store target = new Store(dest, defaultsectorsize))
                {
                    for (int i = 0; i < 1000; ++i)
                    {
                        target.Write(new byte[] { (byte)BufUtils.RandomInt(240), (byte)(i % 5), (byte)BufUtils.RandomInt(240) });
                    }

                    var actual = target.GetMatching(r => r[1] == 3, 2);
                    Assert.IsTrue(actual.Count == 200);
                    Assert.IsTrue(actual.All(r => r.Value[1] == 3));

                    actual = target.GetMatching(r => r.Length > 1 ? r[1] == 3 : false, 1);
                    Assert.IsTrue(actual.Count == 0);
                    Assert.IsTrue(actual.All(r => r.Value[1] == 3));

                    actual = target.GetMatching(r => r[1] == 3, 3);
                    Assert.IsTrue(actual.Count == 200);
                    Assert.IsTrue(actual.All(r => r.Value[1] == 3));
                }
            }
        }
コード例 #2
0
ファイル: UtilsTest.cs プロジェクト: kyapp69/i2p-cs
        public void TestRoulette3()
        {
            var l = BufUtils.Populate <float>(() => BufUtils.RandomInt(2) == 0 ? 0f : BufUtils.RandomFloat(100000), 10000);
            var r = new I2PCore.Utils.RouletteSelection <float, float>(l, v => v, k => k, 2f);

            int iszero = 0;

            for (int i = 0; i < 10000; ++i)
            {
                if (r.GetWeightedRandom() == 0f)
                {
                    ++iszero;
                }
            }

            Assert.IsTrue(iszero > 10000 / 5);
            Assert.IsTrue(iszero < 10000 / 2);

            r = new I2PCore.Utils.RouletteSelection <float, float>(l, v => v, k => k, float.MaxValue);

            iszero = 0;
            for (int i = 0; i < 10000; ++i)
            {
                if (r.GetWeightedRandom() == 0f)
                {
                    ++iszero;
                }
            }

            Assert.IsTrue(iszero < 4);
        }
コード例 #3
0
ファイル: UtilsTest.cs プロジェクト: kyapp69/i2p-cs
        public void TestTickCounter()
        {
            var start = new TickCounter();

            Assert.IsTrue(TickCounter.MaxDelta.DeltaToNowMilliseconds > 0);

            var maxd = TickCounter.MaxDelta;

            System.Threading.Thread.Sleep(200);
            Assert.IsTrue(maxd.DeltaToNowMilliseconds > 0);
            Assert.IsTrue(maxd.DeltaToNowMilliseconds > int.MaxValue / 2);

            Assert.IsTrue(start.DeltaToNowMilliseconds > 0);

            Assert.IsTrue(Math.Round((TickCounter.Now - start).ToSeconds / 3f) == Math.Round((float)start.DeltaToNowSeconds / 3f));

            var start_copy = new TickCounter(start.Ticks);

            System.Threading.Thread.Sleep(BufUtils.RandomInt(300) + 200);

            var startdelta = start.DeltaToNowMilliseconds;
            var now1       = new TickCounter();

            Assert.IsTrue(start.ToString().Length > 0);

            Assert.IsTrue((now1 - start).ToMilliseconds > 0);
            Assert.IsTrue(((now1 - start).ToMilliseconds) / 100 == startdelta / 100);
        }
コード例 #4
0
        public void NextTest()
        {
            int defaultsectorsize = 60;

            using (Stream dest = new MemoryStream())
            {
                using (Store target = new Store(dest, defaultsectorsize))
                {
                    for (int i = 0; i < 1000; ++i)
                    {
                        target.Write(new byte[] { (byte)BufUtils.RandomInt(240), (byte)(i % 7), (byte)BufUtils.RandomInt(240) });
                    }

                    var ix  = 0;
                    var cnt = 0;
                    while ((ix = target.Next(ix)) != -1)
                    {
                        var item = target.Read(ix);
                        Assert.IsTrue(item[1] == (cnt % 7));
                        ++cnt;
                    }

                    Assert.IsTrue(cnt == 1000);
                }
            }
        }
コード例 #5
0
ファイル: GarlicTest.cs プロジェクト: itfenom/i2p-cs
        public void TestAESBlock()
        {
            for (int runs = 0; runs < 10; ++runs)
            {
                var buf    = new BufLen(new byte[30000]);
                var writer = new BufRefLen(buf);

                var data  = BufUtils.RandomBytes(1 + BufUtils.RandomInt(45));
                var datar = new BufRefLen(data);
                var tags  = new List <I2PSessionTag>();
                for (int i = 0; i < BufUtils.RandomInt(5); ++i)
                {
                    tags.Add(new I2PSessionTag());
                }

                var newsession = BufUtils.RandomDouble(1.0) < 0.3 ? new I2PSessionKey() : null;
                var b1         = new GarlicAESBlock(writer, tags, newsession, datar);

                var bldata = new BufLen(buf, 0, writer - buf).Clone();

                var b2 = new GarlicAESBlock(new BufRefLen(bldata));

                var b1ar = new BufLen(b1.ToByteArray());
                var b2ar = new BufLen(b2.ToByteArray());
                Assert.IsTrue(b1ar == b2ar);

                var bufs = new BufRefStream();
                b1.Write(bufs);

                var b3 = new GarlicAESBlock(new BufRefLen(bufs.ToByteArray()));

                var b3ar = new BufLen(b3.ToByteArray());
                Assert.IsTrue(b1ar == b3ar);
            }
        }
コード例 #6
0
        public void MakeAndReadFragmentsWithSerialize()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 200; ++i)
            {
                switch (BufUtils.RandomInt(3))
                {
                case 0:
                    var adatarec = new DataMessage(
                        new BufLen(
                            BufUtils.RandomBytes(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageLocal(adatarec));
                    break;

                case 1:
                    var arec = new DatabaseLookupMessage(
                        new I2PIdentHash(true),
                        new I2PIdentHash(true),
                        DatabaseLookupMessage.LookupTypes.RouterInfo);

                    origmsgs.Add(new TunnelMessageRouter(
                                     arec,
                                     new I2PIdentHash(true)));
                    break;

                case 2:
                    var adatarec2 = new DataMessage(
                        new BufLen(
                            BufUtils.RandomBytes(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageTunnel(adatarec2,
                                                         new I2PIdentHash(true),
                                                         BufUtils.RandomUint()));
                    break;
                }
            }

            var msgs     = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());
            var recvlist = new List <TunnelDataMessage>();

            foreach (var msg in msgs)
            {
                recvlist.Add((TunnelDataMessage)I2NPMessage.ReadHeader16(
                                 new BufRefLen(msg.CreateHeader16.HeaderAndPayload)).Message);
            }

            var mkmsg     = new TunnelDataFragmentReassembly();
            var recvtmsgs = mkmsg.Process(recvlist, out var _);

            foreach (var rmsg in recvtmsgs)
            {
                Assert.IsTrue(origmsgs.SingleOrDefault(m =>
                                                       m.Delivery == rmsg.Delivery &&
                                                       m.Message.CreateHeader16.HeaderAndPayload == rmsg.Message.CreateHeader16.HeaderAndPayload
                                                       ) != null);
            }
        }
コード例 #7
0
        GarlicCreationInfo UseExistingSessionTags(bool explack, uint trackingid, GarlicCloveDelivery[] cloves)
        {
            Garlic msg;
            DeliveryStatusMessage ackmsg = null;

            if (explack)
            {
                msg = AddExplAck(cloves, out ackmsg);
            }
            else
            {
                var exp = new I2PDate(DateTime.UtcNow.AddMinutes(5));
                msg = new Garlic(cloves.Select(d => new GarlicClove(d, exp)).ToArray());
            }

#if LOG_ALL_TUNNEL_TRANSFER
            Logging.LogDebug(() => string.Format(
                                 "DestinationSession: Garlic generated with {0} cloves. {1} tags available.",
                                 msg.Cloves.Count, SessionTags.Count));
#endif

            var payload = msg.ToByteArray();
            var dest    = new BufLen(new byte[61000]);
            var writer  = new BufRefLen(dest, 4);  // Reserve 4 bytes for GarlicMessageLength

            I2PSessionTag tag;
            lock ( SessionTags )
            {
                var ix = BufUtils.RandomInt(SessionTags.Count);
                tag = SessionTags[ix];
                SessionTags.RemoveAt(ix);
            }

            // Tag as header
            writer.Write(tag.Value);

            // AES block
            var aesstart = new BufLen(writer);
            var aesblock = new GarlicAESBlock(writer, null, null, new BufRefLen(payload));

            var pivh = I2PHashSHA256.GetHash(tag.Value);

            Cipher.Init(true, SessionKey.Key.ToParametersWithIV(new BufLen(pivh, 0, 16)));
            Cipher.ProcessBytes(aesblock.DataBuf);

            var length = writer - dest;
            dest.PokeFlip32((uint)(length - 4), 0);

            return(new GarlicCreationInfo(
                       Destination.IdentHash,
                       cloves,
                       new EGGarlic(new BufRefLen(dest, 0, length)),
                       GarlicCreationInfo.KeyUsed.Aes,
                       SessionTags.Count(),
                       trackingid,
                       explack ? (uint?)ackmsg.MessageId : null,
                       LatestEGAckMessageId));
        }
コード例 #8
0
        public void MakeAndReadFragments()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 200; ++i)
            {
                switch (BufUtils.RandomInt(3))
                {
                case 0:
                    var adatarec = new DataMessage(new BufLen(BufUtils.Random(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageTunnel(
                                     adatarec.Header16,
                                     new I2PIdentHash(true),
                                     BufUtils.RandomUint()));
                    break;

                case 1:
                    var arec = new DatabaseLookupMessage(
                        new I2PIdentHash(true),
                        new I2PIdentHash(true),
                        DatabaseLookupMessage.LookupTypes.Normal);

                    origmsgs.Add(new TunnelMessageRouter(arec.Header16, new I2PIdentHash(true)));
                    break;

                case 2:
                    var adatarec2 = new DataMessage(new BufLen(BufUtils.Random(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageLocal(adatarec2.Header16));
                    break;
                }
            }

            var msgs = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());

            var mkmsg     = new TunnelDataFragmentReassembly();
            var recvtmsgs = mkmsg.Process(msgs);

            foreach (var rmsg in recvtmsgs)
            {
                Assert.IsTrue(origmsgs.SingleOrDefault(m =>
                                                       m.Delivery == rmsg.Delivery &&
                                                       m.Header.HeaderAndPayload == rmsg.Header.HeaderAndPayload
                                                       ) != null);
            }
        }
コード例 #9
0
        public void MakeAndReadFragments5Chunked()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 5; ++i)
            {
                var adatarec = new DataMessage(new BufLen(BufUtils.RandomBytes(2048)));

                var amsg = new TunnelMessageRouter(
                    adatarec,
                    new I2PIdentHash(true));

                origmsgs.Add(amsg);
            }

            var msgs = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());

            var mkmsg     = new TunnelDataFragmentReassembly();
            var recvtmsgs = mkmsg.Process(
                msgs.Chunk(a => 2 + BufUtils.RandomInt(2))
                .Shuffle()
                .SelectMany(c => c)
                .Shuffle(), out var _);

            Assert.IsTrue(origmsgs.All(o => recvtmsgs.Any(m =>
                                                          m.Delivery == o.Delivery &&
                                                          m.Message.CreateHeader16.HeaderAndPayload == o.Message.CreateHeader16.HeaderAndPayload
                                                          )));

            var msgs2 = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());

            recvtmsgs = mkmsg.Process(
                msgs2.Chunk(a => 1 + BufUtils.RandomInt(2))
                .Shuffle()
                .ToArray()
                .SelectMany(c => c)
                .ToArray()
                .Skip(1)
                .Shuffle(), out var _);

            Assert.IsFalse(origmsgs.All(o => recvtmsgs.Any(m =>
                                                           m.Delivery == o.Delivery &&
                                                           m.Message.CreateHeader16.HeaderAndPayload == o.Message.CreateHeader16.HeaderAndPayload
                                                           )));
        }
コード例 #10
0
        public void TestRoulette3()
        {
            var populationcount = RouletteSelection <float, float> .IncludeTop;
            var samplecount     = 50000;

            var l = BufUtils.Populate <float>(() => BufUtils.RandomInt(2) == 0 ? 0f : BufUtils.RandomFloat(100000), populationcount);
            var r = new I2PCore.Utils.RouletteSelection <float, float>(l, v => v, k => k);

            int iszero = 0;

            for (int i = 0; i < samplecount; ++i)
            {
                if (r.GetWeightedRandom(null) < float.Epsilon)
                {
                    ++iszero;
                }
            }

            Assert.IsTrue(iszero > 0);
            Assert.IsTrue(iszero < samplecount / 2);
        }
コード例 #11
0
        internal void Execute()
        {
            if (TestRemoteDest != null &&
                OutboundEstablishedPool.Count >= 2 &&
                InboundEstablishedPool.Count >= 2 &&
                TestRemoteDest.InboundEstablishedPool.Count >= 2)
            {
                try
                {
                    SendNewData.Do(() =>
                    {
                        var dest        = TestRemoteDest.MyDestination;
                        var origmessage = new DeliveryStatusMessage(I2NPHeader.GenerateMessageId());
                        var big         = BufUtils.RandomInt(100) < 5;

                        Destinations.Send(dest, true,
                                          new GarlicCloveDeliveryDestination(
                                              origmessage, dest.IdentHash),
                                          (big ?
                                           new GarlicCloveDeliveryDestination(BigMessage, dest.IdentHash) :
                                           new GarlicCloveDeliveryDestination(origmessage, dest.IdentHash)));
                    });
                }
                catch (Exception ex)
                {
                    SendNewData.Reset();
                    DebugUtils.Log(ex);
                }
            }

            QueueStatusLog.Do(() =>
            {
                DebugUtils.LogInformation(string.Format(
                                              "ClientTunnelProvider {4}: Established tunnels in: {0,2}, out: {1,2}. Pending in: {2,2}, out {3,2}",
                                              InboundEstablishedPool.Count, OutboundEstablishedPool.Count,
                                              InboundPending.Count, OutboundPending.Count, MyDestination.IdentHash.Id32Short));
            });

            Destinations.Run();
        }
コード例 #12
0
        public void ReadAllTest()
        {
            int defaultsectorsize = 300;

            using (Stream dest = new MemoryStream())
            {
                using (Store target = new Store(dest, defaultsectorsize))
                {
                    for (int i = 0; i < 1000; ++i)
                    {
                        target.Write(new byte[] { (byte)BufUtils.RandomInt(240), (byte)(i % 5), (byte)BufUtils.RandomInt(240) });
                    }

                    var allofit = target.ReadAll();

                    Assert.IsTrue(allofit.Count == 1000);
                    for (int i = 0; i < 1000; ++i)
                    {
                        Assert.IsTrue(allofit[i].Value[1] == (i % 5));
                    }
                }
            }
        }
コード例 #13
0
        public void MakeAndReadFragments100()
        {
            var origmsgs = new List <TunnelMessage>();

            for (int i = 0; i < 100; ++i)
            {
                switch (BufUtils.RandomInt(3))
                {
                case 0:
                    var adatarec = new DataMessage(new BufLen(BufUtils.RandomBytes(2048)));

                    origmsgs.Add(new TunnelMessageTunnel(
                                     adatarec,
                                     new I2PIdentHash(true),
                                     BufUtils.RandomUint()));
                    break;

                case 1:
                    var arec = new DatabaseLookupMessage(
                        new I2PIdentHash(true),
                        new I2PIdentHash(true),
                        DatabaseLookupMessage.LookupTypes.Normal);

                    origmsgs.Add(new TunnelMessageRouter(
                                     arec,
                                     new I2PIdentHash(true)));
                    break;

                case 2:
                    var adatarec2 = new DataMessage(
                        new BufLen(
                            BufUtils.RandomBytes(2048 + BufUtils.RandomInt(1024))));

                    origmsgs.Add(new TunnelMessageLocal(adatarec2));
                    break;
                }
            }

            var msgs   = TunnelDataMessage.MakeFragments(origmsgs, BufUtils.RandomUint());
            var mkmsg  = new TunnelDataFragmentReassembly();
            var chunks = msgs
                         .Shuffle()
                         .ToArray()
                         .Chunk(a => 1 + BufUtils.RandomInt(10))
                         .Shuffle();

            var recvtmsgs = chunks.SelectMany(c => mkmsg.Process(c, out var _)).ToArray();

            Assert.IsTrue(origmsgs.All(o => recvtmsgs.Any(m =>
                                                          m.Delivery == o.Delivery &&
                                                          m.Message.CreateHeader16.HeaderAndPayload == o.Message.CreateHeader16.HeaderAndPayload
                                                          )));

            var mkmsg2  = new TunnelDataFragmentReassembly();
            var chunks2 = msgs
                          .Shuffle()
                          .ToArray()
                          .Skip(1)
                          .Chunk(a => 1 + BufUtils.RandomInt(10))
                          .Shuffle();

            var recvtmsgs2 = chunks2.SelectMany(c => mkmsg2.Process(c, out var _)).ToArray();

            Assert.IsFalse(origmsgs.All(o => recvtmsgs2.Any(m =>
                                                            m.Delivery == o.Delivery &&
                                                            m.Message.CreateHeader16.HeaderAndPayload == o.Message.CreateHeader16.HeaderAndPayload
                                                            )));
        }
コード例 #14
0
ファイル: SSUState.cs プロジェクト: itfenom/i2p-cs
 bool RandomExtraPadding(BufLen start, BufRefLen writer)
 {
     writer.Write(BufUtils.RandomBytes(BufUtils.RandomInt(16)));
     return(true);
 }
コード例 #15
0
        public void IndexStreamTest1()
        {
            var data1 = new byte[10000];

            data1.Randomize();
            //for ( int i = 0; i < data1.Length; ++i ) data1[i] = (byte)( i & 0xff );

            var data2 = new byte[1000];

            data2.Randomize();

            var data3 = new byte[20000];

            data3.Randomize();

            var filename = Path.GetFullPath(Path.GetTempFileName());

            int defaultsectorsize = 17;

            while (defaultsectorsize < 32000)
            {
                using (Store target = new Store(filename, defaultsectorsize))
                {
                    var ixstream = target.IndexStream();
                    using (var innerstore = new Store(ixstream, defaultsectorsize * 2 + BufUtils.RandomInt(12)))
                    {
                        var ix = innerstore.Write(data1);
                        Assert.AreEqual(data1.Length, innerstore.GetDataLength(ix));
                        var copy = innerstore.Read(ix);
                        Assert.IsTrue(BufUtils.Equal(copy, data1));

                        innerstore.Write(data2, ix);
                        Assert.AreEqual(data2.Length, innerstore.GetDataLength(ix));
                        copy = innerstore.Read(ix);
                        Assert.IsTrue(BufUtils.Equal(copy, data2));

                        innerstore.Write(data3, ix);
                        Assert.AreEqual(data3.Length, innerstore.GetDataLength(ix));
                        copy = innerstore.Read(ix);
                        Assert.IsTrue(BufUtils.Equal(copy, data3));
                    }
                }

                defaultsectorsize = (int)(defaultsectorsize * 1.8);
                File.Delete(filename);
            }
        }
コード例 #16
0
        public void IndexStreamTest3()
        {
            const int MaxSectorSize = 32000;

            var data1 = new byte[100000];

            data1.Randomize();
            //for ( int i = 0; i < data1.Length; ++i ) data1[i] = (byte)( i & 0xff );

            var data2 = new byte[1000];

            data2.Randomize();

            var data3 = new byte[200000];

            data3.Randomize();

            int defaultsectorsize = 17;

            while (defaultsectorsize < MaxSectorSize)
            {
                using (Stream dest = new MemoryStream())
                {
                    using (Store mid = new Store(dest, MaxSectorSize - defaultsectorsize + BufUtils.RandomInt(15)))
                    {
                        mid.IndexStream();
                        mid.IndexStream();
                        mid.IndexStream();

                        using (Store target = new Store(mid.IndexStream(), defaultsectorsize))
                        {
                            var firstsector = new byte[target.FirstSectorDataSize];
                            firstsector.Populate <byte>(1);

                            var threesectors = new byte[target.SectorDataSize * 3];
                            threesectors.Populate <byte>(2);

                            var towrite = new BufLen[] { new BufLen(firstsector), new BufLen(threesectors) };

                            var strix = target.Write(towrite);

                            var ixstream = BufUtils.RandomInt(10) > 5 ?
                                           target.IndexStream(strix, true) :
                                           target.IndexStream(strix, target.FirstSectorDataSize + BufUtils.RandomInt(20));
                            using (var innerstore = new Store(ixstream, defaultsectorsize * 2 + BufUtils.RandomInt(12)))
                            {
                                var ix = innerstore.Write(data1);
                                Assert.AreEqual(data1.Length, innerstore.GetDataLength(ix));
                                var copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data1));

                                innerstore.Write(data2, ix);
                                Assert.AreEqual(data2.Length, innerstore.GetDataLength(ix));
                                copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data2));

                                innerstore.Write(data3, ix);
                                Assert.AreEqual(data3.Length, innerstore.GetDataLength(ix));
                                copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data3));
                            }

                            using (var innerstore = new Store(target.IndexStream(), defaultsectorsize * 2 + BufUtils.RandomInt(12)))
                            {
                                var ix = innerstore.Write(data1);
                                Assert.AreEqual(data1.Length, innerstore.GetDataLength(ix));
                                var copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data1));

                                innerstore.Write(data2, ix);
                                Assert.AreEqual(data2.Length, innerstore.GetDataLength(ix));
                                copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data2));

                                innerstore.Write(data3, ix);
                                Assert.AreEqual(data3.Length, innerstore.GetDataLength(ix));
                                copy = innerstore.Read(ix);
                                Assert.IsTrue(BufUtils.Equal(copy, data3));
                            }

                            Assert.IsTrue(BufUtils.Equal(target.Read(strix).Take(firstsector.Length).ToArray(), firstsector));
                        }
                    }
                }

                defaultsectorsize = (int)(defaultsectorsize * 1.8);
            }
        }
コード例 #17
0
ファイル: TransportTest.cs プロジェクト: githubassets/i2p-cs
        public void TestSSUOutOfOrderFragmentation()
        {
            var fragmenter = new DataFragmenter();

            var smalldata        = new BufLen(BufUtils.RandomBytes(4 + BufUtils.RandomInt(4)));
            var smalldatamessage = new DataMessage(smalldata);

            var smalldata1        = new BufLen(BufUtils.RandomBytes(40 + BufUtils.RandomInt(14)));
            var smalldatamessage1 = new DataMessage(smalldata1);

            var smalldata2        = new BufLen(BufUtils.RandomBytes(130 + BufUtils.RandomInt(39)));
            var smalldatamessage2 = new DataMessage(smalldata2);

            var smalldata3        = new BufLen(BufUtils.RandomBytes(770 + BufUtils.RandomInt(220)));
            var smalldatamessage3 = new DataMessage(smalldata3);

            var data        = new BufLen(BufUtils.RandomBytes(30000 + BufUtils.RandomInt(30)));
            var datamessage = new DataMessage(data);

            var data2        = new BufLen(BufUtils.RandomBytes(20000 + BufUtils.RandomInt(1040)));
            var datamessage2 = new DataMessage(data2);

            var dest   = new byte[MTUConfig.BufferSize];
            var start  = new BufLen(dest);
            var writer = new BufRefLen(dest);

            var tosend = new LinkedList <II2NPHeader16>();

            tosend.AddLast(smalldatamessage.CreateHeader16);
            tosend.AddLast(datamessage.CreateHeader16);
            tosend.AddLast(smalldatamessage1.CreateHeader16);
            tosend.AddLast(smalldatamessage2.CreateHeader16);
            tosend.AddLast(smalldatamessage3.CreateHeader16);
            tosend.AddLast(datamessage2.CreateHeader16);

            var tosendshuffle  = tosend.Shuffle();
            var tosendshuffled = new ConcurrentQueue <II2NPHeader16>(tosendshuffle);

            var sent = new LinkedList <II2NPHeader16>();

            foreach (var one in tosend)
            {
                sent.AddLast(one);
            }

            var sentdata = new LinkedList <BufLen>();

            while (true)
            {
                var flagbuf      = writer.ReadBufLen(1);
                var fragcountbuf = writer.ReadBufLen(1);

                var fragments = fragmenter.Send(writer, tosendshuffled);
                if (fragments == 0)
                {
                    break;
                }

                flagbuf[0] |= (byte)SSUDataMessage.DataMessageFlags.WantReply;
                // no ACKs
                fragcountbuf[0] = (byte)fragments;

                sentdata.AddLast(new BufLen(start, 0, writer - start));
                dest   = new byte[MTUConfig.BufferSize];
                start  = new BufLen(dest);
                writer = new BufRefLen(dest);
            }

            var shuffled = sentdata.Shuffle();

            var receivedmessages = new LinkedList <II2NPHeader16>();

            var defragmenter = new DataDefragmenter();

            foreach (var frag in shuffled)
            {
                var datamsg = new SSUDataMessage(new BufRefLen(frag), defragmenter);
                if (datamsg.NewMessages != null)
                {
                    foreach (var msg in datamsg.NewMessages)
                    {
                        var i2npmsg = I2NPMessage.ReadHeader16((BufRefLen)msg.GetPayload());
                        receivedmessages.AddLast(i2npmsg);
                    }
                }
            }

            Assert.IsTrue(receivedmessages.Count == sent.Count);

            foreach (var sentmsg in sent)
            {
                Assert.IsTrue(receivedmessages.SingleOrDefault(m => ((DataMessage)m.Message).Payload ==
                                                               ((DataMessage)sentmsg.Message).Payload) != null);
            }
        }
コード例 #18
0
ファイル: TransportTest.cs プロジェクト: githubassets/i2p-cs
        // This test does not work
        //[Test]
        public void TestSSU()
        {
            //Logging.LogToFile( "TestSSU.log" );

            RouterContext testcontext = new RouterContext(new I2PCertificate(I2PSigningKey.SigningKeyTypes.DSA_SHA1));

            testcontext.DefaultTCPPort = 2048 + BufUtils.RandomInt(5000);
            testcontext.DefaultUDPPort = 2048 + BufUtils.RandomInt(5000);

            var host = new SSUHost(testcontext, new FixedMTU());

            host.AllowConnectToSelf = true;

            host.ConnectionCreated += host_ConnectionCreated;

            // Remote
            var dnsa = Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(a => a.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
            var addr = new I2PRouterAddress(dnsa, testcontext.UDPPort, 6, "SSU");

            addr.Options["key"] = FreenetBase64.Encode(testcontext.IntroKey);

            RouterContext remotetestcontext = new RouterContext(new I2PCertificate(I2PSigningKey.SigningKeyTypes.DSA_SHA1));

            remotetestcontext.DefaultTCPPort = testcontext.DefaultTCPPort + 5;
            remotetestcontext.DefaultUDPPort = testcontext.DefaultUDPPort + 5;

            var remotehost = new SSUHost(remotetestcontext, new FixedMTU());

            remotehost.AllowConnectToSelf = true;
            var client = remotehost.AddSession(addr, testcontext.MyRouterIdentity);

            client.Connect();

            var data = new BufLen(BufUtils.RandomBytes(30000));

            var messagecount = 900; // If the out queue is larger than 1000 msgs we start discarding them

            for (int i = 0; i < messagecount; ++i)
            {
                client.Send(new DataMessage(data));
            }

            System.Threading.Thread.Sleep(10000);

            for (int i = 0; i < messagecount; ++i)
            {
                if (i % 10 == 0)
                {
                    System.Threading.Thread.Sleep(100);
                }
                client.Send(new DataMessage(data));
            }

            var start = new TickCounter();

            while (DataReceived.Count < 2 * messagecount)
            {
                if (start.DeltaToNow.ToMinutes >= 1)
                {
                    Assert.Fail("Failed to receive sent data due to a timeout");
                    break;
                }

                System.Threading.Thread.Sleep(500);
            }

            for (int i = 0; i < 100; ++i)
            {
                Assert.IsTrue(((DataMessage)DataReceived.Random().Message).DataMessagePayload ==
                              new BufLen(data));
            }

            System.Threading.Thread.Sleep(500);

            client.Terminate();

            System.Threading.Thread.Sleep(500);

            host.Terminate();

            System.Threading.Thread.Sleep(500);
        }