Skip to content

Commit 0d5b9e5

Browse files
authored
fix(jsonrpc): handle null parameters consistently (#6984)
* fix(jsonrpc): handle null parameters consistently Validate nullable JSON-RPC arguments before they are dereferenced. Return stable protocol errors instead of jsonrpc4j's unhandled -32001 fallback, which exposes Java exception types. Validate eth_call's required transaction argument before its block selector. The double-null case now returns -32602 instead of -32600. Align eth_uninstallFilter lookup misses with geth: null, unknown and already removed IDs return false. Empty and non-hexadecimal strings also return false when no filter matches, without new format checks. Non-null lookup misses now return false instead of -32000. Use the value returned by remove to report whether a filter was removed and avoid the race between checking and removing the same entry. Remove the obsolete uninstall ItemNotFoundException declaration and error mapping. Java binaries remain compatible, but source callers catching that checked exception, or implementations still declaring it, may need adjustment when recompiled. Keep getFilterChanges and getFilterLogs on their existing lookup-miss errors, and preserve request-source precedence and filter isolation. Treat null block-detail flags as false and retain DTO defaults for explicitly null optional fields. Preserve filter wildcard semantics. Add binding, service, wire and VM execution regressions for null arguments, error contracts, filter removal, source isolation and concurrent uninstall results. * fix(jsonrpc): reject null required positional parameters Return invalid params for an explicit null filter ID in eth_uninstallFilter, eth_getFilterChanges and eth_getFilterLogs, and for a null fullTransactionObjects flag in eth_getBlockByHash and eth_getBlockByNumber. The block hash or selector is still validated first, and the flag is checked before any block lookup, so the result does not depend on whether the block exists. Unknown non-null filter IDs keep their existing results. This replaces the earlier null-as-false handling of the flag and the filter ID. go-ethereum v1.17.6 rejects null for these required arguments; earlier releases decoded it as a zero value. * refactor(jsonrpc): share the null check for required parameters Route the null checks for the ten required JSON-RPC parameter positions through one requireParam helper instead of repeating the same if/throw block at each site. The "invalid params" and "invalid filter request" messages are unchanged and are now both private constants in TronJsonRpcImpl. Remove the null check from the LogFilter constructor. In production code, LogFilter is only built through LogFilterWrapper from eth_getLogs and eth_newFilter, and both reject a null filter request before reaching it, so the constructor check and its unit test are dropped. Null filter requests remain covered at the service and wire level. Extract getBlockByHash(byte[]) and use it from ethGetBlockByHash and getBlockByJsonHash, so ethGetBlockByHash no longer inlines the block lookup. The validation order is unchanged. No behavior change. * test(jsonrpc): use the three-argument TronJsonRpcImpl constructor Adapt the tests added for null parameter handling to the constructor that now takes the Manager, and drop the removed setManager call. Tests built only from mocks pass a mocked Manager, and tests backed by the shared database pass dbManager, matching the existing tests.
1 parent 1ff2aae commit 0d5b9e5

10 files changed

Lines changed: 944 additions & 43 deletions

File tree

‎framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpc.java‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -307,10 +307,9 @@ String newFilter(FilterRequest fr) throws JsonRpcInvalidParamsException,
307307
@JsonRpcErrors({
308308
@JsonRpcError(exception = JsonRpcMethodNotFoundException.class, code = -32601, data = "{}"),
309309
@JsonRpcError(exception = JsonRpcInvalidParamsException.class, code = -32602, data = "{}"),
310-
@JsonRpcError(exception = ItemNotFoundException.class, code = -32000, data = "{}"),
311310
})
312311
boolean uninstallFilter(String filterId) throws JsonRpcInvalidParamsException,
313-
JsonRpcMethodNotFoundException, ItemNotFoundException;
312+
JsonRpcMethodNotFoundException;
314313

315314
@JsonRpcMethod("eth_getFilterChanges")
316315
@JsonRpcErrors({

‎framework/src/main/java/org/tron/core/services/jsonrpc/TronJsonRpcImpl.java‎

Lines changed: 60 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,8 @@ public enum RequestSource {
126126
}
127127

128128
private static final String FILTER_NOT_FOUND = "filter not found";
129+
private static final String INVALID_PARAMS = "invalid params";
130+
private static final String INVALID_FILTER_REQUEST = "invalid filter request";
129131
public static final int EXPIRE_SECONDS = 5 * 60;
130132
private final int maxBlockFilterNum = Args.getInstance().getJsonRpcMaxBlockFilterNum();
131133
private final int maxLogFilterNum = Args.getInstance().getJsonRpcMaxLogFilterNum();
@@ -396,17 +398,29 @@ public String ethGetBlockTransactionCountByNumber(String blockNumOrTag)
396398
@Override
397399
public BlockResult ethGetBlockByHash(String blockHash, Boolean fullTransactionObjects)
398400
throws JsonRpcInvalidParamsException {
399-
final Block b = getBlockByJsonHash(blockHash);
401+
byte[] hash = hashToByteArray(blockHash);
402+
requireParam(fullTransactionObjects, INVALID_PARAMS);
403+
final Block b = getBlockByHash(hash);
400404
return getBlockResult(b, fullTransactionObjects);
401405
}
402406

403407
@Override
404408
public BlockResult ethGetBlockByNumber(String blockNumOrTag, Boolean fullTransactionObjects)
405409
throws JsonRpcInvalidParamsException {
406-
final Block b = getBlockByNumOrTag(blockNumOrTag);
410+
Long blockNum = parseBlockSelector(blockNumOrTag);
411+
requireParam(fullTransactionObjects, INVALID_PARAMS);
412+
final Block b = getBlockBySelector(blockNum);
407413
return (b == null ? null : getBlockResult(b, fullTransactionObjects));
408414
}
409415

416+
private static <T> T requireParam(T value, String message)
417+
throws JsonRpcInvalidParamsException {
418+
if (value == null) {
419+
throw new JsonRpcInvalidParamsException(message);
420+
}
421+
return value;
422+
}
423+
410424
/**
411425
* Reject any block selector that is not "latest".
412426
* Accepts "latest" silently; throws for other tags, numeric blocks, or invalid input.
@@ -424,20 +438,37 @@ private void requireLatestBlockTag(String blockNumOrTag)
424438
}
425439

426440
private Block getBlockByJsonHash(String blockHash) throws JsonRpcInvalidParamsException {
427-
byte[] bHash = hashToByteArray(blockHash);
428-
return wallet.getBlockById(ByteString.copyFrom(bHash));
441+
return getBlockByHash(hashToByteArray(blockHash));
442+
}
443+
444+
private Block getBlockByHash(byte[] blockHash) {
445+
return wallet.getBlockById(ByteString.copyFrom(blockHash));
429446
}
430447

431448
private Block getBlockByNumOrTag(String blockNumOrTag) throws JsonRpcInvalidParamsException {
449+
return getBlockBySelector(parseBlockSelector(blockNumOrTag));
450+
}
451+
452+
/**
453+
* Validates a block number or tag without reading a block. Returns null for "latest".
454+
*/
455+
private Long parseBlockSelector(String blockNumOrTag) throws JsonRpcInvalidParamsException {
432456
if (JsonRpcApiUtil.isBlockTag(blockNumOrTag)) {
433457
if (LATEST_STR.equalsIgnoreCase(blockNumOrTag)) {
434-
// Return the head block directly from blockStore, bypassing blockIndexStore
435-
// which may not yet be written when latestBlockHeaderNumber is already updated.
436-
return wallet.getNowBlock();
458+
return null;
437459
}
438-
return wallet.getBlockByNum(JsonRpcApiUtil.parseBlockTag(blockNumOrTag, wallet));
460+
return JsonRpcApiUtil.parseBlockTag(blockNumOrTag, wallet);
439461
}
440-
return wallet.getBlockByNum(parseBlockNumber(blockNumOrTag));
462+
return parseBlockNumber(blockNumOrTag);
463+
}
464+
465+
private Block getBlockBySelector(Long blockNum) {
466+
if (blockNum == null) {
467+
// Return the head block directly from blockStore, bypassing blockIndexStore
468+
// which may not yet be written when latestBlockHeaderNumber is already updated.
469+
return wallet.getNowBlock();
470+
}
471+
return wallet.getBlockByNum(blockNum);
441472
}
442473

443474
private BlockResult getBlockResult(Block block, boolean fullTx) {
@@ -708,6 +739,8 @@ public String gasPrice() {
708739
@Override
709740
public String estimateGas(CallArguments args) throws JsonRpcInvalidRequestException,
710741
JsonRpcInvalidParamsException, JsonRpcInternalException {
742+
requireParam(args, INVALID_PARAMS);
743+
711744
byte[] ownerAddress = addressCompatibleToByteArray(args.getFrom());
712745

713746
ContractType contractType = args.getContractType(wallet);
@@ -1036,6 +1069,7 @@ private List<TransactionReceipt> getTransactionReceiptsFromBlock(BlockCapsule bl
10361069
public String getCall(CallArguments transactionCall, Object blockParamObj)
10371070
throws JsonRpcInvalidParamsException, JsonRpcInvalidRequestException,
10381071
JsonRpcInternalException {
1072+
requireParam(transactionCall, INVALID_PARAMS);
10391073

10401074
String blockNumOrTag;
10411075
if (blockParamObj instanceof HashMap) {
@@ -1369,6 +1403,8 @@ public TransactionJson buildTransaction(BuildArguments args)
13691403
throw new JsonRpcMethodNotFoundException(msg);
13701404
}
13711405

1406+
requireParam(args, INVALID_PARAMS);
1407+
13721408
byte[] fromAddressData;
13731409
try {
13741410
fromAddressData = addressCompatibleToByteArray(args.getFrom());
@@ -1477,6 +1513,8 @@ public String newFilter(FilterRequest fr) throws JsonRpcInvalidParamsException,
14771513
JsonRpcMethodNotFoundException, JsonRpcExceedLimitException {
14781514
disableInPBFT("eth_newFilter");
14791515

1516+
requireParam(fr, INVALID_FILTER_REQUEST);
1517+
14801518
// not supports finalized as block parameter
14811519
if (FINALIZED_STR.equalsIgnoreCase(fr.getFromBlock())
14821520
|| FINALIZED_STR.equalsIgnoreCase(fr.getToBlock())) {
@@ -1524,10 +1562,12 @@ public String newBlockFilter() throws JsonRpcMethodNotFoundException,
15241562
}
15251563

15261564
@Override
1527-
public boolean uninstallFilter(String filterId) throws ItemNotFoundException,
1565+
public boolean uninstallFilter(String filterId) throws JsonRpcInvalidParamsException,
15281566
JsonRpcMethodNotFoundException {
15291567
disableInPBFT("eth_uninstallFilter");
15301568

1569+
requireParam(filterId, INVALID_PARAMS);
1570+
15311571
Map<String, BlockFilterAndResult> blockFilter2Result;
15321572
Map<String, LogFilterAndResult> eventFilter2Result;
15331573
if (getSource() == RequestSource.FULLNODE) {
@@ -1539,22 +1579,19 @@ public boolean uninstallFilter(String filterId) throws ItemNotFoundException,
15391579
}
15401580

15411581
filterId = ByteArray.fromHex(filterId);
1542-
if (eventFilter2Result.containsKey(filterId)) {
1543-
eventFilter2Result.remove(filterId);
1544-
} else if (blockFilter2Result.containsKey(filterId)) {
1545-
blockFilter2Result.remove(filterId);
1546-
} else {
1547-
throw new ItemNotFoundException(FILTER_NOT_FOUND);
1582+
if (eventFilter2Result.remove(filterId) != null) {
1583+
return true;
15481584
}
1549-
1550-
return true;
1585+
return blockFilter2Result.remove(filterId) != null;
15511586
}
15521587

15531588
@Override
15541589
public Object[] getFilterChanges(String filterId) throws ItemNotFoundException,
1555-
JsonRpcMethodNotFoundException {
1590+
JsonRpcInvalidParamsException, JsonRpcMethodNotFoundException {
15561591
disableInPBFT("eth_getFilterChanges");
15571592

1593+
requireParam(filterId, INVALID_PARAMS);
1594+
15581595
Map<String, BlockFilterAndResult> blockFilter2Result;
15591596
Map<String, LogFilterAndResult> eventFilter2Result;
15601597
if (getSource() == RequestSource.FULLNODE) {
@@ -1576,6 +1613,8 @@ public LogFilterElement[] getLogs(FilterRequest fr) throws JsonRpcInvalidParamsE
15761613
JsonRpcMethodNotFoundException, JsonRpcTooManyResultException {
15771614
disableInPBFT("eth_getLogs");
15781615

1616+
requireParam(fr, INVALID_FILTER_REQUEST);
1617+
15791618
long currentMaxBlockNum = wallet.getNowBlock().getBlockHeader().getRawData().getNumber();
15801619
//convert FilterRequest to LogFilterWrapper
15811620
LogFilterWrapper logFilterWrapper = new LogFilterWrapper(fr, currentMaxBlockNum, wallet, true);
@@ -1590,6 +1629,8 @@ public LogFilterElement[] getFilterLogs(String filterId) throws
15901629
JsonRpcMethodNotFoundException, JsonRpcTooManyResultException {
15911630
disableInPBFT("eth_getFilterLogs");
15921631

1632+
requireParam(filterId, INVALID_PARAMS);
1633+
15931634
Map<String, LogFilterAndResult> eventFilter2Result;
15941635
if (getSource() == RequestSource.FULLNODE) {
15951636
eventFilter2Result = eventFilter2ResultFull;

‎framework/src/main/java/org/tron/core/services/jsonrpc/filters/LogFilter.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,8 @@ public class LogFilter {
2828
private byte[][] contractAddresses = new byte[0][];
2929
// example: [[func1, func2], null, [A, B], [C]]
3030
// first topic must be func1 or func2,second can be any,third must be A or B,forth must be C
31-
// [A, null] is not allowed.
31+
// A null positional topic is a wildcard, so [A, null] is valid.
32+
// A null entry in an OR-list is invalid, so [[A, null]] is not allowed.
3233
@Getter
3334
@Setter
3435
private List<byte[][]> topics = new ArrayList<>();

‎framework/src/main/java/org/tron/core/services/jsonrpc/types/BuildArguments.java‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.parseQuantityValue;
77
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.requireValidHex;
88

9+
import com.fasterxml.jackson.annotation.JsonSetter;
10+
import com.fasterxml.jackson.annotation.Nulls;
911
import com.google.protobuf.ByteString;
1012
import java.util.Arrays;
1113
import lombok.AllArgsConstructor;
@@ -23,6 +25,13 @@
2325
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
2426
import org.tron.protos.contract.SmartContractOuterClass.SmartContract;
2527

28+
/**
29+
* Arguments for {@code buildTransaction}.
30+
*
31+
* <p>Fields annotated with {@link JsonSetter} retain their defaults when an explicit JSON
32+
* {@code null} is deserialized. This protection applies to Jackson input only; direct setter calls
33+
* may still assign {@code null} and callers must preserve the DTO invariants.
34+
*/
2635
@NoArgsConstructor
2736
@AllArgsConstructor
2837
@ToString
@@ -65,28 +74,34 @@ public class BuildArguments {
6574

6675
@Getter
6776
@Setter
77+
@JsonSetter(nulls = Nulls.SKIP)
6878
private Long tokenId = 0L;
6979
@Getter
7080
@Setter
81+
@JsonSetter(nulls = Nulls.SKIP)
7182
private Long tokenValue = 0L;
7283
@Getter
7384
@Setter
7485
private String abi = "";
7586
@Getter
7687
@Setter
88+
@JsonSetter(nulls = Nulls.SKIP)
7789
private Long consumeUserResourcePercent = 0L;
7890
@Getter
7991
@Setter
92+
@JsonSetter(nulls = Nulls.SKIP)
8093
private Long originEnergyLimit = 0L;
8194
@Getter
8295
@Setter
8396
private String name = "";
8497

8598
@Getter
8699
@Setter
100+
@JsonSetter(nulls = Nulls.SKIP)
87101
private Integer permissionId = 0;
88102
@Getter
89103
@Setter
104+
@JsonSetter(nulls = Nulls.SKIP)
90105
private String extraData = "";
91106

92107
@Getter
@@ -205,4 +220,4 @@ private static boolean calldataEquals(String a, String b) {
205220
return Arrays.equals(ByteArray.fromHexString(a), ByteArray.fromHexString(b));
206221
}
207222

208-
}
223+
}

‎framework/src/main/java/org/tron/core/services/jsonrpc/types/CallArguments.java‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.parseQuantityValue;
66
import static org.tron.core.services.jsonrpc.JsonRpcApiUtil.requireValidHex;
77

8+
import com.fasterxml.jackson.annotation.JsonSetter;
9+
import com.fasterxml.jackson.annotation.Nulls;
810
import com.google.protobuf.ByteString;
911
import lombok.AllArgsConstructor;
1012
import lombok.Getter;
@@ -20,13 +22,21 @@
2022
import org.tron.protos.Protocol.Transaction.Contract.ContractType;
2123
import org.tron.protos.contract.SmartContractOuterClass.SmartContract;
2224

25+
/**
26+
* Arguments for EVM call-style JSON-RPC methods.
27+
*
28+
* <p>Fields annotated with {@link JsonSetter} retain their defaults when an explicit JSON
29+
* {@code null} is deserialized. This protection applies to Jackson input only; direct setter calls
30+
* may still assign {@code null} and callers must preserve the DTO invariants.
31+
*/
2332
@NoArgsConstructor
2433
@AllArgsConstructor
2534
@ToString
2635
public class CallArguments {
2736

2837
@Getter
2938
@Setter
39+
@JsonSetter(nulls = Nulls.SKIP)
3040
private String from = "0x0000000000000000000000000000000000000000";
3141
@Getter
3242
@Setter
@@ -108,4 +118,4 @@ public ContractType getContractType(Wallet wallet) throws JsonRpcInvalidRequestE
108118
public long parseValue() throws JsonRpcInvalidParamsException {
109119
return parseQuantityValue(value);
110120
}
111-
}
121+
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package org.tron.core.jsonrpc;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import com.fasterxml.jackson.databind.node.ObjectNode;
5+
import org.junit.Assert;
6+
import org.junit.Test;
7+
import org.tron.core.services.jsonrpc.types.BuildArguments;
8+
import org.tron.core.services.jsonrpc.types.CallArguments;
9+
10+
public class JsonRpcArgumentNullBindingTest {
11+
12+
private static final ObjectMapper MAPPER = new ObjectMapper();
13+
14+
@Test
15+
public void testBuildArgumentsExplicitNullMatchesOmittedDefaults() throws Exception {
16+
BuildArguments omitted = MAPPER.readValue("{}", BuildArguments.class);
17+
String[] optionalFields = {
18+
"tokenId",
19+
"tokenValue",
20+
"consumeUserResourcePercent",
21+
"originEnergyLimit",
22+
"permissionId",
23+
"extraData"
24+
};
25+
26+
for (String field : optionalFields) {
27+
ObjectNode input = MAPPER.createObjectNode();
28+
input.putNull(field);
29+
BuildArguments explicitNull = MAPPER.treeToValue(input, BuildArguments.class);
30+
31+
assertBuildDefaultsEqual(omitted, explicitNull);
32+
}
33+
}
34+
35+
@Test
36+
public void testCallArgumentsNullFromMatchesOmittedDefault() throws Exception {
37+
CallArguments omitted = MAPPER.readValue("{}", CallArguments.class);
38+
CallArguments explicitNull = MAPPER.readValue("{\"from\":null}", CallArguments.class);
39+
40+
Assert.assertEquals(omitted.getFrom(), explicitNull.getFrom());
41+
Assert.assertEquals(
42+
"0x0000000000000000000000000000000000000000", explicitNull.getFrom());
43+
}
44+
45+
private static void assertBuildDefaultsEqual(BuildArguments expected, BuildArguments actual) {
46+
Assert.assertEquals(expected.getTokenId(), actual.getTokenId());
47+
Assert.assertEquals(expected.getTokenValue(), actual.getTokenValue());
48+
Assert.assertEquals(expected.getConsumeUserResourcePercent(),
49+
actual.getConsumeUserResourcePercent());
50+
Assert.assertEquals(expected.getOriginEnergyLimit(), actual.getOriginEnergyLimit());
51+
Assert.assertEquals(expected.getPermissionId(), actual.getPermissionId());
52+
Assert.assertEquals(expected.getExtraData(), actual.getExtraData());
53+
}
54+
}

0 commit comments

Comments
 (0)