Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -586,11 +586,12 @@ private Sha256Hash getRawHash() {
return Sha256Hash.of(this.transaction.getRawData().toByteArray());
}

public void sign(byte[] privateKey) {
public synchronized void sign(byte[] privateKey) {
SignInterface cryptoEngine = SignUtils.fromPrivate(privateKey);
ByteString sig = ByteString.copyFrom(cryptoEngine.Base64toBytes(cryptoEngine
.signHash(getTransactionId().getBytes())));
this.transaction = this.transaction.toBuilder().addSignature(sig).build();
this.isVerified = false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[NIT] Could we add a test that verifies a signed capsule, calls sign() again, and asserts that isVerified() becomes false while the transaction ID stays the same? The current test signs before the first validation, so it would still pass if this line were removed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in 20c91bf. The new test first validates a signed capsule, calls sign() again, and checks that isVerified() becomes false while the transaction ID stays unchanged. It also verifies that the next validation rejects the updated signature list. Confirmed that the test fails if the cache-reset line in sign() is removed.

}

private static void checkPermission(int permissionId, Permission permission, Transaction.Contract contract) throws PermissionException {
Expand Down Expand Up @@ -690,10 +691,11 @@ public Sha256Hash getTransactionId() {
return this.id;
}

private void setRawData(Transaction.raw rawData) {
private synchronized void setRawData(Transaction.raw rawData) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] Synchronize transaction ID cache population and invalidation.

Could getTransactionId() synchronize on the same capsule monitor as setRawData()?

On a cache miss, getTransactionId() also writes to id. A concurrent caller could finish hashing the previous raw_data after setRawData() has invalidated the cache, repopulating it with a stale transaction ID.

Using the same monitor would serialize cache population and invalidation, ensuring that the cached transaction ID remains consistent with the current raw_data.

Could we also add a concurrency regression test covering this race and verify that the cached transaction ID matches the updated raw_data once both operations complete?

this.transaction = this.transaction.toBuilder().setRawData(rawData).build();
// invalidate trxId
// Cached identity and verification are bound to raw_data.
this.id = null;
this.isVerified = false;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SHOULD] Synchronize transaction mutations with signature validation to prevent stale verification results.

Could we have setRawData() and sign() synchronize on the same capsule monitor as validateSignature()?

With the current direct flag writes, an in-flight validation can complete after either mutation and set isVerified back to true, even though the verification result applies to the previous transaction contents.

The existing concurrency test calls setVerified(false) directly. Could we extend the regression coverage to exercise the actual mutation paths, specifically setFeeLimit() and sign(), while signature validation is in progress?

Please verify that the cached verification result is invalidated once both operations have completed.

This would ensure that transaction mutations and signature validation are properly serialized, rather than relying solely on resetting the verification flag.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 20c91bf. setRawData() and sign() now synchronize on the same capsule monitor as validateSignature(). Added concurrency regressions exercising setFeeLimit() and sign() during an in-flight validation. They verify that mutations wait for validation and leave isVerified false after both operations complete. Both tests fail without the synchronization.

}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@
import com.googlecode.jsonrpc4j.ErrorResolver.JsonError;
import com.googlecode.jsonrpc4j.JsonRpcBasicServer;
import com.googlecode.jsonrpc4j.JsonRpcInterceptor;
import com.googlecode.jsonrpc4j.JsonRpcMethod;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import lombok.extern.slf4j.Slf4j;
import org.tron.core.services.jsonrpc.JsonRpcErrorResolver;
import org.tron.core.services.jsonrpc.JsonRpcMapper;
Expand All @@ -25,13 +30,28 @@
public final class AdminJsonRpcRequestHandler extends JsonRpcBasicServer {

private static final ObjectMapper OBJECT_MAPPER = JsonRpcMapper.create();
private final Set<String> methodNames = collectMethodNames();

public AdminJsonRpcRequestHandler(AdminJsonRpc adminJsonRpc) {
super(OBJECT_MAPPER, adminJsonRpc, AdminJsonRpc.class);
setErrorResolver(JsonRpcErrorResolver.INSTANCE);
setShouldLogInvocationErrors(false);
}

private Set<String> collectMethodNames() {
Set<String> names = new HashSet<>();
for (Method method : AdminJsonRpc.class.getMethods()) {
JsonRpcMethod annotation = method.getAnnotation(JsonRpcMethod.class);
if (annotation == null || !annotation.required()) {
names.add(method.getName());
}
if (annotation != null) {
names.add(annotation.value());
}
}
return Collections.unmodifiableSet(names);
}

/** Parses the complete input before dispatch, returning an empty body for valid notifications. */
public byte[] handleRequest(byte[] body) throws IOException {
// Jackson accepts overlong and surrogate UTF-8 sequences and treats NUL bytes as a sign of
Expand Down Expand Up @@ -75,6 +95,10 @@ private JsonNode check(JsonNode request) {

private JsonNode dispatch(ObjectNode request, JsonNode id) {
boolean notification = !request.has("id");
// jsonrpc4j permanently caches unknown method names, including notifications.
if (!methodNames.contains(request.get("method").asText())) {
return notification ? null : errorResponse(JsonError.METHOD_NOT_FOUND, id);
}
try {
for (JsonRpcInterceptor interceptor : getInterceptorList()) {
interceptor.preHandleJson(request);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import com.google.protobuf.Any;
import com.google.protobuf.ByteString;
import java.math.BigInteger;
import java.security.SignatureException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.TimeoutException;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
Expand All @@ -26,7 +30,9 @@
import org.tron.common.BaseTest;
import org.tron.common.TestConstants;
import org.tron.common.crypto.ECKey;
import org.tron.common.es.ExecutorServiceManager;
import org.tron.common.utils.ByteUtil;
import org.tron.common.utils.Sha256Hash;
import org.tron.common.utils.StringUtil;
import org.tron.core.Wallet;
import org.tron.core.config.args.Args;
Expand All @@ -42,6 +48,7 @@
import org.tron.protos.Protocol.Transaction.Result;
import org.tron.protos.Protocol.Transaction.Result.contractResult;
import org.tron.protos.Protocol.Transaction.raw;
import org.tron.protos.contract.BalanceContract.TransferContract;

@Slf4j
public class TransactionCapsuleTest extends BaseTest {
Expand Down Expand Up @@ -240,21 +247,120 @@ public void fastVerify() {
}
}

@Test
public void shouldInvalidateVerificationCacheWhenRawDataChanges() throws Exception {
List<Consumer<TransactionCapsule>> changes = Arrays.asList(
capsule -> capsule.setReference(1L, new byte[32]),
capsule -> capsule.setExpiration(2000L),
TransactionCapsule::setTimestamp,
capsule -> capsule.setTimestamp(2L),
capsule -> capsule.setFeeLimit(2L));
for (Consumer<TransactionCapsule> change : changes) {
assertRawDataChangeInvalidatesSignature(change);
}
}

private void assertRawDataChangeInvalidatesSignature(Consumer<TransactionCapsule> change)
throws Exception {
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
TransactionCapsule capsule = new TransactionCapsule(createTransferTransaction(key));
capsule.sign(key.getPrivKeyBytes());
Assert.assertTrue(capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertTrue(capsule.isVerified());
Sha256Hash originalId = capsule.getTransactionId();
List<ByteString> originalSignatures = capsule.getInstance().getSignatureList();

change.accept(capsule);

Assert.assertNotEquals(originalId, capsule.getTransactionId());
Assert.assertEquals(originalSignatures, capsule.getInstance().getSignatureList());
Assert.assertFalse(capsule.isVerified());
Assert.assertThrows(ValidateSignatureException.class,
() -> capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertFalse(capsule.isVerified());
}

@Test
public void shouldInvalidateVerificationCacheWhenSignatureIsAppended() throws Exception {
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
TransactionCapsule capsule = new TransactionCapsule(createTransferTransaction(key));
capsule.sign(key.getPrivKeyBytes());
Assert.assertTrue(capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertTrue(capsule.isVerified());
Sha256Hash originalId = capsule.getTransactionId();
ByteString originalSignature = capsule.getInstance().getSignature(0);

capsule.sign(key.getPrivKeyBytes());

Assert.assertEquals(originalId, capsule.getTransactionId());
Assert.assertEquals(2, capsule.getInstance().getSignatureCount());
Assert.assertEquals(originalSignature, capsule.getInstance().getSignature(0));
Assert.assertFalse(capsule.isVerified());
Assert.assertThrows(ValidateSignatureException.class,
() -> capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertFalse(capsule.isVerified());
}

@Test
public void shouldInvalidateVerificationCacheAfterInFlightValidation() throws Exception {
assertMutationInvalidatesVerificationAfterInFlightValidation(
capsule -> capsule.setVerified(false));
}

@Test
public void shouldInvalidateVerificationCacheWhenFeeLimitChangesDuringValidation()
throws Exception {
TransactionCapsule capsule = assertMutationInvalidatesVerificationAfterInFlightValidation(
transaction -> transaction.setFeeLimit(2L));

Assert.assertEquals(2L, capsule.getFeeLimit());
Assert.assertThrows(ValidateSignatureException.class,
() -> capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertFalse(capsule.isVerified());
}

@Test
public void shouldInvalidateVerificationCacheWhenSigningDuringValidation() throws Exception {
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
TransactionCapsule capsule = assertMutationInvalidatesVerificationAfterInFlightValidation(
transaction -> transaction.sign(key.getPrivKeyBytes()));

Assert.assertEquals(2, capsule.getInstance().getSignatureCount());
Assert.assertThrows(ValidateSignatureException.class,
() -> capsule.validateSignature(dbManager.getAccountStore(),
dbManager.getDynamicPropertiesStore()));
Assert.assertFalse(capsule.isVerified());
}

private Transaction createTransferTransaction(ECKey key) {
TransferContract transfer = TransferContract.newBuilder()
.setOwnerAddress(ByteString.copyFrom(key.getAddress()))
.setToAddress(ByteString.copyFrom(key.getAddress()))
.setAmount(1L)
.build();
return Transaction.newBuilder()
.setRawData(raw.newBuilder().setTimestamp(1L).setExpiration(1000L).setFeeLimit(1L)
.addContract(Transaction.Contract.newBuilder().setType(ContractType.TransferContract)
.setParameter(Any.pack(transfer))))
.build();
}

private TransactionCapsule assertMutationInvalidatesVerificationAfterInFlightValidation(
Consumer<TransactionCapsule> mutation) throws Exception {
CountDownLatch validationStarted = new CountDownLatch(1);
CountDownLatch continueValidation = new CountDownLatch(1);
CountDownLatch invalidationCompleted = new CountDownLatch(1);
AtomicReference<Throwable> failure = new AtomicReference<>();
Transaction transaction = Transaction.newBuilder()
.setRawData(raw.newBuilder()
.addContract(Transaction.Contract.newBuilder()
.setType(ContractType.TransferContract)))
.build();
TransactionCapsule capsule = new TransactionCapsule(transaction) {
CountDownLatch mutationStarted = new CountDownLatch(1);
ECKey key = ECKey.fromPrivate(BigInteger.TEN);
TransactionCapsule capsule = new TransactionCapsule(createTransferTransaction(key)) {
@Override
public boolean validatePubSignature(AccountStore accountStore,
DynamicPropertiesStore dynamicPropertiesStore) throws ValidateSignatureException {
boolean valid = super.validatePubSignature(accountStore, dynamicPropertiesStore);
validationStarted.countDown();
try {
if (!continueValidation.await(5, TimeUnit.SECONDS)) {
Expand All @@ -264,40 +370,30 @@ public boolean validatePubSignature(AccountStore accountStore,
Thread.currentThread().interrupt();
throw new ValidateSignatureException("validation interrupted");
}
return true;
return valid;
}
};

Thread validationThread = new Thread(() -> {
try {
capsule.validateSignature(null, null);
} catch (Throwable t) {
failure.set(t);
}
});
Thread invalidationThread = new Thread(() -> {
capsule.setVerified(false);
invalidationCompleted.countDown();
});

capsule.sign(key.getPrivKeyBytes());
ExecutorService workers = ExecutorServiceManager.newFixedThreadPool("signature-cache-test", 2);
try {
validationThread.start();
Future<Boolean> validation = workers.submit(() -> capsule.validateSignature(
dbManager.getAccountStore(), dbManager.getDynamicPropertiesStore()));
Assert.assertTrue(validationStarted.await(5, TimeUnit.SECONDS));
invalidationThread.start();
Assert.assertFalse(invalidationCompleted.await(100, TimeUnit.MILLISECONDS));
Future<?> change = workers.submit(() -> {
mutationStarted.countDown();
mutation.accept(capsule);
});
Assert.assertTrue(mutationStarted.await(5, TimeUnit.SECONDS));
Assert.assertThrows(TimeoutException.class, () -> change.get(100, TimeUnit.MILLISECONDS));

continueValidation.countDown();
validationThread.join(TimeUnit.SECONDS.toMillis(5));
invalidationThread.join(TimeUnit.SECONDS.toMillis(5));

Assert.assertFalse(validationThread.isAlive());
Assert.assertFalse(invalidationThread.isAlive());
Assert.assertNull(failure.get());
Assert.assertTrue(validation.get(5, TimeUnit.SECONDS));
change.get(5, TimeUnit.SECONDS);
Assert.assertFalse(capsule.isVerified());
return capsule;
} finally {
continueValidation.countDown();
validationThread.interrupt();
invalidationThread.interrupt();
ExecutorServiceManager.shutdownAndAwaitTermination(workers, "signature-cache-test");
}
}
}
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package org.tron.core.net.peer;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.spy;

import io.netty.channel.ChannelHandlerContext;
import java.net.InetSocketAddress;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import org.tron.common.BaseMethodTest;
import org.tron.common.utils.PeerManagerStateResetter;
import org.tron.common.utils.ReflectUtils;
import org.tron.core.capsule.BlockCapsule.BlockId;
import org.tron.core.config.Parameter.NetConstants;
Expand All @@ -31,6 +29,11 @@ protected void afterInit() {
service = context.getBean(PeerStatusCheck.class);
}

@Override
protected void beforeDestroy() {
PeerManagerStateResetter.reset();
}

@Test
public void testCheck() {
int maxConnection = 30;
Expand All @@ -39,11 +42,16 @@ public void testCheck() {

for (int i = 0; i < maxConnection; i++) {
InetSocketAddress inetSocketAddress = new InetSocketAddress("201.0.0." + i, 10001);
Channel c1 = spy(Channel.class);
Channel c1 = new Channel() {
@Override
public void send(byte[] data) {
// Peer-status tests do not perform socket I/O.
}
};
ReflectUtils.setFieldValue(c1, "inetSocketAddress", inetSocketAddress);
ReflectUtils.setFieldValue(c1, "inetAddress", inetSocketAddress.getAddress());
ReflectUtils.setFieldValue(c1, "ctx", spy(ChannelHandlerContext.class));
Mockito.doNothing().when(c1).send((byte[]) any());
ReflectUtils.setFieldValue(c1, "ctx",
Mockito.mock(ChannelHandlerContext.class, Mockito.withSettings().stubOnly()));

PeerManager.add(context, c1).setHelloMessageReceive(Mockito.mock(HelloMessage.class));
}
Expand Down
Loading
Loading