Пример #1
0
        public static void SubtestTransport(ITransport ta, ITransport tb, string addr)
        {
            var maddr = Multiaddress.Decode(addr);

            Assert.That(maddr, Is.Not.Null);

            var listener = ta.Listen(maddr);

            Assert.That(listener, Is.Not.Null);

            var dialer = tb.Dialer(maddr);

            Assert.That(dialer, Is.Not.Null);

            var accepted = listener.AcceptAsync(CancellationToken.None);
            var dialed   = dialer.DialAsync(listener.Multiaddress, CancellationToken.None);

            Task.WaitAll(accepted, dialed);

            var a = accepted.Result;
            var b = dialed.Result;

            try
            {
                Assert.DoesNotThrow(() => CheckDataTransfer(a, b));
            }
            finally
            {
                a.Dispose();
                b.Dispose();
            }
        }
Пример #2
0
        public void TestStringToBytes(string s, string h)
        {
            var b1 = Hex.Decode(h);
            var b2 = Multiaddress.Decode(s).ToBytes();

            Assert.Equal(b1, b2);
        }
Пример #3
0
        public void TestBytesToString(string s1, string h)
        {
            var b  = Hex.Decode(h);
            var s2 = Multiaddress.Decode(s1).ToString();

            Assert.Equal(s1, s2);
        }
Пример #4
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="address"></param>
        /// <param name="key"></param>
        /// <param name="collections"></param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <ThreadId> NewDbFromAdd(string address, string key, IList <Models.CollectionInfo> collections, CancellationToken cancellationToken = default)
        {
            Multiaddress addr = Multiaddress.Decode(address);

            byte[] keyBytes = ThreadKey.FromString(key).Bytes;

            NewDBFromAddrRequest request = new()
            {
                Addr = ByteString.CopyFrom(addr.ToBytes()),
                Key  = ByteString.CopyFrom(keyBytes)
            };

            if (collections != null)
            {
                //TODO: Finish mapping
                request.Collections.AddRange(collections.Select(c =>
                {
                    return(_mapper.Map <Grpc.CollectionConfig>(c));
                }).ToArray());
            }

            await _apiClient.NewDBFromAddrAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

            //TODO: Get the threadID and Address
            string threadId = string.Empty;

            return(ThreadId.FromString(threadId));
        }
Пример #5
0
        public SocketListener(Multiaddress localAddress, bool reusePort)
        {
            _reusePort = reusePort;
            SocketType   st;
            ProtocolType pt;

            EndPoint addr;

            if (localAddress != null)
            {
                addr = localAddress.ToEndPoint(out pt, out st);
            }
            else
            {
                st   = SocketType.Stream;
                pt   = ProtocolType.Tcp;
                addr = new IPEndPoint(IPAddress.Loopback, 0);
            }

            _socket = new Socket(addr.AddressFamily, st, pt);
            if (reusePort)
            {
                _socket.ExclusiveAddressUse = false;
                _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            }
            _socket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
            _socket.Bind(addr);
            _socket.Listen(512);

            Address      = _socket.LocalEndPoint;
            Multiaddress = _socket.GetLocalMultiaddress();
        }
Пример #6
0
        private void ConsumeObservedAddress(byte[] observed, INetworkConnection connection)
        {
            if (observed == null)
            {
                return;
            }

            var maddr = Multiaddress.Decode(observed);

            if (maddr == null)
            {
                return;
            }

            var ifaceaddrs = Host.Network.InterfaceListenAddresses;

            if (ifaceaddrs == null)
            {
                return;
            }

            if (!ifaceaddrs.Contains(connection.LocalMultiaddress))
            {
                return;
            }

            _observedAddresses.Add(maddr, connection.RemoteMultiaddress);
        }
