Skip to content

Commit 6ecb02c

Browse files
committed
fix(jsonrpc): normalize error responses and fatal handling
Replace jsonrpc4j's unhandled -32001 fallback with a fixed -32603 response so unmapped exception types and raw messages no longer reach clients. Keep the documented -32001 contract for net_version and eth_chainId through explicit mappings with fixed message and data. Propagate VirtualMachineError, ThreadDeath, LinkageError, and TronError through the JSON-RPC boundary. Scan complete cause chains without allocating a visited set, detecting cycles without missing fatal causes. Classify Throwables escaping dispatch before logging or mapping them. Before rethrowing an Error, unwrap response decorators with a bounded walk and make a best-effort attempt to commit an empty HTTP 500 on the underlying response. Preserve the original error if cleanup fails, and abandon cleanup without delegating into cyclic or unresolved wrappers. Route single requests through handleRequest because the servlet handle API catches Throwable. Catch RuntimeException, IOException, and Error at both dispatch boundaries, then propagate a classified fatal cause or return -32603 when a response is appropriate. This also covers non-fatal Errors from interceptor hooks. Discard partial dispatch output on failure. Recover each failed batch element without discarding earlier results or skipping later requests. Share internal-error construction across serialization, dispatch, and response-parsing failures. Count only the replacement when parsing fails, retaining existing overflow rules and the current single/batch handling of requests without an id. Bound unmapped-exception logging by RPC method and exception type, and log chain-identity failures on state transitions. Log the first escaped dispatch failure in each batch at ERROR with its cause; repeats use DEBUG with only the index and exception type. Restore interrupted status for asynchronous log queries. Reject Boolean, object, and array request IDs before dispatch with -32600 and id:null. Reject non-null scalar params with -32600, preserve valid IDs, and isolate invalid batch elements so their siblings run. Missing, null, array, and object params keep their existing semantics. Remove the obsolete request replay wrapper and HTTP status provider. Add resolver, servlet, embedded-Jetty, chain-identity, asynchronous failure, dispatch-contract, and request-envelope regression coverage. Exercise the real HTTP interceptor chain and observe commitment without performing it on the servlet's behalf. Test interceptor Errors with a real server and preserve the existing notification response-suppression rules with characterization tests. Add a package-private server injection seam for servlet tests without changing production initialization.
1 parent 0d19485 commit 6ecb02c

14 files changed

Lines changed: 3052 additions & 320 deletions

‎framework/src/main/java/org/tron/core/services/filter/CachedBodyRequestWrapper.java‎

Lines changed: 0 additions & 97 deletions
This file was deleted.
Lines changed: 101 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,140 @@
11
package org.tron.core.services.jsonrpc;
22

33
import com.fasterxml.jackson.databind.JsonNode;
4-
import com.googlecode.jsonrpc4j.ErrorData;
54
import com.googlecode.jsonrpc4j.ErrorResolver;
65
import com.googlecode.jsonrpc4j.JsonRpcError;
76
import com.googlecode.jsonrpc4j.JsonRpcErrors;
7+
import com.googlecode.jsonrpc4j.ProxyUtil;
88
import com.googlecode.jsonrpc4j.ReflectionUtil;
99
import java.lang.reflect.Method;
1010
import java.util.List;
11+
import java.util.Set;
12+
import java.util.concurrent.ConcurrentHashMap;
13+
import lombok.extern.slf4j.Slf4j;
14+
import org.apache.commons.lang3.StringUtils;
15+
import org.tron.core.exception.TronError;
1116
import org.tron.core.exception.jsonrpc.JsonRpcException;
1217

