Skip to content

Commit d7df62b

Browse files
authored
fix(net): improve block sync resilience and transaction handling (#7050)
* fix(net): restore transaction revalidation and sanitize relay data Track permission-update owners when blocks are rolled back so cached transaction verification is invalidated. Clear transaction results before caching relay messages and omit full hash lists when transaction inventory is rate limited. * fix(net): recover sync requests after block processing failures Release the global sync request on every block processing failure so another peer can supply the block without waiting for cache expiration. Disconnect only the sender and preserve other peers' queued blocks and sync progress. Reject advertised blocks whose witness is outside the active set instead of silently dropping them. Keep advertisement recovery on the sync path and retain log-only handling for failures during advertised block application. Unify block application errors as BAD_BLOCK while retaining their causes. Log P2P failure details without a stack trace and keep stack traces for unexpected sync failures. * fix(net): preserve pending transaction results during relay Clear results only on the transaction copy cached for relay. Keep the original capsule unchanged so broadcasting cannot erase pending execution results or race with block assembly. * fix(net): tolerate isolated inactive-witness blocks Avoid disconnecting a peer for a single inactive-witness block. Separate basic block validation from advertised-block witness checks, record the last inactive-witness block time per connection, and disconnect only on a repeat within half the current maintenance interval. Log every inactive-witness occurrence before applying the disconnect condition. Keep timestamp, Merkle-root and signature validation ahead of the witness check and allow isolated occurrences to continue processing. * fix(net): check witness activity before block validation Apply the advertised-block witness activity and repeat-offense checks before basic block validation. Log inactive-witness occurrences before rejecting repeats, and retain timestamp, Merkle-root and signature checks for every response that passes the witness check. * fix(net): stop broadcasting inactive-witness blocks Return the advertised-block validation result and stop processing blocks from inactive witnesses before synchronization or relay. Preserve basic block validation and the existing disconnect policy for repeated inactive-witness blocks.
1 parent 632e647 commit d7df62b

14 files changed

Lines changed: 762 additions & 50 deletions

File tree

‎framework/src/main/java/org/tron/core/db/Manager.java‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1001,8 +1001,12 @@ public void eraseBlock() {
10011001
khaosDb.pop();
10021002
revokingStore.fastPop();
10031003
logger.info("End to erase block: {}.", oldHeadBlock);
1004-
oldHeadBlock.getTransactions().forEach(tc ->
1005-
poppedTransactions.add(new TransactionCapsule(tc.getInstance())));
1004+
oldHeadBlock.getTransactions().forEach(tc -> {
1005+
if (isMultiSignTransaction(tc.getInstance())) {
1006+
ownerAddressSet.add(ByteArray.toHexString(tc.getOwnerAddress()));
1007+
}
1008+
poppedTransactions.add(new TransactionCapsule(tc.getInstance()));
1009+
});
10061010
Metrics.gaugeInc(MetricKeys.Gauge.MANAGER_QUEUE, oldHeadBlock.getTransactions().size(),
10071011
MetricLabels.Gauge.QUEUE_POPPED);
10081012

‎framework/src/main/java/org/tron/core/net/P2pEventHandlerImpl.java‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -233,9 +233,6 @@ private boolean checkInvRateLimit(PeerConnection peer, InventoryMessage msg)
233233
if (count + currentSize > maxCountIn10s) {
234234
logger.warn("Drop TRX inv from {}, window:{}, cur:{}, max:{}",
235235
peer.getInetAddress(), count, currentSize, maxCountIn10s);
236-
if (Args.getInstance().isOpenPrintLog()) {
237-
logger.warn("[overload] Drop tx list: {}", msg.getHashList());
238-
}
239236
return false;
240237
}
241238
} else if (invType == InventoryType.BLOCK) {

‎framework/src/main/java/org/tron/core/net/TronNetDelegate.java‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package org.tron.core.net;
22

33
import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL;
4-
import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED;
54

65
import com.google.common.cache.Cache;
76
import com.google.common.cache.CacheBuilder;
@@ -24,6 +23,7 @@
2423
import org.tron.common.prometheus.MetricLabels;
2524
import org.tron.common.prometheus.Metrics;
2625
import org.tron.common.utils.Sha256Hash;
26+
import org.tron.common.utils.Time;
2727
import org.tron.core.ChainBaseManager;
2828
import org.tron.core.capsule.BlockCapsule;
2929
import org.tron.core.capsule.BlockCapsule.BlockId;
@@ -312,12 +312,7 @@ public void processBlock(BlockCapsule block, boolean isSync) throws P2pException
312312
| EventBloomException e) {
313313
metricsService.failProcessBlock(block.getNum(), e.getMessage());
314314
logger.error("Process block failed, {}, reason: {}", blockId.getString(), e.getMessage());
315-
if (e instanceof BadBlockException
316-
&& ((BadBlockException) e).getType().equals(CALC_MERKLE_ROOT_FAILED)) {
317-
throw new P2pException(TypeEnum.BLOCK_MERKLE_INVALID, e);
318-
} else {
319-
throw new P2pException(TypeEnum.BAD_BLOCK, e);
320-
}
315+
throw new P2pException(TypeEnum.BAD_BLOCK, e);
321316
}
322317
}
323318
}
@@ -356,7 +351,7 @@ public void validSignature(BlockCapsule block) throws P2pException {
356351
}
357352
}
358353

