From 532052032b56f1b315dbc9c4aab2c298994badf3 Mon Sep 17 00:00:00 2001 From: 317787106 <317787106@qq.com> Date: Tue, 24 Nov 2026 12:08:48 +0800 Subject: [PATCH] fix(net): sync p2p fixes from libp2p release-v2.3.0 (part 4) Port libp2p PRs #181-185 from release-v2.3.0 after java-tron #7098: - #181 d6292c8: limit inbound PINGs per connection - #182 d55df73: correct DNS TXT handling and publication ordering - #183 49c8b24: rate limit UDP rejection logs and bound packet previews - #184 f4a69fe: expand HELLO capacity and bound pre-handshake frames - #185 18da461: exclude cross-network STATUS candidates Retain java-tron's blocked-IP policy, logger convention and existing regressions. Migrate upstream tests, adapt DNS fixtures to the new behavior, and update source provenance and networking limits. --- p2p/README.md | 14 +- .../java/org/tron/p2p/base/Parameter.java | 14 +- .../java/org/tron/p2p/connection/Channel.java | 3 + .../business/detect/NodeDetectService.java | 14 +- .../business/keepalive/KeepAliveService.java | 5 + .../socket/P2pChannelInitializer.java | 31 +- .../P2pProtobufVarint32FrameDecoder.java | 8 +- .../main/java/org/tron/p2p/discover/Node.java | 2 +- .../p2p/discover/socket/P2pPacketDecoder.java | 151 +++++++- .../org/tron/p2p/dns/lookup/LookUpTxt.java | 22 +- .../java/org/tron/p2p/dns/sync/Client.java | 28 +- .../java/org/tron/p2p/dns/tree/Algorithm.java | 6 +- .../org/tron/p2p/dns/tree/NodesEntry.java | 2 +- .../org/tron/p2p/dns/update/AliClient.java | 7 +- .../org/tron/p2p/dns/update/AwsClient.java | 55 ++- .../p2p/connection/StatusLifecycleTest.java | 142 +++++++- .../keepalive/KeepAliveServiceTest.java | 53 +++ .../OutboundHandshakeTimeoutHandlerTest.java | 13 +- .../P2pPreHandshakeFrameDecoderTest.java | 203 +++++++++++ .../socket/P2pRecvByteBufAllocatorTest.java | 327 ++++++++++++++++++ .../PendingInboundConnectionHandlerTest.java | 76 ++-- .../socket/P2pPacketDecoderRejectionTest.java | 103 ++++++ .../java/org/tron/p2p/dns/AwsRoute53Test.java | 242 ++++++++++++- .../java/org/tron/p2p/dns/DnsNodeTest.java | 11 + .../org/tron/p2p/dns/sync/ClientRootTest.java | 93 +++++ .../java/org/tron/p2p/dns/sync/SyncTest.java | 5 +- .../p2p/dns/update/AwsClientChangeTest.java | 10 +- .../p2p/dns/update/AwsClientRecordsTest.java | 27 +- .../dns/update/DnsSignerPublicationTest.java | 55 ++- 29 files changed, 1612 insertions(+), 110 deletions(-) create mode 100644 p2p/src/test/java/org/tron/p2p/connection/socket/P2pPreHandshakeFrameDecoderTest.java create mode 100644 p2p/src/test/java/org/tron/p2p/connection/socket/P2pRecvByteBufAllocatorTest.java create mode 100644 p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderRejectionTest.java create mode 100644 p2p/src/test/java/org/tron/p2p/dns/sync/ClientRootTest.java diff --git a/p2p/README.md b/p2p/README.md index a24c5e66c56..8463493d31e 100644 --- a/p2p/README.md +++ b/p2p/README.md @@ -3,7 +3,7 @@ Peer discovery, connection management and DNS-based node lists for java-tron. > **Vendored from [tronprotocol/libp2p](https://github.com/tronprotocol/libp2p) -> v2.2.9, synchronized through `release-v2.3.0` at `94dbc75896dc68c72934276c8d3143b4a3540363`.** +> v2.2.9, synchronized through `release-v2.3.0` at `18da461f1312cb7d7c8d13dccf992e5f78a55a36`.** > It lives here as the `:p2p` Gradle module and is consumed as a > project dependency, not as a published artifact — `:common` exposes it via > `api project(":p2p")`. Upstream's own README follows, edited where @@ -19,8 +19,18 @@ Bouncy Castle is upgraded in the root build as well as this module so all consum Pending writes have a 200 MiB per-connection threshold and a 500 MiB shared eviction threshold; the latter triggers asynchronous eviction rather than enforcing a hard global admission limit. Writes that remain incomplete for 10 seconds close the connection. Ordinary inbound HELLOs are -admitted while the total pending count is below 32; trusted IPs can use capacity up to 40 total. +admitted while the total pending count is below 1016; trusted IPs can use capacity up to 1024 total. The per-IP pending limit remains two, and the absolute HELLO deadline remains 10 seconds. +Before HELLO completes, inbound and outbound frames declaring 1024 bytes or more are rejected, +including trusted peers; receive allocations are 1024 bytes and grow to 256 KiB after HELLO. +Established connections retain the existing 5 MiB frame limit. Inbound keepalive PINGs use a +per-connection limiter at one permit per second with Guava's default burst behavior. + +The `net` logger samples UDP discovery rejections by reason, with packet previews capped at +128 bytes. In each summary, `suppressed` counts samples skipped since the previous summary, +and `total` counts rejected packets for that decoder and reason while its log level was enabled. +Pending counts are reported before the next sample, on a one-minute timer, or when the decoder +is removed, provided the log level is enabled. Previously generated DNS tree URLs may need updating; see the [migration notes](#124-migration-for-previously-generated-tree-urls). diff --git a/p2p/src/main/java/org/tron/p2p/base/Parameter.java b/p2p/src/main/java/org/tron/p2p/base/Parameter.java index f78332f0c8f..3a9afbeb09f 100644 --- a/p2p/src/main/java/org/tron/p2p/base/Parameter.java +++ b/p2p/src/main/java/org/tron/p2p/base/Parameter.java @@ -30,11 +30,14 @@ public class Parameter { // Node detection timeout in milliseconds. public static final int NODE_DETECT_TIMEOUT = 2000; - // Admission threshold for ordinary inbound connections, counting all pending HELLOs. - public static final int MAX_PENDING_INBOUND_CONNECTIONS = 32; - // Absolute limit for all inbound connections waiting for HELLO, including trusted IPs. - public static final int MAX_TOTAL_PENDING_INBOUND_CONNECTIONS = 40; + // Assumes the effective soft RLIMIT_NOFILE leaves room for these sockets in addition to + // peak application FD usage and operating headroom; libp2p does not change the process limit. + public static final int MAX_TOTAL_PENDING_INBOUND_CONNECTIONS = 1024; + + // Reserve eight pending HELLO slots for trusted IPs above the ordinary admission threshold. + public static final int MAX_PENDING_INBOUND_CONNECTIONS = + MAX_TOTAL_PENDING_INBOUND_CONNECTIONS - 8; public static final int MAX_PENDING_INBOUND_CONNECTIONS_WITH_SAME_IP = 2; @@ -60,6 +63,9 @@ public class Parameter { public static final int MAX_MESSAGE_LENGTH = 5 * 1024 * 1024; + // Reject frames declaring 1 KiB or more until the HELLO handshake completes. + public static final int MAX_PRE_HANDSHAKE_LENGTH = 1024; + public static volatile P2pConfig p2pConfig; public static volatile List handlerList = new ArrayList<>(); diff --git a/p2p/src/main/java/org/tron/p2p/connection/Channel.java b/p2p/src/main/java/org/tron/p2p/connection/Channel.java index e900bc9dde9..9e8c4256804 100644 --- a/p2p/src/main/java/org/tron/p2p/connection/Channel.java +++ b/p2p/src/main/java/org/tron/p2p/connection/Channel.java @@ -1,6 +1,7 @@ package org.tron.p2p.connection; import com.google.common.base.Throwables; +import com.google.common.util.concurrent.RateLimiter; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; @@ -40,6 +41,8 @@ public class Channel { public volatile boolean waitForPong = false; public volatile long pingSent = System.currentTimeMillis(); + @Getter + private final RateLimiter pingRateLimiter = RateLimiter.create(1.0); @Getter private HelloMessage helloMessage; diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java index ad84205b98c..4eee46970e3 100644 --- a/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java +++ b/p2p/src/main/java/org/tron/p2p/connection/business/detect/NodeDetectService.java @@ -182,6 +182,16 @@ public synchronized void processMessage(Channel channel, Message message) { return; } + int networkId = Parameter.p2pConfig.getNetworkId(); + // Discovery fallback uses this same Node instance when selecting connection candidates. + nodeStat.getNode().setNetworkId(statusMessage.getNetworkId()); + if (statusMessage.getNetworkId() != networkId) { + logger.debug("Ignore STATUS from {}, network id {}, expected {}", socketAddress, + statusMessage.getNetworkId(), networkId); + nodeStatMap.remove(socketAddress, nodeStat); + return; + } + long cost = System.currentTimeMillis() - nodeStat.getLastDetectTime(); if (cost > NODE_DETECT_TIMEOUT || statusMessage.getRemainConnections() == 0) { @@ -236,8 +246,10 @@ private synchronized void setStatusMessage(NodeStat nodeStat, StatusMessage mess public synchronized List getConnectableNodes() { List stats = new ArrayList<>(); List nodes = new ArrayList<>(); + int networkId = Parameter.p2pConfig.getNetworkId(); nodeStatMap.values().forEach(stat -> { - if (stat.getStatusMessage() != null) { + if (stat.getStatusMessage() != null + && stat.getStatusMessage().getNetworkId() == networkId) { stats.add(stat); } }); diff --git a/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java b/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java index e1b5efa69dc..4d8100bb3a6 100644 --- a/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java +++ b/p2p/src/main/java/org/tron/p2p/connection/business/keepalive/KeepAliveService.java @@ -59,6 +59,11 @@ public void close() { public void processMessage(Channel channel, Message message) { switch (message.getType()) { case KEEP_ALIVE_PING: + if (!channel.getPingRateLimiter().tryAcquire()) { + channel.send(new P2pDisconnectMessage(DisconnectReason.BAD_PROTOCOL)); + channel.close(); + return; + } channel.send(new PongMessage()); break; case KEEP_ALIVE_PONG: diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java index 6a4e9eb02d4..dbef23fc42b 100644 --- a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pChannelInitializer.java @@ -4,12 +4,13 @@ import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; -import io.netty.channel.FixedRecvByteBufAllocator; +import io.netty.channel.DefaultMaxMessagesRecvByteBufAllocator; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.handler.timeout.WriteTimeoutHandler; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; +import org.tron.p2p.base.Parameter; import org.tron.p2p.connection.Channel; import org.tron.p2p.connection.ChannelManager; import org.tron.p2p.connection.ConnectionPolicy; @@ -56,10 +57,9 @@ public void initChannel(NioSocketChannel ch) { final Channel channel = new Channel(); channel.init(ch.pipeline(), remoteId, nodeDetectMode); - // limit the size of receiving buffer to 1024 - ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(256 * 1024)); + // Keep incomplete pre-HELLO frames from retaining a normal 256 KiB receive buffer. + ch.config().setRecvByteBufAllocator(new P2pRecvByteBufAllocator(channel)); ch.config().setOption(ChannelOption.SO_RCVBUF, 256 * 1024); - ch.config().setOption(ChannelOption.SO_BACKLOG, 1024); // Route STATUS-probe and regular peer cleanup separately. ch.closeFuture().addListener((ChannelFutureListener) future -> { @@ -99,4 +99,27 @@ private void sendRejection(NioSocketChannel ch, DisconnectCode code) { .addListener(ChannelFutureListener.CLOSE); } + /** Limits receive allocations before HELLO without replacing Netty's cached read handle. */ + private static final class P2pRecvByteBufAllocator + extends DefaultMaxMessagesRecvByteBufAllocator { + + private static final int NORMAL_RECEIVE_BUFFER_SIZE = 256 * 1024; + + private final Channel channel; + + private P2pRecvByteBufAllocator(Channel channel) { + this.channel = channel; + } + + @Override + public Handle newHandle() { + return new MaxMessageHandle() { + @Override + public int guess() { + return channel.isFinishHandshake() + ? NORMAL_RECEIVE_BUFFER_SIZE : Parameter.MAX_PRE_HANDSHAKE_LENGTH; + } + }; + } + } } diff --git a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java index 41390aa9f6b..99c1de26438 100644 --- a/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java +++ b/p2p/src/main/java/org/tron/p2p/connection/socket/P2pProtobufVarint32FrameDecoder.java @@ -80,9 +80,11 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) { in.markReaderIndex(); int preIndex = in.readerIndex(); int length = readRawVarint32(in); - if (length >= Parameter.MAX_MESSAGE_LENGTH) { - logger.warn("Receive a big msg or not encoded msg, host : {}, msg length is : {}", - ctx.channel().remoteAddress(), length); + int maxLength = channel.isFinishHandshake() + ? Parameter.MAX_MESSAGE_LENGTH : Parameter.MAX_PRE_HANDSHAKE_LENGTH; + if (length >= maxLength) { + logger.warn("Receive a big msg or not encoded msg, host : {}, msg length is : {}, limit : {}", + ctx.channel().remoteAddress(), length, maxLength); in.clear(); channel.send(new P2pDisconnectMessage(DisconnectReason.BAD_MESSAGE)); channel.close(); diff --git a/p2p/src/main/java/org/tron/p2p/discover/Node.java b/p2p/src/main/java/org/tron/p2p/discover/Node.java index 2745a68290f..047022a493f 100644 --- a/p2p/src/main/java/org/tron/p2p/discover/Node.java +++ b/p2p/src/main/java/org/tron/p2p/discover/Node.java @@ -35,7 +35,7 @@ public class Node implements Serializable, Cloneable { @Setter private int bindPort; - /** Network identifier learned from discovery PING/PONG messages. */ + /** Network identifier learned from discovery PING/PONG messages or TCP STATUS probes. */ @Setter private int networkId; diff --git a/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java b/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java index c016c2ca264..1e1f219881b 100644 --- a/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java +++ b/p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java @@ -1,27 +1,64 @@ package org.tron.p2p.discover.socket; +import com.google.common.util.concurrent.RateLimiter; import com.google.protobuf.InvalidProtocolBufferException; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.socket.DatagramPacket; import io.netty.handler.codec.MessageToMessageDecoder; +import io.netty.util.concurrent.ScheduledFuture; +import java.util.EnumMap; import java.util.List; +import java.util.concurrent.TimeUnit; import lombok.extern.slf4j.Slf4j; +import org.bouncycastle.util.encoders.Hex; +import org.slf4j.event.Level; import org.tron.p2p.base.Constant; import org.tron.p2p.discover.message.Message; import org.tron.p2p.exception.P2pException; -import org.tron.p2p.utils.ByteArray; @Slf4j(topic = "net") public class P2pPacketDecoder extends MessageToMessageDecoder { + private static final int REPORT_INTERVAL_SECONDS = 60; + private static final int MAX_LOG_DATA_BYTES = 128; + private static final String SUMMARY = + "Suppressed UDP discovery logs: reason={}, suppressed={}, total={}"; + + // Only the channel's event loop updates the counters and reports summaries. + private final EnumMap drops = new EnumMap<>(DropReason.class); + private ScheduledFuture summaryTask; + + public P2pPacketDecoder() { + for (DropReason reason : DropReason.values()) { + drops.put(reason, new DropCounter()); + } + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) { + summaryTask = ctx.executor().scheduleWithFixedDelay(this::flushSummaries, + REPORT_INTERVAL_SECONDS, REPORT_INTERVAL_SECONDS, TimeUnit.SECONDS); + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) { + if (summaryTask != null) { + summaryTask.cancel(false); + summaryTask = null; + } + flushSummaries(); + } + @Override public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List out) throws Exception { ByteBuf buf = packet.content(); int length = buf.readableBytes(); if (length <= 1 || length >= Constant.MAX_DISCOVERY_PACKET_SIZE) { - logger.warn("UDP rcv bad packet, from {} length = {}", packet.sender(), length); + if (shouldLog(DropReason.INVALID_LENGTH)) { + logger.warn("UDP rcv bad packet, from {} length = {}", packet.sender(), length); + } return; } byte[] encoded = new byte[length]; @@ -30,21 +67,107 @@ public void decode(ChannelHandlerContext ctx, DatagramPacket packet, ListOS name resolver ({@link InetAddress}) — reads {@code /etc/hosts} first, - * so LAN IP mappings configured there are returned immediately without a DNS query. - *
  • Random public DNS server (fallback, retried up to {@link #maxRetryTimes} times).
  • + *
  • OS name resolver ({@link InetAddress}) — reads {@code /etc/hosts} first, + * so LAN IP mappings configured there are returned immediately without a DNS query.
  • + *
  • Random public DNS server (fallback, retried up to {@link #maxRetryTimes} times).
  • * * @param domain the domain name to resolve (e.g. {@code "nodes.example.com"}) * @param useIPv4 {@code true} to query A records (IPv4); {@code false} to query AAAA diff --git a/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java b/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java index 12d49d4135b..daf8c3a6fda 100644 --- a/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java +++ b/p2p/src/main/java/org/tron/p2p/dns/sync/Client.java @@ -25,6 +25,7 @@ import org.tron.p2p.exception.DnsException; import org.tron.p2p.exception.DnsException.TypeEnum; import org.tron.p2p.utils.ByteArray; +import org.xbill.DNS.Record; import org.xbill.DNS.TXTRecord; import org.xbill.DNS.TextParseException; @@ -104,17 +105,30 @@ public void syncTree(String urlScheme, ClientTree clientTree, Tree tree) throws public RootEntry resolveRoot(LinkEntry linkEntry) throws TextParseException, DnsException, SignatureException, UnknownHostException { //do not put root in cache - TXTRecord txtRecord = LookUpTxt.lookUpTxt(linkEntry.getDomain()); - if (txtRecord == null) { + return parseRoot(linkEntry, LookUpTxt.lookUpTxtRecords(linkEntry.getDomain())); + } + + // Unrelated TXT records, such as domain ownership verification, may share the root name. + // Check all candidates until a root verifies against the configured public key. + static RootEntry parseRoot(LinkEntry linkEntry, Record[] records) throws DnsException { + if (records == null) { throw new DnsException(TypeEnum.LOOK_UP_ROOT_FAILED, "domain: " + linkEntry.getDomain()); } - for (String txt : txtRecord.getStrings()) { - if (txt.startsWith(Entry.rootPrefix)) { - return RootEntry.parseEntry(txt, linkEntry.getUnCompressHexPublicKey(), - linkEntry.getDomain()); + Exception failure = null; + for (Record record : records) { + for (String txt : ((TXTRecord) record).getStrings()) { + if (txt.startsWith(Entry.rootPrefix)) { + try { + return RootEntry.parseEntry(txt, linkEntry.getUnCompressHexPublicKey(), + linkEntry.getDomain()); + } catch (DnsException | SignatureException | IllegalArgumentException e) { + failure = e; + } + } } } - throw new DnsException(TypeEnum.NO_ROOT_FOUND, "domain: " + linkEntry.getDomain()); + throw new DnsException(TypeEnum.NO_ROOT_FOUND, + TypeEnum.NO_ROOT_FOUND.getDesc() + ", domain: " + linkEntry.getDomain(), failure); } // resolveEntry retrieves an entry from the cache or fetches it from the network diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java b/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java index a6f10435cca..25b30add476 100644 --- a/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/Algorithm.java @@ -74,7 +74,11 @@ public static BigInteger recoverPublicKey(String msg, byte[] sig) throws Signatu } Sign.SignatureData signature = new SignatureData((byte) recId, ByteArray.subArray(sig, 0, 32), ByteArray.subArray(sig, 32, 64)); - return Sign.signedMessageToKey(msg.getBytes(), signature); + try { + return Sign.signedMessageToKey(msg.getBytes(), signature); + } catch (ArithmeticException e) { + throw new SignatureException("Invalid signature", e); + } } /** diff --git a/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java b/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java index d7ca7a6503e..0873204318b 100644 --- a/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java +++ b/p2p/src/main/java/org/tron/p2p/dns/tree/NodesEntry.java @@ -26,7 +26,7 @@ public static NodesEntry parseEntry(String e) throws DnsException { List nodeList; try { nodeList = DnsNode.decompress(content.replace("\"","")); - } catch (InvalidProtocolBufferException | UnknownHostException ex) { + } catch (InvalidProtocolBufferException | UnknownHostException | IllegalArgumentException ex) { throw new DnsException(TypeEnum.INVALID_NODES, ex); } return new NodesEntry(e, nodeList); diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java b/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java index 57b47de4a49..859d67606b3 100644 --- a/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java +++ b/p2p/src/main/java/org/tron/p2p/dns/update/AliClient.java @@ -1,5 +1,7 @@ package org.tron.p2p.dns.update; +import static org.tron.p2p.dns.tree.Entry.rootPrefix; + import com.aliyun.alidns20150109.Client; import com.aliyun.alidns20150109.models.AddDomainRecordRequest; import com.aliyun.alidns20150109.models.AddDomainRecordResponse; @@ -139,10 +141,13 @@ public Map collect for (DescribeDomainRecordsResponseBodyDomainRecordsRecord r : response.getBody() .getDomainRecords().getRecord()) { String name = StringUtils.stripEnd(r.getRR(), "."); - records.put(name, r); if (aliyunRoot.equalsIgnoreCase(name)) { + if (StringUtils.isEmpty(r.value) || !r.value.startsWith(rootPrefix)) { + continue; + } rootContent = r.value; } + records.put(name, r); if (StringUtils.isNotEmpty(r.value) && r.value.startsWith( org.tron.p2p.dns.tree.Entry.nodesPrefix)) { NodesEntry nodesEntry; diff --git a/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java b/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java index 5a366037e6a..b089f6d344c 100644 --- a/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java +++ b/p2p/src/main/java/org/tron/p2p/dns/update/AwsClient.java @@ -1,5 +1,6 @@ package org.tron.p2p.dns.update; +import static org.tron.p2p.dns.tree.Entry.rootPrefix; import static org.tron.p2p.utils.NetUtil.normalizeDomain; import java.math.BigInteger; @@ -57,6 +58,7 @@ public class AwsClient implements Publish { private Route53Client route53Client; private String zoneId; private Set serverNodes; + private long changePollIntervalMillis = 15 * 1000; private static final String symbol = "\""; private static final String postfix = "."; private double changeThreshold; @@ -116,6 +118,11 @@ private String findZoneID(String domain) { @Override public void testConnect() throws Exception { + if (StringUtils.isNotEmpty(zoneId)) { + route53Client.listResourceRecordSets(ListResourceRecordSetsRequest.builder() + .hostedZoneId(zoneId).maxItems("1").build()); + return; + } ListHostedZonesByNameRequest.Builder request = ListHostedZonesByNameRequest.builder(); while (true) { ListHostedZonesByNameResponse response = route53Client.listHostedZonesByName(request.build()); @@ -227,7 +234,12 @@ public Map collectRecords(String rootDomain) throws Exception String content = StringUtils.join(values, ""); content = StringUtils.strip(content, symbol); if (rootDomain.equalsIgnoreCase(name)) { - rootContent = content; + for (String value : values) { + String txt = StringUtils.strip(value, symbol); + if (txt.startsWith(rootPrefix)) { + rootContent = txt; + } + } } if (content.startsWith(org.tron.p2p.dns.tree.Entry.nodesPrefix)) { NodesEntry nodesEntry; @@ -313,15 +325,19 @@ public void submitChanges(List changes, String comment) { while (true) { GetChangeResponse changeResponse = route53Client.getChange(request.build()); count += 1; - if (changeResponse.changeInfo().status() == ChangeStatus.INSYNC || count >= maxRetryLimit) { + if (changeResponse.changeInfo().status() == ChangeStatus.INSYNC) { break; } + if (count >= maxRetryLimit) { + throw new IllegalStateException("Timed out waiting for Route53 change " + + response.changeInfo().id() + " to reach INSYNC"); + } try { - Thread.sleep(15 * 1000); + Thread.sleep(changePollIntervalMillis); } catch (InterruptedException e) { - // Upstream swallows the interrupt without restoring the flag, so this - // loop keeps polling until INSYNC or maxRetryLimit. Behaviour is - // preserved here; see the PR description for the deferred fix. + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while waiting for Route53 change " + + response.changeInfo().id(), e); } } } @@ -351,10 +367,22 @@ public List computeChanges(String domain, Map records, } else { RecordSet recordSet = existing.get(path); String preValue = StringUtils.join(recordSet.values, ""); + List newValues = new ArrayList<>(); + if (path.equalsIgnoreCase(domain)) { + preValue = ""; + for (String oldValue : recordSet.values) { + if (StringUtils.strip(oldValue, symbol).startsWith(rootPrefix)) { + preValue = oldValue; + } else { + newValues.add(oldValue); + } + } + } + newValues.add(newValue); if (!preValue.equalsIgnoreCase(newValue) || recordSet.ttl != ttl) { logger.info("Updating {} from [{}] to [{}]", path, preValue, newValue); - if (path.equalsIgnoreCase(domain)) { + if (path.equalsIgnoreCase(domain) && !preValue.isEmpty()) { try { RootEntry oldRoot = RootEntry.parseEntry(StringUtils.strip(preValue, symbol)); RootEntry newRoot = RootEntry.parseEntry(StringUtils.strip(newValue, symbol)); @@ -364,7 +392,8 @@ public List computeChanges(String domain, Map records, //ignore } } - Change change = newTXTChange(ChangeAction.UPSERT, path, ttl, newValue); + Change change = newTXTChange(ChangeAction.UPSERT, path, ttl, + newValues.toArray(new String[0])); changes.add(change); } } @@ -405,15 +434,21 @@ public static void sortChanges(List changes) { } private static int getChangeOrder(Change change) { + // Publish the root after its dependencies and before deleting old records. + if ((change.action() == ChangeAction.CREATE || change.action() == ChangeAction.UPSERT) + && change.resourceRecordSet().resourceRecords().stream() + .anyMatch(record -> StringUtils.strip(record.value(), symbol).startsWith(rootPrefix))) { + return 3; + } switch (change.action()) { case CREATE: return 1; case UPSERT: return 2; case DELETE: - return 3; - default: return 4; + default: + return 5; } } diff --git a/p2p/src/test/java/org/tron/p2p/connection/StatusLifecycleTest.java b/p2p/src/test/java/org/tron/p2p/connection/StatusLifecycleTest.java index 7e8b0d23d06..f81a2b5cc35 100644 --- a/p2p/src/test/java/org/tron/p2p/connection/StatusLifecycleTest.java +++ b/p2p/src/test/java/org/tron/p2p/connection/StatusLifecycleTest.java @@ -3,21 +3,29 @@ import com.google.protobuf.ByteString; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.SimpleChannelInboundHandler; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; +import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; import io.netty.util.ReferenceCountUtil; import io.netty.util.concurrent.ScheduledFuture; import java.io.DataInputStream; import java.io.OutputStream; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -45,7 +53,10 @@ import org.tron.p2p.connection.message.handshake.HelloMessage; import org.tron.p2p.connection.socket.MessageHandler; import org.tron.p2p.connection.socket.P2pChannelInitializer; +import org.tron.p2p.connection.socket.PeerClient; import org.tron.p2p.discover.Node; +import org.tron.p2p.discover.NodeManager; +import org.tron.p2p.discover.protocol.kad.KadService; import org.tron.p2p.protos.Connect; import org.tron.p2p.protos.Discover; import org.tron.p2p.utils.NetUtil; @@ -244,9 +255,63 @@ public void outboundDetectSuccessKeepsResult() throws Exception { Assert.assertSame(stat, nodeStats().get(stat.getSocketAddress())); Assert.assertNotNull(stat.getStatusMessage()); Assert.assertTrue(stat.finishDetect()); + Assert.assertTrue(detect.getConnectableNodes().contains(stat.getNode())); Assert.assertTrue(NodeDetectService.getBadNodesCache().asMap().isEmpty()); } + @Test + public void outboundForeignNetworkStatusRemovesFreshAndCachedResults() throws Exception { + for (boolean cached : new boolean[]{false, true}) { + StatusMessage previous = cached ? status() : null; + io.netty.channel.Channel server = statusServer( + status(Parameter.p2pConfig.getNetworkId() + 1, 1)); + try { + NodeStat stat = probe((InetSocketAddress) server.localAddress(), false, previous); + + Assert.assertFalse(nodeStats().containsKey(stat.getSocketAddress())); + Assert.assertSame(previous, stat.getStatusMessage()); + Assert.assertFalse(stat.finishDetect()); + Assert.assertTrue(detect.getConnectableNodes().isEmpty()); + Assert.assertTrue(NodeDetectService.getBadNodesCache().asMap().isEmpty()); + Assert.assertTrue(ChannelManager.getBannedNodes().asMap().isEmpty()); + assertNotDialedFromDiscovery(stat.getNode()); + } finally { + server.close().sync(); + } + } + } + + @Test + public void cachedForeignNetworkStatusIsExcludedWithoutChangingCandidateOrder() throws Exception { + NodeStat foreign = cachedStatus("192.0.2.1", Parameter.p2pConfig.getNetworkId() + 1, 50); + NodeStat slow = cachedStatus("192.0.2.2", Parameter.p2pConfig.getNetworkId(), 1); + NodeStat fast = cachedStatus("192.0.2.3", Parameter.p2pConfig.getNetworkId(), 10); + NodeStat unfinished = new NodeStat(new Node(new InetSocketAddress("192.0.2.4", 18888))); + nodeStats().put(unfinished.getSocketAddress(), unfinished); + + List candidates = detect.getConnectableNodes(); + + Assert.assertEquals(2, candidates.size()); + Assert.assertSame(fast.getNode(), candidates.get(0)); + Assert.assertSame(slow.getNode(), candidates.get(1)); + Assert.assertFalse(candidates.contains(foreign.getNode())); + } + + @Test + public void cachedStatusCandidatesUseTheCurrentConfiguredNetwork() throws Exception { + int networkId = Parameter.p2pConfig.getNetworkId(); + NodeStat first = cachedStatus("192.0.2.1", networkId, 1); + NodeStat second = cachedStatus("192.0.2.2", networkId + 1, 1); + + Assert.assertEquals(1, detect.getConnectableNodes().size()); + Assert.assertSame(first.getNode(), detect.getConnectableNodes().get(0)); + + Parameter.p2pConfig.setNetworkId(networkId + 1); + + Assert.assertEquals(1, detect.getConnectableNodes().size()); + Assert.assertSame(second.getNode(), detect.getConnectableNodes().get(0)); + } + @Test public void outboundDetectTimeoutRemovesResult() throws Exception { NodeStat stat = probe((InetSocketAddress) listener.localAddress(), true); @@ -304,8 +369,18 @@ public void channelRead(ChannelHandlerContext ctx, Object msg) { } private NodeStat probe(InetSocketAddress address, boolean expired) throws Exception { + return probe(address, expired, null); + } + + private NodeStat probe(InetSocketAddress address, boolean expired, StatusMessage previous) + throws Exception { NodeStat stat = new NodeStat(new Node(address)); + stat.getNode().setNetworkId(Parameter.p2pConfig.getNetworkId()); stat.setLastDetectTime(System.currentTimeMillis() - (expired ? 3000 : 0)); + stat.setStatusMessage(previous); + if (previous != null) { + stat.setLastSuccessDetectTime(stat.getLastDetectTime() - 1); + } nodeStats().put(address, stat); io.netty.channel.Channel socket = new Bootstrap().group(group).channel(NioSocketChannel.class) .handler(initializer(stat.getNode().getHexId(), true)).connect(address).sync().channel(); @@ -321,6 +396,67 @@ private NodeStat probe(InetSocketAddress address, boolean expired) throws Except return stat; } + private void assertNotDialedFromDiscovery(Node candidate) throws Exception { + Field discovery = NodeManager.class.getDeclaredField("discoverService"); + discovery.setAccessible(true); + Object previous = discovery.get(null); + List dialed = new ArrayList<>(); + try { + discovery.set(null, new KadService() { + @Override + public List getAllNodes() { + return Collections.singletonList(candidate); + } + }); + set(ConnPoolService.class, pool, "peerClient", new PeerClient() { + @Override + public ChannelFuture connectAsync(Node node, boolean nodeDetectMode) { + dialed.add(node); + return null; + } + }); + Parameter.p2pConfig.setMinConnections(1); + Parameter.p2pConfig.setMinActiveConnections(1); + Method connect = ConnPoolService.class.getDeclaredMethod("connect", boolean.class); + connect.setAccessible(true); + + connect.invoke(pool, false); + + Assert.assertTrue(NodeManager.getConnectableNodes().isEmpty()); + Assert.assertTrue(dialed.isEmpty()); + } finally { + discovery.set(null, previous); + } + } + + private NodeStat cachedStatus(String ip, int networkId, int remaining) throws Exception { + NodeStat stat = new NodeStat(new Node(new InetSocketAddress(ip, 18888))); + stat.setStatusMessage(status(networkId, remaining)); + nodeStats().put(stat.getSocketAddress(), stat); + return stat; + } + + private io.netty.channel.Channel statusServer(StatusMessage response) throws Exception { + return new ServerBootstrap().group(group).channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(NioSocketChannel socket) { + socket.pipeline().addLast(new ProtobufVarint32FrameDecoder()); + socket.pipeline().addLast(new ProtobufVarint32LengthFieldPrepender()); + socket.pipeline().addLast(new SimpleChannelInboundHandler() { + @Override + protected void channelRead0(ChannelHandlerContext ctx, ByteBuf frame) + throws Exception { + byte[] data = new byte[frame.readableBytes()]; + frame.readBytes(data); + Assert.assertEquals(MessageType.STATUS, Message.parse(data).getType()); + ctx.writeAndFlush(Unpooled.wrappedBuffer(response.getSendData())); + } + }); + } + }).bind("127.0.0.1", 0).sync().channel(); + } + @SuppressWarnings("unchecked") private Map nodeStats() throws Exception { Field field = NodeDetectService.class.getDeclaredField("nodeStatMap"); @@ -379,8 +515,12 @@ private Discover.Endpoint endpoint() { } private StatusMessage status() throws Exception { + return status(Parameter.p2pConfig.getNetworkId(), 50); + } + + private StatusMessage status(int networkId, int remaining) throws Exception { return new StatusMessage(Connect.StatusMessage.newBuilder().setFrom(endpoint()) - .setNetworkId(Parameter.p2pConfig.getNetworkId()).setMaxConnections(50) + .setNetworkId(networkId).setMaxConnections(50).setCurrentConnections(50 - remaining) .setTimestamp(System.currentTimeMillis()).build().toByteArray()); } diff --git a/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java b/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java index 5d107ed8816..1b28195608e 100644 --- a/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java +++ b/p2p/src/test/java/org/tron/p2p/connection/business/keepalive/KeepAliveServiceTest.java @@ -17,6 +17,7 @@ import org.tron.p2p.connection.message.base.P2pDisconnectMessage; import org.tron.p2p.connection.message.keepalive.PingMessage; import org.tron.p2p.connection.message.keepalive.PongMessage; +import org.tron.p2p.protos.Connect; import org.tron.p2p.protos.Connect.DisconnectReason; /** @@ -30,11 +31,18 @@ public class KeepAliveServiceTest { private static class RecordingChannel extends Channel { final List sent = new ArrayList<>(); + private int closeCount; @Override public void send(Message message) { sent.add(message); } + + @Override + public void close() { + closeCount++; + markDisconnected(); + } } private P2pConfig saved; @@ -67,6 +75,51 @@ public void pingIsAnsweredWithAPong() throws Exception { Assert.assertEquals(1, channel.sent.size()); Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, channel.sent.get(0).getType()); + Assert.assertFalse(channel.isDisconnect()); + } + + @Test + public void inboundPingBurstDisconnectsWithoutPongForRejectedPing() throws Exception { + RecordingChannel channel = channelAt(ADDRESS); + KeepAliveService service = new KeepAliveService(); + try { + // A Guava limiter may have one saved permit after idle, in addition to a fresh permit. + for (int i = 0; i < 3 && !channel.isDisconnect(); i++) { + service.processMessage(channel, new PingMessage()); + } + + Assert.assertTrue("Excess PING must disconnect the peer", channel.isDisconnect()); + Assert.assertEquals(1, channel.closeCount); + int last = channel.sent.size() - 1; + Assert.assertTrue(last >= 1 && last <= 2); + for (int i = 0; i < last; i++) { + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, channel.sent.get(i).getType()); + } + Assert.assertEquals(MessageType.DISCONNECT, channel.sent.get(last).getType()); + Assert.assertEquals(DisconnectReason.BAD_PROTOCOL, + Connect.P2pDisconnectMessage.parseFrom(channel.sent.get(last).getData()).getReason()); + } finally { + service.close(); + } + } + + @Test + public void inboundPingAllowanceIsIndependentForEachConnection() throws Exception { + RecordingChannel channel = channelAt(ADDRESS); + RecordingChannel other = channelAt(ADDRESS); + KeepAliveService service = new KeepAliveService(); + try { + service.processMessage(channel, new PingMessage()); + service.processMessage(other, new PingMessage()); + + Assert.assertEquals(1, channel.sent.size()); + Assert.assertEquals(1, other.sent.size()); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, other.sent.get(0).getType()); + Assert.assertFalse(channel.isDisconnect()); + Assert.assertFalse(other.isDisconnect()); + } finally { + service.close(); + } } @Test diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/OutboundHandshakeTimeoutHandlerTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/OutboundHandshakeTimeoutHandlerTest.java index e80c2ef4d54..25263f503bb 100644 --- a/p2p/src/test/java/org/tron/p2p/connection/socket/OutboundHandshakeTimeoutHandlerTest.java +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/OutboundHandshakeTimeoutHandlerTest.java @@ -157,13 +157,12 @@ public void silentOutboundExpiresAtHelloDeadline() { @Test public void pingTrafficDoesNotExtendHelloDeadline() throws Exception { EmbeddedChannel socket = outbound(REMOTE, false, false); - for (long elapsed = 1; elapsed < Parameter.HANDSHAKE_TIMEOUT_SECONDS; elapsed++) { - advance(socket, 1); - receive(socket, new PingMessage().getSendData()); - Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, - Message.parse(readOutbound(socket)).getType()); - Assert.assertTrue(socket.isOpen()); - } + // Embedded time does not advance the monotonic clock used by the PING rate limit. + advance(socket, Parameter.HANDSHAKE_TIMEOUT_SECONDS - 1); + receive(socket, new PingMessage().getSendData()); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, + Message.parse(readOutbound(socket)).getType()); + Assert.assertTrue(socket.isOpen()); advance(socket, 1); Assert.assertFalse(socket.isOpen()); Assert.assertTrue(ChannelManager.getAllChannels().isEmpty()); diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/P2pPreHandshakeFrameDecoderTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pPreHandshakeFrameDecoderTest.java new file mode 100644 index 00000000000..95cf69fdf35 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pPreHandshakeFrameDecoderTest.java @@ -0,0 +1,203 @@ +package org.tron.p2p.connection.socket; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.message.Message; +import org.tron.p2p.connection.message.MessageType; +import org.tron.p2p.protos.Connect; + +public class P2pPreHandshakeFrameDecoderTest { + + private final List sockets = new ArrayList<>(); + private P2pConfig previousConfig; + + @Before + public void setUp() { + previousConfig = Parameter.p2pConfig; + Parameter.p2pConfig = new P2pConfig(); + } + + @After + public void tearDown() { + try { + sockets.forEach(EmbeddedChannel::finishAndReleaseAll); + } finally { + Parameter.p2pConfig = previousConfig; + } + } + + @Test + public void oversizedPreHandshakeDeclarationIsRejectedBeforeReceivingPayload() throws Exception { + for (int length : new int[]{Parameter.MAX_PRE_HANDSHAKE_LENGTH, + Parameter.MAX_PRE_HANDSHAKE_LENGTH + 1, Parameter.MAX_MESSAGE_LENGTH - 1}) { + TestChannel peer = newPeer(); + EmbeddedChannel socket = sockets.get(sockets.size() - 1); + ByteBuf declaration = frameLength(length); + + Assert.assertFalse(socket.writeInbound(declaration)); + + assertBadMessage(peer, socket); + Assert.assertEquals(0, declaration.refCnt()); + } + } + + @Test + public void incompleteLengthPrefixIsCheckedWhenTheDeclarationCompletes() throws Exception { + TestChannel peer = newPeer(); + EmbeddedChannel socket = sockets.get(0); + + Assert.assertFalse(socket.writeInbound(Unpooled.wrappedBuffer(new byte[]{(byte) 0x80}))); + Assert.assertTrue(socket.isActive()); + Assert.assertNull(peer.rejection); + + Assert.assertFalse(socket.writeInbound(Unpooled.wrappedBuffer(new byte[]{8}))); + + assertBadMessage(peer, socket); + } + + @Test + public void framesBelowPreHandshakeLimitAreDecoded() { + newPeer(); + EmbeddedChannel socket = sockets.get(0); + int length = Parameter.MAX_PRE_HANDSHAKE_LENGTH - 1; + + Assert.assertTrue(socket.writeInbound(frame(length))); + + assertDecodedLength(socket, length); + Assert.assertTrue(socket.isActive()); + } + + @Test + public void trustedPeersStillHaveThePreHandshakeFrameLimit() throws Exception { + Parameter.p2pConfig.getTrustNodes().add(new InetSocketAddress("127.0.0.2", 18888).getAddress()); + TestChannel peer = newPeer(); + EmbeddedChannel socket = sockets.get(0); + Assert.assertTrue(peer.isTrustPeer()); + + Assert.assertFalse(socket.writeInbound(frameLength(Parameter.MAX_PRE_HANDSHAKE_LENGTH))); + + assertBadMessage(peer, socket); + } + + @Test + public void completedHandshakeUsesTheExistingFrameLimit() throws Exception { + TestChannel peer = newPeer(); + EmbeddedChannel socket = sockets.get(0); + peer.setFinishHandshake(true); + int length = Parameter.MAX_PRE_HANDSHAKE_LENGTH + 1; + + Assert.assertTrue(socket.writeInbound(frame(length))); + + assertDecodedLength(socket, length); + Assert.assertTrue(socket.isActive()); + Assert.assertFalse(socket.writeInbound(frameLength(Parameter.MAX_MESSAGE_LENGTH))); + assertBadMessage(peer, socket); + } + + @Test + public void handshakeCompletionAppliesToTheNextFrameInTheSameReadBatch() { + TestChannel peer = newPeer(); + EmbeddedChannel socket = sockets.get(0); + AtomicInteger frames = new AtomicInteger(); + socket.pipeline().addLast(new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + if (frames.incrementAndGet() == 1) { + peer.setFinishHandshake(true); + } + ctx.fireChannelRead(msg); + } + }); + ByteBuf batch = frame(1); + ByteBuf next = frame(Parameter.MAX_PRE_HANDSHAKE_LENGTH + 1); + try { + batch.writeBytes(next); + } finally { + next.release(); + } + + Assert.assertTrue(socket.writeInbound(batch)); + + Assert.assertEquals(2, frames.get()); + assertDecodedLength(socket, 1); + assertDecodedLength(socket, Parameter.MAX_PRE_HANDSHAKE_LENGTH + 1); + Assert.assertTrue(socket.isActive()); + } + + private TestChannel newPeer() { + TestChannel peer = new TestChannel(); + EmbeddedChannel socket = new EmbeddedChannel(new P2pProtobufVarint32FrameDecoder(peer)) { + @Override + protected SocketAddress remoteAddress0() { + return new InetSocketAddress("127.0.0.2", 18888); + } + }; + sockets.add(socket); + peer.setChannelHandlerContext(socket.pipeline().firstContext()); + return peer; + } + + private ByteBuf frameLength(int length) { + ByteBuf bytes = Unpooled.buffer(); + while ((length & ~0x7f) != 0) { + bytes.writeByte((length & 0x7f) | 0x80); + length >>>= 7; + } + bytes.writeByte(length); + return bytes; + } + + private ByteBuf frame(int length) { + return frameLength(length).writeZero(length); + } + + private void assertDecodedLength(EmbeddedChannel socket, int length) { + ByteBuf decoded = socket.readInbound(); + Assert.assertNotNull(decoded); + try { + Assert.assertEquals(length, decoded.readableBytes()); + } finally { + decoded.release(); + } + } + + private void assertBadMessage(TestChannel peer, EmbeddedChannel socket) throws Exception { + Assert.assertTrue(peer.isDisconnect()); + Assert.assertFalse(socket.isActive()); + Assert.assertNotNull(peer.rejection); + Assert.assertEquals(MessageType.DISCONNECT, peer.rejection.getType()); + Assert.assertEquals(Connect.DisconnectReason.BAD_MESSAGE, + Connect.P2pDisconnectMessage.parseFrom(peer.rejection.getData()).getReason()); + Assert.assertNull(socket.readInbound()); + } + + private static class TestChannel extends Channel { + private Message rejection; + + @Override + public void send(Message message) { + rejection = message; + } + + @Override + public void close() { + markDisconnected(); + getCtx().close(); + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/P2pRecvByteBufAllocatorTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pRecvByteBufAllocatorTest.java new file mode 100644 index 00000000000..46d069d2aaa --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/P2pRecvByteBufAllocatorTest.java @@ -0,0 +1,327 @@ +package org.tron.p2p.connection.socket; + +import com.google.protobuf.ByteString; +import io.netty.bootstrap.ServerBootstrap; +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.ChannelInitializer; +import io.netty.channel.RecvByteBufAllocator; +import io.netty.channel.nio.NioEventLoopGroup; +import io.netty.channel.socket.nio.NioServerSocketChannel; +import io.netty.channel.socket.nio.NioSocketChannel; +import io.netty.handler.codec.ByteToMessageDecoder; +import java.io.ByteArrayOutputStream; +import java.lang.reflect.Field; +import java.net.InetAddress; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.tron.p2p.P2pConfig; +import org.tron.p2p.P2pEventHandler; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.p2p.connection.ChannelManager; +import org.tron.p2p.connection.business.handshake.DisconnectCode; +import org.tron.p2p.connection.business.handshake.HandshakeService; +import org.tron.p2p.connection.message.handshake.HelloMessage; +import org.tron.p2p.protos.Connect; +import org.tron.p2p.protos.Discover; + +public class P2pRecvByteBufAllocatorTest { + + private final BlockingQueue connections = new LinkedBlockingQueue<>(); + private final BlockingQueue reads = new LinkedBlockingQueue<>(); + private final BlockingQueue messages = new LinkedBlockingQueue<>(); + private final CountDownLatch inactive = new CountDownLatch(1); + private NioEventLoopGroup group; + private io.netty.channel.Channel server; + private NioSocketChannel accepted; + private Socket client; + private P2pConfig previousConfig; + private List previousHandlers; + private Map previousHandlerMap; + private Map previousBans; + private Object previousHandshakeService; + + @Before + public void setUp() throws Exception { + previousConfig = Parameter.p2pConfig; + previousHandlers = Parameter.handlerList; + previousHandlerMap = Parameter.handlerMap; + previousBans = new HashMap<>(ChannelManager.getBannedNodes().asMap()); + Parameter.p2pConfig = new P2pConfig(); + Parameter.p2pConfig.setIp("127.0.0.1"); + Parameter.p2pConfig.setIpv6(""); + Parameter.p2pConfig.setNodeID(new byte[64]); + Parameter.handlerList = new ArrayList<>(); + Parameter.handlerMap = new HashMap<>(); + ChannelManager.getBannedNodes().invalidateAll(); + previousHandshakeService = setHandshakeService(new HandshakeService()); + Parameter.addP2pEventHandle(new P2pEventHandler() { + { + messageTypes = Collections.singleton((byte) 1); + } + + @Override + public void onMessage(Channel channel, byte[] data) { + messages.add(data); + } + }); + } + + @After + public void tearDown() throws Exception { + try { + if (client != null) { + client.close(); + } + if (accepted != null) { + accepted.close().syncUninterruptibly(); + } + if (server != null) { + server.close().syncUninterruptibly(); + } + if (group != null) { + group.shutdownGracefully(0, 5, TimeUnit.SECONDS).syncUninterruptibly(); + } + Field count = PendingInboundConnectionHandler.class.getDeclaredField("pendingConnections"); + count.setAccessible(true); + Assert.assertEquals("Pending reservation leaked", 0, count.getInt(null)); + Assert.assertTrue(ChannelManager.getAllChannels().isEmpty()); + } finally { + Parameter.p2pConfig = previousConfig; + Parameter.handlerList = previousHandlers; + Parameter.handlerMap = previousHandlerMap; + ChannelManager.getBannedNodes().invalidateAll(); + ChannelManager.getBannedNodes().putAll(previousBans); + setHandshakeService(previousHandshakeService); + } + } + + @Test(timeout = 20000) + public void incompleteLengthPrefixUsesSmallReceiveBufferAndExpires() throws Exception { + connect(); + + Assert.assertEquals(1024, send(new byte[]{(byte) 0x80}).get(0).capacity); + ByteBuf buffer = retainedFrameBuffer(); + Assert.assertEquals(1, buffer.readableBytes()); + Assert.assertEquals(1024, buffer.capacity()); + Assert.assertEquals(1, buffer.refCnt()); + Assert.assertTrue(accepted.isActive()); + + awaitInactive(Parameter.HANDSHAKE_TIMEOUT_SECONDS + 2); + Assert.assertEquals(0, buffer.refCnt()); + } + + @Test(timeout = 10000) + public void incompletePayloadUsesSmallReceiveBuffer() throws Exception { + assertIncompletePayloadUsesSmallReceiveBuffer(); + } + + @Test(timeout = 10000) + public void trustedConnectionsAlsoUseSmallReceiveBuffers() throws Exception { + Parameter.p2pConfig.getTrustNodes().add(InetAddress.getByName("127.0.0.1")); + assertIncompletePayloadUsesSmallReceiveBuffer(); + } + + private void assertIncompletePayloadUsesSmallReceiveBuffer() throws Exception { + connect(); + + Assert.assertEquals(1024, send(new byte[]{(byte) 0x80, 4, 1}).get(0).capacity); + ByteBuf buffer = retainedFrameBuffer(); + Assert.assertEquals(3, buffer.readableBytes()); + Assert.assertEquals(1024, buffer.capacity()); + Assert.assertTrue(accepted.isActive()); + + send(new byte[]{1}); + Assert.assertSame(buffer, retainedFrameBuffer()); + Assert.assertEquals(4, buffer.readableBytes()); + accepted.close().sync(); + awaitInactive(3); + Assert.assertEquals(0, buffer.refCnt()); + } + + @Test(timeout = 10000) + public void fragmentedFrameNearLimitKeepsCumulationSmall() throws Exception { + connect(); + // A padded five-byte varint declaring 1023 bytes, followed by an incomplete payload. + send(new byte[]{(byte) 0xff, (byte) 0x87, (byte) 0x80, (byte) 0x80}); + for (ReadEvent read : send(new byte[1023])) { + Assert.assertEquals(1024, read.capacity); + } + + ByteBuf buffer = retainedFrameBuffer(); + Assert.assertEquals(1027, buffer.readableBytes()); + // Merging fragments can grow beyond one read buffer, including varint overhead. + Assert.assertTrue(buffer.capacity() <= 4096); + Assert.assertTrue(accepted.isActive()); + accepted.close().sync(); + awaitInactive(3); + Assert.assertEquals(0, buffer.refCnt()); + } + + @Test(timeout = 10000) + public void oversizedDeclarationStillClosesAndReleases() throws Exception { + connect(); + send(new byte[]{(byte) 0x80}); + ByteBuf buffer = retainedFrameBuffer(); + + send(new byte[]{8}); + + awaitInactive(3); + Assert.assertEquals(0, buffer.refCnt()); + } + + @Test(timeout = 10000) + public void cachedReceiveHandleGrowsAfterHelloAndAcceptsLargerFrames() throws Exception { + connect(); + byte[] hello = frame(hello()); + send(Arrays.copyOf(hello, 1)); + RecvByteBufAllocator.Handle handle = accepted.eventLoop().submit( + () -> accepted.unsafe().recvBufAllocHandle()).get(); + Assert.assertEquals(1024, handle.guess()); + + byte[] payload = new byte[4096]; + payload[0] = 1; + ByteArrayOutputStream batch = new ByteArrayOutputStream(); + batch.write(hello, 1, hello.length - 1); + batch.write(frame(payload)); + + List batchReads = send(batch.toByteArray()); + + Assert.assertArrayEquals(payload, messages.poll(3, TimeUnit.SECONDS)); + Assert.assertEquals(1024, batchReads.get(0).capacity); + Assert.assertTrue(batchReads.stream().anyMatch(read -> read.capacity == 256 * 1024)); + Assert.assertSame(handle, accepted.eventLoop().submit( + () -> accepted.unsafe().recvBufAllocHandle()).get()); + Assert.assertEquals(256 * 1024, handle.guess()); + Assert.assertEquals(1, ChannelManager.getChannelCount()); + Assert.assertTrue(ChannelManager.getAllChannels().get(0).isFinishHandshake()); + Assert.assertNull(accepted.pipeline().get(PendingInboundConnectionHandler.class)); + Assert.assertTrue(accepted.isActive()); + } + + private void connect() throws Exception { + group = new NioEventLoopGroup(1); + server = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class) + .childHandler(new ChannelInitializer() { + @Override + protected void initChannel(NioSocketChannel socket) { + new P2pChannelInitializer("", false, false).initChannel(socket); + socket.pipeline().addBefore("protoDecode", "captureReceiveCapacity", + new ChannelInboundHandlerAdapter() { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ByteBuf buffer = (ByteBuf) msg; + ReadEvent read = new ReadEvent(buffer.capacity(), buffer.readableBytes()); + ctx.fireChannelRead(msg); + // Observe the real receive allocation without retaining the buffer. + reads.add(read); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + ctx.fireChannelInactive(); + // closeFuture can complete before the decoder releases its cumulation. + inactive.countDown(); + } + }); + connections.add(socket); + } + }).bind("127.0.0.1", 0).sync().channel(); + client = new Socket(); + client.connect(server.localAddress(), 3000); + accepted = connections.poll(5, TimeUnit.SECONDS); + Assert.assertNotNull("Server did not initialize the connection", accepted); + accepted.eventLoop().submit(() -> { }).sync(); + } + + private List send(byte[] bytes) throws Exception { + client.getOutputStream().write(bytes); + client.getOutputStream().flush(); + List result = new ArrayList<>(); + int received = 0; + while (received < bytes.length) { + ReadEvent read = reads.poll(3, TimeUnit.SECONDS); + Assert.assertNotNull("Socket did not read all the supplied bytes", read); + received += read.length; + result.add(read); + } + Assert.assertEquals(bytes.length, received); + accepted.eventLoop().submit(() -> { }).sync(); + return result; + } + + private ByteBuf retainedFrameBuffer() throws Exception { + Field field = ByteToMessageDecoder.class.getDeclaredField("cumulation"); + field.setAccessible(true); + return accepted.eventLoop().submit(() -> (ByteBuf) field.get( + accepted.pipeline().get(P2pProtobufVarint32FrameDecoder.class))).get(); + } + + private void awaitInactive(int timeoutSeconds) throws Exception { + Assert.assertTrue("Decoder did not finish closing", + inactive.await(timeoutSeconds, TimeUnit.SECONDS)); + Assert.assertFalse(accepted.isActive()); + } + + private byte[] hello() throws Exception { + byte[] id = new byte[64]; + id[0] = 1; + Discover.Endpoint endpoint = Discover.Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(id)) + .setAddress(ByteString.copyFromUtf8("127.0.0.1")) + .setPort(18888) + .build(); + return new HelloMessage(Connect.HelloMessage.newBuilder() + .setFrom(endpoint) + .setNetworkId(Parameter.p2pConfig.getNetworkId()) + .setVersion(0) + .setCode(DisconnectCode.NORMAL.getValue()) + .setTimestamp(System.currentTimeMillis()) + .build().toByteArray()).getSendData(); + } + + private byte[] frame(byte[] payload) { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + int length = payload.length; + while ((length & ~0x7f) != 0) { + bytes.write((length & 0x7f) | 0x80); + length >>>= 7; + } + bytes.write(length); + bytes.write(payload, 0, payload.length); + return bytes.toByteArray(); + } + + private Object setHandshakeService(Object service) throws Exception { + Field field = ChannelManager.class.getDeclaredField("handshakeService"); + field.setAccessible(true); + Object previous = field.get(null); + field.set(null, service); + return previous; + } + + private static class ReadEvent { + private final int capacity; + private final int length; + + private ReadEvent(int capacity, int length) { + this.capacity = capacity; + this.length = length; + } + } +} diff --git a/p2p/src/test/java/org/tron/p2p/connection/socket/PendingInboundConnectionHandlerTest.java b/p2p/src/test/java/org/tron/p2p/connection/socket/PendingInboundConnectionHandlerTest.java index b30131a6bca..3725b3ee3c9 100644 --- a/p2p/src/test/java/org/tron/p2p/connection/socket/PendingInboundConnectionHandlerTest.java +++ b/p2p/src/test/java/org/tron/p2p/connection/socket/PendingInboundConnectionHandlerTest.java @@ -146,7 +146,7 @@ public void tearDown() throws Exception { public void ordinaryPendingLimitIsIndependentOfPeerLimit() { config.setMaxConnections(0); for (int i = 0; i < Parameter.MAX_PENDING_INBOUND_CONNECTIONS; i++) { - Assert.assertTrue(inbound("192.0.2." + (i + 1)).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i + 1)).isOpen()); } Assert.assertFalse(inbound("198.51.100.1").isOpen()); Assert.assertTrue(ChannelManager.getAllChannels().isEmpty()); @@ -185,8 +185,8 @@ public void ordinarySaturationDoesNotBlockTrustedInboundConnections() throws Exc InetAddress trusted = InetAddress.getByName("198.51.100.1"); config.getTrustNodes().add(trusted); for (int i = 1; i <= Parameter.MAX_PENDING_INBOUND_CONNECTIONS / 2; i++) { - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); } Assert.assertFalse(inbound("203.0.113.1").isOpen()); Assert.assertTrue(inbound(trusted.getHostAddress()).isOpen()); @@ -194,9 +194,9 @@ public void ordinarySaturationDoesNotBlockTrustedInboundConnections() throws Exc @Test public void trustedPendingConnectionsCountTowardOrdinaryThreshold() throws Exception { - fillTrustedPending(28); + fillTrustedPending(Parameter.MAX_PENDING_INBOUND_CONNECTIONS - 4); for (int i = 1; i <= 4; i++) { - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); } Assert.assertFalse(inbound("203.0.113.1").isOpen()); } @@ -204,7 +204,7 @@ public void trustedPendingConnectionsCountTowardOrdinaryThreshold() throws Excep @Test public void trustedConnectionsUseHigherTotalPendingLimit() throws Exception { for (int i = 1; i <= Parameter.MAX_PENDING_INBOUND_CONNECTIONS; i++) { - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); } fillTrustedPending(Parameter.MAX_TOTAL_PENDING_INBOUND_CONNECTIONS - Parameter.MAX_PENDING_INBOUND_CONNECTIONS); @@ -274,7 +274,7 @@ public void concurrentReservationsRespectOrdinaryPendingThreshold() throws Excep @Test(timeout = 20000) public void concurrentTrustedReservationsRespectTotalLimit() throws Exception { for (int i = 0; i < Parameter.MAX_PENDING_INBOUND_CONNECTIONS * 2; i++) { - config.getTrustNodes().add(InetAddress.getByName("192.0.2." + (i + 1))); + config.getTrustNodes().add(InetAddress.getByName(testIp("192.0", i + 1))); } assertConcurrentLimit(false, Parameter.MAX_TOTAL_PENDING_INBOUND_CONNECTIONS); } @@ -319,20 +319,49 @@ public void repeatedActivationDoesNotRestartDeadline() { public void pingTrafficCannotExtendHandshakeDeadline() throws Exception { EmbeddedChannel socket = inbound(REMOTE_IP); Channel channel = initializeProtocol(socket); - for (int i = 0; i < 3; i++) { - advance(socket, 3); - receive(socket, new PingMessage().getSendData()); - Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, - Message.parse(readOutbound(socket)).getType()); - Assert.assertTrue(socket.isOpen()); - Assert.assertFalse(channel.isFinishHandshake()); - } + // Embedded time does not advance the monotonic clock used by the PING rate limit. + advance(socket, Parameter.HANDSHAKE_TIMEOUT_SECONDS - 1); + receive(socket, new PingMessage().getSendData()); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, + Message.parse(readOutbound(socket)).getType()); + Assert.assertTrue(socket.isOpen()); + Assert.assertFalse(channel.isFinishHandshake()); advance(socket, 1); Assert.assertFalse(socket.isOpen()); Assert.assertTrue(ChannelManager.getAllChannels().isEmpty()); Assert.assertEquals(0, connectCallbacks); } + @Test + public void pingBurstClosesConnectionAndReleasesPendingReservation() throws Exception { + EmbeddedChannel socket = inbound(REMOTE_IP); + Channel channel = initializeProtocol(socket); + receive(socket, new PingMessage().getSendData()); + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, + Message.parse(readOutbound(socket)).getType()); + + Message response = null; + // Allow Guava's saved idle permit, but stop immediately when the connection closes. + for (int i = 0; i < 2 && socket.isOpen(); i++) { + receive(socket, new PingMessage().getSendData()); + response = Message.parse(readOutbound(socket)); + if (socket.isOpen()) { + Assert.assertEquals(MessageType.KEEP_ALIVE_PONG, response.getType()); + } + } + + Assert.assertFalse(socket.isOpen()); + Assert.assertTrue(channel.isDisconnect()); + Assert.assertNotNull(response); + Assert.assertEquals(MessageType.DISCONNECT, response.getType()); + Assert.assertEquals(Connect.DisconnectReason.BAD_PROTOCOL, + Connect.P2pDisconnectMessage.parseFrom(response.getData()).getReason()); + Field count = PendingInboundConnectionHandler.class.getDeclaredField("pendingConnections"); + count.setAccessible(true); + Assert.assertEquals(0, count.getInt(null)); + Assert.assertEquals(0, connectCallbacks); + } + @Test public void pongTrafficCannotExtendHandshakeDeadline() { EmbeddedChannel socket = inbound(REMOTE_IP); @@ -348,8 +377,8 @@ public void pongTrafficCannotExtendHandshakeDeadline() { public void partialFrameTrafficCannotExtendHandshakeDeadline() { EmbeddedChannel socket = inbound(REMOTE_IP); initializeProtocol(socket); - // A valid length prefix for 1024 bytes, with an incomplete payload. - ByteBuf partial = Unpooled.wrappedBuffer(new byte[]{(byte) 0x80, 8, 1}); + // A valid length prefix for 512 bytes, with an incomplete payload. + ByteBuf partial = Unpooled.wrappedBuffer(new byte[]{(byte) 0x80, 4, 1}); socket.writeInbound(partial); for (int i = 0; i < 3; i++) { advance(socket, 3); @@ -568,6 +597,7 @@ public void outboundAndNodeDetectInitializationDoNotConsumeInboundQuota() throws Assert.assertTrue(socket.isOpen()); Assert.assertNull(socket.pipeline().get(PendingInboundConnectionHandler.class)); Assert.assertNotNull(socket.pipeline().get(MessageHandler.class)); + Assert.assertEquals(1024, socket.config().getRecvByteBufAllocator().newHandle().guess()); } Assert.assertFalse(inbound(REMOTE_IP).isOpen()); } @@ -575,7 +605,7 @@ public void outboundAndNodeDetectInitializationDoNotConsumeInboundQuota() throws @Test(timeout = 20000) public void bannedPeerReceivesHelloWithoutReservingCapacity() throws Exception { for (int i = 1; i <= Parameter.MAX_PENDING_INBOUND_CONNECTIONS; i++) { - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); } InetAddress address = InetAddress.getByName("127.0.0.1"); ChannelManager.banNode(address, TimeUnit.MINUTES.toMillis(1)); @@ -587,7 +617,7 @@ public void bannedPeerReceivesHelloWithoutReservingCapacity() throws Exception { @Test(timeout = 20000) public void ordinaryPendingThresholdReturnsTooManyPeers() throws Exception { for (int i = 1; i <= Parameter.MAX_PENDING_INBOUND_CONNECTIONS; i++) { - Assert.assertTrue(inbound("192.0.2." + i).isOpen()); + Assert.assertTrue(inbound(testIp("192.0", i)).isOpen()); } assertAdmissionRejection(DisconnectCode.TOO_MANY_PEERS); } @@ -809,12 +839,16 @@ private NioSocketChannel connectClient(io.netty.channel.Channel server, List> results = new ArrayList<>(); try { for (int i = 0; i < Parameter.MAX_PENDING_INBOUND_CONNECTIONS * 2; i++) { - String ip = sameIp ? REMOTE_IP : "192.0.2." + (i + 1); + String ip = sameIp ? REMOTE_IP : testIp("192.0", i + 1); results.add(executor.submit(() -> { Assert.assertTrue(start.await(5, TimeUnit.SECONDS)); return inbound(ip).isOpen(); diff --git a/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderRejectionTest.java b/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderRejectionTest.java new file mode 100644 index 00000000000..a5527bac076 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/discover/socket/P2pPacketDecoderRejectionTest.java @@ -0,0 +1,103 @@ +package org.tron.p2p.discover.socket; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import com.google.protobuf.ByteString; +import io.netty.buffer.Unpooled; +import io.netty.channel.embedded.EmbeddedChannel; +import io.netty.channel.socket.DatagramPacket; +import java.net.InetSocketAddress; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import org.junit.After; +import org.junit.Test; +import org.tron.p2p.base.Constant; +import org.tron.p2p.discover.message.MessageType; +import org.tron.p2p.discover.message.kad.PingMessage; +import org.tron.p2p.protos.Discover; +import org.tron.p2p.utils.ByteArray; + +public class P2pPacketDecoderRejectionTest { + + private static final InetSocketAddress LOCAL = new InetSocketAddress("127.0.0.1", 18888); + private static final InetSocketAddress PEER = new InetSocketAddress("127.0.0.1", 18889); + private final EmbeddedChannel channel = new EmbeddedChannel(new P2pPacketDecoder()); + + @After + public void tearDown() { + channel.finishAndReleaseAll(); + } + + @Test + public void dropsInvalidPacketsAndForwardsValidPing() throws Exception { + byte[] ping = validPing(); + byte[] missingEndpoint = new PingMessage(Discover.PingMessage.newBuilder() + .setTimestamp(1).build().toByteArray()).getSendData(); + + assertFalse(channel.writeInbound(packet(new byte[0]))); + assertFalse(channel.writeInbound(packet(new byte[1]))); + assertFalse(channel.writeInbound(packet(new byte[Constant.MAX_DISCOVERY_PACKET_SIZE]))); + assertFalse(channel.writeInbound(packet(new byte[] {(byte) 0xff, 0}))); + assertFalse(channel.writeInbound(packet(Arrays.copyOf(ping, ping.length - 1)))); + assertFalse(channel.writeInbound(packet(missingEndpoint))); + + assertTrue(channel.writeInbound(packet(ping))); + UdpEvent event = channel.readInbound(); + assertEquals(PEER, event.getAddress()); + assertEquals(MessageType.KAD_PING, event.getMessage().getType()); + assertArrayEquals(ping, event.getMessage().getSendData()); + } + + @Test + public void previewAddsEllipsisOnlyBeyond128Bytes() { + byte[] data = new byte[129]; + for (int i = 0; i < data.length; i++) { + data[i] = (byte) i; + } + String hex = ByteArray.toHexString(data); + assertEquals(hex.substring(0, 254), P2pPacketDecoder.dataPreview(Arrays.copyOf(data, 127))); + assertEquals(hex.substring(0, 256), P2pPacketDecoder.dataPreview(Arrays.copyOf(data, 128))); + assertEquals(hex.substring(0, 256) + "...", P2pPacketDecoder.dataPreview(data)); + } + + @Test + public void countsSuppressedSamplesPerCounter() { + P2pPacketDecoder.DropCounter first = new P2pPacketDecoder.DropCounter(); + P2pPacketDecoder.DropCounter second = new P2pPacketDecoder.DropCounter(); + + assertTrue(first.trySample()); + assertFalse(first.trySample()); + assertTrue(second.trySample()); + assertFalse(first.trySample()); + + assertEquals(3, first.totalWhileEnabled); + assertEquals(2, first.suppressed); + assertEquals(1, second.totalWhileEnabled); + assertEquals(0, second.suppressed); + } + + @Test + public void removingDecoderCancelsPeriodicSummary() { + channel.freezeTime(); + channel.advanceTimeBy(1, TimeUnit.MINUTES); + assertTrue(channel.runScheduledPendingTasks() > 0); + channel.pipeline().remove(P2pPacketDecoder.class); + assertEquals(-1L, channel.runScheduledPendingTasks()); + } + + private static byte[] validPing() throws Exception { + Discover.Endpoint from = Discover.Endpoint.newBuilder() + .setNodeId(ByteString.copyFrom(new byte[64])) + .setAddress(ByteString.copyFromUtf8("127.0.0.1")) + .setPort(PEER.getPort()).build(); + return new PingMessage(Discover.PingMessage.newBuilder().setFrom(from).build() + .toByteArray()).getSendData(); + } + + private static DatagramPacket packet(byte[] bytes) { + return new DatagramPacket(Unpooled.wrappedBuffer(bytes), LOCAL, PEER); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java b/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java index 97d92de3b3d..e0ac296b6aa 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java +++ b/p2p/src/test/java/org/tron/p2p/dns/AwsRoute53Test.java @@ -24,13 +24,21 @@ import software.amazon.awssdk.services.route53.Route53Client; import software.amazon.awssdk.services.route53.model.Change; import software.amazon.awssdk.services.route53.model.ChangeAction; +import software.amazon.awssdk.services.route53.model.ChangeInfo; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsRequest; +import software.amazon.awssdk.services.route53.model.ChangeResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.ChangeStatus; +import software.amazon.awssdk.services.route53.model.GetChangeRequest; +import software.amazon.awssdk.services.route53.model.GetChangeResponse; import software.amazon.awssdk.services.route53.model.HostedZone; import software.amazon.awssdk.services.route53.model.ListHostedZonesByNameResponse; import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsRequest; import software.amazon.awssdk.services.route53.model.ListResourceRecordSetsResponse; +import software.amazon.awssdk.services.route53.model.NoSuchHostedZoneException; import software.amazon.awssdk.services.route53.model.RRType; import software.amazon.awssdk.services.route53.model.ResourceRecord; import software.amazon.awssdk.services.route53.model.ResourceRecordSet; +import software.amazon.awssdk.services.route53.model.Route53Exception; public class AwsRoute53Test { @@ -38,6 +46,190 @@ public class AwsRoute53Test { private static final String MIXED_DOMAIN = "Nodes.Example.INVALID."; private static final String ZONE_ID = "ZTEST"; + @Test + public void testConnectChecksOnlyConfiguredZoneWithOneRecord() throws Exception { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + client.zoneFailure = Route53Exception.builder().statusCode(403).message("AccessDenied").build(); + client.recordsTruncated = true; + + client.testConnect(); + + Assert.assertEquals(0, client.zoneQueries); + Assert.assertEquals(1, client.recordQueries); + Assert.assertEquals(ZONE_ID, client.requestedZone); + Assert.assertEquals("1", client.requestedMaxItems); + Assert.assertTrue(client.changes.isEmpty()); + } + + @Test + public void testConnectPropagatesConfiguredZoneReadFailures() throws Exception { + for (RuntimeException failure : new RuntimeException[]{ + Route53Exception.builder().statusCode(403).message("AccessDenied").build(), + Route53Exception.builder().statusCode(403).message("InvalidClientTokenId").build(), + NoSuchHostedZoneException.builder().message("NoSuchHostedZone").build()}) { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + client.recordFailure = failure; + + Assert.assertSame(failure, Assert.assertThrows(RuntimeException.class, client::testConnect)); + Assert.assertEquals(0, client.zoneQueries); + Assert.assertEquals(1, client.recordQueries); + Assert.assertEquals(ZONE_ID, client.requestedZone); + Assert.assertEquals("1", client.requestedMaxItems); + } + } + + @Test + public void testConnectListsZonesWhenZoneIdIsMissing() throws Exception { + for (String zoneId : new String[]{null, ""}) { + RecordingAwsClient client = new RecordingAwsClient(zoneId); + + client.testConnect(); + + Assert.assertEquals(1, client.zoneQueries); + Assert.assertEquals(0, client.recordQueries); + Assert.assertTrue(client.changes.isEmpty()); + } + } + + @Test + public void testConnectPropagatesListingFailureWhenZoneIdIsMissing() throws Exception { + RecordingAwsClient client = new RecordingAwsClient(null); + client.zoneFailure = Route53Exception.builder().statusCode(403).message("AccessDenied").build(); + + Assert.assertSame(client.zoneFailure, + Assert.assertThrows(Route53Exception.class, client::testConnect)); + Assert.assertEquals(1, client.zoneQueries); + Assert.assertEquals(0, client.recordQueries); + } + + @Test + public void rootFollowsDependenciesAndPrecedesDeletesAcrossBatches() throws Exception { + List nodes = new ArrayList<>(); + for (int i = 1; i <= 1025; i++) { + nodes.add(new DnsNode(null, "10.0." + (i >> 8) + "." + (i & 255), null, 18888)); + } + Tree tree = new Tree(); + tree.makeTree(1, Tree.merge(nodes, 5), Collections.emptyList(), AlgorithmTest.privateKey); + Map records = tree.toTXT(DOMAIN); + + for (boolean rootExists : new boolean[]{false, true}) { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + Map existing = new HashMap<>(); + if (rootExists) { + Tree old = TreeTest.signedTree(new Tree(), "192.0.2.1"); + existing.put(DOMAIN, new RecordSet(new String[]{"\"verification=abc\"", + "\"" + old.getRootEntry().toFormat() + "\""}, Publish.rootTTL)); + String dependency = records.keySet().stream().filter(name -> name.compareTo(DOMAIN) > 0) + .findFirst().get(); + existing.put(dependency, new RecordSet(new String[]{records.get(dependency)}, 0)); + existing.put("stale." + DOMAIN, + new RecordSet(new String[]{"old TXT"}, Publish.treeNodeTTL)); + } + List changes = client.computeChanges(DOMAIN, records, existing); + + boolean rootSeen = false; + for (Change change : changes) { + if (change.resourceRecordSet().name().equals(DOMAIN)) { + rootSeen = true; + Assert.assertEquals(rootExists ? ChangeAction.UPSERT : ChangeAction.CREATE, + change.action()); + } else if (change.action() == ChangeAction.DELETE) { + Assert.assertTrue("Old records must be deleted after the root changes", rootSeen); + } else { + Assert.assertFalse("Dependencies must be published before the root", rootSeen); + } + } + Assert.assertTrue(rootSeen); + + client.failBatch = 2; + client.submitBatches = true; + Assert.assertThrows(Route53Exception.class, () -> client.submitChanges(changes, "test")); + Assert.assertEquals(1, client.batches.size()); + Assert.assertTrue(client.batches.get(0).stream().noneMatch(change -> + change.resourceRecordSet().name().equals(DOMAIN) + || change.action() == ChangeAction.DELETE)); + } + } + + @Test + public void batchesAreSubmittedBeforeWaitingForInsync() throws Exception { + for (ChangeAction rootAction : new ChangeAction[]{ChangeAction.CREATE, ChangeAction.UPSERT}) { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + client.submitBatches = true; + client.pendingPolls = 1; + + client.submitChanges(changesAcrossBatches(client, rootAction), "test"); + + Assert.assertEquals(Arrays.asList("submit /change/CTEST1", "submit /change/CTEST2", + "PENDING /change/CTEST1", "INSYNC /change/CTEST1", "INSYNC /change/CTEST2"), + client.events); + Assert.assertEquals(2, client.batches.size()); + Assert.assertTrue(client.batches.get(0).stream().noneMatch(change -> + change.resourceRecordSet().name().equals(DOMAIN) + || change.action() == ChangeAction.DELETE)); + Assert.assertTrue(client.batches.get(1).stream().anyMatch(change -> + change.resourceRecordSet().name().equals(DOMAIN) && change.action() == rootAction)); + Assert.assertTrue(client.batches.get(1).stream().anyMatch(change -> + change.action() == ChangeAction.DELETE)); + } + } + + @Test + public void pendingAtRetryLimitFailsPublication() throws Exception { + for (int pendingBatch : new int[]{1, 2}) { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + client.submitBatches = true; + client.pendingBatch = pendingBatch; + client.pendingPolls = AwsClient.maxRetryLimit; + + IllegalStateException failure = Assert.assertThrows(IllegalStateException.class, + () -> client.submitChanges(changesAcrossBatches(client, ChangeAction.CREATE), "test")); + + Assert.assertTrue(failure.getMessage().contains("Timed out")); + Assert.assertTrue(failure.getMessage().contains("/change/CTEST" + pendingBatch)); + Assert.assertEquals(2, client.batches.size()); + Assert.assertEquals(AwsClient.maxRetryLimit, client.events.stream() + .filter(event -> event.equals("PENDING /change/CTEST" + pendingBatch)).count()); + } + } + + @Test + public void interruptedWaitPreservesInterruptAndStopsPolling() throws Exception { + RecordingAwsClient client = new RecordingAwsClient(ZONE_ID); + client.submitBatches = true; + client.pendingPolls = 1; + List changes = changesAcrossBatches(client, ChangeAction.CREATE); + try { + Thread.currentThread().interrupt(); + IllegalStateException failure = Assert.assertThrows(IllegalStateException.class, + () -> client.submitChanges(changes, "test")); + + Assert.assertTrue(failure.getCause() instanceof InterruptedException); + Assert.assertTrue(failure.getMessage().contains("/change/CTEST1")); + Assert.assertTrue(Thread.currentThread().isInterrupted()); + Assert.assertEquals(Arrays.asList("submit /change/CTEST1", "submit /change/CTEST2", + "PENDING /change/CTEST1"), client.events); + } finally { + Thread.interrupted(); + } + } + + private static List changesAcrossBatches(AwsClient client, ChangeAction rootAction) + throws Exception { + List changes = new ArrayList<>(); + for (int i = 0; i < AwsClient.route53ChangeCountLimit; i++) { + changes.add(client.newTXTChange(ChangeAction.CREATE, "dep" + i + "." + DOMAIN, + Publish.treeNodeTTL, "\"tree-branch:\"")); + } + Tree tree = TreeTest.signedTree(new Tree(), "192.0.2.1"); + changes.add(client.newTXTChange(rootAction, DOMAIN, Publish.rootTTL, + "\"" + tree.getRootEntry().toFormat() + "\"")); + changes.add(client.newTXTChange(ChangeAction.DELETE, "stale." + DOMAIN, + Publish.treeNodeTTL, "\"old TXT\"")); + AwsClient.sortChanges(changes); + return changes; + } + @Test public void testChangeSort() { @@ -280,10 +472,24 @@ private static class RecordingAwsClient extends AwsClient { private List records = Collections.emptyList(); private List changes = new ArrayList<>(); private int zoneQueries; + private int recordQueries; private String requestedZone; + private String requestedMaxItems; + private RuntimeException zoneFailure; + private RuntimeException recordFailure; + private boolean recordsTruncated; + private int failBatch; + private boolean submitBatches; + private int pendingBatch = 1; + private int pendingPolls; + private final List events = new ArrayList<>(); + private final List> batches = new ArrayList<>(); private RecordingAwsClient(String zoneId) throws Exception { super("test-key", "test-secret", zoneId, "us-east-1", 0.1); + Field interval = AwsClient.class.getDeclaredField("changePollIntervalMillis"); + interval.setAccessible(true); + interval.setLong(this, 0); Field field = AwsClient.class.getDeclaredField("route53Client"); field.setAccessible(true); ((Route53Client) field.get(this)).close(); @@ -291,16 +497,45 @@ private RecordingAwsClient(String zoneId) throws Exception { new Class[]{Route53Client.class}, (proxy, method, args) -> { if (method.getName().equals("listHostedZonesByName")) { zoneQueries++; + if (zoneFailure != null) { + throw zoneFailure; + } return ListHostedZonesByNameResponse.builder().isTruncated(false) .hostedZones(HostedZone.builder().id("/hostedzone/" + ZONE_ID) .name("EXAMPLE.INVALID.").build()).build(); } if (method.getName().equals("listResourceRecordSets")) { - requestedZone = ((ListResourceRecordSetsRequest) args[0]).hostedZoneId(); + recordQueries++; + ListResourceRecordSetsRequest request = (ListResourceRecordSetsRequest) args[0]; + requestedZone = request.hostedZoneId(); + requestedMaxItems = request.maxItems(); Assert.assertEquals(ZONE_ID, requestedZone); - return ListResourceRecordSetsResponse.builder().isTruncated(false) + if (recordFailure != null) { + throw recordFailure; + } + return ListResourceRecordSetsResponse.builder().isTruncated(recordsTruncated) .resourceRecordSets(records).build(); } + if (method.getName().equals("changeResourceRecordSets")) { + if (batches.size() + 1 == failBatch) { + throw Route53Exception.builder().statusCode(503) + .message("Injected batch failure").build(); + } + batches.add(new ArrayList<>(((ChangeResourceRecordSetsRequest) args[0]) + .changeBatch().changes())); + String id = "/change/CTEST" + batches.size(); + events.add("submit " + id); + return ChangeResourceRecordSetsResponse.builder().changeInfo(ChangeInfo.builder() + .id(id).status(ChangeStatus.PENDING).build()).build(); + } + if (method.getName().equals("getChange")) { + String id = ((GetChangeRequest) args[0]).id(); + ChangeStatus status = id.equals("/change/CTEST" + pendingBatch) && pendingPolls-- > 0 + ? ChangeStatus.PENDING : ChangeStatus.INSYNC; + events.add(status + " " + id); + return GetChangeResponse.builder().changeInfo(ChangeInfo.builder() + .id(id).status(status).build()).build(); + } throw new AssertionError("Unexpected Route53 call: " + method.getName()); })); } @@ -308,6 +543,9 @@ private RecordingAwsClient(String zoneId) throws Exception { @Override public void submitChanges(List changes, String comment) { this.changes = new ArrayList<>(changes); + if (submitBatches) { + super.submitChanges(changes, comment); + } } } } diff --git a/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java b/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java index d8d07f601fa..389179ec6ee 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java +++ b/p2p/src/test/java/org/tron/p2p/dns/DnsNodeTest.java @@ -11,12 +11,23 @@ import org.tron.p2p.dns.tree.Algorithm; import org.tron.p2p.dns.tree.Entry; import org.tron.p2p.dns.tree.NodesEntry; +import org.tron.p2p.exception.DnsException; import org.tron.p2p.protos.Discover.EndPoints; import org.tron.p2p.protos.Discover.Endpoint; import org.tron.p2p.utils.NetUtil; public class DnsNodeTest { + @Test + public void invalidBase64InNodesEntryIsReportedAsDnsException() { + for (String content : new String[]{"!", "A", "AA="}) { + DnsException error = Assert.assertThrows(DnsException.class, + () -> NodesEntry.parseEntry(Entry.nodesPrefix + content)); + Assert.assertEquals(DnsException.TypeEnum.INVALID_NODES, error.getType()); + Assert.assertTrue(error.getCause() instanceof IllegalArgumentException); + } + } + @Test public void invalidIpv4IsNeverPassedToAddressParsing() throws Exception { DnsNode node = new DnsNode(null, "localhost", "2001:db8::1", 18888) { diff --git a/p2p/src/test/java/org/tron/p2p/dns/sync/ClientRootTest.java b/p2p/src/test/java/org/tron/p2p/dns/sync/ClientRootTest.java new file mode 100644 index 00000000000..9722ffa5716 --- /dev/null +++ b/p2p/src/test/java/org/tron/p2p/dns/sync/ClientRootTest.java @@ -0,0 +1,93 @@ +package org.tron.p2p.dns.sync; + +import java.security.SignatureException; +import java.util.Collections; +import org.junit.Assert; +import org.junit.Test; +import org.tron.p2p.dns.tree.Algorithm; +import org.tron.p2p.dns.tree.Entry; +import org.tron.p2p.dns.tree.LinkEntry; +import org.tron.p2p.dns.tree.RootEntry; +import org.tron.p2p.dns.tree.Tree; +import org.tron.p2p.exception.DnsException; +import org.tron.p2p.exception.DnsException.TypeEnum; +import org.web3j.crypto.Sign; +import org.xbill.DNS.DClass; +import org.xbill.DNS.Name; +import org.xbill.DNS.Record; +import org.xbill.DNS.TXTRecord; + +public class ClientRootTest { + + private static final String DOMAIN = "nodes.example.invalid"; + + @Test + public void rootCoexistsWithVerificationTxtInEitherOrder() throws Exception { + Tree tree = tree("01"); + String root = tree.getRootEntry().toFormat(); + TXTRecord verification = txt("site-verification=abc"); + TXTRecord candidate = txt(root); + for (Record[] records : new Record[][]{{candidate, verification}, {verification, candidate}}) { + Assert.assertEquals(root, Client.parseRoot(link(tree), records).toFormat()); + } + } + + @Test + public void invalidRootsDoNotHideAValidRoot() throws Exception { + Tree tree = tree("01"); + RootEntry badSignature = tree("01").getRootEntry(); + byte[] signature = new byte[65]; + signature[64] = 42; + badSignature.setSignature(signature); + RootEntry nonInvertibleRoot = tree("01").getRootEntry(); + byte[] nonInvertibleSignature = new byte[65]; + // r equals the curve order, so its modular inverse does not exist. + byte[] order = Sign.CURVE_PARAMS.getN().toByteArray(); + System.arraycopy(order, order.length - 32, nonInvertibleSignature, 0, 32); + nonInvertibleSignature[63] = 1; + nonInvertibleSignature[64] = 27; + nonInvertibleRoot.setSignature(nonInvertibleSignature); + SignatureException failure = Assert.assertThrows(SignatureException.class, + () -> Algorithm.recoverPublicKey(nonInvertibleRoot.toString(), nonInvertibleSignature)); + Assert.assertTrue(failure.getCause() instanceof ArithmeticException); + TXTRecord valid = txt(tree.getRootEntry().toFormat()); + for (TXTRecord invalid : new TXTRecord[]{txt(Entry.rootPrefix + "!"), + txt(Entry.rootPrefix + "AA"), txt(badSignature.toFormat()), + txt(nonInvertibleRoot.toFormat()), txt(tree("02").getRootEntry().toFormat())}) { + for (Record[] records : new Record[][]{{invalid, valid}, {valid, invalid}}) { + Assert.assertEquals(tree.getRootEntry().toFormat(), + Client.parseRoot(link(tree), records).toFormat()); + } + } + } + + @Test + public void missingLookupAndNoUsableRootRemainDistinct() throws Exception { + LinkEntry link = link(tree("01")); + Assert.assertEquals(TypeEnum.LOOK_UP_ROOT_FAILED, + Assert.assertThrows(DnsException.class, () -> Client.parseRoot(link, null)).getType()); + for (Record[] records : new Record[][]{new Record[0], {txt("site-verification=abc")}, + {txt(Entry.rootPrefix + "!")}, {txt(tree("02").getRootEntry().toFormat())}}) { + Assert.assertEquals(TypeEnum.NO_ROOT_FOUND, + Assert.assertThrows(DnsException.class, () -> Client.parseRoot(link, records)).getType()); + } + DnsException failure = Assert.assertThrows(DnsException.class, + () -> Client.parseRoot(link, new Record[]{txt(Entry.rootPrefix + "!")})); + Assert.assertTrue(failure.getMessage().contains(TypeEnum.NO_ROOT_FOUND.getDesc())); + Assert.assertTrue(failure.getCause() instanceof IllegalArgumentException); + } + + private static Tree tree(String key) throws Exception { + Tree tree = new Tree(); + tree.makeTree(1, Collections.emptyList(), Collections.emptyList(), key); + return tree; + } + + private static LinkEntry link(Tree tree) throws Exception { + return LinkEntry.parseEntry(LinkEntry.buildRepresent(tree.getBase32PublicKey(), DOMAIN)); + } + + private static TXTRecord txt(String value) throws Exception { + return new TXTRecord(Name.fromString(DOMAIN + "."), DClass.IN, 600, value); + } +} diff --git a/p2p/src/test/java/org/tron/p2p/dns/sync/SyncTest.java b/p2p/src/test/java/org/tron/p2p/dns/sync/SyncTest.java index e12865f0fbd..1e94417f965 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/sync/SyncTest.java +++ b/p2p/src/test/java/org/tron/p2p/dns/sync/SyncTest.java @@ -16,6 +16,7 @@ import org.tron.p2p.exception.DnsException.TypeEnum; import org.xbill.DNS.DClass; import org.xbill.DNS.Name; +import org.xbill.DNS.Record; import org.xbill.DNS.TXTRecord; public class SyncTest { @@ -28,8 +29,8 @@ public void testSync() throws Exception { String url = LinkEntry.buildRepresent(published.getBase32PublicKey(), DOMAIN); Client syncClient = new Client(); try (MockedStatic lookup = Mockito.mockStatic(LookUpTxt.class)) { - lookup.when(() -> LookUpTxt.lookUpTxt(DOMAIN)).thenReturn(new TXTRecord( - Name.fromString(DOMAIN + "."), DClass.IN, 60, published.getRootEntry().toFormat())); + lookup.when(() -> LookUpTxt.lookUpTxtRecords(DOMAIN)).thenReturn(new Record[]{new TXTRecord( + Name.fromString(DOMAIN + "."), DClass.IN, 60, published.getRootEntry().toFormat())}); for (Map.Entry entry : published.getEntries().entrySet()) { lookup.when(() -> LookUpTxt.lookUpTxt(entry.getKey(), DOMAIN)).thenReturn(new TXTRecord( Name.fromString(entry.getKey() + "." + DOMAIN + "."), DClass.IN, 60, diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java index 0f15c021266..e51c13e59f0 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientChangeTest.java @@ -8,6 +8,8 @@ import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; +import org.tron.p2p.dns.TreeTest; +import org.tron.p2p.dns.tree.Tree; import org.tron.p2p.dns.update.AwsClient.RecordSet; import software.amazon.awssdk.services.route53.model.Change; import software.amazon.awssdk.services.route53.model.ChangeAction; @@ -71,12 +73,14 @@ public void createsRecordsThatDoNotExistYet() { } @Test - public void leavesUnchangedRecordsAlone() { + public void leavesUnchangedRecordsAlone() throws Exception { Map existing = new HashMap<>(); + String root = TreeTest.signedTree(new Tree(), "192.0.2.1").getRootEntry().toFormat(); // stored values are quoted, which is what splitTxt produces - existing.put(DOMAIN, new RecordSet(new String[] {"\"root-value\""}, ROOT_TTL)); + existing.put(DOMAIN, new RecordSet(new String[] {(String) splitTxt.invoke(client, root)}, + ROOT_TTL)); - List changes = client.computeChanges(DOMAIN, records(DOMAIN, "root-value"), existing); + List changes = client.computeChanges(DOMAIN, records(DOMAIN, root), existing); Assert.assertTrue("identical value and ttl must produce no change", changes.isEmpty()); } diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java index 8a89731062f..84ba7ce3a5b 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java +++ b/p2p/src/test/java/org/tron/p2p/dns/update/AwsClientRecordsTest.java @@ -144,21 +144,20 @@ public void collectRecordsJoinsSplitValuesBeforeParsing() throws Exception { } @Test - public void malformedBase64InANodesEntryAbortsTheWholeCollection() throws Exception { + public void malformedBase64InANodesEntryDoesNotPreventCollectingValidRecords() throws Exception { + DnsNode node = new DnsNode(null, "192.0.2.1", null, 10000); + String valid = Entry.nodesPrefix + DnsNode.compress(Collections.singletonList(node)); when(sdk.listResourceRecordSets(any(ListResourceRecordSetsRequest.class))).thenReturn( - page(false, txt("a." + DOMAIN + ".", 600, quoted(Entry.nodesPrefix + "!!!not-base64!!!")))); - - // The catch around parseEntry only handles DnsException, but - // Algorithm.decode64 raises an unchecked IllegalArgumentException, so a - // single corrupt TXT record takes down the entire publish rather than being - // skipped. Reported in the PR description as a deferred upstream defect and - // pinned here so a fix is visible as a test change. - try { - client.collectRecords(DOMAIN); - Assert.fail("expected the unchecked decoder failure to escape"); - } catch (IllegalArgumentException expected) { - Assert.assertTrue(expected.getMessage().contains("base64")); - } + page(false, + txt("a." + DOMAIN + ".", 600, quoted(Entry.nodesPrefix + "!!!not-base64!!!")), + txt("b." + DOMAIN + ".", 600, quoted(valid)))); + + Map existing = client.collectRecords(DOMAIN); + + Assert.assertTrue(existing.containsKey("b." + DOMAIN)); + Field field = AwsClient.class.getDeclaredField("serverNodes"); + field.setAccessible(true); + Assert.assertEquals(Collections.singleton(node), field.get(client)); } @Test diff --git a/p2p/src/test/java/org/tron/p2p/dns/update/DnsSignerPublicationTest.java b/p2p/src/test/java/org/tron/p2p/dns/update/DnsSignerPublicationTest.java index ea014d092a0..5e7c96c94c2 100644 --- a/p2p/src/test/java/org/tron/p2p/dns/update/DnsSignerPublicationTest.java +++ b/p2p/src/test/java/org/tron/p2p/dns/update/DnsSignerPublicationTest.java @@ -46,6 +46,8 @@ public class DnsSignerPublicationTest { private final List writes = new ArrayList<>(); private Publish client; private boolean failRootWrite; + private String unrelatedRootTxt; + private boolean unrelatedRootFirst; @Parameterized.Parameter public String provider; @@ -60,6 +62,33 @@ public void setUp() throws Exception { client = provider.equals("Aliyun") ? aliClient() : awsClient(); } + @Test + public void publicationPreservesUnrelatedTxtAtRoot() throws Exception { + unrelatedRootTxt = "site-verification=abc"; + for (boolean rootPresent : new boolean[]{false, true}) { + for (boolean unrelatedFirst : new boolean[]{false, true}) { + unrelatedRootFirst = unrelatedFirst; + client = provider.equals("Aliyun") ? aliClient() : awsClient(); + load(tree(OLD_KEY, 1)); + if (!rootPresent) { + records.remove("@"); + } + Tree updated = tree(NEW_KEY, 1); + + client.deploy(DOMAIN, updated); + + Assert.assertEquals(Collections.singletonList("@"), writes); + Assert.assertEquals(rootPresent ? 8 : 1, root().getSeq()); + Assert.assertEquals(updated.getRootEntry().toFormat(), records.get("@")); + assertSigner(NEW_KEY, true); + + writes.clear(); + client.deploy(DOMAIN, tree(NEW_KEY, 1)); + Assert.assertTrue(writes.isEmpty()); + } + } + } + @Test public void signerChangePublishesOnceWithUnchangedNodesAndLinks() throws Exception { Tree published = tree(OLD_KEY, 1); @@ -296,12 +325,14 @@ public boolean addRecord(String domain, String name, String value, long ttl) { @Override public boolean updateRecord(String id, String name, String value, long ttl) { + Assert.assertNotEquals("unrelated-root", id); write(name, value); return true; } @Override public boolean deleteRecord(String id) { + Assert.assertNotEquals("unrelated-root", id); writes.add(id); records.remove(id); return true; @@ -318,6 +349,12 @@ public DescribeDomainRecordsResponse describeDomainRecords( new DescribeDomainRecordsResponseBodyDomainRecordsRecord().setRR(name) .setRecordId(name).setValue(value) .setTTL(name.equals("@") ? (long) Publish.rootTTL : 24L * 60 * 60))); + if (unrelatedRootTxt != null) { + responseRecords.add(unrelatedRootFirst ? 0 : responseRecords.size(), + new DescribeDomainRecordsResponseBodyDomainRecordsRecord().setRR("@") + .setRecordId("unrelated-root").setValue(unrelatedRootTxt) + .setTTL((long) Publish.rootTTL)); + } return new DescribeDomainRecordsResponse().setStatusCode(200) .setBody(new DescribeDomainRecordsResponseBody() .setTotalCount((long) responseRecords.size()) @@ -341,8 +378,13 @@ public void submitChanges(List changes, String comment) { writes.add(name); records.remove(name); } else { + List values = new ArrayList<>(record.resourceRecords()); + if (name.equals("@") && unrelatedRootTxt != null) { + Assert.assertTrue("Root update must preserve unrelated TXT", + values.removeIf(part -> part.value().equals("\"" + unrelatedRootTxt + "\""))); + } StringBuilder value = new StringBuilder(); - record.resourceRecords().forEach(part -> + values.forEach(part -> value.append(part.value().replace("\"", ""))); write(name, value.toString()); } @@ -364,6 +406,17 @@ public void submitChanges(List changes, String comment) { .ttl(name.equals("@") ? (long) Publish.rootTTL : Publish.treeNodeTTL) .resourceRecords(ResourceRecord.builder().value("\"" + value + "\"").build()) .build())); + if (unrelatedRootTxt != null) { + ResourceRecordSet root = responseRecords.stream() + .filter(record -> record.name().equals(DOMAIN)).findFirst() + .orElse(ResourceRecordSet.builder().name(DOMAIN).type(RRType.TXT) + .ttl((long) Publish.rootTTL).build()); + List values = new ArrayList<>(root.resourceRecords()); + values.add(unrelatedRootFirst ? 0 : values.size(), + ResourceRecord.builder().value("\"" + unrelatedRootTxt + "\"").build()); + responseRecords.remove(root); + responseRecords.add(root.toBuilder().resourceRecords(values).build()); + } return ListResourceRecordSetsResponse.builder().isTruncated(false) .resourceRecordSets(responseRecords).build(); });