Solana RPC gateway для клиента и сервера

This commit is contained in:
AidarKC
2026-10-18 00:03:46 +03:00
parent b67d06ce43
commit aa5addb5d9
17 changed files with 228 additions and 85 deletions
@@ -32,6 +32,7 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description")); resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin")); resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo")); resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
return resp; return resp;
} }
@@ -26,6 +26,10 @@ public class Net_GetServerInfo_Response extends Net_Response {
private String description; private String description;
private String origin; private String origin;
private String extraInfo; 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 String getUrl() { return url; }
public void setUrl(String url) { this.url = 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.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer; import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -77,6 +78,9 @@ public final class WsServer {
context.setContextPath("/"); context.setContextPath("/");
server.setHandler(context); server.setHandler(context);
// Universal Solana HTTP JSON-RPC gateway
context.addServlet(new ServletHolder(new SolanaRpcGateway()), "/solana-rpc");
// HTTP debug API // HTTP debug API
DebugApiConfigurator.register(context); DebugApiConfigurator.register(context);
@@ -0,0 +1,14 @@
# Caddy: проксирование SolanaRpcGateway
Добавьте перед общим `handle` с UI / SPA в **каждый** site block SHiNE:
```caddyfile
@solana_rpc path /solana-rpc
handle @solana_rpc {
reverse_proxy 127.0.0.1:7070
}
```
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3/t4 используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
Далее: `caddy validate --config /etc/caddy/Caddyfile`, перезагрузите Caddy и проверьте `POST https://<ваш-сервер>/solana-rpc` с JSON-RPC `getVersion`.
+10
View File
@@ -57,6 +57,8 @@ import {
setContacts, setContacts,
} from './state.js'; } from './state.js';
import { setSolanaCluster } from './services/solana-rpc-gateway.js';
import * as startView from './pages/start-view.js?v=202610072303'; import * as startView from './pages/start-view.js?v=202610072303';
import * as entrySettingsView from './pages/entry-settings-view.js?v=202609260900'; import * as entrySettingsView from './pages/entry-settings-view.js?v=202609260900';
import * as registerView from './pages/register-view.js?v=202609260900'; import * as registerView from './pages/register-view.js?v=202609260900';
@@ -2040,6 +2042,14 @@ async function init() {
}); });
} }
if (hasUrlEntrySettingsOverride() && !urlEntrySettingsReady) return; if (hasUrlEntrySettingsOverride() && !urlEntrySettingsReady) return;
// Public server info: one UI build for both devnet and mainnet.
try {
await authService.reconnect(state.entrySettings.shineServer);
const info = await authService.ws.request('GetServerInfo', {}, 9000);
setSolanaCluster(info?.payload?.solanaCluster ?? info?.solanaCluster);
} catch (error) {
console.warn('Failed to read SHiNE Solana cluster', error);
}
await tryAutoLogin(); await tryAutoLogin();
if (initialNotificationOpenPayload) { if (initialNotificationOpenPayload) {
await handleNotificationClick(initialNotificationOpenPayload); await handleNotificationClick(initialNotificationOpenPayload);
+1 -1
View File
@@ -6,4 +6,4 @@ export const defaultServerAddress = 'shineup.me';
export const defaultServerHttp = `https://${defaultServerAddress}`; export const defaultServerHttp = `https://${defaultServerAddress}`;
export const defaultServerWs = `wss://${defaultServerAddress}/ws`; export const defaultServerWs = `wss://${defaultServerAddress}/ws`;
export const defaultSolanaCluster = 'mainnet-beta'; export const defaultSolanaCluster = 'mainnet-beta';
export const defaultSolanaEndpoint = 'https://public.rpc.solanavibestation.com/'; export const defaultSolanaEndpoint = `${defaultServerHttp}/solana-rpc`;
-1
View File
@@ -12,7 +12,6 @@ import { checkServerAvailabilityByKey, resolveAndCheckShineServerLogin } from '.
export const pageMeta = { id: 'entry-settings-view', title: 'Настройки входа', showAppChrome: false }; export const pageMeta = { id: 'entry-settings-view', title: 'Настройки входа', showAppChrome: false };
const SERVER_FIELDS = [ const SERVER_FIELDS = [
{ key: 'solanaServer', label: 'Сервер Solana' },
{ key: 'shineServerLogin', label: 'Сервер Сияния' }, { key: 'shineServerLogin', label: 'Сервер Сияния' },
{ key: 'arweaveServer', label: 'Сервер Arweave' }, { key: 'arweaveServer', label: 'Сервер Arweave' },
]; ];
@@ -1,5 +1,5 @@
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { defaultSolanaCluster } from '../deploy-config.js';
import { state } from '../state.js'; import { state } from '../state.js';
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js'; import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
@@ -7,7 +7,6 @@ export const pageMeta = { id: 'queue', title: 'Очередь билета' };
const SHINE_PAYMENTS_PROGRAM_ID = 'SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v'; const SHINE_PAYMENTS_PROGRAM_ID = 'SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v';
const SHINE_PAYMENTS_ORACLE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE'; const SHINE_PAYMENTS_ORACLE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE';
const SHINE_MAINNET_SOLANA_ENDPOINT = 'https://solana-rpc.publicnode.com';
const SHINE_PAYMENTS_SEEDS = { const SHINE_PAYMENTS_SEEDS = {
config: 'shine_payments_config', config: 'shine_payments_config',
coef: 'shine_payments_coef_limit', coef: 'shine_payments_coef_limit',
@@ -18,11 +17,11 @@ const SHINE_PAYMENTS_SEEDS = {
}; };
function isTestDeployUi() { function isTestDeployUi() {
return String(defaultSolanaCluster || '').trim().toLowerCase() !== 'mainnet-beta'; return getSolanaCluster() === 'devnet';
} }
function resolveQueueEndpoint(useMainnetQueue) { function resolveQueueEndpoint(useMainnetQueue) {
return useMainnetQueue ? SHINE_MAINNET_SOLANA_ENDPOINT : state.entrySettings.solanaServer; return state.entrySettings.solanaServer;
} }
function utf8Bytes(text) { function utf8Bytes(text) {
@@ -312,9 +311,9 @@ export function render({navigate, chrome}) {
mainnetRow.className = 'checkbox-row'; mainnetRow.className = 'checkbox-row';
mainnetRow.innerHTML = ` mainnetRow.innerHTML = `
<input type="checkbox" id="public-queue-mainnet-source" ${testDeploy ? 'checked' : ''} /> <input type="checkbox" id="public-queue-mainnet-source" ${testDeploy ? 'checked' : ''} />
<span>Показывать данные mainnet (${SHINE_MAINNET_SOLANA_ENDPOINT})</span> <span>Использовать сеть текущего сервера SHiNE</span>
`; `;
mainnetRow.style.display = testDeploy ? '' : 'none'; mainnetRow.style.display = 'none';
const mainnetCheckbox = mainnetRow.querySelector('#public-queue-mainnet-source'); const mainnetCheckbox = mainnetRow.querySelector('#public-queue-mainnet-source');
let lastCoreState = null; let lastCoreState = null;
+3 -12
View File
@@ -1,3 +1,4 @@
import { getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { iconHtml } from '../components/ui-icon.js'; import { iconHtml } from '../components/ui-icon.js';
import { import {
@@ -51,23 +52,13 @@ function getExplorerClusterName(endpoint) {
} }
function isTestRegistrationContour() { function isTestRegistrationContour() {
const solanaCluster = getExplorerClusterName(state.entrySettings.solanaServer); return getSolanaCluster() === 'devnet';
if (solanaCluster !== 'mainnet-beta') return true;
const shineServer = String(state.entrySettings.shineServer || '').trim().toLowerCase();
const shineServerLogin = String(state.entrySettings.shineServerLogin || '').trim().toLowerCase();
return (
shineServer.includes('t1.shineup.me')
|| shineServer.includes('t2.shineup.me')
|| shineServer.includes('t3.shineup.me')
|| shineServer.includes('t4.shineup.me')
|| ['t1', 't2', 't3', 't4'].includes(shineServerLogin)
);
} }
function makeSolanaExplorerTxUrl(signature, endpoint) { function makeSolanaExplorerTxUrl(signature, endpoint) {
const cleanSignature = String(signature || '').trim(); const cleanSignature = String(signature || '').trim();
if (!cleanSignature) return ''; if (!cleanSignature) return '';
const cluster = getExplorerClusterName(endpoint); const cluster = getSolanaCluster() || getExplorerClusterName(endpoint);
const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(cleanSignature)}`); const url = new URL(`https://explorer.solana.com/tx/${encodeURIComponent(cleanSignature)}`);
if (cluster !== 'mainnet-beta') { if (cluster !== 'mainnet-beta') {
url.searchParams.set('cluster', cluster); url.searchParams.set('cluster', cluster);
+10 -18
View File
@@ -1,19 +1,11 @@
import { state } from '../state.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
export const pageMeta = { id: 'solana-rpc-check-view', title: 'Проверка Solana RPC' }; export const pageMeta = { id: 'solana-rpc-check-view', title: 'Проверка Solana RPC' };
const MAINNET_RPC_ENDPOINTS = [ function currentRpcEndpoints() {
{ name: 'GetBlock', url: 'https://go.getblock.us/86aac42ad4484f3c813079afc201451c' }, return [{ name: 'SHiNE SolanaRpcGateway', url: state.entrySettings.solanaServer }];
{ name: 'PublicNode', url: 'https://solana-rpc.publicnode.com' }, }
{ name: 'BlockEden', url: 'https://api.blockeden.xyz/solana/KeCh6p22EX5AeRHxMSmc' },
{ name: 'dRPC', url: 'https://solana.drpc.org/' },
{ name: 'Grove', url: 'https://solana.rpc.grove.city/v1/01fdb492' },
{ name: 'LeoRPC', url: 'https://solana.leorpc.com/?api_key=FREE' },
{ name: 'OnFinality', url: 'https://solana.api.onfinality.io/public' },
{ name: 'Solana Foundation', url: 'https://api.mainnet-beta.solana.com' },
{ name: 'Solana Vibe Station', url: 'https://public.rpc.solanavibestation.com/' },
{ name: 'TheRPC', url: 'https://solana.therpc.io' },
];
const RPC_PAYLOAD = { const RPC_PAYLOAD = {
jsonrpc: '2.0', jsonrpc: '2.0',
@@ -139,10 +131,10 @@ export function render({navigate, chrome}) {
const intro = document.createElement('div'); const intro = document.createElement('div');
intro.className = 'card stack'; intro.className = 'card stack';
intro.innerHTML = ` intro.innerHTML = `
<strong>Проверка mainnet RPC из браузера</strong> <strong>Проверка SolanaRpcGateway</strong>
<p class="meta-muted"> <p class="meta-muted">
Этот экран делает реальный browser fetch к публичным Solana mainnet RPC. Этот экран проверяет RPC-шлюз подключённого сервера SHiNE.
Если ответ приходит прямо здесь, значит нода годится для клиентского UI без промежуточного сервера. RPC-провайдер и сеть определяются сервером SHiNE.
</p> </p>
`; `;
@@ -152,7 +144,7 @@ export function render({navigate, chrome}) {
const runBtn = document.createElement('button'); const runBtn = document.createElement('button');
runBtn.className = 'primary-btn'; runBtn.className = 'primary-btn';
runBtn.type = 'button'; runBtn.type = 'button';
runBtn.textContent = 'Проверить все ноды'; runBtn.textContent = 'Проверить шлюз';
const resetBtn = document.createElement('button'); const resetBtn = document.createElement('button');
resetBtn.className = 'ghost-btn'; resetBtn.className = 'ghost-btn';
@@ -169,7 +161,7 @@ export function render({navigate, chrome}) {
const grid = document.createElement('div'); const grid = document.createElement('div');
grid.className = 'stack'; grid.className = 'stack';
const cards = MAINNET_RPC_ENDPOINTS.map((endpoint) => { const cards = currentRpcEndpoints().map((endpoint) => {
const ui = makeResultCard(endpoint); const ui = makeResultCard(endpoint);
grid.append(ui.card); grid.append(ui.card);
return { endpoint, ui }; return { endpoint, ui };
@@ -194,7 +186,7 @@ export function render({navigate, chrome}) {
runBtn.disabled = true; runBtn.disabled = true;
resetBtn.disabled = true; resetBtn.disabled = true;
summary.className = 'status-line'; summary.className = 'status-line';
summary.textContent = 'Проверяем mainnet RPC из браузера...'; summary.textContent = 'Проверяем SHiNE SolanaRpcGateway...';
let okCount = 0; let okCount = 0;
let warnCount = 0; let warnCount = 0;
+3 -3
View File
@@ -1,8 +1,8 @@
import { confirmSolanaTransactionHttp, getSolanaCluster } from '../services/solana-rpc-gateway.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { import {
SHINE_USERS_ECONOMY_CONFIG_SEED, SHINE_USERS_ECONOMY_CONFIG_SEED,
SHINE_USERS_PROGRAM_ID, SHINE_USERS_PROGRAM_ID,
SOLANA_CLUSTER,
} from '../solana-programs.js'; } from '../solana-programs.js';
import { state } from '../state.js'; import { state } from '../state.js';
import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js'; import { loadSolanaWeb3 } from '../vendor/solana-web3-loader.js';
@@ -136,7 +136,7 @@ export function render({navigate, chrome}) {
const signed = await provider.signTransaction(tx); const signed = await provider.signTransaction(tx);
const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false }); const sig = await connection.sendRawTransaction(signed.serialize(), { skipPreflight: false });
await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed'); await confirmSolanaTransactionHttp(connection, sig, { lastValidBlockHeight });
txLine.textContent = `TX: ${sig}`; txLine.textContent = `TX: ${sig}`;
status.textContent = 'Успешно: init_users_economy_config выполнен.'; status.textContent = 'Успешно: init_users_economy_config выполнен.';
@@ -159,7 +159,7 @@ export function render({navigate, chrome}) {
(() => { (() => {
const t = document.createElement('p'); const t = document.createElement('p');
t.className = 'meta-muted'; t.className = 'meta-muted';
t.textContent = `Cluster: ${SOLANA_CLUSTER}`; t.textContent = `Cluster: ${getSolanaCluster() || "не определён"}`;
return t; return t;
})(), })(),
(() => { (() => {
+6 -10
View File
@@ -1,5 +1,5 @@
import { getSolanaCluster, confirmSolanaTransactionHttp } from '../services/solana-rpc-gateway.js';
import { createTopBar } from '../components/topbar.js'; import { createTopBar } from '../components/topbar.js';
import { defaultSolanaCluster } from '../deploy-config.js';
import { authService, state } from '../state.js'; import { authService, state } from '../state.js';
import { import {
formatSol, formatSol,
@@ -96,7 +96,6 @@ function sessionArgsOrThrow() {
const SHINE_PAYMENTS_PROGRAM_ID = 'SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v'; const SHINE_PAYMENTS_PROGRAM_ID = 'SHiPmXbM9Fs9khzRUW3TGKsS2W84aqaXTxs3ZkajW9v';
const SHINE_PAYMENTS_ORACLE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE'; const SHINE_PAYMENTS_ORACLE_ACCOUNT = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE';
const SHINE_MAINNET_SOLANA_ENDPOINT = 'https://solana-rpc.publicnode.com';
const SHINE_PAYMENTS_SEEDS = { const SHINE_PAYMENTS_SEEDS = {
config: 'shine_payments_config', config: 'shine_payments_config',
coef: 'shine_payments_coef_limit', coef: 'shine_payments_coef_limit',
@@ -117,11 +116,11 @@ const SUPPORT_TICKET_HELP_TEXT = [
].join('\n'); ].join('\n');
function isTestDeployUi() { function isTestDeployUi() {
return String(defaultSolanaCluster || '').trim().toLowerCase() !== 'mainnet-beta'; return getSolanaCluster() === 'devnet';
} }
function resolveSupportQueueEndpoint(useMainnetQueue) { function resolveSupportQueueEndpoint(useMainnetQueue) {
return useMainnetQueue ? SHINE_MAINNET_SOLANA_ENDPOINT : state.entrySettings.solanaServer; return state.entrySettings.solanaServer;
} }
function utf8Bytes(text) { function utf8Bytes(text) {
@@ -801,9 +800,9 @@ export function render({navigate, chrome}) {
mainnetRow.className = 'checkbox-row'; mainnetRow.className = 'checkbox-row';
mainnetRow.innerHTML = ` mainnetRow.innerHTML = `
<input type="checkbox" id="support-ticket-mainnet-source" ${testDeploy ? 'checked' : ''} /> <input type="checkbox" id="support-ticket-mainnet-source" ${testDeploy ? 'checked' : ''} />
<span>Показывать данные mainnet (${SHINE_MAINNET_SOLANA_ENDPOINT})</span> <span>Использовать сеть текущего сервера SHiNE</span>
`; `;
mainnetRow.style.display = testDeploy ? '' : 'none'; mainnetRow.style.display = 'none';
const mainnetCheckbox = mainnetRow.querySelector('#support-ticket-mainnet-source'); const mainnetCheckbox = mainnetRow.querySelector('#support-ticket-mainnet-source');
const actions = document.createElement('div'); const actions = document.createElement('div');
@@ -1224,10 +1223,7 @@ export function render({navigate, chrome}) {
tx.recentBlockhash = bh.blockhash; tx.recentBlockhash = bh.blockhash;
tx.partialSign(walletCtx.keypair); tx.partialSign(walletCtx.keypair);
const signature = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false }); const signature = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false });
await connection.confirmTransaction( await confirmSolanaTransactionHttp(connection, signature, { lastValidBlockHeight: bh.lastValidBlockHeight });
{ signature, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },
'confirmed',
);
const ticketInfo = await connection.getAccountInfo(ticketPda, 'confirmed'); const ticketInfo = await connection.getAccountInfo(ticketPda, 'confirmed');
const ticket = ticketInfo?.data const ticket = ticketInfo?.data
? parsePaymentsTicket(ticketInfo.data) ? parsePaymentsTicket(ticketInfo.data)
@@ -1,3 +1,4 @@
import { sendAndConfirmSolanaHttp } from './solana-rpc-gateway.js';
import { base58ToBytes, base64ToBytes, bytesToBase58, importPkcs8Ed25519, sha256Bytes, signBytes } from './crypto-utils.js'; import { base58ToBytes, base64ToBytes, bytesToBase58, importPkcs8Ed25519, sha256Bytes, signBytes } from './crypto-utils.js';
import { extractSeed32FromPkcs8B64 } from './client-key-utils.js'; import { extractSeed32FromPkcs8B64 } from './client-key-utils.js';
import { import {
@@ -623,7 +624,7 @@ async function createShineUserPdaOnSolana({
const tx = new ctx.solana.Transaction(); const tx = new ctx.solana.Transaction();
if (promoEdIx) tx.add(promoEdIx); if (promoEdIx) tx.add(promoEdIx);
tx.add(rootIx, recordIx, createIx); tx.add(rootIx, recordIx, createIx);
const signature = await ctx.solana.sendAndConfirmTransaction(ctx.connection, tx, [ctx.payerKeypair], { commitment: 'confirmed' }); const signature = await sendAndConfirmSolanaHttp(ctx.connection, tx, [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001` }; return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), blockchainName: `${cleanLogin}-001` };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); } } catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
} }
@@ -660,7 +661,7 @@ export async function closeLegacyShineUserPdaOnSolana({ login, solanaEndpoint, c
], ],
data: serializeCloseLegacyArgs(cleanLogin), data: serializeCloseLegacyArgs(cleanLogin),
}); });
const signature = await solana.sendAndConfirmTransaction(connection, new solana.Transaction().add(ix), [caller], { commitment: 'confirmed' }); const signature = await sendAndConfirmSolanaHttp(connection, new solana.Transaction().add(ix), [caller]);
return { signature, pdaAddress: userPda.toBase58() }; return { signature, pdaAddress: userPda.toBase58() };
} }
@@ -779,7 +780,7 @@ export async function updateShineUserPdaOnSolana({
data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, additionalLimitBytes: addLimit, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }), data: serializeUpdateUserPdaArgs({ login: current.login, rootKey32: rootKey, updatedAtMs, additionalLimitBytes: addLimit, clientKey32: clientKey, authMode, newBlockchainKey32: appendedKey, serverAddresses: addresses, accessServers: nextAccess, recordSignature64: recordSig }),
}); });
try { try {
const signature = await ctx.solana.sendAndConfirmTransaction(ctx.connection, new ctx.solana.Transaction().add(authIx, recordIx, updateIx), [ctx.payerKeypair], { commitment: 'confirmed' }); const signature = await sendAndConfirmSolanaHttp(ctx.connection, new ctx.solana.Transaction().add(authIx, recordIx, updateIx), [ctx.payerKeypair]);
return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), paidLimitBytes: forks.at(-1).paidLimitBytes, forkCount: forks.length }; return { signature, userPda: ctx.userPda.toBase58(), pdaAddress: ctx.userPda.toBase58(), paidLimitBytes: forks.at(-1).paidLimitBytes, forkCount: forks.length };
} catch (error) { throw await attachSolanaLogs(error, ctx.connection); } } catch (error) { throw await attachSolanaLogs(error, ctx.connection); }
} }
@@ -0,0 +1,41 @@
/** Solana JSON-RPC transport. Network selection belongs to the connected SHiNE server. */
export const DEVNET_FAUCET_RPC = 'https://api.devnet.solana.com';
let cluster = '';
export function setSolanaCluster(value) {
const next = String(value || '').toLowerCase();
if (next !== 'devnet' && next !== 'mainnet-beta' && next !== 'testnet') throw new Error(`Unsupported server Solana cluster: ${value}`);
cluster = next;
}
export function getSolanaCluster() { return cluster; }
export function rpcEndpointFromShineHttp(httpBase) {
const base = String(httpBase || '').trim();
if (!/^https?:\/\//i.test(base)) throw new Error('SHiNE server HTTP address is unavailable');
return `${base.replace(/\/+$/, '')}/solana-rpc`;
}
export async function confirmSolanaTransactionHttp(connection, signature, {
lastValidBlockHeight = null, commitment = 'confirmed', timeoutMs = 90_000,
} = {}) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const response = await connection.getSignatureStatuses([signature], { searchTransactionHistory: true });
const status = response?.value?.[0];
if (status?.err) throw new Error(`Solana transaction failed: ${JSON.stringify(status.err)}`);
if (status && (status.confirmationStatus === 'finalized' ||
(commitment !== 'finalized' && status.confirmationStatus === 'confirmed'))) return signature;
if (lastValidBlockHeight != null) {
const height = await connection.getBlockHeight('confirmed');
if (height > lastValidBlockHeight) throw new Error(`Solana transaction expired: ${signature}`);
}
await new Promise((resolve) => setTimeout(resolve, 1800));
}
throw new Error(`Solana transaction confirmation timed out: ${signature}`);
}
export async function sendAndConfirmSolanaHttp(connection, transaction, signers) {
const latest = await connection.getLatestBlockhash('confirmed');
transaction.recentBlockhash = latest.blockhash;
if (!transaction.feePayer && signers?.[0]) transaction.feePayer = signers[0].publicKey;
transaction.sign(...signers);
const signature = await connection.sendRawTransaction(transaction.serialize(), { skipPreflight: false });
await confirmSolanaTransactionHttp(connection, signature, { lastValidBlockHeight: latest.lastValidBlockHeight });
return signature;
}
@@ -1,3 +1,4 @@
import { confirmSolanaTransactionHttp, sendAndConfirmSolanaHttp } from './solana-rpc-gateway.js';
import { extractEd25519Seed32FromStoredValue } from './client-key-utils.js'; import { extractEd25519Seed32FromStoredValue } from './client-key-utils.js';
import { base64ToBytes } from './crypto-utils.js'; import { base64ToBytes } from './crypto-utils.js';
import { loadEncryptedUserSecrets } from './key-vault.js'; import { loadEncryptedUserSecrets } from './key-vault.js';
@@ -259,7 +260,7 @@ export async function requestAirdropSol({ endpoint, address, amountSol = 1 }) {
const pubkey = new solana.PublicKey(String(address || '').trim()); const pubkey = new solana.PublicKey(String(address || '').trim());
const lamports = Math.max(1, Math.floor(Number(amountSol) * solana.LAMPORTS_PER_SOL)); const lamports = Math.max(1, Math.floor(Number(amountSol) * solana.LAMPORTS_PER_SOL));
const signature = await conn.requestAirdrop(pubkey, lamports); const signature = await conn.requestAirdrop(pubkey, lamports);
await conn.confirmTransaction(signature, 'confirmed'); await confirmSolanaTransactionHttp(conn, signature);
return { endpoint: rpc, signature, lamports }; return { endpoint: rpc, signature, lamports };
} }
@@ -283,9 +284,7 @@ export async function transferSol({ endpoint, fromKeypair, toAddress, amountSol
}), }),
); );
const signature = await solana.sendAndConfirmTransaction(conn, tx, [fromKeypair], { const signature = await sendAndConfirmSolanaHttp(conn, tx, [fromKeypair]);
commitment: 'confirmed',
});
return { endpoint: rpc, signature, lamports }; return { endpoint: rpc, signature, lamports };
} }
@@ -338,11 +337,7 @@ export async function transferAllSol({ endpoint, fromKeypair, toAddress }) {
})); }));
tx.sign(fromKeypair); tx.sign(fromKeypair);
const signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false }); const signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
await conn.confirmTransaction({ await confirmSolanaTransactionHttp(conn, signature, { lastValidBlockHeight: latest.lastValidBlockHeight });
signature,
blockhash: latest.blockhash,
lastValidBlockHeight: latest.lastValidBlockHeight,
}, 'confirmed');
return { return {
endpoint: rpc, endpoint: rpc,
signature, signature,
+13 -22
View File
@@ -1,6 +1,6 @@
import { AuthService } from './services/auth-service.js'; import { AuthService } from './services/auth-service.js';
import { listStoredMessages, putStoredMessage, deleteStoredMessage, clearStoredMessages } from './services/message-store.js'; import { listStoredMessages, putStoredMessage, deleteStoredMessage, clearStoredMessages } from './services/message-store.js';
import { SOLANA_ENDPOINT_DEFAULT } from './solana-programs.js'; import { rpcEndpointFromShineHttp, setSolanaCluster } from './services/solana-rpc-gateway.js';
import { import {
DEFAULT_SHINE_SERVER_HTTP, DEFAULT_SHINE_SERVER_HTTP,
DEFAULT_SHINE_SERVER_LOGIN, DEFAULT_SHINE_SERVER_LOGIN,
@@ -110,20 +110,6 @@ function readUrlServerLoginOverride() {
} }
} }
function readUrlSolanaServerOverride() {
try {
const params = new URLSearchParams(window.location.search);
const explicitEndpoint = String(params.get('solanaEndpoint') || params.get('solanaRpc') || '').trim();
if (explicitEndpoint) return explicitEndpoint;
const cluster = String(params.get('solana') || params.get('solanaCluster') || params.get('cluster') || '').trim().toLowerCase();
if (cluster === 'devnet') return 'https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4';
if (cluster === 'mainnet' || cluster === 'mainnet-beta') return DEFAULT_SOLANA_SERVER;
return '';
} catch {
return '';
}
}
function inferTunnelWsUrl() { function inferTunnelWsUrl() {
try { try {
@@ -144,8 +130,8 @@ function inferTunnelWsUrl() {
const LOCAL_WS_OVERRIDE_URL = readLocalWsOverrideUrl() || inferTunnelWsUrl(); const LOCAL_WS_OVERRIDE_URL = readLocalWsOverrideUrl() || inferTunnelWsUrl();
const URL_SHINE_SERVER_HTTP_OVERRIDE = readUrlShineServerHttpOverride(); const URL_SHINE_SERVER_HTTP_OVERRIDE = readUrlShineServerHttpOverride();
const URL_SHINE_SERVER_LOGIN_OVERRIDE = readUrlServerLoginOverride(); const URL_SHINE_SERVER_LOGIN_OVERRIDE = readUrlServerLoginOverride();
const DEFAULT_SOLANA_SERVER = SOLANA_ENDPOINT_DEFAULT; const DEFAULT_SOLANA_SERVER = rpcEndpointFromShineHttp(DEFAULT_SHINE_SERVER_HTTP);
const URL_SOLANA_SERVER_OVERRIDE = readUrlSolanaServerOverride(); const URL_SOLANA_SERVER_OVERRIDE = ''; // RPC always follows SHiNE server
const DEFAULT_SHINE_SERVER = DEFAULT_SHINE_SERVER_WS; const DEFAULT_SHINE_SERVER = DEFAULT_SHINE_SERVER_WS;
const DEFAULT_SHINE_SERVER_LOGIN_VALUE = DEFAULT_SHINE_SERVER_LOGIN; const DEFAULT_SHINE_SERVER_LOGIN_VALUE = DEFAULT_SHINE_SERVER_LOGIN;
const DEFAULT_SHINE_SERVER_HTTP_VALUE = DEFAULT_SHINE_SERVER_HTTP; const DEFAULT_SHINE_SERVER_HTTP_VALUE = DEFAULT_SHINE_SERVER_HTTP;
@@ -425,7 +411,6 @@ function createInitialState({ withStoredSession = true } = {}) {
const storedReactions = loadStoredReactions(); const storedReactions = loadStoredReactions();
const storedEntrySettings = loadStoredEntrySettings(); const storedEntrySettings = loadStoredEntrySettings();
const initialSolanaServer = URL_SOLANA_SERVER_OVERRIDE const initialSolanaServer = URL_SOLANA_SERVER_OVERRIDE
|| storedEntrySettings?.solanaServer
|| DEFAULT_SOLANA_SERVER; || DEFAULT_SOLANA_SERVER;
const initialShineServer = URL_SHINE_SERVER_LOGIN_OVERRIDE || URL_SOLANA_SERVER_OVERRIDE const initialShineServer = URL_SHINE_SERVER_LOGIN_OVERRIDE || URL_SOLANA_SERVER_OVERRIDE
? LOCAL_WS_OVERRIDE_URL ? LOCAL_WS_OVERRIDE_URL
@@ -457,7 +442,7 @@ function createInitialState({ withStoredSession = true } = {}) {
startHint: '', startHint: '',
entrySettings: { entrySettings: {
language: String(storedEntrySettings?.language || 'ru'), language: String(storedEntrySettings?.language || 'ru'),
solanaServer: normalizeStoredSolanaServer(initialSolanaServer), solanaServer: rpcEndpointFromShineHttp(URL_SHINE_SERVER_HTTP_OVERRIDE || storedEntrySettings?.shineServerHttp || DEFAULT_SHINE_SERVER_HTTP),
shineServer: String(LOCAL_WS_OVERRIDE_URL || storedEntrySettings?.shineServer || initialShineServer), shineServer: String(LOCAL_WS_OVERRIDE_URL || storedEntrySettings?.shineServer || initialShineServer),
shineServerLogin: String(initialShineServerLogin), shineServerLogin: String(initialShineServerLogin),
shineServerHttp: String(URL_SHINE_SERVER_HTTP_OVERRIDE || storedEntrySettings?.shineServerHttp || DEFAULT_SHINE_SERVER_HTTP_VALUE), shineServerHttp: String(URL_SHINE_SERVER_HTTP_OVERRIDE || storedEntrySettings?.shineServerHttp || DEFAULT_SHINE_SERVER_HTTP_VALUE),
@@ -1063,7 +1048,7 @@ export function saveEntryLanguage(language) {
} }
export async function saveEntrySettings(nextSettings) { export async function saveEntrySettings(nextSettings) {
const nextSolanaServer = normalizeStoredSolanaServer(nextSettings?.solanaServer || state.entrySettings.solanaServer || DEFAULT_SOLANA_SERVER); const nextSolanaServer = state.entrySettings.solanaServer;
const nextShineServerLogin = String(nextSettings?.shineServerLogin || state.entrySettings.shineServerLogin || DEFAULT_SHINE_SERVER_LOGIN_VALUE).trim().toLowerCase() const nextShineServerLogin = String(nextSettings?.shineServerLogin || state.entrySettings.shineServerLogin || DEFAULT_SHINE_SERVER_LOGIN_VALUE).trim().toLowerCase()
|| DEFAULT_SHINE_SERVER_LOGIN_VALUE; || DEFAULT_SHINE_SERVER_LOGIN_VALUE;
let forcedShineServer = LOCAL_WS_OVERRIDE_URL || ''; let forcedShineServer = LOCAL_WS_OVERRIDE_URL || '';
@@ -1081,7 +1066,7 @@ export async function saveEntrySettings(nextSettings) {
state.entrySettings = { state.entrySettings = {
...state.entrySettings, ...state.entrySettings,
...nextSettings, ...nextSettings,
solanaServer: nextSolanaServer, solanaServer: rpcEndpointFromShineHttp(resolvedShineServerHttp),
shineServer: forcedShineServer, shineServer: forcedShineServer,
shineServerLogin: nextShineServerLogin, shineServerLogin: nextShineServerLogin,
shineServerHttp: resolvedShineServerHttp, shineServerHttp: resolvedShineServerHttp,
@@ -1094,6 +1079,12 @@ export async function saveEntrySettings(nextSettings) {
persistEntrySettings(state.entrySettings); persistEntrySettings(state.entrySettings);
authService.setRemoteAddBlockSessionId(state.entrySettings.remoteAddBlockSessionId); authService.setRemoteAddBlockSessionId(state.entrySettings.remoteAddBlockSessionId);
await authService.reconnect(state.entrySettings.shineServer); await authService.reconnect(state.entrySettings.shineServer);
try {
const info = await authService.ws.request('GetServerInfo', {}, 9000);
setSolanaCluster(info?.payload?.solanaCluster ?? info?.solanaCluster);
} catch (error) {
console.warn('Unable to refresh Solana network from the selected server', error);
}
state.startHint = `Настройки входа сохранены. SHiNE: ${state.entrySettings.shineServerHttp}`; state.startHint = `Настройки входа сохранены. SHiNE: ${state.entrySettings.shineServerHttp}`;
} }
@@ -1101,7 +1092,7 @@ export async function applyUrlServerLoginOverrideIfNeeded() {
if (!URL_SHINE_SERVER_LOGIN_OVERRIDE && !URL_SOLANA_SERVER_OVERRIDE && !LOCAL_WS_OVERRIDE_URL && !URL_SHINE_SERVER_HTTP_OVERRIDE) return false; if (!URL_SHINE_SERVER_LOGIN_OVERRIDE && !URL_SOLANA_SERVER_OVERRIDE && !LOCAL_WS_OVERRIDE_URL && !URL_SHINE_SERVER_HTTP_OVERRIDE) return false;
await saveEntrySettings({ await saveEntrySettings({
...state.entrySettings, ...state.entrySettings,
solanaServer: URL_SOLANA_SERVER_OVERRIDE || state.entrySettings.solanaServer, solanaServer: state.entrySettings.solanaServer,
shineServer: LOCAL_WS_OVERRIDE_URL || state.entrySettings.shineServer, shineServer: LOCAL_WS_OVERRIDE_URL || state.entrySettings.shineServer,
shineServerLogin: URL_SHINE_SERVER_LOGIN_OVERRIDE || state.entrySettings.shineServerLogin, shineServerLogin: URL_SHINE_SERVER_LOGIN_OVERRIDE || state.entrySettings.shineServerLogin,
shineServerHttp: URL_SHINE_SERVER_HTTP_OVERRIDE || state.entrySettings.shineServerHttp, shineServerHttp: URL_SHINE_SERVER_HTTP_OVERRIDE || state.entrySettings.shineServerHttp,