Skip to content

Commit

Permalink
Change type of Peer.EndPoint to DnsEndPoint
Browse files Browse the repository at this point in the history
  • Loading branch information
longfin committed Apr 1, 2019
1 parent dcbaf55 commit afbf585
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 48 deletions.
5 changes: 3 additions & 2 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ To be released.
- Since we decided to depend on TURN ([RFC 5766]) and STUN ([RFC 5389]) to
work around NAT so that `Peer`'s endpoints don't have to be multiple,
`Peer.Urls` was renamed to `Peer.EndPoint` and its type also was changed
from `IImmutableList<Uri>` to `IPEndPoint`.
[[#120], [#123] by Yang Chun Ung, [#126], [#127]]
from `IImmutableList<Uri>` to `DnsEndPoint`.
[[#120], [#123] by Yang Chun Ung, [#126], [#127], [#165]]
- `Swarm` became to ignore tip blocks of the same height (`Index`) that it
already has and deal with only longer (higher) blocks.
- Fixed a bug that occured when `Swarm` was handling multiple responses at the
Expand Down Expand Up @@ -140,6 +140,7 @@ To be released.
[#144]: https://github.com/planetarium/libplanet/pull/144
[#151]: https://github.com/planetarium/libplanet/pull/151
[#159]: https://github.com/planetarium/libplanet/pull/159
[#165]: https://github.com/planetarium/libplanet/issues/165
[RFC 5389]: https://tools.ietf.org/html/rfc5389
[RFC 5766]: https://tools.ietf.org/html/rfc5766

Expand Down
6 changes: 3 additions & 3 deletions Libplanet.Tests/Net/PeerSetDeltaTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,20 @@ public void Serialize()
var peerSetDelta = new PeerSetDelta(
new Peer(
new PrivateKey().PublicKey,
new IPEndPoint(IPAddress.Parse("0.0.0.0"), 1234)
new DnsEndPoint("0.0.0.0", 1234)
),
DateTimeOffset.UtcNow,
new[]
{
new Peer(
new PrivateKey().PublicKey,
new IPEndPoint(IPAddress.Parse("1.2.3.4"), 1234)),
new DnsEndPoint("1.2.3.4", 1234)),
}.ToImmutableHashSet(),
new[]
{
new Peer(
new PrivateKey().PublicKey,
new IPEndPoint(IPAddress.Parse("2.3.4.5"), 1234)),
new DnsEndPoint("2.3.4.5", 1234)),
}.ToImmutableHashSet(),
null
);
Expand Down
2 changes: 1 addition & 1 deletion Libplanet.Tests/Net/PeerTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public void Serialize()
"038f92e8098c897c2a9ae3226eb6337eb" +
"7ca8dbad5e1c8c9b130a9d39171a44134"
));
var endPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 1234);
var endPoint = new DnsEndPoint("0.0.0.0", 1234);
var peer = new Peer(key, endPoint);
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
Expand Down
24 changes: 13 additions & 11 deletions Libplanet.Tests/Net/SwarmTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,13 +56,13 @@ public SwarmTest(ITestOutputHelper output)
{
new Swarm(
new PrivateKey(),
ipAddress: IPAddress.Loopback),
host: IPAddress.Loopback.ToString()),
new Swarm(
new PrivateKey(),
ipAddress: IPAddress.Loopback),
host: IPAddress.Loopback.ToString()),
new Swarm(
new PrivateKey(),
ipAddress: IPAddress.Loopback),
host: IPAddress.Loopback.ToString()),
};
}

Expand Down Expand Up @@ -312,16 +312,16 @@ public void BeComparedProperly()
var pk2 = new PrivateKey();
var a = new Swarm(
pk1,
ipAddress: IPAddress.Parse("0.0.0.0"),
host: "0.0.0.0",
listenPort: 5555);
var b = new Swarm(
pk1,
ipAddress: IPAddress.Parse("0.0.0.0"),
host: "0.0.0.0",
listenPort: 5555,
createdAt: a.LastDistributed);
var c = new Swarm(
pk2,
ipAddress: IPAddress.Parse("0.0.0.0"),
host: "0.0.0.0",
listenPort: 5555);

