Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions common/src/main/java/org/tron/core/Constant.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
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;
import org.tron.protos.Protocol.Transaction;

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<Transaction> trxs) {
Expand All @@ -22,16 +31,32 @@ public TransactionsMessage(List<Transaction> 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;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<TronNetService> netService = mockStatic(TronNetService.class)) {
netService.when(TronNetService::getP2pConfig).thenReturn(p2pConfig);
try (MockedStatic<NodeConfig> nodeConfig = mockStatic(NodeConfig.class)) {
nodeConfig.when(() -> NodeConfig.fromConfig(any())).thenThrow(failure);
try (MockedStatic<Configuration> 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");
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Message> 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<TransactionMessage> 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<PeerManager> 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<Message> 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<Message> 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;
}
}
Loading
Loading