From 6bc9d22e9d5944009271603b4ccb25377f41382a Mon Sep 17 00:00:00 2001 From: GrapeS Date: Fri, 4 Dec 2026 21:07:44 +0800 Subject: [PATCH] fix(net): precheck id counts of inventory and sync messages Reject INVENTORY, FETCH_INV_DATA, BLOCK_CHAIN_INVENTORY and SYNC_BLOCK_CHAIN messages whose id lists exceed what senders produce before decoding them. Move the counting loop used by BLOCK and TRXS into TronMessage.checkRepeatedCount() and reuse it, and move MAX_SPREAD_SIZE into NetConstants so the inventory limit can refer to it. --- .../java/org/tron/core/config/Parameter.java | 2 + .../tron/core/net/message/TronMessage.java | 24 + .../core/net/message/adv/BlockMessage.java | 17 +- .../net/message/adv/InventoryMessage.java | 16 + .../net/message/adv/TransactionsMessage.java | 19 +- .../message/sync/BlockInventoryMessage.java | 10 + .../message/sync/ChainInventoryMessage.java | 9 + .../ChainInventoryMsgHandler.java | 2 +- .../tron/core/net/service/adv/AdvService.java | 2 +- .../core/net/P2pEventHandlerImplTest.java | 28 ++ .../net/message/InventoryPrecheckTest.java | 462 ++++++++++++++++++ 11 files changed, 558 insertions(+), 33 deletions(-) create mode 100644 framework/src/test/java/org/tron/core/net/message/InventoryPrecheckTest.java diff --git a/common/src/main/java/org/tron/core/config/Parameter.java b/common/src/main/java/org/tron/core/config/Parameter.java index 2d8ce0a50ef..e3be74808d2 100644 --- a/common/src/main/java/org/tron/core/config/Parameter.java +++ b/common/src/main/java/org/tron/core/config/Parameter.java @@ -109,6 +109,8 @@ public class NetConstants { public static final int MAX_BLOCK_FETCH_PER_PEER = 100; public static final int MAX_TRX_FETCH_PER_PEER = 1000; public static final int MAX_SYNC_CHAIN_IDS = 30; + // AdvService stops queuing items to spread once more than this many are waiting. + public static final int MAX_SPREAD_SIZE = 1_000; } public class DatabaseConstants { diff --git a/framework/src/main/java/org/tron/core/net/message/TronMessage.java b/framework/src/main/java/org/tron/core/net/message/TronMessage.java index 545dd8bf892..f92628d4653 100644 --- a/framework/src/main/java/org/tron/core/net/message/TronMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/TronMessage.java @@ -18,7 +18,11 @@ package org.tron.core.net.message; +import com.google.protobuf.CodedInputStream; +import java.io.IOException; import org.tron.common.overlay.message.Message; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; public abstract class TronMessage extends Message { @@ -32,4 +36,24 @@ public TronMessage(byte[] rawData) { public TronMessage(byte type, byte[] rawData) { super(type, rawData); } + + /** + * Throws BAD_MESSAGE with {@code reason} if {@code data} has more than {@code maxCount} + * top-level fields with {@code fieldTag}. The fields are counted without being decoded. + */ + protected static void checkRepeatedCount(byte[] data, int fieldTag, int maxCount, + String reason) throws IOException, P2pException { + CodedInputStream input = CodedInputStream.newInstance(data); + int count = 0; + int tag; + while ((tag = input.readTag()) != 0) { + if (tag == fieldTag && ++count > maxCount) { + throw new P2pException(TypeEnum.BAD_MESSAGE, reason); + } + if (!input.skipField(tag)) { + break; + } + } + input.checkLastTagWas(0); + } } 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 8609a96453d..f74f346dadb 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 @@ -3,7 +3,6 @@ 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; @@ -45,20 +44,8 @@ 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); + checkRepeatedCount(data, TRANSACTIONS_TAG, MAX_TRANSACTION_COUNT, + "block transaction count over limit"); } public BlockMessage(BlockCapsule block) { diff --git a/framework/src/main/java/org/tron/core/net/message/adv/InventoryMessage.java b/framework/src/main/java/org/tron/core/net/message/adv/InventoryMessage.java index 1585fe2a351..5e2c70a493e 100644 --- a/framework/src/main/java/org/tron/core/net/message/adv/InventoryMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/adv/InventoryMessage.java @@ -1,9 +1,15 @@ package org.tron.core.net.message.adv; +import static org.tron.core.config.Parameter.NetConstants.MAX_BLOCK_FETCH_PER_PEER; +import static org.tron.core.config.Parameter.NetConstants.MAX_SPREAD_SIZE; +import static org.tron.core.config.Parameter.NetConstants.MAX_TRX_FETCH_PER_PEER; + +import com.google.protobuf.WireFormat; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; +import org.tron.common.math.StrictMathWrapper; import org.tron.common.utils.Sha256Hash; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; @@ -15,10 +21,20 @@ public class InventoryMessage extends TronMessage { + // An inventory carries at most about MAX_SPREAD_SIZE ids and a fetch at most + // MAX_TRX_FETCH_PER_PEER or MAX_BLOCK_FETCH_PER_PEER. The margin covers broadcasts that pass + // AdvService's unlocked queue-size check at the same time and each add one item. + private static final int SENDER_LIMIT_MARGIN = 10; + public static final int MAX_IDS_COUNT = SENDER_LIMIT_MARGIN * StrictMathWrapper.max( + MAX_SPREAD_SIZE, StrictMathWrapper.max(MAX_TRX_FETCH_PER_PEER, MAX_BLOCK_FETCH_PER_PEER)); + private static final int IDS_TAG = (Inventory.IDS_FIELD_NUMBER << 3) + | WireFormat.WIRETYPE_LENGTH_DELIMITED; + protected Inventory inv; public InventoryMessage(byte[] data) throws Exception { super(data); + checkRepeatedCount(data, IDS_TAG, MAX_IDS_COUNT, "inventory ids count over limit"); this.type = MessageTypes.INVENTORY.asByte(); this.inv = ProtoUtil.parseFrom(Protocol.Inventory.parser(), data); } 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 9a13f27e61e..2073d65c413 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 @@ -2,13 +2,11 @@ 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; @@ -41,20 +39,9 @@ public TransactionsMessage(byte[] data) throws Exception { } 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); + // Our TRX fetch requests contain at most this many entries; replies may split the batch. + checkRepeatedCount(data, TRANSACTIONS_TAG, MAX_TRX_FETCH_PER_PEER, + "transactions count over limit"); } public Protocol.Transactions getTransactions() { diff --git a/framework/src/main/java/org/tron/core/net/message/sync/BlockInventoryMessage.java b/framework/src/main/java/org/tron/core/net/message/sync/BlockInventoryMessage.java index 546ef072396..5ecdc299788 100644 --- a/framework/src/main/java/org/tron/core/net/message/sync/BlockInventoryMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/sync/BlockInventoryMessage.java @@ -1,9 +1,11 @@ package org.tron.core.net.message.sync; +import com.google.protobuf.WireFormat; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.config.Parameter.NetConstants; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; import org.tron.p2p.utils.ProtoUtil; @@ -12,10 +14,18 @@ public class BlockInventoryMessage extends TronMessage { + // Peers send this message as SYNC_BLOCK_CHAIN, whose handler accepts at most + // MAX_SYNC_CHAIN_IDS block ids. A chain summary halves the remaining range at each step, so + // its size grows with the logarithm of the chain length. + public static final int MAX_IDS_COUNT = NetConstants.MAX_SYNC_CHAIN_IDS; + private static final int IDS_TAG = (BlockInventory.IDS_FIELD_NUMBER << 3) + | WireFormat.WIRETYPE_LENGTH_DELIMITED; + protected BlockInventory blockInventory; public BlockInventoryMessage(byte[] data) throws Exception { super(data); + checkRepeatedCount(data, IDS_TAG, MAX_IDS_COUNT, "block inventory ids count over limit"); this.type = MessageTypes.BLOCK_INVENTORY.asByte(); this.blockInventory = ProtoUtil.parseFrom(Protocol.BlockInventory.parser(), data); } diff --git a/framework/src/main/java/org/tron/core/net/message/sync/ChainInventoryMessage.java b/framework/src/main/java/org/tron/core/net/message/sync/ChainInventoryMessage.java index e4548fdc9cf..5cf4d68504b 100644 --- a/framework/src/main/java/org/tron/core/net/message/sync/ChainInventoryMessage.java +++ b/framework/src/main/java/org/tron/core/net/message/sync/ChainInventoryMessage.java @@ -1,11 +1,13 @@ package org.tron.core.net.message.sync; +import com.google.protobuf.WireFormat; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.stream.Collectors; import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.config.Parameter.NetConstants; import org.tron.core.net.message.MessageTypes; import org.tron.core.net.message.TronMessage; import org.tron.p2p.utils.ProtoUtil; @@ -14,10 +16,17 @@ public class ChainInventoryMessage extends TronMessage { + // A reply lists the common block and at most SYNC_FETCH_BATCH_NUM blocks after it, and + // ChainInventoryMsgHandler rejects longer lists. + public static final int MAX_IDS_COUNT = (int) NetConstants.SYNC_FETCH_BATCH_NUM + 1; + private static final int IDS_TAG = (ChainInventory.IDS_FIELD_NUMBER << 3) + | WireFormat.WIRETYPE_LENGTH_DELIMITED; + protected ChainInventory chainInventory; public ChainInventoryMessage(byte[] data) throws Exception { super(data); + checkRepeatedCount(data, IDS_TAG, MAX_IDS_COUNT, "chain inventory ids count over limit"); this.type = MessageTypes.BLOCK_CHAIN_INVENTORY.asByte(); chainInventory = ProtoUtil.parseFrom(Protocol.ChainInventory.parser(), data); } diff --git a/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java b/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java index bc3135c19d1..b289a4ef60a 100644 --- a/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java +++ b/framework/src/main/java/org/tron/core/net/messagehandler/ChainInventoryMsgHandler.java @@ -113,7 +113,7 @@ private void check(PeerConnection peer, ChainInventoryMessage msg) throws P2pExc "remainNum is negative: " + msg.getRemainNum()); } - if (blockIds.size() > NetConstants.SYNC_FETCH_BATCH_NUM + 1) { + if (blockIds.size() > ChainInventoryMessage.MAX_IDS_COUNT) { throw new P2pException(TypeEnum.BAD_MESSAGE, "big blockIds size: " + blockIds.size()); } diff --git a/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java b/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java index 355217bcb58..7cc8cd57da8 100644 --- a/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java +++ b/framework/src/main/java/org/tron/core/net/service/adv/AdvService.java @@ -1,6 +1,7 @@ package org.tron.core.net.service.adv; import static org.tron.core.config.Parameter.ChainConstant.BLOCK_PRODUCED_INTERVAL; +import static org.tron.core.config.Parameter.NetConstants.MAX_SPREAD_SIZE; import static org.tron.core.config.Parameter.NetConstants.MAX_TRX_FETCH_PER_PEER; import static org.tron.core.config.Parameter.NetConstants.MSG_CACHE_DURATION_IN_BLOCKS; @@ -47,7 +48,6 @@ public class AdvService { private final int MAX_INV_TO_FETCH_CACHE_SIZE = 100_000; private final int MAX_TRX_CACHE_SIZE = 50_000; private final int MAX_BLOCK_CACHE_SIZE = 10; - private final int MAX_SPREAD_SIZE = 1_000; private final long TIMEOUT = MSG_CACHE_DURATION_IN_BLOCKS * BLOCK_PRODUCED_INTERVAL; @Autowired diff --git a/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java index 135ae68461d..49b57bfcb6c 100644 --- a/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java +++ b/framework/src/test/java/org/tron/core/net/P2pEventHandlerImplTest.java @@ -251,6 +251,34 @@ public void testCheckInvRateLimitBlockBoundary() throws Exception { peer.getPeerStatistics().messageStatistics.tronInBlockInventoryElement.getCount(10)); } + @Test + public void testInventoryOverIdLimitDisconnects() throws Exception { + CommonParameter parameter = CommonParameter.getInstance(); + parameter.setMaxTps(10); + parameter.setMaxBlockInvPerSecond(10); + + PeerStatistics peerStatistics = new PeerStatistics(); + PeerConnection peer = mock(PeerConnection.class); + Mockito.when(peer.getPeerStatistics()).thenReturn(peerStatistics); + + P2pEventHandlerImpl handler = new P2pEventHandlerImpl(); + Method method = handler.getClass() + .getDeclaredMethod("processMessage", PeerConnection.class, byte[].class); + method.setAccessible(true); + + List list = new ArrayList<>(); + for (int i = 0; i <= InventoryMessage.MAX_IDS_COUNT; i++) { + list.add(new Sha256Hash(i, new byte[32])); + } + InventoryMessage msg = new InventoryMessage(list, InventoryType.TRX); + method.invoke(handler, peer, msg.getSendBytes()); + + // The id count is checked before decoding: BAD_MESSAGE -> disconnect(BAD_PROTOCOL). + verify(peer).disconnect(Protocol.ReasonCode.BAD_PROTOCOL); + Assert.assertEquals(0, + peerStatistics.messageStatistics.tronInTrxInventoryElement.getTotalCount()); + } + @Test public void testCheckInvRateLimitUnknownTypeRejected() throws Exception { CommonParameter parameter = CommonParameter.getInstance(); diff --git a/framework/src/test/java/org/tron/core/net/message/InventoryPrecheckTest.java b/framework/src/test/java/org/tron/core/net/message/InventoryPrecheckTest.java new file mode 100644 index 00000000000..b146061dd69 --- /dev/null +++ b/framework/src/test/java/org/tron/core/net/message/InventoryPrecheckTest.java @@ -0,0 +1,462 @@ +package org.tron.core.net.message; + +import com.google.protobuf.Descriptors.Descriptor; +import com.google.protobuf.Descriptors.FieldDescriptor; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Parser; +import com.google.protobuf.WireFormat; +import java.io.ByteArrayOutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Random; +import org.junit.Assert; +import org.junit.Test; +import org.springframework.test.util.ReflectionTestUtils; +import org.tron.common.utils.Sha256Hash; +import org.tron.core.capsule.BlockCapsule.BlockId; +import org.tron.core.exception.P2pException; +import org.tron.core.exception.P2pException.TypeEnum; +import org.tron.core.net.message.adv.FetchInvDataMessage; +import org.tron.core.net.message.adv.InventoryMessage; +import org.tron.core.net.message.sync.BlockInventoryMessage; +import org.tron.core.net.message.sync.ChainInventoryMessage; +import org.tron.core.net.message.sync.SyncBlockChainMessage; +import org.tron.p2p.utils.ProtoUtil; +import org.tron.protos.Protocol.BlockInventory; +import org.tron.protos.Protocol.ChainInventory; +import org.tron.protos.Protocol.Inventory; +import org.tron.protos.Protocol.Inventory.InventoryType; + +/** + * The id-count prechecks of INVENTORY, FETCH_INV_DATA, BLOCK_CHAIN_INVENTORY and + * SYNC_BLOCK_CHAIN: within the limit a message decodes exactly as the parser decodes it, and a + * message with more ids is rejected with BAD_MESSAGE before it is parsed. + */ +public class InventoryPrecheckTest { + + private static final int VARINT = WireFormat.WIRETYPE_VARINT; + private static final int FIXED64 = WireFormat.WIRETYPE_FIXED64; + private static final int LENGTH_DELIMITED = WireFormat.WIRETYPE_LENGTH_DELIMITED; + private static final int START_GROUP = WireFormat.WIRETYPE_START_GROUP; + private static final int END_GROUP = WireFormat.WIRETYPE_END_GROUP; + private static final int FIXED32 = WireFormat.WIRETYPE_FIXED32; + private static final int[] WIRE_TYPES = {VARINT, FIXED64, LENGTH_DELIMITED, START_GROUP, FIXED32}; + private static final int[] NON_GROUP_WIRE_TYPES = {VARINT, FIXED64, LENGTH_DELIMITED, FIXED32}; + + // Field numbers from this one up are not defined by any of the tested messages. + private static final int FIRST_UNKNOWN_FIELD = 1 + highestFieldNumber( + Inventory.getDescriptor(), ChainInventory.getDescriptor(), BlockInventory.getDescriptor()); + private static final int UNKNOWN_FIELD_SPAN = 32; + private static final int MAX_GROUP_DEPTH = 3; + private static final int MAX_GROUP_FIELDS = 3; + private static final int PADDING_SIZE = 8192; + private static final int WRONG_WIRE_TYPE_ENTRIES = 100; + private static final int PAYLOADS_PER_KIND = 5000; + + private enum Kind { + INVENTORY(MessageTypes.INVENTORY, InventoryMessage.MAX_IDS_COUNT, + Inventory.IDS_FIELD_NUMBER, Inventory.TYPE_FIELD_NUMBER), + FETCH_INV_DATA(MessageTypes.FETCH_INV_DATA, InventoryMessage.MAX_IDS_COUNT, + Inventory.IDS_FIELD_NUMBER, Inventory.TYPE_FIELD_NUMBER), + CHAIN_INVENTORY(MessageTypes.BLOCK_CHAIN_INVENTORY, ChainInventoryMessage.MAX_IDS_COUNT, + ChainInventory.IDS_FIELD_NUMBER, ChainInventory.REMAIN_NUM_FIELD_NUMBER), + SYNC_BLOCK_CHAIN(MessageTypes.SYNC_BLOCK_CHAIN, BlockInventoryMessage.MAX_IDS_COUNT, + BlockInventory.IDS_FIELD_NUMBER, BlockInventory.TYPE_FIELD_NUMBER); + + final MessageTypes type; + final int maxIds; + final int idsField; + // The varint field next to the ids: the inventory type or remain_num. + final int otherField; + + Kind(MessageTypes type, int maxIds, int idsField, int otherField) { + this.type = type; + this.maxIds = maxIds; + this.idsField = idsField; + this.otherField = otherField; + } + + boolean isInventory() { + return this == INVENTORY || this == FETCH_INV_DATA; + } + + int idsTag() { + return tag(idsField, LENGTH_DELIMITED); + } + + TronMessage create(byte[] data) throws Exception { + switch (this) { + case INVENTORY: + return new InventoryMessage(data); + case FETCH_INV_DATA: + return new FetchInvDataMessage(data); + case CHAIN_INVENTORY: + return new ChainInventoryMessage(data); + default: + return new SyncBlockChainMessage(data); + } + } + + Parser parser() { + if (isInventory()) { + return Inventory.parser(); + } + return this == CHAIN_INVENTORY ? ChainInventory.parser() : BlockInventory.parser(); + } + + com.google.protobuf.Message decoded(TronMessage msg) { + if (isInventory()) { + return ((InventoryMessage) msg).getInventory(); + } + String field = this == CHAIN_INVENTORY ? "chainInventory" : "blockInventory"; + return (com.google.protobuf.Message) ReflectionTestUtils.getField(msg, field); + } + + int idsCount(com.google.protobuf.Message proto) { + if (isInventory()) { + return ((Inventory) proto).getIdsCount(); + } + return this == CHAIN_INVENTORY ? ((ChainInventory) proto).getIdsCount() + : ((BlockInventory) proto).getIdsCount(); + } + } + + @Test + public void largestHonestMessagesDecode() throws Exception { + List hashes = new ArrayList<>(); + for (int i = 0; i < InventoryMessage.MAX_IDS_COUNT; i++) { + hashes.add(Sha256Hash.wrap(hash(i))); + } + InventoryMessage inv = new InventoryMessage(hashes, InventoryType.BLOCK); + Assert.assertEquals(inv.getInventory(), + new InventoryMessage(inv.getData()).getInventory()); + FetchInvDataMessage fetch = new FetchInvDataMessage(hashes, InventoryType.TRX); + Assert.assertEquals(fetch.getInventory(), + new FetchInvDataMessage(fetch.getData()).getInventory()); + + ChainInventoryMessage chain = new ChainInventoryMessage( + blockIds(ChainInventoryMessage.MAX_IDS_COUNT), Long.MAX_VALUE); + Assert.assertEquals(ReflectionTestUtils.getField(chain, "chainInventory"), + ReflectionTestUtils.getField(new ChainInventoryMessage(chain.getData()), + "chainInventory")); + + SyncBlockChainMessage sync = new SyncBlockChainMessage( + blockIds(BlockInventoryMessage.MAX_IDS_COUNT)); + Assert.assertEquals(ReflectionTestUtils.getField(sync, "blockInventory"), + ReflectionTestUtils.getField(new SyncBlockChainMessage(sync.getData()), + "blockInventory")); + } + + @Test + public void oneIdOverTheLimitIsRejectedBeforeParsing() throws Exception { + for (Kind kind : Kind.values()) { + // A field that declares a length but carries no content follows the ids, so parsing the + // payload would throw InvalidProtocolBufferException; BAD_MESSAGE shows the count was + // checked first. + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i <= kind.maxIds; i++) { + writeVarint(out, kind.idsTag()); + writeVarint(out, 0); + } + writeVarint(out, kind.idsTag()); + writeVarint(out, Sha256Hash.LENGTH); + byte[] data = out.toByteArray(); + assertBadMessage(kind, () -> kind.create(data)); + + byte[] frame = new byte[data.length + 1]; + frame[0] = kind.type.asByte(); + System.arraycopy(data, 0, frame, 1, data.length); + assertBadMessage(kind, () -> TronMessageFactory.create(frame)); + } + } + + @Test + public void onlyTopLevelIdEntriesAreCounted() throws Exception { + for (Kind kind : Kind.values()) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < kind.maxIds; i++) { + byte[] body = kind.isInventory() ? hash(i) : blockId(hash(i), i); + writeVarint(out, kind.idsTag()); + writeVarint(out, body.length); + out.write(body); + } + // The ids field number with a varint wire type is an unknown field to the parser. + for (int i = 0; i < WRONG_WIRE_TYPE_ENTRIES; i++) { + writeVarint(out, tag(kind.idsField, VARINT)); + writeVarint(out, 1); + } + // An unknown length-delimited field. + writeVarint(out, tag(FIRST_UNKNOWN_FIELD, LENGTH_DELIMITED)); + writeVarint(out, PADDING_SIZE); + out.write(new byte[PADDING_SIZE]); + byte[] data = out.toByteArray(); + + TronMessage msg = kind.create(data); + Assert.assertEquals(kind.maxIds, kind.idsCount(kind.decoded(msg))); + Assert.assertEquals(ProtoUtil.parseFrom(kind.parser(), data), kind.decoded(msg)); + } + } + + @Test + public void decodesExactlyLikeTheParserWithinTheLimit() throws Exception { + for (Kind kind : Kind.values()) { + Random random = new Random(20261204L + kind.ordinal()); + int accepted = 0; + int rejectedByParser = 0; + int rejectedByCount = 0; + for (int i = 0; i < PAYLOADS_PER_KIND; i++) { + byte[] data = randomPayload(random, kind); + com.google.protobuf.Message expected; + try { + expected = ProtoUtil.parseFrom(kind.parser(), data); + } catch (InvalidProtocolBufferException e) { + expected = null; + } + + TronMessage msg = null; + Exception error = null; + try { + msg = kind.create(data); + } catch (Exception e) { + error = e; + } + + if (expected == null) { + // The parser rejects it: the message must not be created. + Assert.assertNotNull(kind + " accepted a payload the parser rejects", error); + rejectedByParser++; + } else if (kind.idsCount(expected) <= kind.maxIds) { + // Within the limit: same outcome and same content as the parser. + Assert.assertNull(kind + " rejected a payload the parser accepts: " + error, error); + Assert.assertEquals(expected, kind.decoded(msg)); + accepted++; + } else { + Assert.assertTrue(error instanceof P2pException); + Assert.assertEquals(TypeEnum.BAD_MESSAGE, ((P2pException) error).getType()); + rejectedByCount++; + } + } + // Guard against a generator that never reaches one of the paths. + Assert.assertTrue(kind + " accepted " + accepted, accepted > PAYLOADS_PER_KIND / 10); + Assert.assertTrue(kind + " parser rejected " + rejectedByParser, + rejectedByParser > PAYLOADS_PER_KIND / 10); + if (kind == Kind.SYNC_BLOCK_CHAIN) { + Assert.assertTrue(kind + " count rejected " + rejectedByCount, + rejectedByCount > PAYLOADS_PER_KIND / 100); + } + } + } + + @Test + public void nestedUnknownGroupsMatchTheParser() throws Exception { + // Depths below, at and far beyond the parser's recursion limit. + for (Kind kind : Kind.values()) { + for (int depth : new int[] {50, 99, 100, 101, 150, 3000}) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writeVarint(out, kind.idsTag()); + writeVarint(out, 0); + for (int i = 0; i < depth; i++) { + writeVarint(out, tag(FIRST_UNKNOWN_FIELD, START_GROUP)); + } + for (int i = 0; i < depth; i++) { + writeVarint(out, tag(FIRST_UNKNOWN_FIELD, END_GROUP)); + } + byte[] data = out.toByteArray(); + + boolean parserAccepts; + try { + ProtoUtil.parseFrom(kind.parser(), data); + parserAccepts = true; + } catch (InvalidProtocolBufferException e) { + parserAccepts = false; + } + boolean messageAccepts; + try { + kind.create(data); + messageAccepts = true; + } catch (InvalidProtocolBufferException e) { + messageAccepts = false; + } + Assert.assertEquals(kind + " depth " + depth, parserAccepts, messageAccepts); + } + } + } + + private interface Call { + Object run() throws Exception; + } + + private static void assertBadMessage(Kind kind, Call call) throws Exception { + try { + call.run(); + Assert.fail(kind + " accepted a message over the id limit"); + } catch (P2pException e) { + Assert.assertEquals(TypeEnum.BAD_MESSAGE, e.getType()); + } + } + + private static int highestFieldNumber(Descriptor... descriptors) { + int highest = 0; + for (Descriptor descriptor : descriptors) { + for (FieldDescriptor field : descriptor.getFields()) { + highest = field.getNumber() > highest ? field.getNumber() : highest; + } + } + return highest; + } + + private static int tag(int field, int wireType) { + return (field << 3) | wireType; + } + + private static byte[] hash(int i) { + byte[] h = new byte[Sha256Hash.LENGTH]; + h[0] = (byte) (i >>> 24); + h[1] = (byte) (i >>> 16); + h[2] = (byte) (i >>> 8); + h[3] = (byte) i; + h[Sha256Hash.LENGTH - 1] = 1; + return h; + } + + private static List blockIds(int count) { + List ids = new ArrayList<>(); + for (int i = 0; i < count; i++) { + ids.add(new BlockId(Sha256Hash.wrap(hash(i)), Long.MAX_VALUE - i)); + } + return ids; + } + + /** Encodes a ChainInventory.BlockId; BlockInventory.BlockId has the same fields. */ + private static byte[] blockId(byte[] hash, long number) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + writeVarint(out, tag(ChainInventory.BlockId.HASH_FIELD_NUMBER, LENGTH_DELIMITED)); + writeVarint(out, hash.length); + out.write(hash, 0, hash.length); + writeVarint(out, tag(ChainInventory.BlockId.NUMBER_FIELD_NUMBER, VARINT)); + writeVarint(out, number); + return out.toByteArray(); + } + + private static void writeVarint(ByteArrayOutputStream out, long value) { + while ((value & ~0x7FL) != 0) { + out.write((int) ((value & 0x7F) | 0x80)); + value >>>= 7; + } + out.write((int) value); + } + + private static long randomVarint(Random random) { + long[] values = {0, 1, 2, 127, 128, 16_384, Long.MAX_VALUE, -1, Integer.MIN_VALUE}; + return random.nextBoolean() ? values[random.nextInt(values.length)] : random.nextLong(); + } + + private static byte[] randomBytes(Random random, int length) { + byte[] bytes = new byte[length]; + random.nextBytes(bytes); + return bytes; + } + + /** Writes a well-formed field; groups nest at most MAX_GROUP_DEPTH levels. */ + private static void writeField(ByteArrayOutputStream out, Random random, int field, + int wireType, int depth) { + if (wireType == START_GROUP && depth >= MAX_GROUP_DEPTH) { + wireType = VARINT; + } + writeVarint(out, tag(field, wireType)); + switch (wireType) { + case VARINT: + writeVarint(out, randomVarint(random)); + break; + case FIXED64: + out.write(randomBytes(random, Long.BYTES), 0, Long.BYTES); + break; + case LENGTH_DELIMITED: + byte[] content = randomBytes(random, random.nextInt(Sha256Hash.LENGTH)); + writeVarint(out, content.length); + out.write(content, 0, content.length); + break; + case START_GROUP: + for (int i = random.nextInt(MAX_GROUP_FIELDS + 1); i > 0; i--) { + writeUnknown(out, random, depth + 1); + } + // Usually the matching END_GROUP, sometimes one for another field. + int endField = random.nextInt(10) == 0 ? field + 1 : field; + writeVarint(out, tag(endField, END_GROUP)); + break; + default: + out.write(randomBytes(random, Integer.BYTES), 0, Integer.BYTES); + break; + } + } + + /** Writes a field that none of the tested messages defines, with a random wire type. */ + private static void writeUnknown(ByteArrayOutputStream out, Random random, int depth) { + int field = FIRST_UNKNOWN_FIELD + random.nextInt(UNKNOWN_FIELD_SPAN); + writeField(out, random, field, WIRE_TYPES[random.nextInt(WIRE_TYPES.length)], depth); + } + + /** + * A payload that interleaves id entries with the other varint field, unknown fields, the known + * fields under wire types the parser does not expect for them, and a few raw bytes; some + * payloads are then truncated, get a byte flipped or end with a stray END_GROUP. + */ + private static byte[] randomPayload(Random random, Kind kind) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int ids = random.nextInt(kind == Kind.SYNC_BLOCK_CHAIN ? kind.maxIds + 4 : 200); + int others = random.nextInt(24); + // Some block id payloads carry one entry whose body is not a valid BlockId. + int junkIndex = !kind.isInventory() && ids > 0 && random.nextInt(4) == 0 + ? random.nextInt(ids) : -1; + int idIndex = 0; + while (ids + others > 0) { + if (random.nextInt(ids + others) < ids) { + byte[] body; + if (kind.isInventory()) { + body = randomBytes(random, random.nextInt(Sha256Hash.LENGTH + 8)); + } else if (idIndex == junkIndex) { + body = randomBytes(random, random.nextInt(Sha256Hash.LENGTH)); + } else { + body = blockId(randomBytes(random, Sha256Hash.LENGTH), randomVarint(random)); + } + writeVarint(out, kind.idsTag()); + writeVarint(out, body.length); + out.write(body, 0, body.length); + idIndex++; + ids--; + continue; + } + others--; + int choice = random.nextInt(20); + if (choice < 6) { + writeVarint(out, tag(kind.otherField, VARINT)); + writeVarint(out, randomVarint(random)); + } else if (choice < 15) { + writeUnknown(out, random, 0); + } else if (choice < 19) { + boolean onIds = random.nextBoolean(); + int field = onIds ? kind.idsField : kind.otherField; + int expected = onIds ? LENGTH_DELIMITED : VARINT; + int wireType = NON_GROUP_WIRE_TYPES[random.nextInt(NON_GROUP_WIRE_TYPES.length)]; + writeField(out, random, field, wireType == expected ? FIXED64 : wireType, 0); + } else { + out.write(randomBytes(random, 1), 0, 1); + } + } + byte[] data = out.toByteArray(); + if (data.length > 0 && random.nextInt(6) == 0) { + data = Arrays.copyOf(data, random.nextInt(data.length)); + } + if (data.length > 0 && random.nextInt(8) == 0) { + data[random.nextInt(data.length)] ^= (byte) (1 + random.nextInt(255)); + } + if (random.nextInt(25) == 0) { + ByteArrayOutputStream stray = new ByteArrayOutputStream(); + stray.write(data, 0, data.length); + writeVarint(stray, tag(FIRST_UNKNOWN_FIELD, END_GROUP)); + data = stray.toByteArray(); + } + return data; + } +}