Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.tron.core.net.service.relay;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.protobuf.ByteString;
import java.net.InetSocketAddress;
import java.util.Arrays;
Expand Down Expand Up @@ -42,6 +44,7 @@
public class RelayService {

private static final int MAX_PEER_COUNT_PER_ADDRESS = 5;
private static final long HELLO_MESSAGE_TIMESTAMP_THRESHOLD = TimeUnit.MINUTES.toMillis(5);

@Autowired
private ChainBaseManager chainBaseManager;
Expand Down Expand Up @@ -74,6 +77,10 @@ public class RelayService {

private int maxFastForwardNum = Args.getInstance().getMaxFastForwardNum();

private final Cache<ByteString, Long> helloReplayCache = CacheBuilder.newBuilder()
.maximumSize(100)
.build();

public void init() {
manager = ctx.getBean(Manager.class);
witnessScheduleStore = ctx.getBean(WitnessScheduleStore.class);
Expand Down Expand Up @@ -156,6 +163,22 @@ public boolean checkHelloMessage(HelloMessage message, Channel channel) {
return false;
}

long now = System.currentTimeMillis();
long timestamp = msg.getTimestamp();
if (timestamp < now - HELLO_MESSAGE_TIMESTAMP_THRESHOLD
|| timestamp > now + HELLO_MESSAGE_TIMESTAMP_THRESHOLD) {
logger.warn("HelloMessage from {}, timestamp {} is outside the window around {}",
channel.getInetAddress(), timestamp, now);
return false;
}

Long lastTimestamp = helloReplayCache.getIfPresent(msg.getAddress());

@lxcmyf lxcmyf Sep 17, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[MUST] The getIfPresent → signature verification → put sequence is not atomic. Replays of the same address/timestamp on different channels can pass concurrently and both add trust. After signature verification, commit the timestamp with an address-scoped atomic compare-and-update or equivalent lock, and add a concurrency test.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exploiting this scenario requires first obtaining a Hello message with a valid witness signature that is still within the freshness window, then replaying it concurrently over multiple connections. Given these prerequisites and the added complexity of synchronization or atomic update logic, we will retain the current implementation without adding concurrency control in this PR.

if (lastTimestamp != null && msg.getTimestamp() <= lastTimestamp) {
logger.warn("HelloMessage from {}, timestamp {} is not greater than last {}",
channel.getInetAddress(), msg.getTimestamp(), lastTimestamp);
return false;
}

boolean flag;
try {
Sha256Hash hash = Sha256Hash.of(CommonParameter
Expand All @@ -172,6 +195,7 @@ public boolean checkHelloMessage(HelloMessage message, Channel channel) {
flag = Arrays.equals(sigAddress, witnessPermissionAddress);
}
if (flag) {
helloReplayCache.put(msg.getAddress(), msg.getTimestamp());
TronNetService.getP2pConfig().getTrustNodes().add(channel.getInetAddress());
DesensitizedConverter.addSensitive(channel.getInetAddress().toString().substring(1),
ByteArray.toHexString(msg.getAddress().toByteArray()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;

import com.google.common.cache.Cache;
import com.google.protobuf.ByteString;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
Expand All @@ -13,6 +14,7 @@
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.Hex;
Expand Down Expand Up @@ -73,6 +75,11 @@ public static void init() {
@After
public void clearPeers() {
closePeer();
Cache<?, ?> cache =
(Cache<?, ?>) ReflectUtils.getFieldObject(service, "helloReplayCache");
if (cache != null) {
cache.invalidateAll();
}
}

@Test
Expand Down Expand Up @@ -250,6 +257,130 @@ private void testCheckHelloMessage() {
}
}

private HelloMessage buildSignedHello(long timestamp) throws Exception {
String key = "0154435f065a57fec6af1e12eaa2fa600030639448d7809f4c65bdcf8baed7e5";
ByteString address = getFromHexString("418A8D690BF36806C36A7DAE3AF796643C1AA9CC01");
Node node = new Node(NetUtil.getNodeId(), "127.0.0.1", null, 10001);
HelloMessage msg = new HelloMessage(node, timestamp,
ChainBaseManager.getChainBaseManager());
SignInterface engine = SignUtils.fromPrivate(ByteArray.fromHexString(key),
Args.getInstance().isECKeyCryptoEngine());
ByteString sig = ByteString.copyFrom(engine.Base64toBytes(engine
.signHash(Sha256Hash.of(CommonParameter.getInstance()
.isECKeyCryptoEngine(), ByteArray.fromLong(timestamp)).getBytes())));
msg.setHelloMessage(msg.getHelloMessage().toBuilder()
.setAddress(address)
.setSignature(sig)
.build());
return msg;
}

private Channel buildChannel() {
InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10001);
Channel c = mock(Channel.class);
Mockito.when(c.getInetSocketAddress()).thenReturn(addr);
Mockito.when(c.getInetAddress()).thenReturn(addr.getAddress());
return c;
}

private void setupRelayServiceDeps() throws Exception {
Field f1 = service.getClass().getDeclaredField("witnessScheduleStore");
f1.setAccessible(true);
f1.set(service, chainBaseManager.getWitnessScheduleStore());
Field f2 = service.getClass().getDeclaredField("manager");
f2.setAccessible(true);
f2.set(service, dbManager);
ReflectUtils.setFieldValue(tronNetService, "p2pConfig", new P2pConfig());
}

@Test
public void testCheckHelloMessage_staleTimestamp() throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
long threshold = TimeUnit.MINUTES.toMillis(5);
long staleTimestamp = System.currentTimeMillis() - threshold - 1000;
HelloMessage msg = buildSignedHello(staleTimestamp);
boolean result = service.checkHelloMessage(msg, buildChannel());
Assert.assertFalse(result);
}

@Test
public void testCheckHelloMessage_futureTimestampDoesNotPoisonCache() throws Exception {
assertTimestampRejectedWithoutPoisoningCache(
System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));
}

@Test
public void testCheckHelloMessage_maxTimestampDoesNotPoisonCache() throws Exception {
assertTimestampRejectedWithoutPoisoningCache(Long.MAX_VALUE);
}

@Test
public void testCheckHelloMessage_minTimestampDoesNotPoisonCache() throws Exception {
assertTimestampRejectedWithoutPoisoningCache(Long.MIN_VALUE);
}

private void assertTimestampRejectedWithoutPoisoningCache(long timestamp) throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
Channel channel = buildChannel();
Assert.assertFalse(service.checkHelloMessage(buildSignedHello(timestamp), channel));
Assert.assertFalse(TronNetService.getP2pConfig().getTrustNodes()
.contains(channel.getInetAddress()));
Assert.assertTrue(service.checkHelloMessage(
buildSignedHello(System.currentTimeMillis()), channel));
}

@Test
public void testCheckHelloMessage_freshTimestamp() throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
long freshTimestamp = System.currentTimeMillis();
HelloMessage msg = buildSignedHello(freshTimestamp);
boolean result = service.checkHelloMessage(msg, buildChannel());
Assert.assertTrue(result);
}

@Test
public void testCheckHelloMessage_replayRejected() throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
long t = System.currentTimeMillis();
HelloMessage msg1 = buildSignedHello(t);
Assert.assertTrue(service.checkHelloMessage(msg1, buildChannel()));
HelloMessage msg2 = buildSignedHello(t);
Assert.assertFalse(service.checkHelloMessage(msg2, buildChannel()));
}

@Test
public void testCheckHelloMessage_strictlyLargerTimestampPasses() throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
long t = System.currentTimeMillis();
Assert.assertTrue(service.checkHelloMessage(buildSignedHello(t), buildChannel()));
Assert.assertTrue(service.checkHelloMessage(buildSignedHello(t + 1), buildChannel()));
}

@Test
public void testCheckHelloMessage_badSigDoesNotPoisonCache() throws Exception {
initWitness();
setupRelayServiceDeps();
Args.getInstance().fastForward = true;
long t = System.currentTimeMillis();
HelloMessage badMsg = buildSignedHello(t);
badMsg.setHelloMessage(badMsg.getHelloMessage().toBuilder()
.setSignature(ByteString.copyFrom(new byte[65]))
.build());
Assert.assertFalse(service.checkHelloMessage(badMsg, buildChannel()));
HelloMessage goodMsg = buildSignedHello(t);
Assert.assertTrue(service.checkHelloMessage(goodMsg, buildChannel()));
}

@Test
public void testNullWitnessAddress() {
try {
Expand Down
Loading