SHA256
Solana RPC gateway для клиента и сервера
This commit is contained in:
+1
@@ -32,6 +32,7 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
|
||||
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
|
||||
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
|
||||
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
|
||||
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
+4
@@ -26,6 +26,10 @@ public class Net_GetServerInfo_Response extends Net_Response {
|
||||
private String description;
|
||||
private String origin;
|
||||
private String extraInfo;
|
||||
private String solanaCluster;
|
||||
|
||||
public String getSolanaCluster() { return solanaCluster; }
|
||||
public void setSolanaCluster(String cluster) { this.solanaCluster = cluster; }
|
||||
|
||||
public String getUrl() { return url; }
|
||||
public void setUrl(String url) { this.url = url; }
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
package server.ws;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.http.HttpServlet;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Single, provider-independent Solana HTTP JSON-RPC gateway. */
|
||||
public final class SolanaRpcGateway extends HttpServlet {
|
||||
private static final ObjectMapper JSON = new ObjectMapper();
|
||||
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
|
||||
private static final Set<String> METHODS = Set.of(
|
||||
"getBalance", "getAccountInfo", "getMultipleAccounts", "getProgramAccounts",
|
||||
"getLatestBlockhash", "getBlockHeight", "isBlockhashValid", "getFeeForMessage",
|
||||
"getMinimumBalanceForRentExemption", "getSignatureStatuses", "getSignatureStatus",
|
||||
"getTransaction", "getParsedTransaction", "getEpochInfo", "getSlot", "getVersion",
|
||||
"getTokenAccountBalance", "getTokenAccountsByOwner", "getSignaturesForAddress",
|
||||
"simulateTransaction", "getRecentPrioritizationFees", "sendTransaction"
|
||||
);
|
||||
private static final ConcurrentHashMap<String, Window> LIMITS = new ConcurrentHashMap<>();
|
||||
private static final int MAX_BYTES = 256 * 1024;
|
||||
private record Window(long minute, int count) {}
|
||||
|
||||
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
|
||||
cors(req, resp);
|
||||
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||
resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||
resp.setStatus(204);
|
||||
}
|
||||
|
||||
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||
cors(req, resp);
|
||||
resp.setContentType("application/json; charset=utf-8");
|
||||
if (req.getContentLengthLong() > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
|
||||
byte[] bytes = req.getInputStream().readNBytes(MAX_BYTES + 1);
|
||||
if (bytes.length > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
|
||||
final JsonNode call;
|
||||
try {
|
||||
call = JSON.readTree(bytes);
|
||||
if (call == null || !call.isObject() || !call.path("jsonrpc").asText().equals("2.0")
|
||||
|| !call.has("id") || !call.path("params").isArray()
|
||||
|| !METHODS.contains(call.path("method").asText())) {
|
||||
fail(resp, 400, "Unsupported JSON-RPC request"); return;
|
||||
}
|
||||
} catch (Exception ex) { fail(resp, 400, "Invalid JSON"); return; }
|
||||
boolean write = "sendTransaction".equals(call.path("method").asText());
|
||||
String client = req.getRemoteAddr();
|
||||
if ("127.0.0.1".equals(client) || "::1".equals(client)) {
|
||||
String forwarded = req.getHeader("X-Forwarded-For");
|
||||
if (forwarded != null && !forwarded.isBlank()) {
|
||||
String first = forwarded.split(",", 2)[0].trim();
|
||||
if (first.matches("[0-9a-fA-F:.]{3,48}")) client = first;
|
||||
}
|
||||
}
|
||||
long minute = System.currentTimeMillis() / 60_000L;
|
||||
String key = client + (write ? ":write" : ":read");
|
||||
Window window = LIMITS.compute(key, (k, old) -> old == null || old.minute != minute
|
||||
? new Window(minute, 1) : new Window(minute, old.count + 1));
|
||||
if (window.count > (write ? 6 : 180)) { fail(resp, 429, "RPC request limit exceeded"); return; }
|
||||
String rpc = AppConfig.getInstance().getStringOrEmpty("solana.rpcUrl");
|
||||
if (!rpc.startsWith("https://") && !rpc.startsWith("http://")) {
|
||||
fail(resp, 503, "Solana RPC is not configured"); return;
|
||||
}
|
||||
try {
|
||||
HttpRequest upstream = HttpRequest.newBuilder(URI.create(rpc))
|
||||
.timeout(Duration.ofSeconds(30)).header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(bytes)).build();
|
||||
HttpResponse<byte[]> answer = HTTP.send(upstream, HttpResponse.BodyHandlers.ofByteArray());
|
||||
resp.setStatus(answer.statusCode());
|
||||
resp.getOutputStream().write(answer.body());
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt(); fail(resp, 502, "RPC interrupted");
|
||||
} catch (Exception ex) { fail(resp, 502, "RPC upstream unavailable"); }
|
||||
}
|
||||
|
||||
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
|
||||
String origin = req.getHeader("Origin");
|
||||
if (origin == null) return;
|
||||
try {
|
||||
URI uri = URI.create(origin);
|
||||
String host = uri.getHost();
|
||||
if (host != null && (host.equals("shineup.me") || host.endsWith(".shineup.me")
|
||||
|| host.equals("localhost") || host.equals("127.0.0.1"))) {
|
||||
resp.setHeader("Access-Control-Allow-Origin", origin);
|
||||
resp.setHeader("Vary", "Origin");
|
||||
}
|
||||
} catch (IllegalArgumentException ignored) { }
|
||||
}
|
||||
|
||||
private static void fail(HttpServletResponse response, int code, String message) throws IOException {
|
||||
response.setStatus(code);
|
||||
response.getWriter().write(JSON.createObjectNode().put("error", message).toString());
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import server.keyrotation.KeyRotationRebuildScheduler;
|
||||
|
||||
import org.eclipse.jetty.server.Server;
|
||||
import org.eclipse.jetty.servlet.ServletContextHandler;
|
||||
import org.eclipse.jetty.servlet.ServletHolder;
|
||||
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -77,6 +78,9 @@ public final class WsServer {
|
||||
context.setContextPath("/");
|
||||
server.setHandler(context);
|
||||
|
||||
// Universal Solana HTTP JSON-RPC gateway
|
||||
context.addServlet(new ServletHolder(new SolanaRpcGateway()), "/solana-rpc");
|
||||
|
||||
// HTTP debug API
|
||||
DebugApiConfigurator.register(context);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user