Пример #7
0
        public static Task <Socket> CreateConnectionAsync(this Multiaddress ma)
        {
            IPEndPoint ep;
            var        socket = CreateSocket(ma, out ep);

#if NETSTANDARD1_6
            return(socket.ConnectAsync(ep)
                   .ContinueWith(_ => socket));
#else
            var tcs = new TaskCompletionSource <Socket>();

            try
            {
                socket.BeginConnect(ep, ar =>
                {
                    try
                    {
                        socket.EndConnect(ar);
                        tcs.TrySetResult(socket);
                    }
                    catch (Exception e)
                    {
                        tcs.TrySetException(e);
                    }
                }, null);
            }
            catch (Exception e)
            {
                tcs.TrySetException(e);
            }

            return(tcs.Task);
#endif
        }
Пример #8
0
        public static Multiaddress ToMultiaddress(this EndPoint ep, ProtocolType protocolType)
        {
            var ma = new Multiaddress();

            var ip = (IPEndPoint)ep;

            if (ip != null)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    ma.Add <IP4>(ip.Address);
                }
                if (ip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    ma.Add <IP6>(ip.Address);
                }

                if (protocolType == ProtocolType.Tcp)
                {
                    ma.Add <TCP>((ushort)ip.Port);
                }
                if (protocolType == ProtocolType.Udp)
                {
                    ma.Add <UDP>((ushort)ip.Port);
                }
            }

            return(ma);
        }
Пример #9
0
 public SocketDialer(Multiaddress localAddress, TimeSpan?timeout, bool reusePort)
 {
     _timeout          = timeout;
     _reusePort        = reusePort;
     LocalAddress      = localAddress?.ToEndPoint();
     LocalMultiaddress = localAddress;
 }
Пример #10
0
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }

            var token = JToken.Load(reader);

            switch (token.Type)
            {
            case JTokenType.Null:
                return(null);

            case JTokenType.String:
                return(Multiaddress.Decode((string)token));

            case JTokenType.Bytes:
                return(Multiaddress.Decode((byte[])token));

            case JTokenType.Object:
                var value = (string)token["$value"];
                return(value == null ? null : Multiaddress.Decode(value));

            default:
                throw new SerializationException("Unknown Multiaddress format");
            }
        }
Пример #11
0
        public IConnection Dial(Multiaddress remoteAddress)
        {
            ProtocolType p;
            SocketType   s;
            var          ip = remoteAddress.ToEndPoint(out p, out s);

            return(Dial(ip, s, p));
        }
Пример #12
0
        public Task <IConnection> DialAsync(Multiaddress remoteAddress, CancellationToken cancellationToken)
        {
            ProtocolType p;
            SocketType   s;
            var          ip = remoteAddress.ToEndPoint(out p, out s);

            return(DialAsync(ip, s, p, cancellationToken));
        }
Пример #13
0
        public static Socket CreateConnection(this Multiaddress ma)
        {
            IPEndPoint ep;
            var        socket = CreateSocket(ma, out ep);

            socket.Connect(ep);
            return(socket);
        }
Пример #14
0
        public static Socket CreateListener(this Multiaddress ma, int backlog = 10)
        {
            IPEndPoint ep;
            var        socket = CreateSocket(ma, out ep);

            socket.Bind(ep);
            socket.Listen(backlog);
            return(socket);
        }
Пример #15
0
        public static Socket CreateSocket(this Multiaddress ma, out IPEndPoint ep)
        {
            ProtocolType pt;
            SocketType   st;

            ep = ma.ToEndPoint(out pt, out st);

            return(new Socket(ep.AddressFamily, st, pt));
        }
Пример #16
0
        public void TestTcpTransportCantListenUtp()
        {
            var utpa = Multiaddress.Decode("/ip4/127.0.0.1/udp/0/utp");

            Assert.That(utpa, Is.Not.Null);

            var tpt = new TcpTransport();

            Assert.Throws <NotSupportedException>(() => tpt.Listen(utpa));
        }
Пример #17
0
        public void Multiaddress_GivenIPv6Udp_ReturnsValidEndPoint()
        {
            var          ma = Multiaddress.Decode("/ip6/::1/udp/1337");
            ProtocolType p;
            var          ep = ma.ToEndPoint(out p);

            Assert.Equal(AddressFamily.InterNetworkV6, ep.AddressFamily);
            Assert.Equal(IPAddress.IPv6Loopback, ep.Address);
            Assert.Equal(1337, ep.Port);
            Assert.Equal(ProtocolType.Udp, p);
        }