359-
public boolean validBlock(BlockCapsule block) throws P2pException {
354+
public void validBlock(BlockCapsule block) throws P2pException {
360355
long time = System.currentTimeMillis();
361356
if (block.getTimeStamp() - time > timeout) {
362357
throw new P2pException(TypeEnum.BAD_BLOCK,
@@ -368,7 +363,24 @@ public boolean validBlock(BlockCapsule block) throws P2pException {
368363
throw new P2pException(TypeEnum.BLOCK_MERKLE_INVALID, e.getMessage());
369364
}
370365
validSignature(block);
371-
return witnessScheduleStore.getActiveWitnesses().contains(block.getWitnessAddress());
366+
}
367+
368+
public boolean validAdvBlock(PeerConnection peer, BlockCapsule block) throws P2pException {
369+
boolean activeWitness = witnessScheduleStore.getActiveWitnesses()
370+
.contains(block.getWitnessAddress());
371+
if (!activeWitness) {
372+
logger.warn("Block witness is not active, block: {}, peer: {}",
373+
block.getBlockId().getString(), peer.getInetSocketAddress());
374+
long now = Time.getCurrentMillis();
375+
long lastTime = peer.getLastInactiveWitnessBlockTime();
376+
peer.setLastInactiveWitnessBlockTime(now);
377+
if (now - lastTime < getMaintenanceTimeInterval() / 2) {
378+
throw new P2pException(TypeEnum.BAD_BLOCK,
379+
"Repeated block from an inactive witness: " + block.getBlockId().getString());
380+
}
381+
}
382+
validBlock(block);
383+
return activeWitness;
372384
}
373385

374386
public PbftSignCapsule getBlockPbftCommitData(long blockNum) {

‎framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,9 @@ private void check(PeerConnection peer, BlockMessage msg) throws P2pException {
134134

135135
private void processBlock(PeerConnection peer, BlockCapsule block) throws P2pException {
136136
BlockId blockId = block.getBlockId();
137-
boolean flag = tronNetDelegate.validBlock(block);
138-
if (!flag) {
139-
logger.warn("Receive a bad block from {}, {}, {}",
140-
peer.getInetSocketAddress(), blockId.getString(),
141-
Hex.toHexString(block.getWitnessAddress().toByteArray()));
137+
if (!tronNetDelegate.validAdvBlock(peer, block)) {
142138
return;
143139
}
144-
145140
if (!tronNetDelegate.containBlock(block.getParentBlockId())) {
146141
logger.warn("Get unlink block {} from {}, head is {}", blockId.getString(),
147142
peer.getInetAddress(), tronNetDelegate.getHeadBlockId().getString());

‎framework/src/main/java/org/tron/core/net/peer/PeerConnection.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,10 @@ public class PeerConnection {
9696
@Getter
9797
private volatile long blockRcvTime;
9898

99+
@Getter
100+
@Setter
101+
private volatile long lastInactiveWitnessBlockTime;
102+
99103
/**
100104
* Sliding factor of the fetch latency Exponentially Weighted Moving Average (EWMA):
101105
* each new sample contributes

‎framework/src/main/java/org/tron/core/net/service/adv/AdvService.java‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,8 @@ public int fastBroadcastTransaction(TransactionMessage msg) {
169169

170170
Item item = new Item(msg.getMessageId(), InventoryType.TRX);
171171
trxCount.add();
172-
trxCache.put(item, new TransactionMessage(msg.getTransactionCapsule().getInstance()));
172+
trxCache.put(item, new TransactionMessage(
173+
msg.getTransactionCapsule().getInstance().toBuilder().clearRet().build()));
173174

174175
List<Sha256Hash> list = new ArrayList<>();
175176
list.add(msg.getMessageId());
@@ -216,7 +217,8 @@ public void broadcast(Message msg) {
216217
TransactionMessage trxMsg = (TransactionMessage) msg;
217218
item = new Item(trxMsg.getMessageId(), InventoryType.TRX);
218219
trxCount.add();
219-
trxCache.put(item, new TransactionMessage(trxMsg.getTransactionCapsule().getInstance()));
220+
trxCache.put(item, new TransactionMessage(
221+
trxMsg.getTransactionCapsule().getInstance().toBuilder().clearRet().build()));
220222
} else {
221223
logger.error("Adv item is neither block nor trx, type: {}", msg.getType());
222224
return;

‎framework/src/main/java/org/tron/core/net/service/sync/SyncService.java‎

Lines changed: 10 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -339,26 +339,21 @@ private synchronized void handleSyncBlock() {
339339
}
340340

341341
private void processSyncBlock(BlockCapsule block, PeerConnection peerConnection) {
342-
boolean flag = true;
343-
boolean attackFlag = false;
344342
BlockId blockId = block.getBlockId();
345343
try {
346344
tronNetDelegate.validSignature(block);
347345
tronNetDelegate.processBlock(block, true);
348346
peerConnection.setBlockRcvTime(System.currentTimeMillis());
349347
pbftDataSyncHandler.processPBFTCommitData(block);
350-
} catch (P2pException p2pException) {
351-
logger.error("Process sync block {} failed, type: {}",
352-
blockId.getString(), p2pException.getType());
353-
attackFlag = p2pException.getType().equals(TypeEnum.BLOCK_SIGN_INVALID)
354-
|| p2pException.getType().equals(TypeEnum.BLOCK_MERKLE_INVALID);
355-
flag = false;
356348
} catch (Exception e) {
357-
logger.error("Process sync block {} failed", blockId.getString(), e);
358-
flag = false;
359-
}
360-
361-
if (attackFlag) {
349+
if (e instanceof P2pException) {
350+
logger.error("Process sync block {} from {} failed, type: {}, reason: {}",
351+
blockId.getString(), peerConnection.getInetSocketAddress(),
352+
((P2pException) e).getType(), e.getMessage());
353+
} else {
354+
logger.error("Process sync block {} from {} failed",
355+
blockId.getString(), peerConnection.getInetSocketAddress(), e);
356+
}
362357
invalid(blockId, peerConnection);
363358
peerConnection.disconnect(ReasonCode.BAD_BLOCK);
364359
return;
@@ -369,12 +364,8 @@ private void processSyncBlock(BlockCapsule block, PeerConnection peerConnection)
369364
if (blockId.equals(bid)) {
370365
peer.setBlockBothHave(blockId);
371366
peer.getSyncBlockToFetch().remove(bid);
372-
if (flag) {
373-
if (peer.getSyncBlockToFetch().isEmpty() && peer.isFetchAble()) {
374-
syncNext(peer);
375-
}
376-
} else {
377-
peer.disconnect(ReasonCode.BAD_BLOCK);
367+
if (peer.getSyncBlockToFetch().isEmpty() && peer.isFetchAble()) {
368+
syncNext(peer);
378369
}
379370
}
380371
}

‎framework/src/test/java/org/tron/core/db/ManagerTest.java‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -936,6 +936,39 @@ public void getVerifyTxsSkipsBlockWhenPermissionTxAlreadyConsumed() throws Excep
936936
}
937937
}
938938

939+
@Test
940+
public void eraseBlockMarksPermissionUpdateOwnerForVerification() throws Exception {
941+
byte[] owner = ByteArray.fromHexString(Wallet.getAddressPreFixString()
942+
+ "548794500882809695A8A687866E76D4271A1ABC");
943+
AccountContract.AccountPermissionUpdateContract contract =
944+
AccountContract.AccountPermissionUpdateContract.newBuilder()
945+
.setOwnerAddress(ByteString.copyFrom(owner))
946+
.build();
947+
TransactionCapsule permissionUpdate = new TransactionCapsule(contract,
948+
ContractType.AccountPermissionUpdateContract);
949+
BlockCapsule rolledBackBlock = new BlockCapsule(1, Sha256Hash.ZERO_HASH.getByteString(), 0,
950+
Arrays.asList(permissionUpdate.getInstance()));
951+
rolledBackBlock.setMerkleRoot();
952+
953+
Manager manager = new Manager();
954+
ChainBaseManager mockedChainManager = mock(ChainBaseManager.class);
955+
DynamicPropertiesStore mockedDynamicPropertiesStore = mock(DynamicPropertiesStore.class);
956+
when(mockedChainManager.getDynamicPropertiesStore()).thenReturn(mockedDynamicPropertiesStore);
957+
when(mockedDynamicPropertiesStore.getLatestBlockHeaderHash())
958+
.thenReturn(Sha256Hash.wrap(new byte[32]));
959+
when(mockedChainManager.getBlockById(any(Sha256Hash.class))).thenReturn(rolledBackBlock);
960+
ReflectUtils.setFieldValue(manager, "chainBaseManager", mockedChainManager);
961+
ReflectUtils.setFieldValue(manager, "khaosDb", mock(KhaosDatabase.class));
962+
ReflectUtils.setFieldValue(manager, "revokingStore", mock(RevokingDatabase.class));
963+
964+
manager.eraseBlock();
965+
966+
@SuppressWarnings("unchecked")
967+
Set<String> ownerAddressSet =
968+
(Set<String>) ReflectUtils.getFieldObject(manager, "ownerAddressSet");
969+
Assert.assertTrue(ownerAddressSet.contains(ByteArray.toHexString(owner)));
970+
}
971+
939972
@Test
940973
public void doNotSwitch()
941974
throws ValidateSignatureException, ContractValidateException, ContractExeException,

‎framework/src/test/java/org/tron/core/net/TronNetDelegateTest.java‎

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
import com.google.protobuf.ByteString;
66
import java.lang.reflect.Field;
7+
import java.net.InetSocketAddress;
8+
import java.util.Collections;
79
import org.junit.Assert;
810
import org.junit.Test;
911
import org.mockito.Mockito;
@@ -17,9 +19,14 @@
1719
import org.tron.core.capsule.TransactionCapsule;
1820
import org.tron.core.config.args.Args;
1921
import org.tron.core.db.Manager;
22+
import org.tron.core.exception.BadBlockException;
2023
import org.tron.core.exception.P2pException;
2124
import org.tron.core.exception.P2pException.TypeEnum;
25+
import org.tron.core.exception.ValidateScheduleException;
26+
import org.tron.core.metrics.MetricsService;
27+
import org.tron.core.net.peer.PeerConnection;
2228
import org.tron.core.store.DynamicPropertiesStore;
29+
import org.tron.core.store.WitnessScheduleStore;
2330
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
2431
import org.tron.protos.contract.BalanceContract.TransferContract;
2532

@@ -185,5 +192,127 @@ public void testValidBlockMerkleRoot() throws Exception {
185192
} catch (P2pException e) {
186193
Assert.assertEquals(TypeEnum.BLOCK_MERKLE_INVALID, e.getType());
187194
}
195+
PeerConnection peer = new PeerConnection();
196+
WitnessScheduleStore schedule = mock(WitnessScheduleStore.class);
197+
setField(tronNetDelegate, "witnessScheduleStore", schedule);
198+
Mockito.when(schedule.getActiveWitnesses())
199+
.thenReturn(Collections.singletonList(tampered.getWitnessAddress()));
200+
try {
201+
tronNetDelegate.validAdvBlock(peer, tampered);
202+
Assert.fail("Invalid Merkle root must still be rejected for an active witness");
203+
} catch (P2pException e) {
204+
Assert.assertEquals(TypeEnum.BLOCK_MERKLE_INVALID, e.getType());
205+
}
206+
Assert.assertEquals(0, peer.getLastInactiveWitnessBlockTime());
207+
}
208+
209+
@Test
210+
public void testValidBlockDoesNotCheckWitnessActivity() throws Exception {
211+
TronNetDelegate delegate = Mockito.spy(new TronNetDelegate());
212+
WitnessScheduleStore schedule = mock(WitnessScheduleStore.class);
213+
setField(delegate, "witnessScheduleStore", schedule);
214+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 0,
215+
ByteString.copyFromUtf8("witness"));
216+
block.setMerkleRoot();
217+
Mockito.doNothing().when(delegate).validSignature(block);
218+
delegate.validBlock(block);
219+
Mockito.verify(schedule, Mockito.never()).getActiveWitnesses();
220+
}
221+
222+
@Test
223+
public void testValidAdvBlockChecksSignatureAfterWitnessActivity() throws Exception {
224+
TronNetDelegate delegate = Mockito.spy(new TronNetDelegate());
225+
WitnessScheduleStore schedule = mock(WitnessScheduleStore.class);
226+
setField(delegate, "witnessScheduleStore", schedule);
227+
Mockito.when(schedule.getActiveWitnesses()).thenReturn(Collections.emptyList());
228+
Mockito.doReturn(21_600_000L).when(delegate).getMaintenanceTimeInterval();
229+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 0, ByteString.EMPTY);
230+
block.setMerkleRoot();
231+
P2pException failure = new P2pException(TypeEnum.BLOCK_SIGN_INVALID, "invalid signature");
232+
Mockito.doThrow(failure).when(delegate).validSignature(block);
233+
PeerConnection peer = Mockito.spy(new PeerConnection());
234+
Mockito.doReturn(new InetSocketAddress("127.0.0.1", 18888))
235+
.when(peer).getInetSocketAddress();
236+
try {
237+
delegate.validAdvBlock(peer, block);
238+
Assert.fail("Invalid signature must still be rejected after witness activity handling");
239+
} catch (P2pException e) {
240+
Assert.assertSame(failure, e);
241+
}
242+
Assert.assertTrue(peer.getLastInactiveWitnessBlockTime() > 0);
243+
}
244+
245+
@Test
246+
public void testRepeatedInactiveWitnessIsRejectedBeforeBasicValidation() throws Exception {
247+
TronNetDelegate delegate = Mockito.spy(new TronNetDelegate());
248+
WitnessScheduleStore schedule = mock(WitnessScheduleStore.class);
249+
setField(delegate, "witnessScheduleStore", schedule);
250+
Mockito.when(schedule.getActiveWitnesses()).thenReturn(Collections.emptyList());
251+
Mockito.doReturn(21_600_000L).when(delegate).getMaintenanceTimeInterval();
252+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 0, ByteString.EMPTY);
253+
PeerConnection peer = Mockito.spy(new PeerConnection());
254+
Mockito.doReturn(new InetSocketAddress("127.0.0.1", 18888))
255+
.when(peer).getInetSocketAddress();
256+
peer.setLastInactiveWitnessBlockTime(System.currentTimeMillis());
257+
258+
try {
259+
delegate.validAdvBlock(peer, block);
260+
Assert.fail("Repeated inactive witness must be rejected before basic validation");
261+
} catch (P2pException e) {
262+
Assert.assertEquals(TypeEnum.BAD_BLOCK, e.getType());
263+
}
264+
Mockito.verify(delegate, Mockito.never()).validBlock(block);
265+
}
266+
267+
@Test
268+
public void testValidAdvBlockAcceptsActiveWitnessWithoutChangingHistory() throws Exception {
269+
TronNetDelegate delegate = Mockito.spy(new TronNetDelegate());
270+
WitnessScheduleStore schedule = mock(WitnessScheduleStore.class);
271+
setField(delegate, "witnessScheduleStore", schedule);
272+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 0,
273+
ByteString.copyFromUtf8("witness"));
274+
block.setMerkleRoot();
275+
Mockito.doNothing().when(delegate).validSignature(block);
276+
Mockito.when(schedule.getActiveWitnesses())
277+
.thenReturn(Collections.singletonList(block.getWitnessAddress()));
278+
PeerConnection peer = new PeerConnection();
279+
peer.setLastInactiveWitnessBlockTime(86_400_000L);
280+
281+
Assert.assertTrue(delegate.validAdvBlock(peer, block));
282+
283+
Mockito.verify(delegate).validSignature(block);
284+
Assert.assertEquals(86_400_000L, peer.getLastInactiveWitnessBlockTime());
285+
}
286+
287+
@Test
288+
public void testProcessBlockWrapsScheduleFailureWithCause() throws Exception {
289+
assertProcessBlockFailure(new ValidateScheduleException("invalid scheduled witness"));
290+
}
291+
292+
@Test
293+
public void testProcessBlockWrapsMerkleFailureWithCause() throws Exception {
294+
assertProcessBlockFailure(new BadBlockException(
295+
BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED, "invalid merkle root"));
296+
}
297+
298+
private void assertProcessBlockFailure(Exception failure) throws Exception {
299+
TronNetDelegate delegate = new TronNetDelegate();
300+
Manager manager = mock(Manager.class);
301+
ChainBaseManager chainManager = mock(ChainBaseManager.class);
302+
setField(delegate, "dbManager", manager);
303+
setField(delegate, "chainBaseManager", chainManager);
304+
setField(delegate, "metricsService", mock(MetricsService.class));
305+
Mockito.when(manager.getBlockedTimer()).thenReturn(new ThreadLocal<>());
306+
Mockito.when(chainManager.getHeadBlockId())
307+
.thenReturn(new BlockCapsule.BlockId(Sha256Hash.ZERO_HASH, 0));
308+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 0, ByteString.EMPTY);
309+
Mockito.doThrow(failure).when(manager).pushBlock(block);
310+
try {
311+
delegate.processBlock(block, true);
312+
Assert.fail("Expected block validation failure");
313+
} catch (P2pException e) {
314+
Assert.assertEquals(TypeEnum.BAD_BLOCK, e.getType());
315+
Assert.assertSame(failure, e.getCause());
316+
}
188317
}
189318
}

0 commit comments

Comments
 (0)