1318
/**
1419
* {@link ErrorResolver} that uses annotations.
1520
*/
21+
@Slf4j(topic = "API")
1622
public enum JsonRpcErrorResolver implements ErrorResolver {
1723
INSTANCE;
1824

25+
private static final Set<String> SEEN_FAILURES = ConcurrentHashMap.newKeySet();
26+
1927
/**
2028
* {@inheritDoc}
2129
*/
2230
@Override
2331
public JsonError resolveError(
2432
Throwable thrownException, Method method, List<JsonNode> arguments) {
25-
JsonRpcError resolver = getResolverForException(thrownException, method);
26-
if (notFoundResolver(resolver)) {
27-
return null;
33+
Error fatal = findFatalCause(thrownException);
34+
if (fatal != null) {
35+
throw fatal;
36+
}
37+
38+
JsonRpcError resolver = method == null
39+
? null : getResolverForException(thrownException, method);
40+
if (resolver == null) {
41+
logUnhandledException(method, thrownException);
42+
return new JsonError(JsonError.INTERNAL_ERROR.code, "Internal error", null);
2843
}
2944

3045
String message = hasErrorMessage(resolver) ? resolver.message() : thrownException.getMessage();
46+
if (StringUtils.isBlank(message)) {
47+
message = defaultMessageFor(resolver.code());
48+
}
3149

32-
// data priority: exception > annotation > default ErrorData
50+
// data priority: exception > annotation
3351
Object data = null;
3452
if (thrownException instanceof JsonRpcException) {
3553
JsonRpcException jsonRpcException = (JsonRpcException) thrownException;
3654
data = jsonRpcException.getData();
3755
}
3856

39-
if (data == null) {
40-
data = hasErrorData(resolver)
41-
? resolver.data()
42-
: new ErrorData(resolver.exception().getName(), message);
57+
if (data == null && hasErrorData(resolver)) {
58+
data = resolver.data();
4359
}
44-
60+
4561
return new JsonError(resolver.code(), message, data);
4662
}
4763

64+
static Error findFatalCause(Throwable throwable) {
65+
// Avoid allocations when handling memory exhaustion, without truncating deep cause chains.
66+
// Check both fast-pointer steps so cycle detection cannot skip a fatal cause inside a cycle.
67+
Throwable slow = throwable;
68+
Throwable fast = throwable;
69+
while (fast != null) {
70+
if (isFatal(fast)) {
71+
return (Error) fast;
72+
}
73+
fast = fast.getCause();
74+
if (fast == null) {
75+
return null;
76+
}
77+
if (isFatal(fast)) {
78+
return (Error) fast;
79+
}
80+
fast = fast.getCause();
81+
slow = slow.getCause();
82+
if (fast == slow) {
83+
return null;
84+
}
85+
}
86+
return null;
87+
}
88+
89+
private static boolean isFatal(Throwable cause) {
90+
return cause instanceof VirtualMachineError
91+
|| cause instanceof ThreadDeath
92+
|| cause instanceof LinkageError
93+
|| cause instanceof TronError;
94+
}
95+
96+
private static void logUnhandledException(Method method, Throwable thrownException) {
97+
String methodName = rpcMethodName(method);
98+
String exceptionName = thrownException.getClass().getName();
99+
String key = methodName + '\0' + exceptionName;
100+
if (SEEN_FAILURES.add(key)) {
101+
// The first occurrence retains the Throwable for diagnosis. Repeated failures omit both
102+
// the stack and exception message so a request loop cannot flood the WARN log.
103+
logger.warn("Unhandled exception in JSON-RPC method {}", methodName, thrownException);
104+
} else {
105+
logger.debug("Repeated unhandled exception in JSON-RPC method {} ({})",
106+
methodName, exceptionName);
107+
}
108+
}
109+
110+
static void clearSeenFailuresForTest() {
111+
SEEN_FAILURES.clear();
112+
}
113+
114+
private static String rpcMethodName(Method method) {
115+
if (method == null) {
116+
return "unknown";
117+
}
118+
try {
119+
return ProxyUtil.getMethodName(method);
120+
} catch (RuntimeException e) {
121+
return method.getName();
122+
}
123+
}
124+
125+
private static String defaultMessageFor(int code) {
126+
switch (code) {
127+
case -32600:
128+
return "Invalid Request";
129+
case -32601:
130+
return "Method not found";
131+
case -32602:
132+
return "Invalid params";
133+
default:
134+
return "Internal error";
135+
}
136+
}
137+
48138
private JsonRpcError getResolverForException(Throwable thrownException, Method method) {
49139
JsonRpcErrors errors = ReflectionUtil.getAnnotation(method, JsonRpcErrors.class);
50140
if (hasAnnotations(errors)) {
@@ -57,10 +147,6 @@ private JsonRpcError getResolverForException(Throwable thrownException, Method m
57147
return null;
58148
}
59149

60-
private boolean notFoundResolver(JsonRpcError resolver) {
61-
return resolver == null;
62-
}
63-
64150
private boolean hasErrorMessage(JsonRpcError em) {
65151
// noinspection ConstantConditions
66152
return em.message() != null && !em.message().trim().isEmpty();
@@ -78,4 +164,4 @@ private boolean hasAnnotations(JsonRpcErrors errors) {
78164
private boolean isExceptionInstanceOfError(Throwable target, JsonRpcError em) {
79165
return em.exception().isInstance(target);
80166
}
81-
}
167+
}

0 commit comments

Comments
 (0)