public void Bad_Port() { var tcp = new MultiAddress("/tcp/65535"); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/tcp/x")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/tcp/65536")); var udp = new MultiAddress("/udp/65535"); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/upd/x")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/udp/65536")); }
public void Bad_IPAddress() { var ipv4 = new MultiAddress("/ip4/127.0.0.1"); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip4/x")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip4/127.")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip4/::1")); var ipv6 = new MultiAddress("/ip6/::1"); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip6/x")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip6/03:")); ExceptionAssert.Throws<FormatException>(() => new MultiAddress("/ip6/127.0.0.1")); }
public async Task <MultiAddress> RemoveAddressFilterAsync(MultiAddress address, bool persist = false, CancellationToken cancel = default(CancellationToken)) { // go-ipfs always does persist, https://github.com/ipfs/go-ipfs/issues/4605 var json = await ipfs.DoCommandAsync("swarm/filters/rm", cancel, address.ToString()); var addrs = (JArray)(JObject.Parse(json)["Strings"]); var a = addrs.FirstOrDefault(); if (a == null) { return(null); } return(new MultiAddress((string)a)); }
public async Task Read_From_OtherNode() { using (var a = new TempNode()) using (var b = new TempNode()) using (var c = new TempNode()) { var psk = new PeerTalk.Cryptography.PreSharedKey().Generate(); // Start bootstrap node. b.Options.Discovery.DisableMdns = true; b.Options.Swarm.MinConnections = 0; b.Options.Swarm.PrivateNetworkKey = psk; b.Options.Discovery.BootstrapPeers = new MultiAddress[0]; await b.StartAsync(); var bootstrapPeers = new MultiAddress[] { (await b.LocalPeer).Addresses.First() }; Console.WriteLine($"B is {await b.LocalPeer}"); // Node that has the content. c.Options.Discovery.DisableMdns = true; c.Options.Swarm.MinConnections = 0; c.Options.Swarm.PrivateNetworkKey = psk; c.Options.Discovery.BootstrapPeers = bootstrapPeers; await c.StartAsync(); await c.Swarm.ConnectAsync(bootstrapPeers[0]); Console.WriteLine($"C is {await c.LocalPeer}"); var fsn = await c.FileSystem.AddTextAsync("some content"); var cid = fsn.Id; // Node that reads the content. a.Options.Discovery.DisableMdns = true; a.Options.Swarm.MinConnections = 0; a.Options.Swarm.PrivateNetworkKey = psk; a.Options.Discovery.BootstrapPeers = bootstrapPeers; await a.StartAsync(); Console.WriteLine($"A is {await a.LocalPeer}"); var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); var content = await a.FileSystem.ReadAllTextAsync(cid, cts.Token); Assert.AreEqual("some content", content); } }
public async Task Listening_IPv6Any() { var peerA = new Peer { Id = _self.Id, PublicKey = _self.PublicKey, AgentVersion = _self.AgentVersion }; MultiAddress addr = "/ip6/::/tcp/0"; var swarmA = new SwarmService { LocalPeer = peerA }; var peerB = new Peer { Id = _other.Id, PublicKey = _other.PublicKey, AgentVersion = _other.AgentVersion }; var swarmB = new SwarmService { LocalPeer = peerB }; await swarmA.StartAsync(); await swarmB.StartAsync(); try { var another = await swarmA.StartListeningAsync(addr); Assert.IsFalse(peerA.Addresses.Contains(addr)); Assert.IsTrue(peerA.Addresses.Contains(another)); await swarmB.ConnectAsync(another); Assert.IsTrue(swarmB.KnownPeers.Contains(peerA)); // TODO: Assert.IsTrue(swarmA.KnownPeers.Contains(peerB)); await swarmA.StopListeningAsync(addr); Assert.AreEqual(0, peerA.Addresses.Count()); } finally { await swarmA.StopAsync(); await swarmB.StopAsync(); } }
public void JsonSerialization() { var a = new MultiAddress("/ip6/fe80::7573:b0a8:46b0:0bad/tcp/4009"); var json = JsonConvert.SerializeObject(a); Assert.Equal($"\"{a}\"", json); var b = JsonConvert.DeserializeObject <MultiAddress>(json); Assert.Equal(a.ToString(), b.ToString()); a = null; json = JsonConvert.SerializeObject(a); b = JsonConvert.DeserializeObject <MultiAddress>(json); Assert.Null(b); }
public void Parsing() { var a = new MultiAddress(somewhere); Assert.AreEqual(3, a.Protocols.Count); Assert.AreEqual("ip4", a.Protocols[0].Name); Assert.AreEqual("10.1.10.10", a.Protocols[0].Value); Assert.AreEqual("tcp", a.Protocols[1].Name); Assert.AreEqual("29087", a.Protocols[1].Value); Assert.AreEqual("ipfs", a.Protocols[2].Name); Assert.AreEqual("QmVcSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC", a.Protocols[2].Value); ExceptionAssert.Throws<ArgumentNullException>(() => new MultiAddress((string)null)); ExceptionAssert.Throws<ArgumentNullException>(() => new MultiAddress("")); ExceptionAssert.Throws<ArgumentNullException>(() => new MultiAddress(" ")); }
public async Task <MultiAddress> RemoveAsync(MultiAddress address, CancellationToken cancel = default(CancellationToken)) { var addrs = (await ListAsync(cancel)).ToList(); if (!addrs.Any(a => a == address)) { return(address); } addrs.Remove(address); var strings = addrs.Select(a => a.ToString()); await ipfs.Config.SetAsync("Bootstrap", JToken.FromObject(strings), cancel); return(address); }
public async Task RemotePeer_Contains_ConnectedAddress2() { // Only works on Windows because connecting to 127.0.0.100 is allowed // when listening on 0.0.0.0 if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return; } var peerB = new Peer { AgentVersion = "peerB", Id = "QmdpwjdB94eNm2Lcvp9JqoCxswo3AKQqjLuNZyLixmCM1h", PublicKey = "CAASXjBcMA0GCSqGSIb3DQEBAQUAA0sAMEgCQQDlTSgVLprWaXfmxDr92DJE1FP0wOexhulPqXSTsNh5ot6j+UiuMgwb0shSPKzLx9AuTolCGhnwpTBYHVhFoBErAgMBAAE=" }; var swarmB = new SwarmService { LocalPeer = peerB }; await swarmB.StartAsync(); var peerBAddress = await swarmB.StartListeningAsync("/ip4/0.0.0.0/tcp/0"); var peerBPort = peerBAddress.Protocols[1].Value; Assert.IsTrue(peerB.Addresses.Any()); var swarm = new SwarmService { LocalPeer = _self }; await swarm.StartAsync(); try { MultiAddress ma = $"/ip4/127.0.0.100/tcp/{peerBPort}/ipfs/{peerB.Id}"; var connection = await swarm.ConnectAsync(ma); var remote = connection.RemotePeer; Assert.AreEqual(remote.ConnectedAddress, ma); CollectionAssert.Contains(remote.Addresses.ToArray(), ma); } finally { await swarm.StopAsync(); await swarmB.StopAsync(); } }
/// <inheritdoc /> public async Task <Stream> ConnectAsync(MultiAddress address, CancellationToken cancel = default) { var port = address.Protocols .Where(p => p.Name == "udp") .Select(p => int.Parse(p.Value)) .First(); var ip = address.Protocols .Where(p => p.Name == "ip4" || p.Name == "ip6") .First(); var socket = new Socket( ip.Name == "ip4" ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp); // Handle cancellation of the connect attempt cancel.Register(() => { socket.Dispose(); socket = null; }); try { _log.Debug("connecting to " + address); await socket.ConnectAsync(ip.Value, port).ConfigureAwait(false); _log.Debug("connected " + address); } catch (Exception) when(cancel.IsCancellationRequested) { // eat it, the caller has cancelled and doesn't care. } catch (Exception e) { _log.Warn("failed " + address, e); throw; } if (cancel.IsCancellationRequested) { _log.Debug("cancel " + address); socket?.Dispose(); cancel.ThrowIfCancellationRequested(); } return(new DatagramStream(socket, true)); }
public async Task Resolving() { var local = new MultiAddress("/ip4/127.0.0.1/tcp/5001"); var r0 = await local.ResolveAsync(); Assert.AreEqual(1, r0.Count); Assert.AreEqual(local, r0[0]); var dns = await new MultiAddress("/dns/libp2p.io/tcp/5001").ResolveAsync(); Assert.AreNotEqual(0, dns.Count); var dns4 = await new MultiAddress("/dns4/libp2p.io/tcp/5001").ResolveAsync(); var dns6 = await new MultiAddress("/dns6/libp2p.io/tcp/5001").ResolveAsync(); Assert.AreEqual(dns.Count, dns4.Count + dns6.Count); }
public void Connect_Cancelled() { var cs = new CancellationTokenSource(); cs.Cancel(); var remoteId = "QmXFX2P5ammdmXQgfqGkfswtEVFsZUJ5KeHRXQYCTdiTAb"; MultiAddress remoteAddress = $"/ip4/127.0.0.1/tcp/4002/ipfs/{remoteId}"; var swarm = new Swarm { LocalPeer = self }; ExceptionAssert.Throws <Exception>(() => { var _ = swarm.ConnectAsync(remoteAddress, cs.Token).Result; }); }
public void Parsing() { var a = new MultiAddress(somewhere); Assert.Equal(3, a.Protocols.Count); Assert.Equal("ip4", a.Protocols[0].Name); Assert.Equal("10.1.10.10", a.Protocols[0].Value); Assert.Equal("tcp", a.Protocols[1].Name); Assert.Equal("29087", a.Protocols[1].Value); Assert.Equal("ipfs", a.Protocols[2].Name); Assert.Equal("QmVcSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC", a.Protocols[2].Value); Assert.Equal(0, new MultiAddress((string)null).Protocols.Count); Assert.Equal(0, new MultiAddress("").Protocols.Count); Assert.Equal(0, new MultiAddress(" ").Protocols.Count); }
public void PeerID_ipfs_p2p_are_equal() { var ipfs = new MultiAddress( "/ip4/10.1.10.10/tcp/29087/ipfs/QmVcSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC"); var p2p = new MultiAddress("/ip4/10.1.10.10/tcp/29087/p2p/QmVcSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC"); Assert.Equal(ipfs, p2p); var p2p1 = new MultiAddress("/ip4/10.1.10.10/tcp/29087/p2p/QmVCSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC"); Assert.NotEqual(p2p, p2p1); var p2p2 = new MultiAddress("/p2p/QmVcSqVEsvm5RR9mBLjwpb2XjFVn5bPdPL69mL8PH45pPC"); Assert.NotEqual(p2p, p2p2); }
public async Task <MultiAddress> RemoveAsync(MultiAddress address, CancellationToken cancel = default) { var addrs = (await ListAsync(cancel).ConfigureAwait(false)).ToList(); if (addrs.All(a => a != address)) { return(address); } addrs.Remove(address); var strings = addrs.Select(a => a.ToString()); await _configApi.SetAsync("Bootstrap", JToken.FromObject(strings), cancel).ConfigureAwait(false); return(address); }
public void Collection() { MultiAddress a = "/ip4/127.0.0.1"; MultiAddress b = "/ip4/127.0.0.2"; var policy = new MultiAddressBlackList(); Assert.IsFalse(policy.IsReadOnly); Assert.AreEqual(0, policy.Count); Assert.IsFalse(policy.Contains(a)); Assert.IsFalse(policy.Contains(b)); policy.Add(a); Assert.AreEqual(1, policy.Count); Assert.IsTrue(policy.Contains(a)); Assert.IsFalse(policy.Contains(b)); policy.Add(a); Assert.AreEqual(1, policy.Count); Assert.IsTrue(policy.Contains(a)); Assert.IsFalse(policy.Contains(b)); policy.Add(b); Assert.AreEqual(2, policy.Count); Assert.IsTrue(policy.Contains(a)); Assert.IsTrue(policy.Contains(b)); policy.Remove(b); Assert.AreEqual(1, policy.Count); Assert.IsTrue(policy.Contains(a)); Assert.IsFalse(policy.Contains(b)); var array = new MultiAddress[1]; policy.CopyTo(array, 0); Assert.AreSame(a, array[0]); foreach (var filter in policy) { Assert.AreSame(a, filter); } policy.Clear(); Assert.AreEqual(0, policy.Count); Assert.IsFalse(policy.Contains(a)); Assert.IsFalse(policy.Contains(b)); }
public async Task Listening_AnyPort() { var peerA = new Peer { Id = self.Id, PublicKey = self.PublicKey, AgentVersion = self.AgentVersion }; MultiAddress addr = "/ip4/127.0.0.1/tcp/0"; var swarmA = new Swarm { LocalPeer = peerA }; var peerB = new Peer { Id = other.Id, PublicKey = other.PublicKey, AgentVersion = other.AgentVersion }; var swarmB = new Swarm { LocalPeer = peerB }; await swarmA.StartAsync(); await swarmB.StartAsync(); try { var another = await swarmA.StartListeningAsync(addr); Assert.IsTrue(peerA.Addresses.Contains(another)); await swarmB.ConnectAsync(another); Assert.IsTrue(swarmB.KnownPeers.Contains(peerA)); // TODO: Assert.IsTrue(swarmA.KnownPeers.Contains(peerB)); await swarmA.StopListeningAsync(addr); Assert.IsFalse(peerA.Addresses.Contains(another)); } finally { await swarmA.StopAsync(); await swarmB.StopAsync(); } }
public async Task <MultiAddress> AddAddressFilterAsync(MultiAddress address, bool persist = false, CancellationToken cancel = default(CancellationToken)) { var addrs = (await ListAddressFiltersAsync(persist, cancel).ConfigureAwait(false)).ToList(); if (addrs.Any(a => a == address)) { return(address); } addrs.Add(address); var strings = addrs.Select(a => a.ToString()); await ipfs.Config.SetAsync("Swarm.AddrFilters", JToken.FromObject(strings), cancel).ConfigureAwait(false); (await ipfs.SwarmService.ConfigureAwait(false)).WhiteList.Add(address); return(address); }
/// <inheritdoc /> public MultiAddress Listen(MultiAddress address, Action <Stream, MultiAddress, MultiAddress> handler, CancellationToken cancel) { var port = address.Protocols .Where(p => p.Name == "udp") .Select(p => int.Parse(p.Value)) .FirstOrDefault(); var ip = address.Protocols .Where(p => p.Name == "ip4" || p.Name == "ip6") .First(); var ipAddress = IPAddress.Parse(ip.Value); var endPoint = new IPEndPoint(ipAddress, port); var socket = new Socket( endPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); socket.Bind(endPoint); // If no port specified, then add it. var actualPort = ((IPEndPoint)socket.LocalEndPoint).Port; if (port != actualPort) { address = address.Clone(); var protocol = address.Protocols.FirstOrDefault(p => p.Name == "udp"); if (protocol != null) { protocol.Value = actualPort.ToString(); } else { address.Protocols.AddRange(new MultiAddress("/udp/" + actualPort).Protocols); } } // TODO: UDP listener throw new NotImplementedException(); #if false var stream = new DatagramStream(socket, ownsSocket: true); handler(stream, address, null); return(address); #endif }
public async Task <IEnumerable <MultiAddress> > ListAddressFiltersAsync(bool persist = false, CancellationToken cancel = default) { try { var json = await _configApi.GetAsync("Swarm.AddrFilters", cancel).ConfigureAwait(false); return(json == null ? new MultiAddress[0] : json.Select(a => MultiAddress.TryCreate((string)a)).Where(a => a != null)); } catch (KeyNotFoundException) { var strings = DefaultFilters.Select(a => a.ToString()); await _configApi.SetAsync("Swarm.AddrFilters", JToken.FromObject(strings), cancel) .ConfigureAwait(false); return(DefaultFilters); } }
public async Task <MultiAddress> AddAsync(MultiAddress address, CancellationToken cancel = default(CancellationToken)) { // Throw if missing peer ID var _ = address.PeerId; var addrs = (await ListAsync(cancel)).ToList(); if (addrs.Any(a => a == address)) { return(address); } addrs.Add(address); var strings = addrs.Select(a => a.ToString()); await ipfs.Config.SetAsync("Bootstrap", JToken.FromObject(strings), cancel); return(address); }
public void Cloning() { var ma1 = new MultiAddress("/ip4/10.1.10.10/tcp/29087"); var ma2 = ma1.Clone(); Assert.Equal(ma1, ma2); Assert.NotSame(ma1, ma2); Assert.NotSame(ma1.Protocols, ma2.Protocols); for (var i = 0; i < ma1.Protocols.Count; ++i) { var p1 = ma1.Protocols[i]; var p2 = ma2.Protocols[i]; Assert.Equal(p1.Code, p2.Code); Assert.Equal(p1.Name, p2.Name); Assert.Equal(p1.Value, p2.Value); Assert.NotSame(p1, p2); } }
public void RoundTripping() { var addresses = new[] { somewhere, "/ip4/1.2.3.4/tcp/80/http", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/tcp/443/https", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/udp/8001", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/sctp/8001", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/dccp/8001", "/ip4/1.2.3.4/tcp/80/ws", "/libp2p-webrtc-star/ip4/127.0.0.1/tcp/9090/ws/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/tcp/1234/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/1.2.3.4/tcp/80/udt", "/ip4/1.2.3.4/tcp/80/utp", "/onion/aaimaq4ygg2iegci:80", "/onion/timaq4ygg2iegci7:80/http", "/p2p-circuit/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/dns/ipfs.io", "/dns4/ipfs.io", "/dns6/ipfs.io", "/dns4/wss0.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic", "/ip4/127.0.0.0/ipcidr/16", "/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN", "/ip4/127.0.0.1/udp/4023/quic" }; foreach (var a in addresses) { var ma0 = new MultiAddress(a); var ms = new MemoryStream(); ma0.Write(ms); ms.Position = 0; var ma1 = new MultiAddress(ms); Assert.Equal(ma0, ma1); var ma2 = new MultiAddress(ma0.ToString()); Assert.Equal(ma0, ma2); var ma3 = new MultiAddress(ma0.ToArray()); Assert.Equal(ma0, ma3); } }
/// <summary> /// Get the peers that are connected to this node. /// </summary> /// <returns> /// A sequence of <see cref="ConnectedPeer">Connected Peers</see>. /// </returns> public async Task <IEnumerable <ConnectedPeer> > PeersAsync() { var json = await ipfs.DoCommandAsync("swarm/peers", null, "verbose=true"); var result = JObject.Parse(json); return(((JArray)JObject.Parse(json)["Strings"]) .Select(s => { var parts = ((string)s).Split(' '); var address = new MultiAddress(parts[0]); return new ConnectedPeer { Id = address.Protocols.First(p => p.Name == "ipfs").Value, ConnectedAddress = parts[0], Latency = ParseLatency(parts[1]) }; })); }
public async Task <MultiAddress> RemoveAddressFilterAsync(MultiAddress address, bool persist = false, CancellationToken cancel = default) { var addrs = (await ListAddressFiltersAsync(persist, cancel).ConfigureAwait(false)).ToList(); if (addrs.All(a => a != address)) { return(null); } addrs.Remove(address); var strings = addrs.Select(a => a.ToString()); await _configApi.SetAsync("Swarm.AddrFilters", JToken.FromObject(strings), cancel).ConfigureAwait(false); _swarmService.WhiteList.Remove(address); return(address); }
/// <summary>Creates a new <see cref="SiteInfo"/> instance from the given BPL site entity and given (optional) operator.</summary> public SiteInfo(Site site, Operator opco) { if (site == null) return; SiteId = Class.CreateId(site.Id.LocalId); Operator = opco; Type = site.PoiType; Position = site.Position; if (!site.LocalizedName.IsEmpty) { Name = site.LocalizedName; } else if (site.Name.NotEmpty()) { Name = new MultiString(site.Name); } if (!site.LocalizedAddress.IsEmpty) { Address = (MultiAddress)site.LocalizedAddress; } else if (site.Address != null) { Address = new MultiAddress(site.Address); } var biz = site.BusinessInfo; if (biz != null) { Description = biz.Description; WorkingHours = biz.WorkingHours; if (biz.RatingCount > 0) { RatingCount = biz.RatingCount; RatingScore = ((Percent)biz.RatingScore).Normalize(); } else { RatingScore = Percent.Undefined; } foreach (var p in biz.PhoneNumbers) { Contacts.Add(new Contact { Type = ContactTypes.Phone, Value = p.ToString() }); } if (biz.Email.NotEmpty()) { Contacts.Add(new Contact { Type = ContactTypes.Email, Value = biz.Email }); } if (biz.Website.NotEmpty()) { Contacts.Add(new Contact { Type = ContactTypes.Website, Value = biz.Website }); } CustomProperties = biz.CustomProperties; } }
public void Value_Equality() { var a0 = new MultiAddress(somewhere); var a1 = new MultiAddress(somewhere); var b = new MultiAddress(nowhere); MultiAddress c = null; MultiAddress d = null; Assert.True(c == d); Assert.False(c == b); Assert.False(b == c); Assert.False(c != d); Assert.True(c != b); Assert.True(b != c); #pragma warning disable 1718 Assert.True(a0 == a0); Assert.True(a0 == a1); Assert.False(a0 == b); #pragma warning disable 1718 Assert.False(a0 != a0); Assert.False(a0 != a1); Assert.True(a0 != b); Assert.True(a0.Equals(a0)); Assert.True(a0.Equals(a1)); Assert.False(a0.Equals(b)); Assert.Equal(a0, a0); Assert.Equal(a0, a1); Assert.NotEqual(a0, b); Assert.Equal(a0, a0); Assert.Equal(a0, a1); Assert.NotEqual(a0, b); Assert.Equal(a0.GetHashCode(), a0.GetHashCode()); Assert.Equal(a0.GetHashCode(), a1.GetHashCode()); Assert.NotEqual(a0.GetHashCode(), b.GetHashCode()); }
public async Task <IEnumerable <Peer> > PeersAsync(CancellationToken cancel = default) { var json = await Client.DoCommandAsync("swarm/peers", cancel, null, "verbose=true"); var result = JObject.Parse(json); // Older servers return an array of strings var strings = (JArray)result["Strings"]; if (strings != null) { return(strings .Select(s => { var parts = ((string)s).Split(' '); var address = new MultiAddress(parts[0]); return new Peer { Id = address.PeerId, ConnectedAddress = parts[0], Latency = Duration.Parse(parts[1]) }; })); } // Current servers return JSON var peers = (JArray)result["Peers"]; if (peers != null) { return(peers.Select(p => new Peer { Id = (string)p["Peer"], ConnectedAddress = new MultiAddress((string)p["Addr"] + "/ipfs/" + (string)p["Peer"]), Latency = Duration.Parse((string)p["Latency"]) })); } // Hmmm. Another change we can handle throw new FormatException("Unknown response from 'swarm/peers"); }
public void WithPeerId() { var id = "QmQusTXc1Z9C1mzxsqC9ZTFXCgSkpBRGgW4Jk2QYHxKE22"; var id3 = "QmQusTXc1Z9C1mzxsqC9ZTFXCgSkpBRGgW4Jk2QYHxKE33"; var ma1 = new MultiAddress("/ip4/127.0.0.1/tcp/4001"); Assert.Equal($"{ma1}/p2p/{id}", ma1.WithPeerId(id)); ma1 = new MultiAddress($"/ip4/127.0.0.1/tcp/4001/ipfs/{id}"); Assert.Same(ma1, ma1.WithPeerId(id)); ma1 = new MultiAddress($"/ip4/127.0.0.1/tcp/4001/p2p/{id}"); Assert.Same(ma1, ma1.WithPeerId(id)); Assert.Throws <Exception>(() => { ma1 = new MultiAddress($"/ip4/127.0.0.1/tcp/4001/ipfs/{id3}"); Assert.Same(ma1, ma1.WithPeerId(id)); }); }
public void Connect_Refused() { const string remoteId = "QmXFX2P5ammdmXQgfqGkfswtEVFsZUJ5KeHRXQYCTdiTAb"; MultiAddress remoteAddress = $"/ip4/127.0.0.1/tcp/4040/ipfs/{remoteId}"; var swarm = new SwarmService { LocalPeer = _self }; swarm.StartAsync().Wait(); try { ExceptionAssert.Throws <Exception>(() => { var _ = swarm.ConnectAsync(remoteAddress).Result; }); } finally { swarm.StopAsync().Wait(); } }
public async Task <IEnumerable <MultiAddress> > ListAsync(CancellationToken cancel = default) { if (_discoveryOptions.BootstrapPeers != null) { return(_discoveryOptions.BootstrapPeers); } try { var json = await _configApi.GetAsync("Bootstrap", cancel); return(json == null ? new MultiAddress[0] : json.Select(a => MultiAddress.TryCreate((string)a)).Where(a => a != null)); } catch (KeyNotFoundException) { var strings = Defaults.Select(a => a.ToString()); await _configApi.SetAsync("Bootstrap", JToken.FromObject(strings), cancel).ConfigureAwait(false); return(Defaults); } }
public void Connect_Not_Peer() { var remoteId = "QmXFX2P5ammdmXQgfqGkfswtEVFsZUJ5KeHRXQYCTdiTAb"; MultiAddress remoteAddress = $"/dns/npmjs.com/tcp/80/ipfs/{remoteId}"; var swarm = new Swarm { LocalPeer = self }; swarm.StartAsync().Wait(); try { ExceptionAssert.Throws <Exception>(() => { var _ = swarm.ConnectAsync(remoteAddress).Result; }); } finally { swarm.StopAsync().Wait(); } }
public async Task Stop_Closes_Listeners() { var peer = new Peer { Id = self.Id, PublicKey = self.PublicKey, AgentVersion = self.AgentVersion }; MultiAddress addr = "/ip4/0.0.0.0/tcp/0"; var swarm = new Swarm { LocalPeer = peer }; try { await swarm.StartAsync(); await swarm.StartListeningAsync(addr); Assert.IsTrue(peer.Addresses.Count() > 0); await swarm.StopAsync(); Assert.AreEqual(0, peer.Addresses.Count()); await swarm.StartAsync(); await swarm.StartListeningAsync(addr); Assert.IsTrue(peer.Addresses.Count() > 0); await swarm.StopAsync(); Assert.AreEqual(0, peer.Addresses.Count()); } catch (Exception) { await swarm.StopAsync(); throw; } }
/// <summary> /// Convert the message into a <see cref="Peer"/>. /// </summary> /// <param name="peer"></param> /// <returns></returns> public bool TryToPeer(out Peer peer) { peer = null; // Sanity checks. if (Id == null || Id.Length == 0) { return(false); } var id = new MultiHash(Id); peer = new Peer { Id = id }; if (Addresses != null) { var x = new MultiAddress($"/ipfs/{id}"); peer.Addresses = Addresses .Select(bytes => { try { var ma = new MultiAddress(bytes); ma.Protocols.AddRange(x.Protocols); return(ma); } catch { return(null); } }) .Where(a => a != null) .ToArray(); } return(true); }
/// <summary> /// Close connection to a given address /// /// 'ipfs swarm disconnect' closes a connection to a peer address. The address format /// is an ipfs multiaddr: /// /// ipfs swarm disconnect /ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ /// </summary> /// <param name="multiAddress">address of peer to disconnect from</param> /// <returns>'disconnect <address> successs' on success</returns> public async Task<IpfsPeerConnectionStatus> Disconnect(MultiAddress multiAddress) { var ret = await Disconnect(ToEnumerable(multiAddress)); return ret.First(); }
public void Trusted_Peers_Add_Missing_Peer_ID() { var missingPeerId = new MultiAddress("/ip4/25.196.147.100/tcp/4001"); var ipfs = new IpfsClient(); ExceptionAssert.Throws<IpfsException>(() => ipfs.TrustedPeers.Add(missingPeerId), "invalid ipfs address"); }
public void RoundTripping() { var addresses = new[] { somewhere, "/ip4/1.2.3.4/tcp/80/http", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/tcp/443/https", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/udp/8001", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/sctp/8001", "/ip6/3ffe:1900:4545:3:200:f8ff:fe21:67cf/dccp/8001", "/ip4/1.2.3.4/tcp/80/ws", "/libp2p-webrtc-star/ip4/127.0.0.1/tcp/9090/ws/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC", "/ip4/127.0.0.1/ipfs/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC/tcp/1234", "/ip4/1.2.3.4/tcp/80/udt", "/ip4/1.2.3.4/tcp/80/utp", "/onion/aaimaq4ygg2iegci:80", "/onion/timaq4ygg2iegci7:80/http", }; foreach (var a in addresses) { var ma0 = new MultiAddress(a); var ms = new MemoryStream(); ma0.Write(ms); ms.Position = 0; var ma1 = new MultiAddress(ms); Assert.AreEqual<MultiAddress>(ma0, ma1); var ma2 = new MultiAddress(ma0.ToString()); Assert.AreEqual<MultiAddress>(ma0, ma2); var ma3 = new MultiAddress(ma0.ToArray()); Assert.AreEqual<MultiAddress>(ma0, ma3); } }
public void Value_Equality() { var a0 = new MultiAddress(somewhere); var a1 = new MultiAddress(somewhere); var b = new MultiAddress(nowhere); MultiAddress c = null; MultiAddress d = null; Assert.IsTrue(c == d); Assert.IsFalse(c == b); Assert.IsFalse(b == c); Assert.IsFalse(c != d); Assert.IsTrue(c != b); Assert.IsTrue(b != c); #pragma warning disable 1718 Assert.IsTrue(a0 == a0); Assert.IsTrue(a0 == a1); Assert.IsFalse(a0 == b); #pragma warning disable 1718 Assert.IsFalse(a0 != a0); Assert.IsFalse(a0 != a1); Assert.IsTrue(a0 != b); Assert.IsTrue(a0.Equals(a0)); Assert.IsTrue(a0.Equals(a1)); Assert.IsFalse(a0.Equals(b)); Assert.AreEqual(a0, a0); Assert.AreEqual(a0, a1); Assert.AreNotEqual(a0, b); Assert.AreEqual<MultiAddress>(a0, a0); Assert.AreEqual<MultiAddress>(a0, a1); Assert.AreNotEqual<MultiAddress>(a0, b); Assert.AreEqual(a0.GetHashCode(), a0.GetHashCode()); Assert.AreEqual(a0.GetHashCode(), a1.GetHashCode()); Assert.AreNotEqual(a0.GetHashCode(), b.GetHashCode()); }