Пример #18
0
        public void Socket_GivenMultiaddress_CreatesSocket()
        {
            var ma = Multiaddress.Decode("/ip4/127.0.0.1/tcp/1337");

            using (var socket = ma.CreateSocket())
            {
                Assert.Equal(AddressFamily.InterNetwork, socket.AddressFamily);
                Assert.Equal(ProtocolType.Tcp, socket.ProtocolType);
                Assert.Equal(SocketType.Stream, socket.SocketType);
            }
        }
        public static bool IsIPLoopback(this Multiaddress ma)
        {
            var ep = ma.ToEndPoint();

            if (ep == null)
            {
                return(false);
            }

            return(ep.Address.Equals(IPAddress.Loopback) || ep.Address.Equals(IPAddress.IPv6Loopback));
        }
Пример #20
0
        public void Multiaddress_GivenIPv4Tcp_ReturnsValidEndPoint()
        {
            var          ma = Multiaddress.Decode("/ip4/127.0.0.1/tcp/1337");
            ProtocolType p;
            var          ep = ma.ToEndPoint(out p);

            Assert.Equal(AddressFamily.InterNetwork, ep.AddressFamily);
            Assert.Equal(IPAddress.Loopback, ep.Address);
            Assert.Equal(1337, ep.Port);
            Assert.Equal(ProtocolType.Tcp, p);
        }
Пример #21
0
        public static IEnumerable <Multiaddress> Match(this Multiaddress match, params Multiaddress[] addrs)
        {
            foreach (var a in addrs.Where(x => match.Protocols.Count == x.Protocols.Count))
            {
                var i = 0;

                if (a.Protocols.All(p2 => match.Protocols[i++].Code == p2.Code))
                {
                    yield return(a);
                }
            }
        }
Пример #22
0
        public TcpDialer(TcpTransport t, Multiaddress laddr, TimeSpan?timeout, bool reusePort)
        {
            var la = laddr.ToEndPoint();

            if (la == null)
            {
                throw new Exception("Invalid address");
            }

            _transport = t;
            _dialer    = new SocketDialer(laddr, timeout, reusePort);
        }
Пример #23
0
        public ITransportDialer Dialer(Multiaddress laddr, TimeSpan?timeout = null, bool reusePort = true)
        {
            ITransportDialer d;

            if (_dialers.TryGetValue(laddr.ToString(), out d))
            {
                return(d);
            }

            d = CreateDialer(laddr, timeout, reusePort);
            _dialers.TryAdd(laddr.ToString(), d);
            return(d);
        }
Пример #24
0
        public static Multiaddress ToMultiaddress(this IPAddress ip)
        {
            var ma = new Multiaddress();

            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                ma.Add <IP4>(ip);
            }
            if (ip.AddressFamily == AddressFamily.InterNetworkV6)
            {
                ma.Add <IP6>(ip);
            }
            return(ma);
        }
Пример #25
0
        public void TestEqual()
        {
            var m1 = Multiaddress.Decode("/ip4/127.0.0.1/udp/1234");
            var m2 = Multiaddress.Decode("/ip4/127.0.0.1/tcp/1234");
            var m3 = Multiaddress.Decode("/ip4/127.0.0.1/tcp/1234");
            var m4 = Multiaddress.Decode("/ip4/127.0.0.1/tcp/1234");

            Assert.NotEqual(m1, m2);
            Assert.NotEqual(m2, m1);
            Assert.Equal(m2, m3);
            Assert.Equal(m3, m2);
            Assert.Equal(m1, m1);
            Assert.Equal(m2, m4);
            Assert.Equal(m4, m3);
        }
