public void TestPeerServicesCreation()
        {
            var fakeLogger     = new FakeLogging();
            var socketFactory  = new SocketFactory(fakeLogger, 10);
            var fakeDiscoverer = new FakeDiscoverer();

            using INodeSink fakeNodeSink = new FakeNodeSink(_messageTag, 2003, 10, 40);
            Assert.ThrowsException <ArgumentException>(() => new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, null, fakeDiscoverer, socketFactory, 10, 40));
            Assert.ThrowsException <ArgumentException>(() => new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, null, socketFactory, 10, 40));
            Assert.ThrowsException <ArgumentException>(() => new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, null, 10, 40));
            Assert.ThrowsException <ArgumentException>(() => new PeerServices(_messageTag, _messageTag, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, null, 10, 40));
            IPeerServices peerServices = new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, socketFactory, 10, 40);

            Assert.IsNotNull(peerServices);
            Assert.IsNotNull(peerServices.ProxyingServices);
            Assert.IsNotNull(peerServices.KnownNodes);
            Assert.IsNull(fakeLogger.LastLog);
            Assert.IsNull(peerServices.GetClient("localhost", 80));
            Assert.IsNotNull(fakeLogger.LastLog);
            Assert.ThrowsException <InvalidOperationException>(() => peerServices.CreateListenerFor(fakeNodeSink));
            Assert.ThrowsException <ArgumentException>(() => peerServices.WithCancellationTokenSource(null));
            peerServices.WithCancellationTokenSource(new CancellationTokenSource());
            Assert.IsNotNull(peerServices.Source);
            var client = peerServices.GetClient("localhost", 80);

            Assert.IsNotNull(client);
        }
        public void TestPeerServicesDisposal()
        {
            var fakeLogger     = new FakeLogging();
            var socketFactory  = new SocketFactory(fakeLogger, 10);
            var fakeDiscoverer = new FakeDiscoverer();
            var source         = new CancellationTokenSource();

            using IPeerServices peerServices = new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, socketFactory, 10, 40);
            peerServices.WithCancellationTokenSource(source);
            Assert.IsNotNull(peerServices);
            Assert.IsNull(fakeLogger.LastLog);
            INodeSink fakeNodeSink = new FakeNodeSink(_messageTag, 2004, 10, 40);

            peerServices.KnownNodes.Add("nodeToForget", "localhost", 80);
            Assert.IsTrue(peerServices.KnownNodes.IsKnown("nodeToForget"));
            peerServices.Dispose();
            Assert.IsFalse(peerServices.KnownNodes.IsKnown("nodeToForget"));
            var peerListener = peerServices.CreateListenerFor(fakeNodeSink);

            Assert.IsNull(peerListener);
            Assert.IsNull(fakeLogger.LastLog);
            var peerClient = peerServices.GetClient("localhost", 80);

            Assert.IsNull(peerClient);
            Assert.IsNull(fakeLogger.LastLog);
            peerServices.KnownNodes.Add("test2", "localhost", 80);
            Assert.IsFalse(peerServices.KnownNodes.IsKnown("test2"));
            var peerClient2 = peerServices.KnownNodes.GetClient("test2");

            Assert.IsNull(peerClient2);
            Assert.IsNull(fakeLogger.LastLog);
        }
        public void TestListenerForProxyingWithSomeRealSocketsWithBrokenConnections()
        {
            //TODO use event to reinstate proxying
            var fakeLogger       = new FakeLogging();
            var fakeDiscoverer   = new FakeDiscoverer();
            var source           = new CancellationTokenSource();
            var fakeSink         = new TestSink(_tag, 1, 242);
            var externalNodeSink = new ProxyNodeSink(_tag, 6000, fakeLogger, source);
            var internalNodeSink = new FakeNodeSink(_tag, 5000, 10, 40);

            using var referenceListener = new ListenerForPeer(externalNodeSink, fakeDiscoverer, source, fakeLogger);
            using var internalListener  = new ListenerForPeer(internalNodeSink, fakeDiscoverer, source, fakeLogger);
            referenceListener.Start();
            internalListener.Start();
            using var internalConnection = new ConnectionToPeer("RequestProxying", internalNodeSink, referenceListener.ExternalAddress, referenceListener.ExternalPortNumber, source, fakeLogger);
            internalConnection.AllocateChannel(internalNodeSink).SendAsync(ProxyNodeSink.ProxyRequest).Wait();
            int retries = 10;

            while (externalNodeSink.ListenerForProxying == null && retries-- > 0)
            {
                WaitForOthers(100);
            }
            var lfp = externalNodeSink.ListenerForProxying;

            Assert.IsNotNull(lfp, "Should have a ListenerForProxying by now");
            lfp.Start();
            WaitForOthers(300);
            internalConnection.SetDefaultSink(fakeSink);
            using var externalConnection = new ConnectionToPeer("ExternalMessage", internalNodeSink, lfp.ExternalAddress, lfp.ExternalPortNumber, source, fakeLogger);
            externalConnection.AllocateChannel(externalNodeSink); // just to bump channel
            var outsideChannel = externalConnection.AllocateChannel(externalNodeSink);

            outsideChannel.SendAsync(new ReadOnlySequence <byte>(new byte[] { _tag, 1, 2 })).Wait();
            retries = 10;
            while (fakeSink.ChannelProcessed == 0 && retries-- > 0)
            {
                WaitForOthers(100);
            }
            AssertHasSameItems <byte>(nameof(fakeSink.BytesProcessed), fakeSink.BytesProcessed.ToArray(), 2);
            Assert.AreEqual(1ul, fakeSink.ChannelProcessed);
            retries = 10;
            while (externalNodeSink.MessagesReceived.Count == 0 && retries-- > 0)
            {
                WaitForOthers(100);
            }
            AssertHasSameItems <byte>(nameof(externalNodeSink.MessagesReceived), externalNodeSink.MessagesReceived.SelectMany(l => l.ToArray()), 242);
            AssertHasLogLine(fakeLogger, "Debug: Sinked Message 'Ag' from Channel ProxyingClient#1@2 using new pair to Proxied Channel 1. Sent: True");
            AssertHasLogLine(fakeLogger, "Debug: Responded with Message '8g' from Channel ListenerClient#1@1 to External Channel 2. Sent: True");
            lfp.Stop();
            retries = 10;
            while (lfp.Alive && retries-- > 0)
            {
                WaitForOthers(100);
            }
            WaitForOthers(300);
            Assert.IsTrue(referenceListener.Alive, "External listener should stay alive after lfp having stopped");
        }
        public void TestListenerForProxyingMinimally()
        {
            var fakeLogger = new FakeLogging();

            using var fakeDiscoverer = new FakeDiscoverer();
            var source             = new CancellationTokenSource();
            var fakeExternalSocket = new TestSocket(holdYourHorses: true, _tag, 1, 240, 128);
            var fakeInternalSocket = new TestSocket(holdYourHorses: true, _tag, 1, 241, 1);
            var fakeSink           = new TestSink(_tag, 1, 242);
            var fakeNodeSink       = new FakeNodeSink(_tag, 2000, 10, 40);

            using var referenceListener = new ListenerForPeer(fakeNodeSink, fakeDiscoverer, source, fakeLogger);
            var internalConnection = new ConnectionInitiatedByPeer("TLFPM", fakeNodeSink, fakeInternalSocket, fakeSink, source, fakeLogger);

            internalConnection.SetDefaultSink(fakeNodeSink);
            using var lfp = new TestListenerForProxying(fakeExternalSocket, referenceListener.ExternalAddress, referenceListener.ExternalAddress, 333, internalConnection, new SocketFactory(fakeLogger, 3), source, fakeLogger);
            lfp.Start();
            WaitForOthers(100);
            fakeExternalSocket.ReleaseYourHorses();
            var max = 5;

            while (AllBytes(fakeInternalSocket).Length < 4 && max-- > 0)
            {
                WaitForOthers(100);
            }
            var allInternalBytes = AllBytes(fakeInternalSocket);

            Assert.IsNotNull(fakeLogger.LastLog);
            AssertHasSameItems <byte>(nameof(fakeInternalSocket.BytesSent), allInternalBytes.ToArray(), _tag, 1, 240, 1);
            WaitForOthers(100);
            fakeInternalSocket.ReleaseYourHorses();
            max = 7;
            while (AllBytes(fakeExternalSocket).Length < 4 && max-- > 0)
            {
                WaitForOthers(100);
            }
            AssertHasSameItems <byte>(nameof(fakeExternalSocket.BytesSent), AllBytes(fakeExternalSocket).ToArray(), _tag, 1, 241, 128);
            fakeSink.Reset();
            long lastIndex = allInternalBytes.Length - 1;

            fakeSink.SinkAsync(allInternalBytes.Slice(0, lastIndex), new TestChannel(allInternalBytes.Slice(lastIndex).First.Span[0])).Wait();
            max = 12;
            while (fakeSink.ChannelProcessed == 0ul && max-- > 0)
            {
                WaitForOthers(100);
            }
            WaitForOthers(300);
            AssertHasSameItems <byte>(nameof(fakeSink.BytesProcessed), fakeSink.BytesProcessed.ToArray(), _tag, 1, 240);
            Assert.AreEqual((ulong)1, fakeSink.ChannelProcessed);
            AssertHasLogLine(fakeLogger, "Debug: Sinked Message '8A' from Channel ProxyingClient#1@128 using new pair to Proxied Channel 1. Sent: True");
            AssertHasLogLine(fakeLogger, "Debug: Responded with Message '8Q' from Channel TLFPM@1 to External Channel 128. Sent: True");
        }
        public void TestPeerListenerCreation()
        {
            var fakeLogger     = new FakeLogging();
            var socketFactory  = new SocketFactory(fakeLogger, 10);
            var fakeDiscoverer = new FakeDiscoverer();
            var source         = new CancellationTokenSource();

            using IPeerServices peerServices = new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, socketFactory, 10, 40);
            peerServices.WithCancellationTokenSource(source);
            Assert.IsNotNull(peerServices);
            Assert.IsNull(fakeLogger.LastLog);
            INodeSink fakeNodeSink = new FakeNodeSink(_messageTag, 2002, 10, 40);

            using var peerListener = peerServices.CreateListenerFor(fakeNodeSink);
            Assert.IsNotNull(peerListener);
            Assert.IsNull(fakeLogger.LastLog);
        }
        public void TestProxyListenerCreation()
        {
            var fakeLogger     = new FakeLogging();
            var socketFactory  = new SocketFactory(fakeLogger, 10);
            var fakeDiscoverer = new FakeDiscoverer();
            var source         = new CancellationTokenSource();

            using IPeerServices peerServices = new PeerServices(_messageTag, 0, "UnitTest", "unit", 4096, fakeLogger, fakeDiscoverer, socketFactory, 10, 40);
            peerServices.WithCancellationTokenSource(source);
            Assert.IsNotNull(peerServices);
            Assert.IsNull(fakeLogger.LastLog);
            INodeSink   fakeNodeSink = new FakeNodeSink(_messageTag, 8002, 10, 40);
            IConnection connection   = new ConnectionToPeer("Test", fakeNodeSink, "localhost", 8003, source, fakeLogger);

            using var peerListener = peerServices.ProxyingServices.CreateListenerForProxying("rafael.interlockledger.network", "localhost", 9000, connection);
            Assert.IsNotNull(peerListener);
            Assert.IsNull(fakeLogger.LastLog);
            Assert.AreEqual("rafael.interlockledger.network", peerListener.ExternalAddress);
        }