Skip to content

Commit 8be801c

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. Log unmapped exceptions, chain-identity failures, and asynchronous log-query failures and interruptions at DEBUG with the Throwable, classifying fatal causes before logging the failures. Log the first escaped dispatch failure in each batch at ERROR with the Throwable; 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 6d5adc4 commit 8be801c

15 files changed

Lines changed: 3182 additions & 319 deletions

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

Lines changed: 0 additions & 97 deletions
This file was deleted.

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

Lines changed: 94 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
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 lombok.extern.slf4j.Slf4j;
12+
import org.apache.commons.lang3.StringUtils;
13+
import org.tron.core.exception.TronError;
1114
import org.tron.core.exception.jsonrpc.JsonRpcException;
1215

1316
/**
1417
* {@link ErrorResolver} that uses annotations.
1518
*/
19+
@Slf4j(topic = "API")
1620
public enum JsonRpcErrorResolver implements ErrorResolver {
1721
INSTANCE;
1822

@@ -22,29 +26,108 @@ public enum JsonRpcErrorResolver implements ErrorResolver {
2226
@Override
2327
public JsonError resolveError(
2428
Throwable thrownException, Method method, List<JsonNode> arguments) {
25-
JsonRpcError resolver = getResolverForException(thrownException, method);
26-
if (notFoundResolver(resolver)) {
27-
return null;
29+
Error fatal = findFatalCause(thrownException);
30+
if (fatal != null) {
31+
throw fatal;
32+
}
33+
34+
JsonRpcError resolver = method == null
35+
? null : getResolverForException(thrownException, method);
36+
if (resolver == null) {
37+
logUnhandledException(method, thrownException);
38+
return new JsonError(JsonError.INTERNAL_ERROR.code, "Internal error", null);
2839
}
2940

3041
String message = hasErrorMessage(resolver) ? resolver.message() : thrownException.getMessage();
42+
if (StringUtils.isBlank(message)) {
43+
message = defaultMessageFor(resolver.code());
44+
}
3145

32-
// data priority: exception > annotation > default ErrorData
46+
// data priority: exception > annotation
3347
Object data = null;
3448
if (thrownException instanceof JsonRpcException) {
3549
JsonRpcException jsonRpcException = (JsonRpcException) thrownException;
3650
data = jsonRpcException.getData();
3751
}
3852

39-
if (data == null) {
40-
data = hasErrorData(resolver)
41-
? resolver.data()
42-
: new ErrorData(resolver.exception().getName(), message);
53+
if (data == null && hasErrorData(resolver)) {
54+
data = resolver.data();
4355
}
44-
56+
4557
return new JsonError(resolver.code(), message, data);
4658
}
4759

60+
/**
61+
* Returns the first {@link VirtualMachineError}, {@link ThreadDeath}, {@link LinkageError} or
62+
* {@link TronError} found in {@code throwable} or its cause chain, or {@code null} if there is
63+
* none.
64+
*
65+
* <p>This is the JSON-RPC layer's propagation policy for fatal causes, not a statement that
66+
* other {@link Error}s are safe to recover from. Callers should apply it before any logging so a
67+
* fatal cause is never recorded as an ordinary failure. The scan has no depth cutoff, terminates
68+
* on cyclic cause chains, and uses neither recursion nor auxiliary collections.
69+
*/
70+
public static Error findFatalCause(Throwable throwable) {
71+
// Avoid allocations when handling memory exhaustion, without truncating deep cause chains.
72+
// Check both fast-pointer steps so cycle detection cannot skip a fatal cause inside a cycle.
73+
Throwable slow = throwable;
74+
Throwable fast = throwable;
75+
while (fast != null) {
76+
if (isFatal(fast)) {
77+
return (Error) fast;
78+
}
79+
fast = fast.getCause();
80+
if (fast == null) {
81+
return null;
82+
}
83+
if (isFatal(fast)) {
84+
return (Error) fast;
85+
}
86+
fast = fast.getCause();
87+
slow = slow.getCause();
88+
if (fast == slow) {
89+
return null;
90+
}
91+
}
92+
return null;
93+
}
94+
95+
private static boolean isFatal(Throwable cause) {
96+
return cause instanceof VirtualMachineError
97+
|| cause instanceof ThreadDeath
98+
|| cause instanceof LinkageError
99+
|| cause instanceof TronError;
100+
}
101+
102+
private static void logUnhandledException(Method method, Throwable thrownException) {
103+
logger.debug("Unhandled exception in JSON-RPC method {}", rpcMethodName(method),
104+
thrownException);
105+
}
106+
107+
private static String rpcMethodName(Method method) {
108+
if (method == null) {
109+
return "unknown";
110+
}
111+
try {
112+
return ProxyUtil.getMethodName(method);
113+
} catch (RuntimeException e) {
114+
return method.getName();
115+
}
116+
}
117+
118+
private static String defaultMessageFor(int code) {
119+
switch (code) {
120+
case -32600:
121+
return "Invalid Request";
122+
case -32601:
123+
return "Method not found";
124+
case -32602:
125+
return "Invalid params";
126+
default:
127+
return "Internal error";
128+
}
129+
}
130+
48131
private JsonRpcError getResolverForException(Throwable thrownException, Method method) {
49132
JsonRpcErrors errors = ReflectionUtil.getAnnotation(method, JsonRpcErrors.class);
50133
if (hasAnnotations(errors)) {
@@ -57,10 +140,6 @@ private JsonRpcError getResolverForException(Throwable thrownException, Method m
57140
return null;
58141
}
59142

60-
private boolean notFoundResolver(JsonRpcError resolver) {
61-
return resolver == null;
62-
}
63-
64143
private boolean hasErrorMessage(JsonRpcError em) {
65144
// noinspection ConstantConditions
66145
return em.message() != null && !em.message().trim().isEmpty();
@@ -78,4 +157,4 @@ private boolean hasAnnotations(JsonRpcErrors errors) {
78157
private boolean isExceptionInstanceOfError(Throwable target, JsonRpcError em) {
79158
return em.exception().isInstance(target);
80159
}
81-
}
160+
}

0 commit comments

Comments
 (0)