Пример #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="dbId">The ID of the database.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
        /// <returns></returns>
        public async Task <DBInfo> GetDbInfoAsync(ThreadId dbId, CancellationToken cancellationToken = default)
        {
            GetDBInfoRequest request = new()
            {
                DbID = ByteString.CopyFrom(dbId.Bytes)
            };

            GetDBInfoReply dbInfo = await _apiClient.GetDBInfoAsync(request, headers : _threadContext.Metadata, cancellationToken : cancellationToken);

            return(new DBInfo()
            {
                Key = ThreadKey.FromBytes(dbInfo.Key.ToByteArray()).ToString(),
                Addrs = dbInfo.Addrs.Select(addr => Multiaddress.Decode(addr.ToByteArray()).ToString()).ToList()
            });
        }
Пример #27
0
        public void TestGetValue()
        {
            var a =
                Multiaddress.Decode(
                    "/ip4/127.0.0.1/utp/tcp/5555/udp/1234/utp/ipfs/QmbHVEEepCi7rn7VL7Exxpd2Ci9NNB6ifvqwhsrbRMgQFP");

            Assert.Equal("127.0.0.1", a.Protocols.OfType <IP4>().FirstOrDefault()?.ToString());
            Assert.Equal("", a.Protocols.OfType <UTP>().FirstOrDefault()?.ToString());
            Assert.Equal("5555", a.Protocols.OfType <TCP>().FirstOrDefault()?.ToString());
            Assert.Equal("1234", a.Protocols.OfType <UDP>().FirstOrDefault()?.ToString());
            Assert.Equal("QmbHVEEepCi7rn7VL7Exxpd2Ci9NNB6ifvqwhsrbRMgQFP", a.Protocols.OfType <IPFS>().FirstOrDefault()?.ToString());

            a = Multiaddress.Decode("/ip4/0.0.0.0/unix/a/b/c/d");
            Assert.Equal("0.0.0.0", a.Protocols.OfType <IP4>().FirstOrDefault()?.ToString());
            Assert.Equal("a/b/c/d", a.Protocols.OfType <Unix>().FirstOrDefault()?.ToString());
        }
Пример #28
0
        public void TestBytesSplitAndJoin(string s, params string[] res)
        {
            var m     = Multiaddress.Decode(s);
            var split = m.Split().ToArray();

            Assert.Equal(split.Length, res.Length);

            for (var i = 0; i < split.Length; i++)
            {
                Assert.Equal(split[i].ToString(), res[i]);
            }

            var joined = Multiaddress.Join(split);

            Assert.Equal(m, joined);
        }
Пример #29
0
        public static IPEndPoint ToEndPoint(this Multiaddress ma, out ProtocolType protocolType, out SocketType socketType)
        {
            IPAddress addr = null;
            IP        ip   = ma.Protocols.OfType <IP4>().SingleOrDefault();

            if (ip != null)
            {
                addr = (IPAddress)ip.Value;
            }
            else
            {
                ip = ma.Protocols.OfType <IP6>().SingleOrDefault();
                if (ip != null)
                {
                    addr = (IPAddress)ip.Value;
                }
            }

            int?   port = null;
            Number n    = ma.Protocols.OfType <TCP>().SingleOrDefault();

            if (n != null)
            {
                port         = (ushort)n.Value;
                protocolType = ProtocolType.Tcp;
                socketType   = SocketType.Stream;
            }
            else
            {
                n = ma.Protocols.OfType <UDP>().SingleOrDefault();
                if (n != null)
                {
                    port         = (ushort)n.Value;
                    protocolType = ProtocolType.Udp;
                    socketType   = SocketType.Dgram;
                }
                else
                {
                    protocolType = ProtocolType.Unknown;
                    socketType   = SocketType.Unknown;
                }
            }

            return(new IPEndPoint(addr ?? IPAddress.Any, port ?? 0));
        }
Пример #30
0
        public ITransportListener Listen(Multiaddress laddr)
        {
            if (!Matches(laddr))
            {
                throw new NotSupportedException($"Tcp transport cannot listen on {laddr}");
            }

            ITransportListener l;

            if (_listeners.TryGetValue(laddr.ToString(), out l))
            {
                return(l);
            }

            l = CreateListener(laddr);
            _listeners.TryAdd(laddr.ToString(), l);
            return(l);
        }