Assert.Equal(a, b);
Expand Down Expand Up @@ -584,10 +584,10 @@ public void CanDenyNullParams()
[Fact]
public void CanResolveEndPoint()
{
var expected = new IPEndPoint(IPAddress.Parse("1.2.3.4"), 5678);
var expected = new DnsEndPoint("1.2.3.4", 5678);
Swarm s = new Swarm(
new PrivateKey(),
ipAddress: IPAddress.Parse("1.2.3.4"),
host: "1.2.3.4",
listenPort: 5678);

Assert.Equal(expected, s.EndPoint);
Expand All @@ -610,8 +610,10 @@ public async Task CanStopGracefullyWhileStarting()
[Fact]
public async Task AsPeerThrowSwarmExceptionWhenUnbound()
{
Swarm swarm =
new Swarm(new PrivateKey(), ipAddress: IPAddress.Loopback);
Swarm swarm = new Swarm(
new PrivateKey(),
host: IPAddress.Loopback.ToString()
);
Assert.Throws<SwarmException>(() => swarm.AsPeer);

await StartAsync(swarm, _blockchains[0]);
Expand All @@ -635,7 +637,7 @@ public async Task ExchangeWithIceServer()

var seed = new Swarm(
new PrivateKey(),
ipAddress: IPAddress.Loopback);
host: IPAddress.Loopback.ToString());
var swarmA = new Swarm(new PrivateKey(), iceServers: iceServers);
var swarmB = new Swarm(new PrivateKey(), iceServers: iceServers);

Expand Down
14 changes: 7 additions & 7 deletions Libplanet/Net/Peer.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Net;
using System.Runtime.Serialization;
using Libplanet.Crypto;
Expand All @@ -15,7 +12,7 @@ namespace Libplanet.Net
[GeneratedEquality]
public partial class Peer : ISerializable
{
public Peer(PublicKey publicKey, IPEndPoint endPoint)
public Peer(PublicKey publicKey, DnsEndPoint endPoint)
{
if (publicKey == null)
{
Expand All @@ -33,7 +30,9 @@ public Peer(PublicKey publicKey, IPEndPoint endPoint)
protected Peer(SerializationInfo info, StreamingContext context)
{
PublicKey = new PublicKey(info.GetValue<byte[]>("public_key"));
EndPoint = info.GetValue<IPEndPoint>("end_point");
EndPoint = new DnsEndPoint(
info.GetString("end_point_host"),
info.GetInt32("end_point_port"));
}

[EqualityKey]
Expand All @@ -42,7 +41,7 @@ protected Peer(SerializationInfo info, StreamingContext context)

[EqualityKey]
[Pure]
public IPEndPoint EndPoint { get; }
public DnsEndPoint EndPoint { get; }

[Pure]
public Address Address => new Address(PublicKey);
Expand All @@ -53,7 +52,8 @@ StreamingContext context
)
{
info.AddValue("public_key", PublicKey.Format(true));
info.AddValue("end_point", EndPoint);
info.AddValue("end_point_host", EndPoint.Host);
info.AddValue("end_point_port", EndPoint.Port);
}

public override string ToString()
Expand Down
70 changes: 46 additions & 24 deletions Libplanet/Net/Swarm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public partial class Swarm : ICollection<Peer>, IDisposable
private readonly AsyncLock _distributeMutex;
private readonly AsyncLock _receiveMutex;
private readonly AsyncLock _blockSyncMutex;
private readonly IPAddress _ipAddress;
private readonly string _host;
private readonly TurnClient _turnClient;

private readonly ILogger _logger;
Expand All @@ -58,14 +58,14 @@ public partial class Swarm : ICollection<Peer>, IDisposable
public Swarm(
PrivateKey privateKey,
int millisecondsDialTimeout = 15000,
IPAddress ipAddress = null,
string host = null,
int? listenPort = null,
DateTimeOffset? createdAt = null,
IEnumerable<IceServer> iceServers = null)
: this(
privateKey,
TimeSpan.FromMilliseconds(millisecondsDialTimeout),
ipAddress,
host,
listenPort,
createdAt,
iceServers)
Expand All @@ -75,7 +75,7 @@ public Swarm(
public Swarm(
PrivateKey privateKey,
TimeSpan dialTimeout,
IPAddress ipAddress = null,
string host = null,
int? listenPort = null,
DateTimeOffset? createdAt = null,
IEnumerable<IceServer> iceServers = null)
Expand Down Expand Up @@ -107,23 +107,23 @@ public Swarm(
_blockSyncMutex = new AsyncLock();
_runningMutex = new AsyncLock();

_ipAddress = ipAddress;
_host = host;
_listenPort = listenPort;

if (_ipAddress != null && _listenPort != null)
if (_host != null && _listenPort != null)
{
EndPoint = new IPEndPoint(_ipAddress, listenPort.Value);
EndPoint = new DnsEndPoint(_host, listenPort.Value);
}

if (iceServers != null)
{
_turnClient = IceServer.CreateTurnClient(iceServers).Result;
}

if (ipAddress == null && _turnClient == null)
if (_host == null && _turnClient == null)
{
throw new ArgumentException(
$"Swarm needs {nameof(ipAddress)} or {iceServers}.");
$"Swarm needs {nameof(host)} or {iceServers}.");
}

string loggerId = _privateKey.PublicKey.ToAddress().ToHex();
Expand All @@ -145,7 +145,7 @@ public Swarm(

public bool IsReadOnly => false;

public IPEndPoint EndPoint { get; private set; }
public DnsEndPoint EndPoint { get; private set; }

[Uno.EqualityKey]
public Address Address => _privateKey.PublicKey.ToAddress();
Expand Down Expand Up @@ -248,16 +248,7 @@ public async Task<ISet<Peer>> AddPeersAsync(
{
if (_turnClient != null)
{
var ep = peer.EndPoint;
if (IPAddress.IsLoopback(ep.Address))
{
// This translation is only used in test case
// because a seed node exposes loopback address
// as public address to other node in test case
ep = await _turnClient.GetMappedAddressAsync();
}

await _turnClient.CreatePermissionAsync(ep);
await CreatePermission(peer);
}

_logger.Debug($"Trying to DialPeerAsync({peer})...");
Expand Down Expand Up @@ -424,12 +415,15 @@ public async Task StartAsync<T>(

if (behindNAT)
{
EndPoint = await _turnClient.AllocateRequestAsync(
TurnAllocationLifetime);
IPEndPoint turnEp = await _turnClient.AllocateRequestAsync(
TurnAllocationLifetime
);
EndPoint = new DnsEndPoint(
turnEp.Address.ToString(), turnEp.Port);
}
else
{
EndPoint = new IPEndPoint(_ipAddress, _listenPort.Value);
EndPoint = new DnsEndPoint(_host, _listenPort.Value);
}

try
Expand Down Expand Up @@ -1474,7 +1468,35 @@ private string ToNetMQAddress(Peer peer)
throw new ArgumentNullException(nameof(peer));
}

return $"tcp://{peer.EndPoint}";
return $"tcp://{peer.EndPoint.Host}:{peer.EndPoint.Port}";
}

private async Task CreatePermission(Peer peer)
{
var peerHost = peer.EndPoint.Host;
if (IPAddress.TryParse(peerHost, out IPAddress asIp))
{
var ep = new IPEndPoint(asIp, peer.EndPoint.Port);
if (IPAddress.IsLoopback(asIp))
{
// This translation is only used in test case because a
// seed node exposes loopback address as public address to
// other node in test case
ep = await _turnClient.GetMappedAddressAsync();
}

await _turnClient.CreatePermissionAsync(ep);
}
else
{
IPAddress[] ips = await Dns.GetHostAddressesAsync(peerHost);
foreach (IPAddress ip in ips)
{
await _turnClient.CreatePermissionAsync(
new IPEndPoint(ip, peer.EndPoint.Port)
);
}
}
}
}
}

0 comments on commit afbf585

Please sign in to comment.