Skip to content

Commit 0b59aca

Browse files
authored
fix(net): validate block transactions before propagation (#7066)
* 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): validate block transactions before propagation Reject transactions with a contract count other than one before relaying received blocks. Apply shared timestamp, transaction structure, Merkle root and witness signature checks to both advertised and sync blocks, while keeping current active-witness checks specific to advertised blocks. Validate Merkle roots at network admission and remove the redundant Manager check and capsule validation cache. Keep the existing signature failure types, messages and causes. * fix(net): reject block transactions smaller than 80 bytes Check the full serialized transaction size before Merkle validation for advertised and sync blocks. Exclude short transaction encodings from the 64-byte internal-node hash input domain. * fix(net): keep block timestamp checks at message ingress Rely on BlockMsgHandler to check timestamps for advertised and sync blocks. Remove the duplicate one-second wall-clock rejection from shared block validation.
1 parent 14a5505 commit 0b59aca

9 files changed

Lines changed: 539 additions & 47 deletions

File tree

‎chainbase/src/main/java/org/tron/core/capsule/BlockCapsule.java‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,6 @@
5353
public class BlockCapsule implements ProtoCapsule<Block> {
5454

5555
public boolean generatedByMyself = false;
56-
private volatile boolean merkleValidated = false;
5756
@Getter
5857
@Setter
5958
private TransactionRetCapsule result;
@@ -233,16 +232,12 @@ public Sha256Hash calcMerkleRoot() {
233232
}
234233

235234
public void validateMerkleRoot() throws BadBlockException {
236-
if (merkleValidated) {
237-
return;
238-
}
239235
Sha256Hash actual = calcMerkleRoot();
240236
if (!actual.equals(getMerkleRoot())) {
241237
throw new BadBlockException(CALC_MERKLE_ROOT_FAILED,
242238
String.format("merkle root mismatch for block %d: expected %s, actual %s",
243239
getNum(), getMerkleRoot(), actual));
244240
}
245-
merkleValidated = true;
246241
}
247242

248243
public void setMerkleRoot() {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1223,7 +1223,8 @@ public List<TransactionCapsule> getVerifyTxs(BlockCapsule block) {
12231223
}
12241224

12251225
/**
1226-
* save a block.
1226+
* Save a block. Untrusted callers must first use network prevalidation to check its timestamp,
1227+
* transaction structure, Merkle root and block signature.
12271228
*/
12281229
public void pushBlock(final BlockCapsule block)
12291230
throws ValidateSignatureException, ContractValidateException, ContractExeException,
@@ -1265,7 +1266,6 @@ public void pushBlock(final BlockCapsule block)
12651266
try (PendingManager pm = new PendingManager(this)) {
12661267

12671268
if (!block.generatedByMyself) {
1268-
block.validateMerkleRoot();
12691269
consensus.receiveBlock(block);
12701270
}
12711271

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

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,15 @@
6262
import org.tron.core.net.peer.PeerConnection;
6363
import org.tron.core.store.WitnessScheduleStore;
6464
import org.tron.protos.Protocol.Inventory.InventoryType;
65+
import org.tron.protos.Protocol.Transaction;
6566

6667
@Slf4j(topic = "net")
6768
@Component
6869
public class TronNetDelegate {
6970

71+
// Keep Merkle leaf encodings larger than the 64-byte internal-node input.
72+
private static final int MIN_TRANSACTION_SIZE = 80;
73+
7074
@Autowired
7175
private Manager dbManager;
7276

@@ -89,8 +93,6 @@ public class TronNetDelegate {
8993

9094
private int blockIdCacheSize = 100;
9195

92-
private long timeout = 1000;
93-
9496
@Getter // for test
9597
private volatile boolean hitDown = false;
9698

@@ -352,10 +354,19 @@ public void validSignature(BlockCapsule block) throws P2pException {
352354
}
353355

354356
public void validBlock(BlockCapsule block) throws P2pException {
355-
long time = System.currentTimeMillis();
356-
if (block.getTimeStamp() - time > timeout) {
357-
throw new P2pException(TypeEnum.BAD_BLOCK,
358-
"time:" + time + ",block time:" + block.getTimeStamp());
357+
for (Transaction transaction : block.getInstance().getTransactionsList()) {
358+
int contractCount = transaction.getRawData().getContractCount();
359+
if (contractCount != 1) {
360+
throw new P2pException(TypeEnum.BAD_BLOCK,
361+
"Invalid contract count: " + contractCount
362+
+ ", block: " + block.getBlockId().getString());
363+
}
364+
int transactionSize = transaction.getSerializedSize();
365+
if (transactionSize < MIN_TRANSACTION_SIZE) {
366+
throw new P2pException(TypeEnum.BAD_BLOCK,
367+
"Invalid transaction size: " + transactionSize
368+
+ ", block: " + block.getBlockId().getString());
369+
}
359370
}
360371
try {
361372
block.validateMerkleRoot();

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ private synchronized void handleSyncBlock() {
341341
private void processSyncBlock(BlockCapsule block, PeerConnection peerConnection) {
342342
BlockId blockId = block.getBlockId();
343343
try {
344-
tronNetDelegate.validSignature(block);
344+
tronNetDelegate.validBlock(block);
345345
tronNetDelegate.processBlock(block, true);
346346
peerConnection.setBlockRcvTime(System.currentTimeMillis());
347347
pbftDataSyncHandler.processPBFTCommitData(block);

‎framework/src/test/java/org/tron/core/capsule/BlockCapsuleTest.java‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,13 @@ public void testValidateMerkleRoot() throws Exception {
106106
1234,
107107
ByteString.copyFrom("1234567".getBytes()));
108108

109+
local.addTransaction(new TransactionCapsule(
110+
TransferContract.newBuilder().setAmount(1).build(), ContractType.TransferContract));
111+
109112
// valid block: setMerkleRoot then validate — should not throw
110113
local.setMerkleRoot();
111114
local.validateMerkleRoot(); // no exception
112115

113-
// flag is set — second call must be a no-op (no recomputation)
114116
local.validateMerkleRoot(); // still no exception
115117

116118
// tamper with a transaction to break merkle
@@ -124,14 +126,29 @@ public void testValidateMerkleRoot() throws Exception {
124126
new TransactionCapsule(transferContract, ContractType.TransferContract));
125127
// merkle root was set before adding the tx, so it is now stale/invalid
126128

127-
BlockCapsule tampered = new BlockCapsule(local.getInstance());
128-
// tampered has no merkleValidated flag set
129129
try {
130-
tampered.validateMerkleRoot();
130+
local.validateMerkleRoot();
131131
Assert.fail("Expected BadBlockException for merkle mismatch");
132132
} catch (BadBlockException e) {
133133
Assert.assertTrue(e.getMessage().contains("merkle"));
134134
}
135+
local.setMerkleRoot();
136+
local.validateMerkleRoot();
137+
}
138+
139+
@Test
140+
public void testAddAllTransactionsMakesMerkleRootStale() throws Exception {
141+
BlockCapsule block = new BlockCapsule(1, Sha256Hash.ZERO_HASH, 1234, ByteString.EMPTY);
142+
block.setMerkleRoot();
143+
block.validateMerkleRoot();
144+
TransactionCapsule transaction = new TransactionCapsule(
145+
TransferContract.newBuilder().setAmount(999).build(), ContractType.TransferContract);
146+
147+
block.addAllTransactions(Arrays.asList(transaction));
148+
149+
Assert.assertThrows(BadBlockException.class, block::validateMerkleRoot);
150+
block.setMerkleRoot();
151+
block.validateMerkleRoot();
135152
}
136153

137154
/* @Test

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

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,13 @@
88
import static org.mockito.Mockito.doThrow;
99
import static org.mockito.Mockito.mock;
1010
import static org.mockito.Mockito.spy;
11+
import static org.mockito.Mockito.times;
1112
import static org.mockito.Mockito.verify;
1213
import static org.mockito.Mockito.when;
1314
import static org.tron.common.utils.Commons.adjustAssetBalanceV2;
1415
import static org.tron.common.utils.Commons.adjustTotalShieldedPoolValue;
1516
import static org.tron.common.utils.Commons.getExchangeStoreFinal;
1617
import static org.tron.common.utils.StringUtil.encode58Check;
17-
import static org.tron.core.exception.BadBlockException.TypeEnum.CALC_MERKLE_ROOT_FAILED;
1818
import static org.tron.protos.Protocol.Transaction.Result.contractResult.SUCCESS;
1919

2020
import com.beust.jcommander.internal.Lists;
@@ -106,6 +106,7 @@
106106
import org.tron.core.exception.ValidateScheduleException;
107107
import org.tron.core.exception.ValidateSignatureException;
108108
import org.tron.core.exception.ZksnarkException;
109+
import org.tron.core.net.TronNetDelegate;
109110
import org.tron.core.store.AccountStore;
110111
import org.tron.core.store.CodeStore;
111112
import org.tron.core.store.DynamicPropertiesStore;
@@ -506,23 +507,21 @@ public void adjustAssetBalanceV2Test() {
506507
}
507508

508509
@Test
509-
public void pushBlockInvalidMerkelRoot() {
510-
Transaction trx = Transaction.newBuilder().build();
511-
TransactionCapsule moreTrans = new TransactionCapsule(trx);
512-
blockCapsule2.addTransaction(moreTrans); // add one more transaction will change merkroot
513-
blockCapsule2.sign(ByteArray.fromHexString(Args.getLocalWitnesses()
514-
.getPrivateKey()));
515-
try {
516-
dbManager.pushBlock(blockCapsule2);
517-
Assert.assertTrue(false);
518-
} catch (BadBlockException e) {
519-
Assert.assertTrue(e instanceof BadBlockException);
520-
Assert.assertTrue(e.getType().equals(CALC_MERKLE_ROOT_FAILED));
521-
Assert.assertTrue(e.getMessage().startsWith(
522-
"merkle root mismatch for block " + blockCapsule2.getNum() + ":"));
523-
} catch (Exception e) {
524-
Assert.assertFalse(e instanceof Exception);
525-
}
510+
public void pushPrevalidatedBlockDoesNotRepeatMerkleValidation() throws Exception {
511+
byte[] witnessKey = ByteArray.fromHexString(Args.getLocalWitnesses().getPrivateKey());
512+
BlockCapsule block = new BlockCapsule(1, chainManager.getGenesisBlockId(), 1,
513+
ByteString.copyFrom(ECKey.fromPrivate(witnessKey).getAddress()));
514+
block.setMerkleRoot();
515+
block.sign(witnessKey);
516+
BlockCapsule received = spy(block);
517+
518+
context.getBean(TronNetDelegate.class).validBlock(received);
519+
dbManager.pushBlock(received);
520+
521+
Assert.assertEquals(received.getBlockId(), chainManager.getHeadBlockId());
522+
Assert.assertEquals(received.getInstance(),
523+
chainManager.getBlockStore().get(received.getBlockId().getBytes()).getInstance());
524+
verify(received, times(1)).validateMerkleRoot();
526525
}
527526

528527
@Test

0 commit comments

Comments
 (0)