diff --git a/common/src/main/java/org/tron/core/Constant.java b/common/src/main/java/org/tron/core/Constant.java index 2710787b890..816728fc650 100644 --- a/common/src/main/java/org/tron/core/Constant.java +++ b/common/src/main/java/org/tron/core/Constant.java @@ -13,6 +13,8 @@ public class Constant { public static final int NODE_TYPE_LIGHT_NODE = 1; // Transaction + // Keep Merkle leaf encodings larger than the 64-byte internal-node input. + public static final int MIN_TRANSACTION_SIZE = 80; public static final long TRANSACTION_MAX_BYTE_SIZE = 500 * 1_024L; public static final int CREATE_ACCOUNT_TRANSACTION_MIN_BYTE_SIZE = 500; public static final int CREATE_ACCOUNT_TRANSACTION_MAX_BYTE_SIZE = 10000; diff --git a/framework/src/main/java/org/tron/core/net/TronNetDelegate.java b/framework/src/main/java/org/tron/core/net/TronNetDelegate.java index cf749b2f837..99ca30b803a 100644 --- a/framework/src/main/java/org/tron/core/net/TronNetDelegate.java +++ b/framework/src/main/java/org/tron/core/net/TronNetDelegate.java @@ -1,5 +1,6 @@ package org.tron.core.net; +import static org.tron.core.Constant.MIN_TRANSACTION_SIZE; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; import com.google.common.cache.Cache; @@ -68,9 +69,6 @@ @Component public class TronNetDelegate { - // Keep Merkle leaf encodings larger than the 64-byte internal-node input. - private static final int MIN_TRANSACTION_SIZE = 80; - @Autowired private Manager dbManager; diff --git a/framework/src/main/java/org/tron/core/net/message/TronMessageFactory.java b/framework/src/main/java/org/tron/core/net/message/TronMessageFactory.java index 9635ea87410..a7d0ac6b666 100644 --- a/framework/src/main/java/org/tron/core/net/message/TronMessageFactory.java +++ b/framework/src/main/java/org/tron/core/net/message/TronMessageFactory.java @@ -7,7 +7,6 @@ import org.tron.core.net.message.adv.BlockMessage; import org.tron.core.net.message.adv.FetchInvDataMessage; import org.tron.core.net.message.adv.InventoryMessage; -import org.tron.core.net.message.adv.TransactionMessage; import org.tron.core.net.message.adv.TransactionsMessage; import org.tron.core.net.message.base.DisconnectMessage; import org.tron.core.net.message.handshake.HelloMessage; @@ -56,8 +55,6 @@ private static TronMessage create(byte type, byte[] packed) throws Exception { return new PingMessage(packed); case P2P_PONG: return new PongMessage(packed); - case TRX: - return new TransactionMessage(packed); case BLOCK: return new BlockMessage(packed); case TRXS: diff --git a/framework/src/main/java/org/tron/core/net/message/adv/BlockMessage.java b/framework/src/main/java/org/tron/core/net/message/adv/BlockMessage.java index 267cc71f714..8609a96453d 100644 --- a/framework/src/main/java/org/tron/core/net/message/adv/BlockMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/adv/BlockMessage.java @@ -1,31 +1,66 @@ package org.tron.core.net.message.adv; +import static org.tron.core.Constant.MIN_TRANSACTION_SIZE; +import static org.tron.core.config.Parameter.ChainConstant.BLOCK_SIZE; + import com.google.protobuf.CodedInputStream; +import com.google.protobuf.WireFormat; +import java.io.IOException; import org.tron.common.overlay.message.Message; import org.tron.common.utils.Sha256Hash; +import org.tron.core.Constant; import org.tron.core.capsule.BlockCapsule; import org.tron.core.capsule.BlockCapsule.BlockId; import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; +import org.tron.protos.Protocol.Block; public class BlockMessage extends TronMessage { + public static final int MAX_BLOCK_SIZE = BLOCK_SIZE + Constant.ONE_THOUSAND; + + // Every accepted transaction is at least MIN_TRANSACTION_SIZE bytes; header and + // repeated-field overhead only make this upper bound more conservative. + private static final int MAX_TRANSACTION_COUNT = MAX_BLOCK_SIZE / MIN_TRANSACTION_SIZE; + private static final int TRANSACTIONS_TAG = (Block.TRANSACTIONS_FIELD_NUMBER << 3) + | WireFormat.WIRETYPE_LENGTH_DELIMITED; + private BlockCapsule block; public BlockMessage(byte[] data) throws Exception { super(data); + precheck(data); this.type = MessageTypes.BLOCK.asByte(); - CodedInputStream input = getCodedInputStream(data); - this.block = new BlockCapsule(input); - // A top-level block must end at EOF, not at an unmatched END_GROUP tag. - input.checkLastTagWas(0); + this.block = new BlockCapsule(getCodedInputStream(data)); if (Message.isFilter()) { Message.compareBytes(data, block.getInstance().toByteArray()); TransactionCapsule.validContractProto(block.getInstance().getTransactionsList()); } } + private void precheck(byte[] data) throws IOException, P2pException { + if (data.length > MAX_BLOCK_SIZE) { + throw new P2pException(TypeEnum.BAD_MESSAGE, "block size over limit"); + } + CodedInputStream input = CodedInputStream.newInstance(data); + int transactionCount = 0; + int tag; + while ((tag = input.readTag()) != 0) { + if (tag == TRANSACTIONS_TAG && ++transactionCount > MAX_TRANSACTION_COUNT) { + throw new P2pException(TypeEnum.BAD_MESSAGE, "block transaction count over limit"); + } + // Skip each field without constructing transactions, bytes or unknown-field objects. + if (!input.skipField(tag)) { + break; + } + } + // A top-level block must end at EOF, not at an unmatched END_GROUP tag. + input.checkLastTagWas(0); + } + public BlockMessage(BlockCapsule block) { data = block.getData(); this.type = MessageTypes.BLOCK.asByte(); diff --git a/framework/src/main/java/org/tron/core/net/message/adv/TransactionsMessage.java b/framework/src/main/java/org/tron/core/net/message/adv/TransactionsMessage.java index 18a365b4d36..9a13f27e61e 100644 --- a/framework/src/main/java/org/tron/core/net/message/adv/TransactionsMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/adv/TransactionsMessage.java @@ -1,8 +1,14 @@ package org.tron.core.net.message.adv; +import static org.tron.core.config.Parameter.NetConstants.MAX_TRX_FETCH_PER_PEER; + import com.google.protobuf.CodedInputStream; +import com.google.protobuf.WireFormat; +import java.io.IOException; import java.util.List; import org.tron.core.capsule.TransactionCapsule; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; import org.tron.protos.Protocol; @@ -10,6 +16,9 @@ public class TransactionsMessage extends TronMessage { + private static final int TRANSACTIONS_TAG = (Protocol.Transactions.TRANSACTIONS_FIELD_NUMBER << 3) + | WireFormat.WIRETYPE_LENGTH_DELIMITED; + private Protocol.Transactions transactions; public TransactionsMessage(List trxs) { @@ -22,16 +31,32 @@ public TransactionsMessage(List trxs) { public TransactionsMessage(byte[] data) throws Exception { super(data); + precheck(data); this.type = MessageTypes.TRXS.asByte(); - CodedInputStream input = getCodedInputStream(data); - this.transactions = Protocol.Transactions.parseFrom(input); - input.checkLastTagWas(0); + this.transactions = Protocol.Transactions.parseFrom(getCodedInputStream(data)); if (isFilter()) { compareBytes(data, transactions.toByteArray()); TransactionCapsule.validContractProto(transactions.getTransactionsList()); } } + private void precheck(byte[] data) throws IOException, P2pException { + CodedInputStream input = CodedInputStream.newInstance(data); + int transactionCount = 0; + int tag; + while ((tag = input.readTag()) != 0) { + // Our TRX fetch requests contain at most this many entries; replies may split the batch. + if (tag == TRANSACTIONS_TAG && ++transactionCount > MAX_TRX_FETCH_PER_PEER) { + throw new P2pException(TypeEnum.BAD_MESSAGE, "transactions count over limit"); + } + // Count only top-level entries without parsing transaction contents. + if (!input.skipField(tag)) { + break; + } + } + input.checkLastTagWas(0); + } + public Protocol.Transactions getTransactions() { return transactions; } diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java index 0c0cc70a152..992c41804ef 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/BlockMsgHandler.java @@ -1,7 +1,6 @@ package org.tron.core.net.messagehandler; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; -import static org.tron.core.config.Parameter.ChainConstant.BLOCK_SIZE; import lombok.extern.slf4j.Slf4j; import org.bouncycastle.util.encoders.Hex; @@ -50,7 +49,7 @@ public class BlockMsgHandler implements TronMsgHandler { @Autowired private WitnessProductBlockService witnessProductBlockService; - private int maxBlockSize = BLOCK_SIZE + Constant.ONE_THOUSAND; + private int maxBlockSize = BlockMessage.MAX_BLOCK_SIZE; private boolean fastForward = Args.getInstance().isFastForward(); diff --git a/framework/src/test/java/org/tron/core/config/args/DynamicArgsReloadTest.java b/framework/src/test/java/org/tron/core/config/args/DynamicArgsReloadTest.java index b0b47ad92df..1d24eb0e616 100644 --- a/framework/src/test/java/org/tron/core/config/args/DynamicArgsReloadTest.java +++ b/framework/src/test/java/org/tron/core/config/args/DynamicArgsReloadTest.java @@ -99,20 +99,15 @@ public void restoreConfiguration() { } @Test - public void retriesAfterInvalidApiSettings() throws Exception { + public void reloadsNewerFileAfterInvalidPeerAddresses() throws Exception { assertRecoversAfterInvalidConfig( - "node.rpc.maxConcurrentCallsPerConnection = -1", - "node.rpc.maxRstStream = -1", - "node.rpc.maxRstStream = 2147483647", - "node.rpc.secondsPerWindow = -1", - "node.rpc.maxMessageSize = -1", - "node.http.maxMessageSize = -1", - "node.jsonrpc.maxMessageSize = -1"); + "node.active = [\"192.0.2.3:not-a-port\"]", + "node.passive = [\"192.0.2.4:not-a-port\"]"); } @Test - public void retriesAfterWrongConfigType() throws Exception { - assertRecoversAfterInvalidConfig("node.rpc.maxMessageSize = []"); + public void reloadsNewerFileAfterWrongPeerConfigType() throws Exception { + assertRecoversAfterInvalidConfig("node.active = true", "node.passive = true"); } @Test @@ -130,9 +125,11 @@ private void assertReloadsNewerFileAfterError(Error failure) throws Exception { long editedTimestamp = writeConfig("", "192.0.2.3", "192.0.2.4", initialTimestamp + 2000); try (MockedStatic netService = mockStatic(TronNetService.class)) { netService.when(TronNetService::getP2pConfig).thenReturn(p2pConfig); - try (MockedStatic nodeConfig = mockStatic(NodeConfig.class)) { - nodeConfig.when(() -> NodeConfig.fromConfig(any())).thenThrow(failure); + try (MockedStatic configuration = mockStatic(Configuration.class)) { + configuration.when(() -> Configuration.getByFileName(configFile.toString())) + .thenThrow(failure); reloadTask.run(); + configuration.verify(() -> Configuration.getByFileName(configFile.toString())); } assertEquals(editedTimestamp, lastModified()); assertNodes("192.0.2.1", "192.0.2.2"); diff --git a/framework/src/test/java/org/tron/core/net/message/TronMessageFactoryTest.java b/framework/src/test/java/org/tron/core/net/message/TronMessageFactoryTest.java new file mode 100644 index 00000000000..d672fd161d5 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/message/TronMessageFactoryTest.java @@ -0,0 +1,113 @@ +package org.tron.core.net.message; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockConstruction; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.InetSocketAddress; +import org.junit.Test; +import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; +import org.tron.common.overlay.message.Message; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; +import org.tron.core.net.P2pEventHandlerImpl; +import org.tron.core.net.message.adv.TransactionMessage; +import org.tron.core.net.message.adv.TransactionsMessage; +import org.tron.core.net.message.handshake.HelloMessage; +import org.tron.core.net.peer.PeerConnection; +import org.tron.core.net.peer.PeerManager; +import org.tron.p2p.base.Parameter; +import org.tron.p2p.connection.Channel; +import org.tron.protos.Protocol.ReasonCode; +import org.tron.protos.Protocol.Transaction; + +public class TronMessageFactoryTest { + + @Test + public void trxIsRejectedBeforeParsingRegardlessOfPayloadContents() { + byte[][] payloads = {new byte[0], {0x0c}, {0x0a, 0x7f}, + new byte[Parameter.MAX_MESSAGE_LENGTH - 2]}; + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(() -> Message.getCodedInputStream(any(byte[].class))) + .thenThrow(new AssertionError("TRX payload must not be parsed")); + for (byte[] payload : payloads) { + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(MessageTypes.TRX, payload))); + assertEquals(TypeEnum.NO_SUCH_MESSAGE, exception.getType()); + assertTrue(exception.getMessage().startsWith("TRX, len=")); + } + } + } + + @Test + public void canonicalTrxIsRejectedBeforeMessageConstruction() { + byte[] payload = sampleTransaction().toByteArray(); + try (MockedConstruction messages = + mockConstruction(TransactionMessage.class)) { + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(MessageTypes.TRX, payload))); + assertEquals(TypeEnum.NO_SUCH_MESSAGE, exception.getType()); + assertTrue(messages.constructed().isEmpty()); + } + } + + @Test + public void trxIsRejectedAtP2pEntryWithNoSuchMessage() { + Channel channel = mock(Channel.class); + PeerConnection peer = mock(PeerConnection.class); + when(peer.getHelloMessageReceive()).thenReturn(mock(HelloMessage.class)); + when(peer.getInetSocketAddress()).thenReturn(new InetSocketAddress("127.0.0.1", 10001)); + try (MockedStatic peers = mockStatic(PeerManager.class)) { + peers.when(() -> PeerManager.getPeerConnection(channel)).thenReturn(peer); + new P2pEventHandlerImpl().onMessage(channel, + withType(MessageTypes.TRX, new byte[] {0x0c})); + verify(peer).disconnect(ReasonCode.NO_SUCH_MESSAGE); + verify(peer, never()).getPeerStatistics(); + } + } + + @Test + public void directTransactionConstructionRetainsItsExistingBehavior() throws Exception { + Transaction transaction = sampleTransaction(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + assertEquals(transaction, + new TransactionMessage(transaction.toByteArray()).getTransactionCapsule().getInstance()); + assertEquals(transaction, + new TransactionMessage(transaction).getTransactionCapsule().getInstance()); + } + } + + @Test + public void supportedMessageTypesStillDecode() throws Exception { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + TransactionsMessage batch = (TransactionsMessage) TronMessageFactory.create( + withType(MessageTypes.TRXS, new byte[0])); + assertEquals(0, batch.getTransactions().getTransactionsCount()); + assertEquals(MessageTypes.P2P_PING, TronMessageFactory.create( + withType(MessageTypes.P2P_PING, new byte[] {(byte) 0xc0})).getType()); + } + } + + private static Transaction sampleTransaction() { + return Transaction.newBuilder().setRawData(Transaction.raw.newBuilder() + .setTimestamp(123456789L).setExpiration(123516789L)).build(); + } + + private static byte[] withType(MessageTypes type, byte[] payload) { + byte[] data = new byte[payload.length + 1]; + data[0] = type.asByte(); + System.arraycopy(payload, 0, data, 1, payload.length); + return data; + } +} diff --git a/framework/src/test/java/org/tron/core/net/message/adv/BlockMessageTest.java b/framework/src/test/java/org/tron/core/net/message/adv/BlockMessageTest.java index 2deb40d5437..373e6b342fe 100644 --- a/framework/src/test/java/org/tron/core/net/message/adv/BlockMessageTest.java +++ b/framework/src/test/java/org/tron/core/net/message/adv/BlockMessageTest.java @@ -2,20 +2,36 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; import com.google.protobuf.ByteString; +import com.google.protobuf.CodedOutputStream; import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.WireFormat; +import java.io.ByteArrayOutputStream; import java.util.Arrays; import org.junit.Test; +import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.tron.common.overlay.message.Message; +import org.tron.core.Constant; +import org.tron.core.capsule.BlockCapsule; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; +import org.tron.core.net.message.MessageTypes; +import org.tron.core.net.message.TronMessageFactory; import org.tron.protos.Protocol.Block; import org.tron.protos.Protocol.BlockHeader; +import org.tron.protos.Protocol.Transaction; public class BlockMessageTest { + private static final int MAX_TRANSACTION_COUNT = + BlockMessage.MAX_BLOCK_SIZE / Constant.MIN_TRANSACTION_SIZE; + private static Block sampleBlock() { return Block.newBuilder().setBlockHeader(BlockHeader.newBuilder() .setRawData(BlockHeader.raw.newBuilder().setNumber(100).setTimestamp(123456789L)) @@ -52,4 +68,154 @@ public void endGroupByteInsideABytesFieldIsAccepted() throws Exception { } } + @Test + public void rawSizeBoundaryIsAcceptedWithEitherFilterSetting() throws Exception { + for (int size : new int[] {BlockMessage.MAX_BLOCK_SIZE - 1, BlockMessage.MAX_BLOCK_SIZE}) { + // The two tags and two three-byte lengths add eight bytes at these sizes. + Block block = Block.newBuilder().setBlockHeader(BlockHeader.newBuilder() + .setWitnessSignature(ByteString.copyFrom(new byte[size - 8]))).build(); + byte[] data = block.toByteArray(); + assertEquals(size, data.length); + for (boolean filter : new boolean[] {false, true}) { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(filter); + assertEquals(block, new BlockMessage(data).getBlockCapsule().getInstance()); + } + } + } + } + + @Test + public void oversizedRawPayloadIsRejectedBeforeCapsuleConstruction() { + byte[] data = new byte[BlockMessage.MAX_BLOCK_SIZE + 1]; + for (boolean filter : new boolean[] {false, true}) { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS); + MockedConstruction capsules = mockConstruction(BlockCapsule.class)) { + messages.when(Message::isFilter).thenReturn(filter); + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(data))); + assertEquals(TypeEnum.BAD_MESSAGE, exception.getType()); + assertEquals("block size over limit", exception.getMessage()); + assertTrue(capsules.constructed().isEmpty()); + } + } + } + + @Test + public void oversizedNoncanonicalPayloadIsRejectedDespiteSmallParsedSize() throws Exception { + byte[] data = new byte[BlockMessage.MAX_BLOCK_SIZE + 2]; + for (int i = 0; i < data.length; i += 2) { + // Repeated empty occurrences of the singular block_header merge into one header. + data[i] = 0x12; + } + assertEquals(2, Block.parseFrom(data).getSerializedSize()); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + P2pException exception = assertThrows(P2pException.class, () -> new BlockMessage(data)); + assertEquals(TypeEnum.BAD_MESSAGE, exception.getType()); + assertEquals("block size over limit", exception.getMessage()); + } + } + + @Test + public void transactionCountBoundaryIsAccepted() throws Exception { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + for (int count : new int[] {0, MAX_TRANSACTION_COUNT - 1, MAX_TRANSACTION_COUNT}) { + BlockMessage message = new BlockMessage(emptyTransactions(count)); + assertEquals(count, message.getBlockCapsule().getInstance().getTransactionsCount()); + assertEquals(count, message.getBlockCapsule().getTransactions().size()); + } + } + } + + @Test + public void excessiveTransactionsAreRejectedBeforeCapsuleConstruction() { + byte[] data = emptyTransactions(MAX_TRANSACTION_COUNT + 1); + for (boolean filter : new boolean[] {false, true}) { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS); + MockedConstruction capsules = mockConstruction(BlockCapsule.class)) { + messages.when(Message::isFilter).thenReturn(filter); + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(data))); + assertEquals(TypeEnum.BAD_MESSAGE, exception.getType()); + assertEquals("block transaction count over limit", exception.getMessage()); + assertTrue(capsules.constructed().isEmpty()); + } + } + } + + @Test + public void transactionTagsInsideBytesAreNotCounted() throws Exception { + Transaction transaction = Transaction.newBuilder() + .addSignature(ByteString.copyFrom(emptyTransactions(MAX_TRANSACTION_COUNT + 1))) + .build(); + Block block = sampleBlock().toBuilder().addTransactions(transaction).build(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + assertEquals(block, new BlockMessage(block.toByteArray()).getBlockCapsule().getInstance()); + } + } + + @Test + public void transactionTagsInsideUnknownGroupsAreNotCounted() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + CodedOutputStream output = CodedOutputStream.newInstance(bytes); + output.writeTag(1000, WireFormat.WIRETYPE_START_GROUP); + output.writeRawBytes(emptyTransactions(MAX_TRANSACTION_COUNT + 1)); + output.writeTag(1000, WireFormat.WIRETYPE_END_GROUP); + output.flush(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + Block block = new BlockMessage(bytes.toByteArray()).getBlockCapsule().getInstance(); + assertEquals(0, block.getTransactionsCount()); + assertEquals(MAX_TRANSACTION_COUNT + 1, + block.getUnknownFields().getField(1000).getGroupList().get(0) + .getField(Block.TRANSACTIONS_FIELD_NUMBER).getLengthDelimitedList().size()); + } + } + + @Test + public void transactionFieldWithWrongWireTypeIsNotCounted() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + CodedOutputStream output = CodedOutputStream.newInstance(bytes); + for (int i = 0; i <= MAX_TRANSACTION_COUNT; i++) { + output.writeUInt32(Block.TRANSACTIONS_FIELD_NUMBER, 0); + } + output.flush(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + Block block = new BlockMessage(bytes.toByteArray()).getBlockCapsule().getInstance(); + assertEquals(0, block.getTransactionsCount()); + assertEquals(MAX_TRANSACTION_COUNT + 1, + block.getUnknownFields().getField(Block.TRANSACTIONS_FIELD_NUMBER) + .getVarintList().size()); + } + } + + @Test + public void malformedLengthsStillReportParseFailure() { + for (byte[] data : new byte[][] {{0x0a, 0x01}, {0x0a, (byte) 0x80}, + {0x0a, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0f}}) { + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(data))); + assertEquals(TypeEnum.PARSE_MESSAGE_FAILED, exception.getType()); + } + } + + private static byte[] emptyTransactions(int count) { + byte[] data = new byte[count * 2]; + for (int i = 0; i < data.length; i += 2) { + data[i] = 0x0a; + } + return data; + } + + private static byte[] withType(byte[] data) { + byte[] message = new byte[data.length + 1]; + message[0] = MessageTypes.BLOCK.asByte(); + System.arraycopy(data, 0, message, 1, data.length); + return message; + } + } diff --git a/framework/src/test/java/org/tron/core/net/message/adv/TransactionsMessageTest.java b/framework/src/test/java/org/tron/core/net/message/adv/TransactionsMessageTest.java new file mode 100644 index 00000000000..4918179200e --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/message/adv/TransactionsMessageTest.java @@ -0,0 +1,170 @@ +package org.tron.core.net.message.adv; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.CALLS_REAL_METHODS; +import static org.mockito.Mockito.mockStatic; +import static org.tron.core.config.Parameter.NetConstants.MAX_TRX_FETCH_PER_PEER; + +import com.google.protobuf.ByteString; +import com.google.protobuf.CodedInputStream; +import com.google.protobuf.CodedOutputStream; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.WireFormat; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Collections; +import org.junit.Test; +import org.mockito.MockedStatic; +import org.tron.common.overlay.message.Message; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; +import org.tron.core.net.message.MessageTypes; +import org.tron.core.net.message.TronMessageFactory; +import org.tron.p2p.base.Parameter; +import org.tron.protos.Protocol.Transaction; +import org.tron.protos.Protocol.Transactions; + +public class TransactionsMessageTest { + + @Test + public void transactionCountBoundaryIsAccepted() throws Exception { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + for (int count : new int[] {0, 1, MAX_TRX_FETCH_PER_PEER - 1, MAX_TRX_FETCH_PER_PEER}) { + TransactionsMessage message = new TransactionsMessage(emptyTransactions(count)); + assertEquals(count, message.getTransactions().getTransactionsCount()); + } + } + } + + @Test + public void excessiveTransactionsAreRejectedBeforeParsingWithEitherFilterSetting() { + byte[] data = withType(emptyTransactions(MAX_TRX_FETCH_PER_PEER + 1)); + for (boolean filter : new boolean[] {false, true}) { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS); + MockedStatic transactions = mockStatic(Transactions.class, + CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(filter); + transactions.when(() -> Transactions.parseFrom(any(CodedInputStream.class))) + .thenThrow(new AssertionError("protobuf parsing must not be reached")); + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(data)); + assertEquals(TypeEnum.BAD_MESSAGE, exception.getType()); + assertEquals("transactions count over limit", exception.getMessage()); + } + } + } + + @Test + public void transactionTagsInsideBytesAreNotCounted() throws Exception { + Transaction transaction = Transaction.newBuilder() + .addSignature(ByteString.copyFrom(emptyTransactions(MAX_TRX_FETCH_PER_PEER + 1))) + .build(); + Transactions expected = Transactions.newBuilder().addTransactions(transaction).build(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + assertEquals(expected, new TransactionsMessage(expected.toByteArray()).getTransactions()); + } + } + + @Test + public void transactionTagsInsideUnknownGroupsAreNotCounted() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + CodedOutputStream output = CodedOutputStream.newInstance(bytes); + output.writeTag(1000, WireFormat.WIRETYPE_START_GROUP); + output.writeRawBytes(emptyTransactions(MAX_TRX_FETCH_PER_PEER + 1)); + output.writeTag(1000, WireFormat.WIRETYPE_END_GROUP); + output.flush(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + Transactions parsed = new TransactionsMessage(bytes.toByteArray()).getTransactions(); + assertEquals(0, parsed.getTransactionsCount()); + assertEquals(MAX_TRX_FETCH_PER_PEER + 1, + parsed.getUnknownFields().getField(1000).getGroupList().get(0) + .getField(Transactions.TRANSACTIONS_FIELD_NUMBER).getLengthDelimitedList().size()); + } + } + + @Test + public void transactionFieldWithWrongWireTypeIsNotCounted() throws Exception { + ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + CodedOutputStream output = CodedOutputStream.newInstance(bytes); + for (int i = 0; i <= MAX_TRX_FETCH_PER_PEER; i++) { + output.writeUInt32(Transactions.TRANSACTIONS_FIELD_NUMBER, 0); + } + output.flush(); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + Transactions parsed = new TransactionsMessage(bytes.toByteArray()).getTransactions(); + assertEquals(0, parsed.getTransactionsCount()); + assertEquals(MAX_TRX_FETCH_PER_PEER + 1, + parsed.getUnknownFields().getField(Transactions.TRANSACTIONS_FIELD_NUMBER) + .getVarintList().size()); + } + } + + @Test + public void largeSingleTransactionDoesNotGetAnAdditionalSizeLimit() throws Exception { + Transaction transaction = Transaction.newBuilder() + .addSignature(ByteString.copyFrom(new byte[2_100_000])).build(); + Transactions expected = Transactions.newBuilder().addTransactions(transaction).build(); + byte[] data = expected.toByteArray(); + assertTrue(data.length > BlockMessage.MAX_BLOCK_SIZE); + assertTrue(data.length + 1 < Parameter.MAX_MESSAGE_LENGTH); + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(false); + assertEquals(expected, new TransactionsMessage(data).getTransactions()); + } + } + + @Test + public void trailingEndGroupIsRejectedWithEitherFilterSetting() { + byte[] canonical = emptyTransactions(1); + for (boolean filter : new boolean[] {false, true}) { + try (MockedStatic messages = mockStatic(Message.class, CALLS_REAL_METHODS)) { + messages.when(Message::isFilter).thenReturn(filter); + for (byte[] suffix : new byte[][] {{0x0c}, {0x14}, {0x0c, 0x08, 0x01}}) { + byte[] malformed = Arrays.copyOf(canonical, canonical.length + suffix.length); + System.arraycopy(suffix, 0, malformed, canonical.length, suffix.length); + assertThrows(InvalidProtocolBufferException.class, + () -> new TransactionsMessage(malformed)); + } + } + } + } + + @Test + public void malformedLengthsStillReportParseFailure() { + for (byte[] data : new byte[][] {{0x0a, 0x01}, {0x0a, (byte) 0x80}, + {0x0a, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, 0x0f}}) { + P2pException exception = assertThrows(P2pException.class, + () -> TronMessageFactory.create(withType(data))); + assertEquals(TypeEnum.PARSE_MESSAGE_FAILED, exception.getType()); + } + } + + @Test + public void outgoingConstructorRetainsItsExistingBehavior() { + TransactionsMessage message = new TransactionsMessage( + Collections.nCopies(MAX_TRX_FETCH_PER_PEER + 1, Transaction.getDefaultInstance())); + assertEquals(MAX_TRX_FETCH_PER_PEER + 1, message.getTransactions().getTransactionsCount()); + } + + private static byte[] emptyTransactions(int count) { + byte[] data = new byte[count * 2]; + for (int i = 0; i < data.length; i += 2) { + data[i] = 0x0a; + } + return data; + } + + private static byte[] withType(byte[] data) { + byte[] message = new byte[data.length + 1]; + message[0] = MessageTypes.TRXS.asByte(); + System.arraycopy(data, 0, message, 1, data.length); + return message; + } +}