Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions p2p/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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).
Expand Down
14 changes: 10 additions & 4 deletions p2p/src/main/java/org/tron/p2p/base/Parameter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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<P2pEventHandler> handlerList = new ArrayList<>();
Expand Down
3 changes: 3 additions & 0 deletions p2p/src/main/java/org/tron/p2p/connection/Channel.java
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -236,8 +246,10 @@ private synchronized void setStatusMessage(NodeStat nodeStat, StatusMessage mess
public synchronized List<Node> getConnectableNodes() {
List<NodeStat> stats = new ArrayList<>();
List<Node> 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);
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 -> {
Expand Down Expand Up @@ -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;
}
};
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,11 @@ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> 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();
Expand Down
2 changes: 1 addition & 1 deletion p2p/src/main/java/org/tron/p2p/discover/Node.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
151 changes: 137 additions & 14 deletions p2p/src/main/java/org/tron/p2p/discover/socket/P2pPacketDecoder.java
Original file line number Diff line number Diff line change
@@ -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<DatagramPacket> {

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<DropReason, DropCounter> 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<Object> 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];
Expand All @@ -30,21 +67,107 @@ public void decode(ChannelHandlerContext ctx, DatagramPacket packet, List<Object
UdpEvent event = new UdpEvent(Message.parse(encoded), packet.sender());
out.add(event);
} catch (P2pException pe) {
if (pe.getType().equals(P2pException.TypeEnum.BAD_MESSAGE)) {
logger.error("Message validation failed, type {}, len {}, address {}", encoded[0],
encoded.length, packet.sender());
} else {
logger.info("Parse msg failed, type {}, len {}, address {}", encoded[0], encoded.length,
packet.sender());
if (pe.getType() == P2pException.TypeEnum.BAD_MESSAGE) {
if (shouldLog(DropReason.INVALID_MESSAGE)) {
logger.error("Message validation failed, type {}, len {}, address {}",
encoded[0], length, packet.sender());
}
} else if (shouldLog(DropReason.PARSE_FAILURE)) {
logger.info("Parse msg failed, type {}, len {}, address {}",
encoded[0], length, packet.sender());
}
} catch (InvalidProtocolBufferException e) {
logger.warn("An exception occurred while parsing the message, type {}, len {}, address {}, "
+ "data {}, cause: {}", encoded[0], encoded.length, packet.sender(),
ByteArray.toHexString(encoded), e.getMessage());
if (shouldLog(DropReason.INVALID_PROTOBUF)) {
logger.warn("An exception occurred while parsing the message, type {}, len {}, address {}, "
+ "data {}, cause: {}", encoded[0], length, packet.sender(), dataPreview(encoded),
e.getClass().getSimpleName());
}
} catch (Exception e) {
logger.error("An exception occurred while parsing the message, type {}, len {}, address {}, "
+ "data {}", encoded[0], encoded.length, packet.sender(),
ByteArray.toHexString(encoded), e);
if (shouldLog(DropReason.UNEXPECTED_ERROR)) {
logger.error("An exception occurred while parsing the message, type {}, len {}, "
+ "address {}, data {}", encoded[0], length, packet.sender(), dataPreview(encoded));
}
}
}

static String dataPreview(byte[] encoded) {
int length = Integer.min(encoded.length, MAX_LOG_DATA_BYTES);
String hex = Hex.toHexString(encoded, 0, length);
return length < encoded.length ? hex + "..." : hex;
}

private boolean shouldLog(DropReason reason) {
DropCounter counter = drops.get(reason);
if (!reason.isEnabled() || !counter.trySample()) {
return false;
}
reportSuppressed(reason, counter);
return true;
}

private void flushSummaries() {
drops.forEach(P2pPacketDecoder::reportSuppressed);
}

private static void reportSuppressed(DropReason reason, DropCounter counter) {
if (counter.suppressed == 0 || !reason.isEnabled()) {
return;
}
switch (reason.level) {
case WARN:
logger.warn(SUMMARY, reason, counter.suppressed, counter.totalWhileEnabled);
break;
case INFO:
logger.info(SUMMARY, reason, counter.suppressed, counter.totalWhileEnabled);
break;
case ERROR:
logger.error(SUMMARY, reason, counter.suppressed, counter.totalWhileEnabled);
break;
default:
throw new AssertionError(reason.level);
}
counter.suppressed = 0;
}

private enum DropReason {
INVALID_LENGTH(Level.WARN),
INVALID_MESSAGE(Level.ERROR),
PARSE_FAILURE(Level.INFO),
INVALID_PROTOBUF(Level.WARN),
UNEXPECTED_ERROR(Level.ERROR);

final Level level;

DropReason(Level level) {
this.level = level;
}

boolean isEnabled() {
switch (level) {
case WARN:
return logger.isWarnEnabled();
case INFO:
return logger.isInfoEnabled();
case ERROR:
return logger.isErrorEnabled();
default:
throw new AssertionError(level);
}
}
}

static final class DropCounter {
private final RateLimiter limiter = RateLimiter.create(1.0 / REPORT_INTERVAL_SECONDS);
long totalWhileEnabled;
long suppressed;

boolean trySample() {
totalWhileEnabled++;
if (limiter.tryAcquire()) {
return true;
}
suppressed++;
return false;
}
}
}
Loading
Loading