Visitar URL original
feat(api): add peer management to admin RPC by 317787106 · Pull Request #86 · 317787106/java-tron · GitHub
Skip to content

feat(api): add peer management to admin RPC - #86

Closed
317787106 wants to merge 28 commits into
feature/admin_rpcfrom
feature/peer_management
Closed

317787106 wants to merge 28 commits into
feature/admin_rpcfrom
feature/peer_management

Conversation

@317787106

@317787106 317787106 commented Aug 20, 2026 •

Copy link
Copy Markdown
Owner

What does this PR do?

Adds runtime peer management to Admin JSON-RPC over HTTP and IPC, so operators can adjust active nodes, inspect connections, and block malicious IPs without restarting FullNode.

The API adds admin_addPeer, admin_removePeer, admin_disconnectPeer, admin_listActivePeers, admin_blockIp, admin_unblockIp, and admin_listBlockedIps. Mutations return a shared PeerOperationResult; active-peer queries reuse the connection, latency, and synchronization statistics used by PeerConnection.log(). The IPC client also supports optional text-table output for admin_listActivePeers.

Why are these changes required?

Operators need to disconnect or block identified malicious peers and add trusted endpoints promptly when investigating degraded connectivity or network isolation. Persistent manual IP blocking keeps those decisions effective across node restarts.

Integration with the built-in p2p module

Upstream PR #6992 has merged libp2p into java-tron as the local :p2p module. This PR targets feature/admin_rpc, which already includes that change from release_v4.8.3, and contains both the framework integration and the required p2p implementation and tests. It has no dependency on a separate libp2p PR, SNAPSHOT artifact, or release.

  • framework owns Admin HTTP/IPC dispatch, operation coordination, peer statistics, and persistence of normalized IPs and blockedAtMillis timestamps in CommonStore["blocked-ips"].
  • p2p provides addActiveNode, removeActiveNode, disconnect, and replaceBlockedIps, plus TCP admission, dialing, candidate filtering, and disconnection enforcement.
  • ConnectionPolicy publishes an immutable IP set through a volatile reference and normalizes IPv4-mapped IPv6 addresses for matching. P2pConfig.blockedIps supplies the initial policy; runtime changes update the policy without writing back to startup configuration.
  • The independently runnable p2p-standalone.jar retains --blocked-ips / -b. Its argument coverage is consolidated in StartAppArgsTest, and the module README documents startup and runtime usage.

Behavior and compatibility

  • admin_addPeer adds an active endpoint without adding it to trustNodes or waiting for a successful connection. Adding a blocked IP is rejected.
  • admin_removePeer removes the active endpoint and closes its connection. admin_disconnectPeer only closes the current connection; an active node can reconnect later.
  • When node.dynamicConfig.enable is enabled, add/remove operations return a structured failure directing operators to update node.active. Other peer-management operations remain available.
  • Persisted blocks are loaded and installed before network initialization. Malformed stored data is deleted on a best-effort basis and the node starts with an empty manual blocklist.
  • A blocklist change first installs the p2p policy and closes matching connections, then persists the snapshot, then publishes the framework query snapshot. A persistence failure returns an internal error and leaves the query snapshot unchanged, although the runtime policy may already have changed; retrying the operation reapplies and persists the intended snapshot.
  • Blocking applies to TCP connections and dialing candidates. UDP discovery traffic remains outside its scope. FullNode gains no new peer-management configuration switch.
  • Connect.proto adds DisconnectReason.REQUESTED = 0x0F for explicit disconnects. The existing disconnect message structure, consensus rules, and chain-data formats remain unchanged.

Testing

  • Coverage includes startup policy installation, persistence and corrupt-data recovery, update ordering and retries, idempotency, concurrent mutations, dynamic-config restrictions, IP normalization, and TCP inbound/outbound rejection.
  • HTTP/IPC dispatch, error codes, peer statistics, IPC text output, network lifecycle, and effective-connection compatibility have regression coverage.
  • Full p2p suite: 383 tests, 3 existing skips, no failures or errors; StartAppArgsTest includes all 11 argument tests.
  • Related framework suites: 197 tests, no failures or errors.
  • All-module checkstyleMain and checkstyleTest passed.
  • :p2p:buildStandaloneJar and a standalone JAR help invocation with --blocked-ips passed.

@317787106 317787106 changed the title support peer management based on ipc feat(net): support runtime peer management Aug 20, 2026
@317787106 317787106 changed the title feat(net): support runtime peer management feat(api): add peer management to admin RPC Aug 20, 2026
Add peer management to Admin HTTP and IPC, including active-peer inspection,
persistent IP blocking, and optional IPC text output.

Implement the management APIs and TCP connection policy in the built-in p2p
module. Retain the standalone blocked-ips option and consolidate its tests
in StartAppArgsTest.

Base the change on feature/admin_rpc with java-tron 4.8.3.
317787106 and others added 24 commits October 7, 2026 16:08
* 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.
…col#6985)

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, make a best-effort attempt to commit an
empty HTTP 500 so the container does not render its default error page.
Preserve the original error if cleanup fails, and leave an already
committed response untouched.

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 batch
request-serialization and response-parsing recoveries at DEBUG with the
element index and the Throwable. 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.
The node.rpc.maxRstStream and secondsPerWindow options defaulted to
0, which left the HTTP/2 RST_STREAM frame limit unset, and the limit
was configured only when both values were positive. Give them
sensible defaults, validate them at load time, and apply the limit
unconditionally so the configuration behaves consistently.

- NodeConfig: default maxRstStream/secondsPerWindow to 1000/5.
  In postProcess, reject negative values for either option and reject
  Integer.MAX_VALUE specifically for maxRstStream, which grpc-java
  treats as disabling the limit. Independently replace each zero with
  its default and log a warning.
- RpcService: always configure maxRstFramesPerWindow from the config
  values; validation stays solely in NodeConfig, consistent with the
  neighboring maxConcurrentCallsPerConnection option.
- reference.conf, docs/configuration.md and config/README.md:
  document the new defaults and the 0 fallback for compatibility.
- Tests: pin the Java and reference defaults, preserve positive
  overrides, and verify PING at the RST limit followed by GOAWAY
  after one additional reset using a prebuilt HTTP/2 frame burst.

Note: an explicit 0 now falls back to the default instead of leaving
the limit unset, and maxRstStream = 2147483647 is rejected at startup.
1. bump jsonrpc4j to 1.7, the latest release
2. add jakarta.servlet-api 5.0.0 as a test dependency; jsonrpc4j
   declares it optional, and Mockito needs it on the classpath to mock
   JsonRpcServer, whose new handle overload takes jakarta servlet
   types; the servlet dispatches through handleRequest and never
   calls that overload
3. drop javax.jws-api; jsonrpc4j 1.7 logs a missing
   javax.jws.WebParam at debug level instead of error, and no code
   uses @WebParam
4. accept one wire-level behavior change: when a positional parameter
   cannot be converted to the declared Java type (for example an
   object or array where a string is expected), the response changes
   from -32700 "JSON parse error" with id "null" to -32602 "Failed
   to read method parameter at index N" with the request id preserved
   and no data field; this also applies to batch entries, and a
   request without an id still gets this error with id null; the
   error is produced inside jsonrpc4j and does not pass through the
   error resolver
5. transitive changes on the runtime classpath: commons-codec 1.15 ->
   1.16.1, httpcore 4.4.13 -> 4.4.16, httpcore-nio 4.4.5 -> 4.4.16,
   jakarta.jws-api 3.0.0 added, net.iharder:base64 removed; slf4j-api
   and jackson keep resolving to 2.0.17 and 2.18.10
6. update the dispatch contract test, extend the error integration
   test with conversion errors in single, batch and id-less requests,
   and update the dependency verification metadata accordingly
0xbigapple and others added 3 commits October 14, 2026 22:17
# Conflicts:
#	common/src/main/resources/reference.conf
#	framework/build.gradle
#	framework/src/main/java/org/tron/core/config/args/Args.java
#	framework/src/main/java/org/tron/core/config/args/CommandLineArguments.java
#	framework/src/main/java/org/tron/core/services/admin/AdminJsonRpc.java
#	framework/src/main/java/org/tron/core/services/admin/AdminJsonRpcImpl.java
#	framework/src/main/java/org/tron/core/services/admin/AdminJsonRpcRequestHandler.java
#	framework/src/main/java/org/tron/core/services/admin/http/AdminRpcHttpService.java
#	framework/src/main/java/org/tron/core/services/admin/http/AdminRpcServlet.java
#	framework/src/main/java/org/tron/core/services/admin/http/VirtualHostValidator.java
#	framework/src/main/java/org/tron/core/services/admin/ipc/client/IpcClient.java
#	framework/src/main/java/org/tron/core/services/admin/ipc/client/IpcConsoleCommands.java
#	framework/src/main/java/org/tron/core/services/admin/ipc/client/IpcResponse.java
#	framework/src/main/java/org/tron/core/services/admin/ipc/server/IpcRequestHandler.java
#	framework/src/main/java/org/tron/core/services/admin/ipc/server/IpcSocketFiles.java
#	framework/src/main/java/org/tron/core/services/jsonrpc/JsonRpcServlet.java
#	framework/src/main/java/org/tron/program/FullNode.java
#	framework/src/test/java/org/tron/core/services/admin/http/AdminRpcServletTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/client/IpcClientTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/client/IpcConsoleCommandsTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/client/IpcResponseTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/server/AdminJsonRpcRequestTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/server/IpcRequestHandlerTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/server/IpcServiceTest.java
#	framework/src/test/java/org/tron/core/services/admin/ipc/server/IpcSocketFilesTest.java
#	framework/src/test/java/org/tron/program/FullNodeTest.java
#	gradle/verification-metadata.xml
@317787106 317787106 closed this Oct 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants