SHA256
Регистрация V2: не проверено end-to-end
This commit is contained in:
+97
-2
@@ -2,6 +2,7 @@ package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.BchBlockEntry;
|
||||
import server.archive.registration.VerifiedFreeRegistrationImporter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
@@ -50,6 +51,7 @@ public final class ArweaveBlockSyncService {
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build();
|
||||
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter();
|
||||
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||
@@ -68,6 +70,7 @@ public final class ArweaveBlockSyncService {
|
||||
public void runCycle() throws Exception {
|
||||
recoverInterruptedCanonicalRebuilds();
|
||||
discover();
|
||||
discoverFreeRegistrations();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
@@ -116,6 +119,12 @@ public final class ArweaveBlockSyncService {
|
||||
|
||||
try {
|
||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
continue; // Не парсить регистрацию как BchBlockEntry.
|
||||
}
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
@@ -172,6 +181,18 @@ public final class ArweaveBlockSyncService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
try {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
} catch (Exception e) {
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
||||
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
||||
queued++;
|
||||
@@ -474,10 +495,84 @@ public final class ArweaveBlockSyncService {
|
||||
}finally{BlockchainResyncGuard.end(activeName);}
|
||||
}
|
||||
|
||||
|
||||
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
|
||||
private void discoverFreeRegistrations() throws Exception {
|
||||
long stored;
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
stored = rs.next() ? rs.getLong(1) : 0;
|
||||
}
|
||||
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
|
||||
long high = minHeight;
|
||||
long retryFrom = Long.MAX_VALUE;
|
||||
String cursor = null;
|
||||
int count = 0;
|
||||
do {
|
||||
JsonNode response = graphQlPage(minHeight, cursor, true);
|
||||
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
|
||||
JsonNode txs = response.path("data").path("transactions");
|
||||
JsonNode edges = txs.path("edges");
|
||||
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
|
||||
String next = null;
|
||||
for (JsonNode edge : edges) {
|
||||
next = edge.path("cursor").asText(null);
|
||||
JsonNode node = edge.path("node");
|
||||
String id = node.path("id").asText("").trim();
|
||||
long height = node.path("block").path("height").asLong(-1);
|
||||
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
|
||||
high = Math.max(high, height);
|
||||
try {
|
||||
byte[] idBytes = B64URL.decode(id);
|
||||
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
|
||||
DownloadedDataItem item = downloadSignedDataItem(id);
|
||||
if (!isRegistrationItem(item.rawDataItem()))
|
||||
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
|
||||
registrationImporter.importSigned(item.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
count++;
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
retryFrom = Math.min(retryFrom, height);
|
||||
log.debug("Registration DataItem {} is not downloadable yet", id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
retryFrom = Math.min(retryFrom, height);
|
||||
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
|
||||
}
|
||||
}
|
||||
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
|
||||
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
|
||||
throw new IOException("Registration GraphQL cursor missing");
|
||||
} while (cursor != null);
|
||||
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE free_registration_arweave_sync_state
|
||||
SET last_block_height=?, updated_at_ms=? WHERE id=1
|
||||
""")) {
|
||||
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
|
||||
}
|
||||
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
|
||||
}
|
||||
|
||||
private static boolean isRegistrationItem(byte[] raw) {
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
|
||||
}
|
||||
|
||||
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
||||
return graphQlPage(minHeight, cursor, false);
|
||||
}
|
||||
|
||||
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
|
||||
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
||||
String query = "query { transactions(tags:[{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}], block:{min:" + minHeight + "}, first:"
|
||||
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
|
||||
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
|
||||
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
|
||||
+ cfg.syncPageSize() + ", after:" + after
|
||||
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
||||
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import server.archive.ArweaveBlocksConfig;
|
||||
import server.archive.TurboDataItemUploader;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationApiBridge;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.PrintWriter;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLFeatureNotSupportedException;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/** Единственная точка подключения API без циклической зависимости Gradle-модулей. */
|
||||
public final class FreeRegistrationApiBootstrap {
|
||||
private static volatile FreeRegistrationWorkflow workflow;
|
||||
private static volatile LocalRegistrarSigner signer;
|
||||
private FreeRegistrationApiBootstrap() {}
|
||||
|
||||
public static synchronized void startOrThrow() throws Exception {
|
||||
if (workflow != null) return;
|
||||
AppConfig cfg=AppConfig.getInstance();
|
||||
LocalRegistrarSigner newSigner=null;
|
||||
FreeRegistrationIssuer issuer=null;
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner);
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),new VerifiedFreeRegistrationImporter());
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher);
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
}
|
||||
public static synchronized void close() {
|
||||
RegistrationApiBridge.uninstall();
|
||||
workflow=null;
|
||||
if(signer!=null) signer.close();
|
||||
signer=null;
|
||||
}
|
||||
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
|
||||
Map<String,Object> out=new LinkedHashMap<>();
|
||||
switch(op) {
|
||||
case "GetNamespaces" -> {
|
||||
out.put("namespaces",w.listNamespaces().stream().map(ns->Map.of(
|
||||
"name",ns.namespace(), "type",ns.type(), "minLocalLength",ns.minLoginLength(),
|
||||
"registrationFeeLamports",ns.priceLamports(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
|
||||
)).toList());
|
||||
}
|
||||
case "CheckRegistrationLogin" -> {
|
||||
var info=w.checkLogin(req.getFullLogin());
|
||||
out.put("loginAvailable",info.loginAvailable());
|
||||
out.put("namespaceType",info.namespaceType());
|
||||
out.put("minLocalLength",info.minLocalLength());
|
||||
out.put("registrationFeeLamports",info.registrationFeeLamports());
|
||||
}
|
||||
case "CheckRegistrationEmail" -> out.put("emailAvailable",w.checkEmail(req.getEmail()).emailAvailable());
|
||||
case "StartFreeRegistration" -> {
|
||||
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
|
||||
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
|
||||
out.put("challengeId",state.challengeId()); out.put("expiresAtMs",state.expiresAtMs());
|
||||
}
|
||||
case "ConfirmFreeRegistration" -> {
|
||||
var value=w.confirm(req.getChallengeId(),req.getCode());
|
||||
out.put("fullLogin",value.fullLogin());out.put("dataItemId",value.dataItemId());
|
||||
out.put("publicationStatus",value.state());out.put("chainConfirmed",false);
|
||||
}
|
||||
case "GetRegistrationStatus" -> {
|
||||
var value=w.getStatus(req.getFullLogin());
|
||||
out.put("registrationStatus",value.status());
|
||||
out.put("dataItemId",value.dataItemId()==null?"":value.dataItemId());
|
||||
out.put("publicationStatus",value.publicationStatus()==null?"":value.publicationStatus());
|
||||
// Публичная историческая часть сертификата для бесплатного → Solana upgrade.
|
||||
if("FREE_CERT".equals(value.status())) {
|
||||
out.put("innerSignature64B64",value.innerSignature64B64()==null?"":value.innerSignature64B64());
|
||||
out.put("rootPublicKey",value.rootPublicKey()==null?"":value.rootPublicKey());
|
||||
out.put("blockchainPublicKey",value.blockchainPublicKey()==null?"":value.blockchainPublicKey());
|
||||
out.put("clientPublicKey",value.clientPublicKey()==null?"":value.clientPublicKey());
|
||||
out.put("defaultServerLogin",value.defaultServerLogin()==null?"":value.defaultServerLogin());
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown registration operation");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
private static byte[] decodeKey(String base64) {
|
||||
if(base64==null || base64.length()>64)throw new IllegalArgumentException("Invalid public key");
|
||||
byte[] decoded=Base64.getDecoder().decode(base64);
|
||||
if(decoded.length!=32)throw new IllegalArgumentException("Invalid public key length");
|
||||
return decoded;
|
||||
}
|
||||
private static DataSource dbSource() {
|
||||
return new DataSource() {
|
||||
@Override public Connection getConnection() throws SQLException {return DbController.getInstance().getConnection();}
|
||||
@Override public Connection getConnection(String u,String p) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||
@Override public PrintWriter getLogWriter(){return null;}
|
||||
@Override public void setLogWriter(PrintWriter p){}
|
||||
@Override public void setLoginTimeout(int t){}
|
||||
@Override public int getLoginTimeout(){return 0;}
|
||||
@Override public Logger getParentLogger(){return Logger.getGlobal();}
|
||||
@Override public <T> T unwrap(Class<T> type) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||
@Override public boolean isWrapperFor(Class<?> type){return false;}
|
||||
};
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.text.Normalizer;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
|
||||
public final class FreeRegistrationCertificateV1 {
|
||||
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
|
||||
private static final List<Ans104DataItem.Tag> TAGS = List.of(
|
||||
new Ans104DataItem.Tag("App", "test5591"),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
|
||||
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||
byte[] clientKey, byte[] innerSignature,
|
||||
byte[] emailSha256, byte[] owner32, String idBase64Url) {}
|
||||
|
||||
private FreeRegistrationCertificateV1() {}
|
||||
|
||||
public static String validateLogin(String login) {
|
||||
if (login == null || !login.matches("[a-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
|
||||
throw new IllegalArgumentException("Full login must be lowercase ASCII, <= 30 bytes");
|
||||
return login;
|
||||
}
|
||||
|
||||
public static byte[] identityFields(String login, byte[] root32, byte[] blockchain32, byte[] client32) {
|
||||
byte[] name = validateLogin(login).getBytes(StandardCharsets.UTF_8);
|
||||
require32(root32); require32(blockchain32); require32(client32);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(1); out.write(0); out.write(name.length); out.writeBytes(name);
|
||||
out.writeBytes(root32); out.writeBytes(blockchain32); out.writeBytes(client32);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] innerMessage(byte[] identity) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.writeBytes(DOMAIN); out.writeBytes(identity);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static String normalizeEmail(String email) {
|
||||
if (email == null) throw new IllegalArgumentException("Email is required");
|
||||
String value = Normalizer.normalize(email.strip(), Normalizer.Form.NFC).toLowerCase(Locale.ROOT);
|
||||
if (value.isBlank() || value.indexOf('@') < 1 || value.contains(" "))
|
||||
throw new IllegalArgumentException("Invalid email");
|
||||
return value;
|
||||
}
|
||||
|
||||
public static byte[] emailHash(String email) {
|
||||
return sha256(normalizeEmail(email).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email, RegistrarSigner signer) {
|
||||
byte[] fields = identityFields(login, root32, blockchain32, client32);
|
||||
byte[] inner = signer.sign(innerMessage(fields));
|
||||
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
payload.writeBytes(fields);
|
||||
payload.writeBytes(inner);
|
||||
payload.writeBytes(emailHash(email));
|
||||
byte[] data = payload.toByteArray();
|
||||
byte[] owner = signer.publicKey32();
|
||||
require32(owner);
|
||||
byte[] outer = signer.sign(Ans104DataItem.buildSigningMessage(owner, TAGS, data));
|
||||
byte[] raw = Ans104DataItem.serializeEd25519(outer, owner, TAGS, data);
|
||||
verify(raw, owner);
|
||||
return raw;
|
||||
}
|
||||
|
||||
public static Verified verify(byte[] signedDataItem, byte[] registrarPublicKey32) {
|
||||
require32(registrarPublicKey32);
|
||||
Ans104DataItem item = new Ans104DataItem(signedDataItem);
|
||||
if (!item.ownerEquals(registrarPublicKey32) || !item.verifySignature())
|
||||
throw new IllegalArgumentException("Invalid outer ANS-104 registrar signature");
|
||||
if (!item.tags().equals(TAGS) || item.target().length != 0 || item.anchor().length != 0)
|
||||
throw new IllegalArgumentException("Unexpected registration tags/target/anchor");
|
||||
byte[] data = item.data();
|
||||
if (data.length < 3 + 96 + 64 + 32 || data[0] != 1 || data[1] != 0)
|
||||
throw new IllegalArgumentException("Invalid certificate version/length");
|
||||
int len = data[2] & 0xff;
|
||||
if (data.length != 3 + len + 96 + 64 + 32)
|
||||
throw new IllegalArgumentException("Invalid certificate byte length");
|
||||
String login = validateLogin(new String(data, 3, len, StandardCharsets.UTF_8));
|
||||
int offset = 3 + len;
|
||||
byte[] root = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] blockchain = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] client = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] innerSig = Arrays.copyOfRange(data, offset, offset+64); offset += 64;
|
||||
byte[] emailSha = Arrays.copyOfRange(data, offset, offset+32);
|
||||
byte[] fields = Arrays.copyOfRange(data, 0, 3 + len + 96);
|
||||
if (!Ed25519Util.verify(innerMessage(fields), innerSig, registrarPublicKey32))
|
||||
throw new IllegalArgumentException("Invalid inner certificate signature");
|
||||
return new Verified(login, root, blockchain, client, innerSig, emailSha,
|
||||
item.owner32(), Base64.getUrlEncoder().withoutPadding().encodeToString(item.id32()));
|
||||
}
|
||||
|
||||
private static void require32(byte[] key) {
|
||||
if (key == null || key.length != 32) throw new IllegalArgumentException("Expected 32-byte public key");
|
||||
}
|
||||
private static byte[] sha256(byte[] data) {
|
||||
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import sync.util.Base58Util;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||
public final class FreeRegistrationIssuer {
|
||||
private final DataSource db;
|
||||
private final RegistrarSigner signer;
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||
this.db = java.util.Objects.requireNonNull(db);
|
||||
this.signer = java.util.Objects.requireNonNull(signer);
|
||||
}
|
||||
|
||||
/** Код 1111 учебный: не подтверждает владение email. */
|
||||
public synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email, String code) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(fullLogin);
|
||||
if (!"1111".equals(code)) throw new IllegalArgumentException("Invalid demo email code");
|
||||
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
|
||||
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
|
||||
try (Connection conn = db.getConnection()) {
|
||||
conn.setReadOnly(true);
|
||||
String sql = """
|
||||
SELECT namespace_type, min_localpart_len, registrar_pubkey, default_server_login
|
||||
FROM shine_namespace_current WHERE namespace = ?
|
||||
""";
|
||||
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||
statement.setString(1, namespace);
|
||||
try (ResultSet rs = statement.executeQuery()) {
|
||||
if (!rs.next() || rs.getInt("namespace_type") != 2 ||
|
||||
fullLogin.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||
throw new IllegalArgumentException("Free namespace is unavailable");
|
||||
byte[] nsPub = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (!Arrays.equals(nsPub, signer.publicKey32()))
|
||||
throw new IllegalStateException("Registrar public key does not match on-chain namespace");
|
||||
String server = rs.getString("default_server_login");
|
||||
if (server == null || server.isBlank())
|
||||
throw new IllegalStateException("Free namespace server is not configured");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
|
||||
ps.setString(1, fullLogin);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||
ps.setBytes(1, expectedEmail);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||
}
|
||||
}
|
||||
}
|
||||
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import server.archive.TurboDataItemUploader;
|
||||
import blockchain.Ans104DataItem;
|
||||
|
||||
/** Отдельный транспорт регистрации. Публикация не является пользовательским AddBlock. */
|
||||
public final class FreeRegistrationPublisher {
|
||||
private final FreeRegistrationIssuer issuer;
|
||||
private final TurboDataItemUploader uploader;
|
||||
private final VerifiedFreeRegistrationImporter importer;
|
||||
|
||||
public FreeRegistrationPublisher(FreeRegistrationIssuer issuer, TurboDataItemUploader uploader,
|
||||
VerifiedFreeRegistrationImporter importer) {
|
||||
this.issuer = java.util.Objects.requireNonNull(issuer);
|
||||
this.uploader = java.util.Objects.requireNonNull(uploader);
|
||||
this.importer = java.util.Objects.requireNonNull(importer);
|
||||
}
|
||||
/** Для повтора ПОСЛЕ потери ACK передавайте точно те же signedBytes. */
|
||||
public VerifiedFreeRegistrationImporter.ImportResult publishSigned(byte[] signedBytes) throws Exception {
|
||||
Ans104DataItem parsed = new Ans104DataItem(signedBytes);
|
||||
importer.validateForUpload(signedBytes); // строго до HTTP/Turbo списания кредитов
|
||||
// Импорт на этой точке вызовет полную проверку обеих подписей и namespace
|
||||
// ПОСЛЕ успешного ACK Turbo, а не до окончательного подтверждения Arweave.
|
||||
TurboDataItemUploader.UploadResult acknowledged = uploader.upload(signedBytes, parsed.id32());
|
||||
String expectedId = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(parsed.id32());
|
||||
if (!expectedId.equals(acknowledged.dataItemId()))
|
||||
throw new IllegalStateException("Unexpected Turbo DataItem id");
|
||||
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||
}
|
||||
public VerifiedFreeRegistrationImporter.ImportResult register(String fullLogin, byte[] root, byte[] blockchain,
|
||||
byte[] client, String email, String demoCode) throws Exception {
|
||||
byte[] signed = issuer.issue(fullLogin, root, blockchain, client, email, demoCode);
|
||||
return publishSigned(signed);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import shine.db.DbController;
|
||||
import java.security.SecureRandom;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Внутренний state machine публичных операций регистрации v2. */
|
||||
public final class FreeRegistrationWorkflow {
|
||||
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, String serverLogin) {}
|
||||
public record Availability(boolean nameFree, boolean emailHashFree) {}
|
||||
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports) {}
|
||||
public record EmailCheck(boolean emailAvailable) {}
|
||||
public record Started(String challengeId, long expiresAtMs) {}
|
||||
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
|
||||
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
|
||||
String rootPublicKey, String blockchainPublicKey, String clientPublicKey,
|
||||
String defaultServerLogin) {}
|
||||
|
||||
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
|
||||
long expiresAtMs, byte[] signedBytes) {}
|
||||
private final Map<String, Draft> pending = new ConcurrentHashMap<>();
|
||||
private static final long TTL_MS = Duration.ofMinutes(15).toMillis();
|
||||
private static final int MAX_PENDING = 512;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private final FreeRegistrationIssuer issuer;
|
||||
private final FreeRegistrationPublisher publisher;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
|
||||
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||
this.issuer = issuer;
|
||||
this.publisher = publisher;
|
||||
}
|
||||
public List<NamespaceInfo> listNamespaces() throws Exception {
|
||||
List<NamespaceInfo> result = new ArrayList<>();
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,default_server_login
|
||||
FROM shine_namespace_current ORDER BY namespace
|
||||
"""); ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
|
||||
rs.getString(4),rs.getString(5)));
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
public LoginCheck checkLogin(String login) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(login);
|
||||
String namespace=login.substring(login.indexOf('@')+1);
|
||||
try (Connection c=DbController.getInstance().getConnection()) {
|
||||
int type, minimum; String fee;
|
||||
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports FROM shine_namespace_current WHERE namespace=?")) {
|
||||
p.setString(1,namespace);
|
||||
try (ResultSet rs=p.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
|
||||
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3);
|
||||
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
|
||||
p.setString(1, login);
|
||||
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee); }
|
||||
}
|
||||
}
|
||||
}
|
||||
public EmailCheck checkEmail(String email) throws Exception {
|
||||
byte[] hash=FreeRegistrationCertificateV1.emailHash(email);
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
p.setBytes(1,hash);
|
||||
try(ResultSet rs=p.executeQuery()) { return new EmailCheck(!rs.next()); }
|
||||
}
|
||||
}
|
||||
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
|
||||
public Availability availability(String login,String email) throws Exception {
|
||||
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
|
||||
}
|
||||
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
|
||||
if (issuer == null || publisher == null) throw new IllegalStateException("Free registration is disabled");
|
||||
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
|
||||
LoginCheck checked = checkLogin(login);
|
||||
if (checked.namespaceType()!=2 || !checked.loginAvailable()) throw new IllegalStateException("Login is unavailable");
|
||||
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
|
||||
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < System.currentTimeMillis());
|
||||
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||
byte[] id=new byte[32]; RANDOM.nextBytes(id);
|
||||
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
|
||||
long expires=System.currentTimeMillis()+TTL_MS;
|
||||
pending.put(challenge,new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,expires,null));
|
||||
return new Started(challenge,expires);
|
||||
}
|
||||
public synchronized Completed confirm(String challenge, String demoCode) throws Exception {
|
||||
if (publisher == null) throw new IllegalStateException("Free registration disabled");
|
||||
Draft d=pending.get(challenge);
|
||||
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
|
||||
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
|
||||
}
|
||||
if (!"1111".equals(demoCode)) throw new IllegalArgumentException("Invalid demo code");
|
||||
// При ошибке Turbo сохраняем единожды подписанные bytes и повторно отправляем ТОТ ЖЕ DataItem.
|
||||
byte[] signed=d.signedBytes;
|
||||
if(signed==null) {
|
||||
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email,demoCode);
|
||||
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||
}
|
||||
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
|
||||
// Сохраняем draft до TTL, чтобы потерянный WS-ответ не вынуждал выпускать другой сертификат.
|
||||
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
|
||||
}
|
||||
public State getStatus(String login) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(login);
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("""
|
||||
SELECT i.registration_status,i.free_data_item_id,f.publication_status,f.inner_signature,
|
||||
i.root_key,i.blockchain_key,i.client_key,n.default_server_login
|
||||
FROM user_identity_current i
|
||||
LEFT JOIN free_registration_certificate f ON f.data_item_id=i.free_data_item_id
|
||||
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||
WHERE i.normalized_login=?
|
||||
""")) {
|
||||
p.setString(1,login);
|
||||
try (ResultSet r=p.executeQuery()) {
|
||||
return r.next()?new State(r.getString(1),r.getString(2),r.getString(3),
|
||||
r.getBytes(4)==null?null:Base64.getEncoder().encodeToString(r.getBytes(4)),
|
||||
r.getString(5),r.getString(6),r.getString(7),r.getString(8))
|
||||
:new State("NOT_FOUND",null,null,null,null,null,null,null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import utils.crypto.Ed25519Util;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/** Временный signer. Файл вне Git: одно значение Base64 от 32-байтного Ed25519 seed. */
|
||||
public final class LocalRegistrarSigner implements RegistrarSigner {
|
||||
private final byte[] seed32;
|
||||
private final byte[] publicKey32;
|
||||
private boolean closed;
|
||||
|
||||
public LocalRegistrarSigner(byte[] seed) {
|
||||
if (seed == null || seed.length != 32) throw new IllegalArgumentException("Registrar seed must be 32 bytes");
|
||||
this.seed32 = seed.clone();
|
||||
this.publicKey32 = Ed25519Util.derivePublicKey(seed32);
|
||||
}
|
||||
|
||||
public static LocalRegistrarSigner fromConfig(AppConfig config) throws Exception {
|
||||
if (!config.getBoolean("freeRegistration.enabled", false))
|
||||
throw new IllegalStateException("Free registration is disabled");
|
||||
String path = config.getStringOrEmpty("freeRegistration.registrarSeedFile");
|
||||
if (path.isEmpty()) throw new IllegalStateException("Registrar key path is not configured");
|
||||
byte[] seed = Base64.getDecoder().decode(Files.readString(Path.of(path), StandardCharsets.UTF_8).trim());
|
||||
try { return new LocalRegistrarSigner(seed); }
|
||||
finally { Arrays.fill(seed, (byte) 0); }
|
||||
}
|
||||
|
||||
@Override public synchronized byte[] publicKey32() { return publicKey32.clone(); }
|
||||
@Override public synchronized byte[] sign(byte[] message) {
|
||||
if (closed) throw new IllegalStateException("Signer closed");
|
||||
return Ed25519Util.sign(message, seed32);
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
Arrays.fill(seed32, (byte) 0);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Интерфейс приватного регистратора: private key не передаётся в бизнес-логику. */
|
||||
public interface RegistrarSigner extends AutoCloseable {
|
||||
byte[] publicKey32();
|
||||
byte[] sign(byte[] message);
|
||||
@Override default void close() {}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import shine.db.DbController;
|
||||
import sync.util.Base58Util;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Только верифицированный сертификат. Локальная БД — проекция Arweave/Solana. */
|
||||
public final class VerifiedFreeRegistrationImporter {
|
||||
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
|
||||
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
|
||||
|
||||
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
|
||||
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
|
||||
if (raw == null || raw.length < 200 || raw.length > 16_384)
|
||||
throw new IllegalArgumentException("Invalid registration size");
|
||||
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||
String login = extractCanonicalLogin(item);
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
String namespace = login.substring(login.indexOf('@') + 1);
|
||||
var cert = FreeRegistrationCertificateV1.verify(raw, readRegistrar(c, namespace, login));
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT free_data_item_id FROM user_identity_current WHERE normalized_login=?")) {
|
||||
ps.setString(1, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
ps.setBytes(1, cert.emailSha256());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||
}
|
||||
}
|
||||
return cert;
|
||||
}
|
||||
}
|
||||
|
||||
/** Единая точка импорта: один и тот же raw ANS-104 из Turbo и Arweave. */
|
||||
public ImportResult importSigned(byte[] raw, Provenance provenance) throws Exception {
|
||||
if (raw == null || raw.length > 16_384 || raw.length < 200)
|
||||
throw new IllegalArgumentException("Invalid registration data item size");
|
||||
// Сначала разбираем/проверяем структурный контейнер, затем сверяем owner с on-chain namespace.
|
||||
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||
String login = extractCanonicalLogin(item);
|
||||
String namespace = login.substring(login.indexOf('@') + 1);
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
byte[] registrar = readRegistrar(c, namespace, login);
|
||||
FreeRegistrationCertificateV1.Verified cert = FreeRegistrationCertificateV1.verify(raw, registrar);
|
||||
String id = cert.idBase64Url();
|
||||
String publication = provenance == Provenance.ARWEAVE_CONFIRMED ? "ARWEAVE_CONFIRMED" : "TURBO_ACCEPTED";
|
||||
long now = System.currentTimeMillis();
|
||||
// Защита от коллизий и двойного импорта: имя и email захвачены индексами UNIQUE.
|
||||
try (PreparedStatement check = c.prepareStatement("""
|
||||
SELECT f.raw_signed_data_item, f.publication_status, u.root_key, u.client_key,
|
||||
u.blockchain_key FROM free_registration_certificate f
|
||||
JOIN user_identity_current u ON u.login=f.login
|
||||
WHERE f.data_item_id=? FOR UPDATE OF f
|
||||
""")) {
|
||||
check.setString(1, id);
|
||||
try (ResultSet r = check.executeQuery()) {
|
||||
if (r.next()) {
|
||||
if (!Arrays.equals(raw, r.getBytes(1)))
|
||||
throw new SQLException("DataItem id collision with different raw bytes");
|
||||
if (!r.getString(3).equals(Base58Util.encode(cert.rootKey())) ||
|
||||
!r.getString(4).equals(Base58Util.encode(cert.clientKey())) ||
|
||||
!r.getString(5).equals(Base58Util.encode(cert.blockchainKey())))
|
||||
throw new SQLException("Accepted identity keys conflict with certificate");
|
||||
if (provenance == Provenance.ARWEAVE_CONFIRMED) {
|
||||
try (PreparedStatement up = c.prepareStatement("""
|
||||
UPDATE free_registration_certificate SET publication_status='ARWEAVE_CONFIRMED',last_seen_at_ms=?
|
||||
WHERE data_item_id=?
|
||||
""")) {
|
||||
up.setLong(1, now); up.setString(2, id); up.executeUpdate();
|
||||
}
|
||||
}
|
||||
c.commit();
|
||||
return new ImportResult(login, id, true, provenance);
|
||||
}
|
||||
}
|
||||
}
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
INSERT INTO user_identity_current (
|
||||
login, normalized_login, namespace, registration_source, registration_status,
|
||||
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||
VALUES (?, ?, ?, 'ARWEAVE', 'FREE_CERT', NULL, ?, ?, ?, ?, ?, false, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login); insert.setString(2, login); insert.setString(3, namespace);
|
||||
insert.setString(4, id); insert.setString(5, Base58Util.encode(cert.rootKey()));
|
||||
insert.setString(6, Base58Util.encode(cert.clientKey()));
|
||||
insert.setString(7, Base58Util.encode(cert.blockchainKey()));
|
||||
insert.setString(8, login + "-001"); insert.setLong(9, now); insert.setLong(10, now);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
INSERT INTO free_registration_certificate (
|
||||
data_item_id, login, namespace, email_sha256, inner_signature,
|
||||
raw_signed_data_item, publication_status, registered_at_ms, last_seen_at_ms)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)
|
||||
""")) {
|
||||
insert.setString(1, id); insert.setString(2, login); insert.setString(3, namespace);
|
||||
insert.setBytes(4, cert.emailSha256()); insert.setBytes(5, cert.innerSignature());
|
||||
insert.setBytes(6, raw); insert.setString(7, publication);
|
||||
insert.setLong(8, now); insert.setLong(9, now); insert.executeUpdate();
|
||||
}
|
||||
c.commit();
|
||||
return new ImportResult(login, id, false, provenance);
|
||||
} catch (Exception e) {
|
||||
c.rollback(); throw e;
|
||||
} finally { c.setAutoCommit(oldAutoCommit); }
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractCanonicalLogin(blockchain.Ans104DataItem item) {
|
||||
boolean marker = item.tags().contains(new blockchain.Ans104DataItem.Tag("t", "reg"));
|
||||
if (!marker) throw new IllegalArgumentException("Not a registration DataItem");
|
||||
byte[] bytes = item.data();
|
||||
if (bytes.length < 3 || bytes[0] != 1 || bytes[1] != 0) throw new IllegalArgumentException("Bad certificate header");
|
||||
int len = bytes[2] & 0xff;
|
||||
if (len < 3 || len > 30 || bytes.length < 3 + len + 96 + 64 + 32)
|
||||
throw new IllegalArgumentException("Invalid certificate login length");
|
||||
return FreeRegistrationCertificateV1.validateLogin(
|
||||
new String(bytes, 3, len, java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static byte[] readRegistrar(Connection c, String namespace, String login) throws Exception {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT registrar_pubkey, min_localpart_len, default_server_login
|
||||
FROM shine_namespace_current WHERE namespace=? AND namespace_type=2
|
||||
""")) {
|
||||
ps.setString(1, namespace);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalStateException("Unknown/free namespace not yet synchronized");
|
||||
if (login.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||
throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
if (rs.getString("default_server_login") == null || rs.getString("default_server_login").isBlank())
|
||||
throw new IllegalArgumentException("Namespace has no access server");
|
||||
byte[] key = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (key.length != 32) throw new IllegalArgumentException("Invalid registrar pubkey");
|
||||
return key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package server.archive;
|
||||
|
||||
import server.archive.registration.*;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Запуск: java ... server.archive.FreeRegistrationCertificateV1Check file.hex */
|
||||
public final class FreeRegistrationCertificateV1Check {
|
||||
static final HexFormat HEX = HexFormat.of();
|
||||
public static void main(String[] args) throws Exception {
|
||||
byte[] raw = HEX.parseHex(Files.readString(Path.of(args[0])).trim());
|
||||
byte[] pub = HEX.parseHex("174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd5");
|
||||
var result = FreeRegistrationCertificateV1.verify(raw, pub);
|
||||
if (!"bob@free".equals(result.login()) || !result.idBase64Url().equals(
|
||||
java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(
|
||||
HEX.parseHex("45ef42eda7c7e76d222ecce8a7678edb923ae63f8419ea0899701551c2466770"))))
|
||||
throw new AssertionError("Wrong fixture identity / DataItem id");
|
||||
byte[] corrupted = raw.clone(); corrupted[corrupted.length-1] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(corrupted, pub); throw new AssertionError("Email bit flip accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
corrupted = raw.clone(); corrupted[corrupted.length-40] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(corrupted, pub); throw new AssertionError("Inner signature tampering accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
|
||||
byte[] seed = Ed25519Util.generatePrivateKeyFromString("TEST-only-reg-v1-check");
|
||||
try (var signer = new LocalRegistrarSigner(seed)) {
|
||||
byte[] cert = FreeRegistrationCertificateV1.issue("bob@free",
|
||||
HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8"),
|
||||
HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7"),
|
||||
HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d"),
|
||||
" Alice.Example+Tag@Example.COM ", signer);
|
||||
var verified = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||
if (!Arrays.equals(verified.emailSha256(),
|
||||
HEX.parseHex("cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
|
||||
throw new AssertionError("Email normalization differs");
|
||||
}
|
||||
System.out.println("PASS: Java registrar fixture, inner+outer Ed25519, email normalization, tamper rejection");
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package server.archive;
|
||||
|
||||
import server.archive.registration.*;
|
||||
import javax.sql.DataSource;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Только проверки без БД/сети; полное E2E требует PostgreSQL и Turbo. */
|
||||
public final class FreeRegistrationWorkflowLocalCheck {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var signer = new RegistrarSigner() {
|
||||
public byte[] publicKey32() { return new byte[32]; }
|
||||
public byte[] sign(byte[] message) { return new byte[64]; }
|
||||
};
|
||||
DataSource noDb = new DataSource() {
|
||||
public java.sql.Connection getConnection() throws java.sql.SQLException { throw new java.sql.SQLException("No database in local test"); }
|
||||
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException { return getConnection(); }
|
||||
public java.io.PrintWriter getLogWriter() {return null;}
|
||||
public void setLogWriter(java.io.PrintWriter x) {}
|
||||
public void setLoginTimeout(int x) {}
|
||||
public int getLoginTimeout() {return 0;}
|
||||
public java.util.logging.Logger getParentLogger() {return java.util.logging.Logger.getAnonymousLogger();}
|
||||
public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {throw new java.sql.SQLException("unsupported");}
|
||||
public boolean isWrapperFor(Class<?> iface) {return false;}
|
||||
};
|
||||
var issuer = new FreeRegistrationIssuer(noDb, signer);
|
||||
var importer = new VerifiedFreeRegistrationImporter();
|
||||
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(), importer));
|
||||
byte[] k1 = new byte[32], k2 = new byte[32], k3 = new byte[32];
|
||||
k1[0] = 1; k2[0] = 2; k3[0] = 3;
|
||||
var start = workflow.start("bob@free", k1, k2, k3, "hello@example.org");
|
||||
if (start.challengeId().isBlank() || start.expiresAtMs() <= System.currentTimeMillis())
|
||||
throw new AssertionError("Cannot start a bounded challenge");
|
||||
try { workflow.confirm(start.challengeId(), "wrong"); throw new AssertionError("Bad demo code accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
try { workflow.confirm("unknown", "1111"); throw new AssertionError("Missing challenge accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
try { workflow.start("BOB@free", k1, k2, k3, "hello@example.org"); throw new AssertionError("Invalid login accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||
throw new AssertionError("Invalid bytes accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
System.out.println("PASS: workflow nonce/code checks + reject invalid signed bytes");
|
||||
}
|
||||
}
|
||||
@@ -23,9 +23,13 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_1 = 1;
|
||||
public static final int SCHEMA_VERSION_31 = 31;
|
||||
public static final int SCHEMA_VERSION_32 = 32;
|
||||
public static final int SCHEMA_VERSION_33 = 33;
|
||||
public static final int SCHEMA_VERSION_34 = 34;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
public static final String POSTGRES_MIGRATION_V33_RESOURCE = "postgres/migration_v33.sql";
|
||||
public static final String POSTGRES_MIGRATION_V34_RESOURCE = "postgres/migration_v34.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -125,9 +129,17 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_32) {
|
||||
if (currentVersion == SCHEMA_VERSION_32) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V33_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion == SCHEMA_VERSION_33) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V34_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_34) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 32, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 34, found " + currentVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -213,7 +213,7 @@ public final class CurrentUsersDAO {
|
||||
String sql = """
|
||||
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
||||
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
|
||||
FROM solana_user_pda_current su
|
||||
FROM user_identity_current su
|
||||
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
|
||||
WHERE (? IS NULL OR su.is_server = ?)
|
||||
AND (
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DbController;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
|
||||
/** Единая авторитетная проекция: FREE_CERT не притворяется Solana PDA. */
|
||||
public final class RegistrationIdentityDAO {
|
||||
public record ResolvedIdentity(String fullLogin, String rootKey, String blockchainKey,
|
||||
String clientKey, String registrationSource, String registrationStatus,
|
||||
String namespace, String accessServerLogin, boolean hasSolanaPda) {
|
||||
public boolean isFree() { return "FREE_CERT".equals(registrationStatus); }
|
||||
}
|
||||
private static final RegistrationIdentityDAO INSTANCE = new RegistrationIdentityDAO();
|
||||
public static RegistrationIdentityDAO getInstance() { return INSTANCE; }
|
||||
private RegistrationIdentityDAO() {}
|
||||
|
||||
public ResolvedIdentity get(String login) throws SQLException {
|
||||
try (Connection c = DbController.getInstance().getConnection()) { return get(c, login); }
|
||||
}
|
||||
public ResolvedIdentity get(Connection c, String login) throws SQLException {
|
||||
if (login == null || login.isBlank()) return null;
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT i.login, i.root_key, i.blockchain_key, i.client_key,
|
||||
i.registration_source, i.registration_status, i.namespace,
|
||||
i.solana_pda_address, n.default_server_login,
|
||||
s.server_login AS actual_access_server
|
||||
FROM user_identity_current i
|
||||
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||
LEFT JOIN user_access_servers_current s ON s.user_login=i.login
|
||||
WHERE i.normalized_login=LOWER(BTRIM(?))
|
||||
ORDER BY s.server_login ASC
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
boolean hasPda = rs.getString("solana_pda_address") != null;
|
||||
String status = rs.getString("registration_status");
|
||||
String server = "FREE_CERT".equals(status) ? rs.getString("default_server_login")
|
||||
: rs.getString("actual_access_server");
|
||||
if ("FREE_CERT".equals(status) && hasPda)
|
||||
throw new SQLException("Inconsistent free user: Solana PDA must be absent");
|
||||
if (!"FREE_CERT".equals(status) && !hasPda)
|
||||
throw new SQLException("Inconsistent paid user: Solana PDA is missing");
|
||||
return new ResolvedIdentity(rs.getString("login"), rs.getString("root_key"),
|
||||
rs.getString("blockchain_key"), rs.getString("client_key"),
|
||||
rs.getString("registration_source"), status, rs.getString("namespace"), server, hasPda);
|
||||
}
|
||||
}
|
||||
}
|
||||
public boolean isFreeCertificate(String login) throws SQLException {
|
||||
ResolvedIdentity identity = get(login);
|
||||
return identity != null && identity.isFree();
|
||||
}
|
||||
}
|
||||
+13
-11
@@ -46,26 +46,28 @@ public final class UserAccessServersCurrentDAO {
|
||||
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
u.login AS user_login,
|
||||
i.login AS user_login,
|
||||
s.login AS server_login,
|
||||
s.server_address AS server_url,
|
||||
s.client_key AS server_client_key
|
||||
FROM solana_user_pda_current u
|
||||
FROM user_identity_current i
|
||||
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT BTRIM(a.login_value) AS server_login
|
||||
FROM jsonb_array_elements_text(
|
||||
CASE
|
||||
WHEN BTRIM(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb
|
||||
ELSE u.access_servers_json::jsonb
|
||||
END
|
||||
) WITH ORDINALITY AS a(login_value, ord)
|
||||
WHERE a.ord = 1
|
||||
SELECT CASE WHEN i.registration_status = 'FREE_CERT'
|
||||
THEN ns.default_server_login
|
||||
ELSE (SELECT BTRIM(a.login_value)
|
||||
FROM jsonb_array_elements_text(
|
||||
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||
WITH ORDINALITY AS a(login_value, ord)
|
||||
WHERE a.ord = 1)
|
||||
END AS server_login
|
||||
) primary_access
|
||||
JOIN solana_user_pda_current s
|
||||
ON s.normalized_login = LOWER(primary_access.server_login)
|
||||
AND s.is_server = TRUE
|
||||
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
||||
WHERE u.normalized_login = LOWER(BTRIM(?))
|
||||
WHERE i.normalized_login = LOWER(BTRIM(?))
|
||||
LIMIT 1
|
||||
""";
|
||||
try (Connection c = db.getConnection();
|
||||
|
||||
@@ -18,7 +18,7 @@ public final class CurrentUsersSql {
|
||||
current_users.blockchain_key AS blockchain_key,
|
||||
current_users.client_key AS client_key,
|
||||
current_users.is_server AS is_server
|
||||
FROM solana_user_pda_current current_users
|
||||
FROM user_identity_current current_users
|
||||
) %s
|
||||
""".formatted(alias);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
-- SHiNE DB v33: общий индекс идентичностей, namespace и сертификаты.
|
||||
-- ТОЛЬКО dev/test до проверки всей серверной авторизации.
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE user_identity_current (
|
||||
login TEXT PRIMARY KEY,
|
||||
normalized_login TEXT NOT NULL UNIQUE,
|
||||
namespace TEXT,
|
||||
registration_source TEXT NOT NULL CHECK (registration_source IN ('SOLANA', 'ARWEAVE')),
|
||||
registration_status TEXT NOT NULL CHECK (registration_status IN ('PAID_DIRECT', 'FREE_CERT', 'PAID_UPGRADED')),
|
||||
solana_pda_address TEXT UNIQUE,
|
||||
free_data_item_id TEXT UNIQUE,
|
||||
root_key TEXT NOT NULL,
|
||||
client_key TEXT NOT NULL,
|
||||
blockchain_key TEXT NOT NULL,
|
||||
blockchain_name TEXT NOT NULL,
|
||||
is_server BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
registered_at_ms BIGINT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL,
|
||||
CHECK ((registration_status = 'FREE_CERT' AND solana_pda_address IS NULL AND free_data_item_id IS NOT NULL)
|
||||
OR (registration_status <> 'FREE_CERT' AND solana_pda_address IS NOT NULL))
|
||||
);
|
||||
CREATE INDEX idx_user_identity_namespace ON user_identity_current(namespace);
|
||||
|
||||
INSERT INTO user_identity_current (
|
||||
login, normalized_login, namespace, registration_source, registration_status,
|
||||
solana_pda_address, root_key, client_key, blockchain_key, blockchain_name,
|
||||
is_server, registered_at_ms, updated_at_ms
|
||||
)
|
||||
SELECT login, normalized_login,
|
||||
CASE WHEN position('@' in login) > 0 THEN split_part(login, '@', 2) ELSE NULL END,
|
||||
'SOLANA', 'PAID_DIRECT', pda_address, root_key, client_key, blockchain_key,
|
||||
blockchain_name, is_server, created_at_ms, updated_at_ms
|
||||
FROM solana_user_pda_current
|
||||
ON CONFLICT (login) DO NOTHING;
|
||||
|
||||
CREATE TABLE shine_namespace_current (
|
||||
namespace TEXT PRIMARY KEY,
|
||||
pda_address TEXT NOT NULL UNIQUE,
|
||||
namespace_type SMALLINT NOT NULL CHECK(namespace_type IN (1,2)),
|
||||
min_localpart_len SMALLINT NOT NULL CHECK (min_localpart_len BETWEEN 1 AND 30),
|
||||
registration_fee_lamports NUMERIC(20,0) NOT NULL CHECK (registration_fee_lamports >= 0),
|
||||
registrar_pubkey TEXT,
|
||||
default_server_login TEXT,
|
||||
slot BIGINT NOT NULL,
|
||||
last_tx_signature TEXT NOT NULL DEFAULT '',
|
||||
raw_data_base64 TEXT NOT NULL,
|
||||
CHECK ((namespace_type = 1 AND registrar_pubkey IS NULL AND default_server_login IS NULL)
|
||||
OR (namespace_type = 2 AND registrar_pubkey IS NOT NULL AND default_server_login IS NOT NULL))
|
||||
);
|
||||
|
||||
CREATE TABLE free_registration_certificate (
|
||||
data_item_id TEXT PRIMARY KEY,
|
||||
login TEXT NOT NULL UNIQUE REFERENCES user_identity_current(login),
|
||||
namespace TEXT NOT NULL REFERENCES shine_namespace_current(namespace),
|
||||
email_sha256 BYTEA NOT NULL UNIQUE CHECK (octet_length(email_sha256) = 32),
|
||||
inner_signature BYTEA NOT NULL CHECK (octet_length(inner_signature) = 64),
|
||||
raw_signed_data_item BYTEA NOT NULL,
|
||||
publication_status TEXT NOT NULL CHECK (publication_status IN ('TURBO_ACCEPTED','ARWEAVE_SEEN','ARWEAVE_CONFIRMED')),
|
||||
registered_at_ms BIGINT NOT NULL,
|
||||
last_seen_at_ms BIGINT NOT NULL
|
||||
);
|
||||
CREATE INDEX idx_free_registration_namespace ON free_registration_certificate(namespace);
|
||||
|
||||
-- Существующие объекты (в том числе десятки FK) должны ссылаться на логическую
|
||||
-- идентичность, иначе бесплатный пользователь не сможет иметь профиль/связи/каналы.
|
||||
-- Воссоздаём существующие FK с теми же ON DELETE/UPDATE и deferrable-настройками.
|
||||
DO $$
|
||||
DECLARE
|
||||
item RECORD;
|
||||
definition TEXT;
|
||||
BEGIN
|
||||
FOR item IN SELECT c.conname, c.conrelid::regclass AS child_table,
|
||||
pg_get_constraintdef(c.oid) AS definition
|
||||
FROM pg_constraint c
|
||||
WHERE c.contype = 'f' AND c.confrelid = 'solana_user_pda_current'::regclass
|
||||
LOOP
|
||||
definition := replace(item.definition,
|
||||
'REFERENCES solana_user_pda_current(', 'REFERENCES user_identity_current(');
|
||||
IF definition = item.definition THEN
|
||||
RAISE EXCEPTION 'Unexpected FK expression: %', item.definition;
|
||||
END IF;
|
||||
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', item.child_table, item.conname);
|
||||
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I %s', item.child_table, item.conname, definition);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- Любое поступившее из Solana состояние дополняет существующую идентичность.
|
||||
-- Бесплатный → платный допускается ТОЛЬКО при совпадении всех публичных ключей;
|
||||
-- старые on-chain key rotations разрешены, если статус уже платный.
|
||||
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
DECLARE old_user user_identity_current%ROWTYPE;
|
||||
BEGIN
|
||||
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
|
||||
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
|
||||
IF TG_OP = 'INSERT' AND EXISTS (
|
||||
SELECT 1 FROM solana_user_pda_current prior
|
||||
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||
) THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
SELECT * INTO old_user FROM user_identity_current
|
||||
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||
END IF;
|
||||
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||
END IF;
|
||||
INSERT INTO user_identity_current (
|
||||
login, normalized_login, namespace, registration_source, registration_status,
|
||||
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||
VALUES (NEW.login, NEW.normalized_login,
|
||||
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||
'SOLANA', CASE WHEN old_user.free_data_item_id IS NOT NULL THEN 'PAID_UPGRADED' ELSE 'PAID_DIRECT' END,
|
||||
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||
ON CONFLICT (login) DO UPDATE SET
|
||||
registration_source='SOLANA',
|
||||
registration_status=EXCLUDED.registration_status,
|
||||
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER trg_sync_identity_from_solana
|
||||
BEFORE INSERT OR UPDATE ON solana_user_pda_current
|
||||
FOR EACH ROW EXECUTE FUNCTION shine_sync_identity_from_solana();
|
||||
|
||||
-- Free namespace: сервер доступа задаётся namespace, а не клиентским полем.
|
||||
-- Реальный сервер должен иметь on-chain PDA и открытый адрес.
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
||||
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF p_user_login IS NULL OR btrim(p_user_login) = '' THEN RETURN; END IF;
|
||||
DELETE FROM user_access_servers_current WHERE lower(user_login) = lower(p_user_login);
|
||||
INSERT INTO user_access_servers_current (
|
||||
user_login, server_login, server_url, server_client_key, user_record_number,
|
||||
user_updated_at_ms, server_record_number, server_updated_at_ms, refreshed_at_ms)
|
||||
SELECT i.login, srv.login, srv.server_address, srv.client_key,
|
||||
COALESCE(u.record_number, 0), i.updated_at_ms,
|
||||
srv.record_number, srv.updated_at_ms,
|
||||
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
FROM user_identity_current i
|
||||
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||
CROSS JOIN LATERAL (
|
||||
SELECT CASE WHEN i.registration_status = 'FREE_CERT' THEN ns.default_server_login
|
||||
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||
WITH ORDINALITY AS a(value, position) WHERE position=1) END AS login
|
||||
) effective
|
||||
JOIN solana_user_pda_current srv
|
||||
ON lower(srv.login) = lower(effective.login) AND srv.is_server = true
|
||||
AND btrim(coalesce(srv.server_address, '')) <> ''
|
||||
WHERE lower(i.login) = lower(p_user_login)
|
||||
ON CONFLICT (user_login, server_login) DO UPDATE SET
|
||||
server_url=EXCLUDED.server_url, server_client_key=EXCLUDED.server_client_key,
|
||||
user_record_number=EXCLUDED.user_record_number,
|
||||
user_updated_at_ms=EXCLUDED.user_updated_at_ms,
|
||||
server_record_number=EXCLUDED.server_record_number,
|
||||
server_updated_at_ms=EXCLUDED.server_updated_at_ms,
|
||||
refreshed_at_ms=EXCLUDED.refreshed_at_ms;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_server(p_server_login TEXT)
|
||||
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
DECLARE u RECORD;
|
||||
BEGIN
|
||||
IF p_server_login IS NULL OR btrim(p_server_login) = '' THEN RETURN; END IF;
|
||||
DELETE FROM user_access_servers_current WHERE lower(server_login) = lower(p_server_login);
|
||||
FOR u IN
|
||||
SELECT i.login FROM user_identity_current i
|
||||
LEFT JOIN solana_user_pda_current p ON p.login=i.login
|
||||
LEFT JOIN shine_namespace_current ns ON ns.namespace=i.namespace
|
||||
WHERE lower(p_server_login) = lower(
|
||||
CASE WHEN i.registration_status='FREE_CERT' THEN ns.default_server_login
|
||||
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||
COALESCE(NULLIF(p.access_servers_json,''),'[]')::jsonb)
|
||||
WITH ORDINALITY AS a(value, position) WHERE position=1) END)
|
||||
LOOP PERFORM shine_refresh_user_access_servers_for_user(u.login); END LOOP;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_all()
|
||||
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
DECLARE u RECORD;
|
||||
BEGIN
|
||||
TRUNCATE TABLE user_access_servers_current;
|
||||
FOR u IN SELECT login FROM user_identity_current LOOP
|
||||
PERFORM shine_refresh_user_access_servers_for_user(u.login);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_free_routing_from_identity()
|
||||
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.registration_status = 'FREE_CERT' THEN
|
||||
PERFORM shine_refresh_user_access_servers_for_user(NEW.login);
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER trg_refresh_free_routing_from_identity
|
||||
AFTER INSERT OR UPDATE ON user_identity_current
|
||||
FOR EACH ROW EXECUTE FUNCTION shine_refresh_free_routing_from_identity();
|
||||
|
||||
UPDATE db_schema_version SET schema_version=33,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id=1;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- SHiNE v34. Отдельный checkpoint Arweave сертификатов, не смешивать с блоками.
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS free_registration_arweave_sync_state (
|
||||
id SMALLINT PRIMARY KEY CHECK (id=1),
|
||||
last_block_height BIGINT NOT NULL DEFAULT 0 CHECK (last_block_height>=0),
|
||||
updated_at_ms BIGINT NOT NULL DEFAULT 0
|
||||
);
|
||||
INSERT INTO free_registration_arweave_sync_state (id,last_block_height,updated_at_ms)
|
||||
VALUES (1,0,0) ON CONFLICT (id) DO NOTHING;
|
||||
UPDATE db_schema_version SET schema_version=34,
|
||||
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||
COMMIT;
|
||||
+18
@@ -169,6 +169,8 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchain
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
|
||||
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -186,6 +188,14 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
||||
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
|
||||
|
||||
// --- Registration V2: 6 согласованных публичных операций ---
|
||||
Map.entry("GetNamespaces", new Net_Registration_Handler("GetNamespaces")),
|
||||
Map.entry("CheckRegistrationLogin", new Net_Registration_Handler("CheckRegistrationLogin")),
|
||||
Map.entry("CheckRegistrationEmail", new Net_Registration_Handler("CheckRegistrationEmail")),
|
||||
Map.entry("StartFreeRegistration", new Net_Registration_Handler("StartFreeRegistration")),
|
||||
Map.entry("ConfirmFreeRegistration", new Net_Registration_Handler("ConfirmFreeRegistration")),
|
||||
Map.entry("GetRegistrationStatus", new Net_Registration_Handler("GetRegistrationStatus")),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
||||
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
|
||||
@@ -291,6 +301,14 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
||||
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
|
||||
|
||||
// --- Registration V2 ---
|
||||
Map.entry("GetNamespaces", Net_Registration_Request.class),
|
||||
Map.entry("CheckRegistrationLogin", Net_Registration_Request.class),
|
||||
Map.entry("CheckRegistrationEmail", Net_Registration_Request.class),
|
||||
Map.entry("StartFreeRegistration", Net_Registration_Request.class),
|
||||
Map.entry("ConfirmFreeRegistration", Net_Registration_Request.class),
|
||||
Map.entry("GetRegistrationStatus", Net_Registration_Request.class),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
||||
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
|
||||
|
||||
+12
-4
@@ -76,9 +76,12 @@ public final class JsonInboundProcessor {
|
||||
return out;
|
||||
}
|
||||
|
||||
// DEBUG: сырой вход (обрезаем, чтобы не убить лог)
|
||||
// Не писать email, challenge и ключи в лог даже на DEBUG.
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId, shorten(json, 1200));
|
||||
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId,
|
||||
json.contains("FreeRegistration") || json.contains("RegistrationEmail")
|
||||
|| json.contains("RegistrationLogin") || json.contains("GetNamespaces")
|
||||
|| json.contains("GetRegistrationStatus") ? "<registration payload redacted>" : shorten(json, 1200));
|
||||
}
|
||||
|
||||
// 1) Парсим общий пакет
|
||||
@@ -178,7 +181,7 @@ public final class JsonInboundProcessor {
|
||||
} catch (Exception mapErr) {
|
||||
// Важно: вот это часто “теряется”, если не логировать отдельно
|
||||
log.error("❌ JSON map error (op={}, requestId={}, login={}, sessionId={}): merged={}",
|
||||
op, safe(requestId), ctxLogin, ctxSessionId, shorten(merged.toString(), 1200), mapErr);
|
||||
op, safe(requestId), ctxLogin, ctxSessionId, "<redacted>", mapErr);
|
||||
|
||||
Net_Exception_Response err = NetExceptionResponseFactory.error(
|
||||
op,
|
||||
@@ -202,7 +205,7 @@ public final class JsonInboundProcessor {
|
||||
// DEBUG: нормализованный запрос (уже распарсен)
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("REQ OBJ (login={}, sessionId={}, op={}, requestId={}): {}",
|
||||
ctxLogin, ctxSessionId, safe(op), safe(requestId), shorten(safeToString(request), 1200));
|
||||
ctxLogin, ctxSessionId, safe(op), safe(requestId), isRegistrationOperation(op) ? "<registration payload redacted>" : shorten(safeToString(request), 1200));
|
||||
}
|
||||
|
||||
// REMOTE-пользователь успешно авторизован, но этот сервер не является
|
||||
@@ -372,6 +375,11 @@ public final class JsonInboundProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRegistrationOperation(String op) {
|
||||
return op != null && (op.endsWith("Registration") || op.startsWith("CheckRegistration")
|
||||
|| op.equals("GetNamespaces") || op.equals("GetRegistrationStatus"));
|
||||
}
|
||||
|
||||
private static String safe(String s) {
|
||||
return s != null ? s : "";
|
||||
}
|
||||
|
||||
+5
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import utils.config.SolanaProgramsConfig;
|
||||
import shine.db.dao.RegistrationIdentityDAO;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
@@ -34,6 +35,10 @@ public final class SolanaUserPdaImportService {
|
||||
public static SessionTypeCheckResult checkSessionTypeAgainstPda(String loginRaw, String sessionKeyApi, int requestedSessionType) throws Exception {
|
||||
String login = normalizeLogin(loginRaw);
|
||||
if (login == null) return SessionTypeCheckResult.noRecord();
|
||||
// У FREE_CERT нет Solana PDA. Это НЕ означает отсутствие идентичности:
|
||||
// AuthChallenge и подпись clientKey уже проверяются через общий индекс.
|
||||
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity != null && identity.isFree()) return SessionTypeCheckResult.noRecord();
|
||||
|
||||
ParsedSolanaUser parsed = fetchFromSolana(login);
|
||||
if (parsed == null) return SessionTypeCheckResult.noRecord();
|
||||
|
||||
+17
@@ -11,6 +11,23 @@ import java.util.Base64;
|
||||
final class KeyRotationApiSupport {
|
||||
private KeyRotationApiSupport() {}
|
||||
|
||||
/** Free identity не имеет Solana PDA и не вправе менять ключи/форки. */
|
||||
static server.logic.ws_protocol.JSON.entyties.Net_Response denyFreeRotation(
|
||||
server.logic.ws_protocol.JSON.entyties.Net_Request req, String login) {
|
||||
try {
|
||||
var identity = shine.db.dao.RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity == null) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 404, "KEY_ROTATION_USER_NOT_FOUND", "Пользователь не найден");
|
||||
if (identity.isFree()) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 403, "KEY_ROTATION_PAID_ONLY", "Для смены ключей необходима регистрация в Solana");
|
||||
return null;
|
||||
} catch (java.sql.SQLException e) {
|
||||
// fail closed при неготовой миграции / ошибке БД
|
||||
return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 503, "KEY_ROTATION_IDENTITY_UNAVAILABLE", "Невозможно проверить полномочия пользователя");
|
||||
}
|
||||
}
|
||||
|
||||
static String normalizePublicKey32(String raw) {
|
||||
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
|
||||
if (normalized == null || normalized.isBlank()) {
|
||||
|
||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationAbort_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
|
||||
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
|
||||
|
||||
+2
@@ -44,6 +44,8 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
|
||||
}
|
||||
|
||||
+2
@@ -22,6 +22,8 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
String login = ctx.getLogin().trim();
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||
|
||||
+2
@@ -47,6 +47,8 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
|
||||
KeyRotationSessionEntry initial;
|
||||
|
||||
+2
@@ -24,6 +24,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
|
||||
final String signature;
|
||||
|
||||
+2
@@ -39,6 +39,8 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
|
||||
if (currentSessionId.isEmpty()) {
|
||||
|
||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
String login = ctx.getLogin().trim();
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
|
||||
/** API доступно анонимному клиенту, но без разрешения приватных операций. */
|
||||
public final class Net_Registration_Handler implements JsonMessageHandler {
|
||||
private final String operation;
|
||||
private static final java.util.Map<ConnectionContext, long[]> LIMITS =
|
||||
java.util.Collections.synchronizedMap(new java.util.WeakHashMap<>());
|
||||
private static long globalMinute=-1;
|
||||
private static int globalHits=0;
|
||||
private static boolean throttled(ConnectionContext ctx) {
|
||||
long minute=System.currentTimeMillis()/60000L;
|
||||
synchronized (LIMITS) {
|
||||
if(globalMinute!=minute){globalMinute=minute;globalHits=0;}
|
||||
if(++globalHits>1200) return true;
|
||||
if(ctx==null) return false;
|
||||
long[] bucket=LIMITS.computeIfAbsent(ctx, c->new long[]{minute,0});
|
||||
if(bucket[0]!=minute){bucket[0]=minute;bucket[1]=0;}
|
||||
return ++bucket[1]>30;
|
||||
}
|
||||
}
|
||||
public Net_Registration_Handler(String operation) { this.operation=operation; }
|
||||
@Override public Net_Response handle(Net_Request base, ConnectionContext ctx) throws Exception {
|
||||
Net_Registration_Request request=(Net_Registration_Request)base;
|
||||
if (throttled(ctx)) return NetExceptionResponseFactory.error(request,429,"RATE_LIMITED","Слишком много запросов регистрации");
|
||||
RegistrationApiBridge.Service service=RegistrationApiBridge.get();
|
||||
if (service==null) return NetExceptionResponseFactory.error(request,503,"REGISTRATION_UNAVAILABLE","Регистрация на сервере пока не настроена");
|
||||
try {
|
||||
java.util.Map<String,Object> values=service.execute(operation,request);
|
||||
Net_Registration_Response out=new Net_Registration_Response();
|
||||
out.setOp(request.getOp()); out.setRequestId(request.getRequestId());
|
||||
out.setStatus(WireCodes.Status.OK); out.setValues(values);
|
||||
return out;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Без echo исходного email, чтобы не публиковать PII в ответе/логе.
|
||||
return NetExceptionResponseFactory.error(request,400,"INVALID_REGISTRATION_INPUT","Данные регистрации не прошли проверку");
|
||||
} catch (IllegalStateException e) {
|
||||
return NetExceptionResponseFactory.error(request,409,"REGISTRATION_CONFLICT","Регистрация недоступна или данные уже заняты");
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** JSON payload; публичные данные пользователя, пароли/приватные ключи не принимаются. */
|
||||
public final class Net_Registration_Request extends Net_Request {
|
||||
private String fullLogin;
|
||||
private String email;
|
||||
private String rootPublicKeyB64;
|
||||
private String blockchainPublicKeyB64;
|
||||
private String clientPublicKeyB64;
|
||||
private String challengeId;
|
||||
private String code;
|
||||
public String getFullLogin() { return fullLogin; }
|
||||
public void setFullLogin(String v) { fullLogin = v; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String v) { email = v; }
|
||||
public String getRootPublicKeyB64() { return rootPublicKeyB64; }
|
||||
public void setRootPublicKeyB64(String v) { rootPublicKeyB64 = v; }
|
||||
public String getBlockchainPublicKeyB64() { return blockchainPublicKeyB64; }
|
||||
public void setBlockchainPublicKeyB64(String v) { blockchainPublicKeyB64 = v; }
|
||||
public String getClientPublicKeyB64() { return clientPublicKeyB64; }
|
||||
public void setClientPublicKeyB64(String v) { clientPublicKeyB64 = v; }
|
||||
public String getChallengeId() { return challengeId; }
|
||||
public void setChallengeId(String v) { challengeId = v; }
|
||||
public String getCode() { return code; }
|
||||
public void setCode(String v) { code = v; }
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||
|
||||
/** Значения результата помещаются на верхний уровень объекта перед стандартной WS-обёрткой. */
|
||||
public final class Net_Registration_Response extends Net_Response {
|
||||
private Map<String, Object> values = Map.of();
|
||||
public void setValues(Map<String,Object> values) { this.values = Map.copyOf(values); }
|
||||
@JsonAnyGetter public Map<String,Object> getValues() { return values; }
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** SPI: HTTP/WS модуль не зависит от archive-модуля, устраняя циклический Gradle dependency. */
|
||||
public final class RegistrationApiBridge {
|
||||
@FunctionalInterface public interface Service {
|
||||
Map<String, Object> execute(String operation, Net_Registration_Request request) throws Exception;
|
||||
}
|
||||
private static volatile Service service;
|
||||
private RegistrationApiBridge() {}
|
||||
public static void install(Service implementation) { service = java.util.Objects.requireNonNull(implementation); }
|
||||
public static void uninstall() { service = null; }
|
||||
public static Service get() { return service; }
|
||||
}
|
||||
+58
@@ -2,6 +2,7 @@ package sync.codec;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import sync.util.Base58Util;
|
||||
import sync.util.SolanaPdaUtil;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
@@ -29,6 +30,8 @@ public final class ShineUsersCodec {
|
||||
public static final int IX_CLOSE_LEGACY_USER_PDA =
|
||||
6;
|
||||
|
||||
public static final int IX_CREATE_NAMESPACE = 7;
|
||||
|
||||
public static final long START_REGISTRATION_FEE_LAMPORTS =
|
||||
10_000_000L;
|
||||
|
||||
@@ -151,6 +154,16 @@ public final class ShineUsersCodec {
|
||||
null
|
||||
);
|
||||
|
||||
case IX_CREATE_NAMESPACE ->
|
||||
new ParsedInstruction(
|
||||
TxKind.CREATE_NAMESPACE,
|
||||
true,
|
||||
accountAt(accounts, 1),
|
||||
null,
|
||||
null,
|
||||
null
|
||||
);
|
||||
|
||||
case IX_CREATE_USER_PDA ->
|
||||
parseV12PdaMutationInstruction(
|
||||
TxKind.CREATE_USER_PDA, reader, accounts
|
||||
@@ -731,10 +744,55 @@ public final class ShineUsersCodec {
|
||||
}
|
||||
}
|
||||
|
||||
/** Строгий декодер бинарного namespace 1.0 с on-chain PDA address check. */
|
||||
public static NamespaceSnapshot parseNamespaceAccount(
|
||||
String pdaAddress, long slot, String rawDataBase64,
|
||||
String lastTxSignature, String programId
|
||||
) {
|
||||
byte[] bytes = Base64.getDecoder().decode(rawDataBase64);
|
||||
if (bytes.length < 13 || bytes[0] != 1 || bytes[1] != 0) {
|
||||
throw new IllegalArgumentException("Not a namespace PDA 1.0");
|
||||
}
|
||||
Reader r = new Reader(bytes);
|
||||
r.readU8(); r.readU8();
|
||||
int type = r.readU8();
|
||||
if (type != 1 && type != 2) throw new IllegalArgumentException("Invalid namespace type");
|
||||
int minLen = r.readU8();
|
||||
String namespace = r.readStringU8();
|
||||
if (!namespace.matches("[a-z0-9_]+") || minLen < 1 || namespace.length() + minLen + 1 > 30) {
|
||||
throw new IllegalArgumentException("Invalid namespace");
|
||||
}
|
||||
byte[] feeLittleEndian = r.readFixed(8);
|
||||
byte[] feeBigEndian = new byte[9];
|
||||
for (int n = 0; n < 8; n++) feeBigEndian[8 - n] = feeLittleEndian[n];
|
||||
java.math.BigInteger fee = new java.math.BigInteger(feeBigEndian);
|
||||
String registrarKey = null, serverLogin = null;
|
||||
if (type == 2) {
|
||||
registrarKey = Base58Util.encode(r.readFixed(32));
|
||||
serverLogin = r.readStringU8();
|
||||
if (!serverLogin.matches("[a-z0-9_]+@[a-z0-9_]+") || serverLogin.length() > 30) {
|
||||
throw new IllegalArgumentException("Invalid access server login");
|
||||
}
|
||||
}
|
||||
if (r.remaining() != 0 || !pdaAddress.equals(SolanaPdaUtil.findNamespacePda(namespace, programId))) {
|
||||
throw new IllegalArgumentException("Invalid namespace bytes or PDA address");
|
||||
}
|
||||
return new NamespaceSnapshot(namespace, pdaAddress, type, minLen,
|
||||
fee, registrarKey, serverLogin, slot, lastTxSignature, rawDataBase64);
|
||||
}
|
||||
|
||||
public record NamespaceSnapshot(
|
||||
String namespace, String pdaAddress, int type, int minLocalpartLength,
|
||||
java.math.BigInteger registrationFeeLamports, String registrarPublicKey,
|
||||
String defaultServerLogin, long slot, String lastTxSignature,
|
||||
String rawDataBase64
|
||||
) {}
|
||||
|
||||
public enum TxKind {
|
||||
INIT_USERS_ECONOMY_CONFIG,
|
||||
UPDATE_USERS_ECONOMY_CONFIG,
|
||||
CREATE_USER_PDA,
|
||||
CREATE_NAMESPACE,
|
||||
UPDATE_USER_PDA,
|
||||
CLOSE_LEGACY_USER_PDA,
|
||||
OTHER
|
||||
|
||||
+26
-17
@@ -386,6 +386,7 @@ public final class SolanaUsersSyncService
|
||||
);
|
||||
|
||||
storage.applyHistoryBatch(
|
||||
List.of(),
|
||||
List.of(),
|
||||
List.of(),
|
||||
newState
|
||||
@@ -452,6 +453,7 @@ public final class SolanaUsersSyncService
|
||||
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshotsToPersist =
|
||||
new ArrayList<>();
|
||||
List<ShineUsersCodec.NamespaceSnapshot> namespacesToPersist = new ArrayList<>();
|
||||
|
||||
ShineUsersCodec.EconomyConfigState economyState =
|
||||
state.economyConfigState();
|
||||
@@ -528,15 +530,19 @@ public final class SolanaUsersSyncService
|
||||
SolanaRpcClient.AccountBatchResult exactAccounts =
|
||||
rpcClient.getCurrentAccounts(exactFetchPdaAddresses, newestSeen.slot());
|
||||
for (ProgramAccountUpdate account : exactAccounts.updates()) {
|
||||
ShineUsersCodec.UserPdaSnapshot snapshot =
|
||||
ShineUsersCodec.parseUserPdaAccount(
|
||||
account.address(),
|
||||
account.slot(),
|
||||
account.dataBase64(),
|
||||
latestRelevantSignatureByPda.getOrDefault(account.address(), "")
|
||||
);
|
||||
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
|
||||
snapshotsToPersist.add(snapshot);
|
||||
String lastSignature = latestRelevantSignatureByPda.getOrDefault(account.address(), "");
|
||||
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
|
||||
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
|
||||
var ns = ShineUsersCodec.parseNamespaceAccount(account.address(),
|
||||
account.slot(), account.dataBase64(), lastSignature, config.programId());
|
||||
namespacesToPersist.removeIf(existing -> existing.pdaAddress().equals(ns.pdaAddress()));
|
||||
namespacesToPersist.add(ns);
|
||||
} else {
|
||||
var snapshot = ShineUsersCodec.parseUserPdaAccount(account.address(),
|
||||
account.slot(), account.dataBase64(), lastSignature);
|
||||
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
|
||||
snapshotsToPersist.add(snapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -558,6 +564,7 @@ public final class SolanaUsersSyncService
|
||||
storage.applyHistoryBatch(
|
||||
txEntries,
|
||||
snapshotsToPersist,
|
||||
namespacesToPersist,
|
||||
newState
|
||||
);
|
||||
|
||||
@@ -595,6 +602,7 @@ public final class SolanaUsersSyncService
|
||||
|
||||
List<ShineUsersCodec.UserPdaSnapshot> currentSnapshots =
|
||||
new ArrayList<>();
|
||||
List<ShineUsersCodec.NamespaceSnapshot> currentNamespaces = new ArrayList<>();
|
||||
|
||||
int processedAccounts =
|
||||
0;
|
||||
@@ -604,14 +612,14 @@ public final class SolanaUsersSyncService
|
||||
processedAccounts++;
|
||||
|
||||
try {
|
||||
currentSnapshots.add(
|
||||
ShineUsersCodec.parseUserPdaAccount(
|
||||
account.address(),
|
||||
account.slot(),
|
||||
account.dataBase64(),
|
||||
""
|
||||
)
|
||||
);
|
||||
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
|
||||
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
|
||||
currentNamespaces.add(ShineUsersCodec.parseNamespaceAccount(
|
||||
account.address(), account.slot(), account.dataBase64(), "", config.programId()));
|
||||
} else {
|
||||
currentSnapshots.add(ShineUsersCodec.parseUserPdaAccount(
|
||||
account.address(), account.slot(), account.dataBase64(), ""));
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
|
||||
@@ -654,6 +662,7 @@ public final class SolanaUsersSyncService
|
||||
|
||||
storage.replaceCurrentFromFullSnapshot(
|
||||
currentSnapshots,
|
||||
currentNamespaces,
|
||||
newState
|
||||
);
|
||||
|
||||
|
||||
+49
@@ -248,6 +248,7 @@ public final class PostgresStorageRepository
|
||||
public synchronized void applyHistoryBatch(
|
||||
List<TxHistoryEntry> txEntries,
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
||||
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
|
||||
SyncStateSnapshot newState
|
||||
) throws Exception {
|
||||
|
||||
@@ -268,6 +269,7 @@ public final class PostgresStorageRepository
|
||||
snapshots
|
||||
);
|
||||
|
||||
upsertNamespaceSnapshots(connection, namespaces);
|
||||
upsertCurrentSnapshots(
|
||||
connection,
|
||||
snapshots
|
||||
@@ -297,6 +299,7 @@ public final class PostgresStorageRepository
|
||||
|
||||
public synchronized void replaceCurrentFromFullSnapshot(
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
||||
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
|
||||
SyncStateSnapshot newState
|
||||
) throws Exception {
|
||||
|
||||
@@ -306,6 +309,7 @@ public final class PostgresStorageRepository
|
||||
connection.setAutoCommit(false);
|
||||
|
||||
try {
|
||||
upsertNamespaceSnapshots(connection, namespaces);
|
||||
upsertCurrentSnapshots(
|
||||
connection,
|
||||
snapshots
|
||||
@@ -459,6 +463,39 @@ public final class PostgresStorageRepository
|
||||
}
|
||||
}
|
||||
|
||||
private void upsertNamespaceSnapshots(Connection connection,
|
||||
List<ShineUsersCodec.NamespaceSnapshot> namespaces) throws Exception {
|
||||
if (namespaces == null || namespaces.isEmpty()) return;
|
||||
String sql = """
|
||||
INSERT INTO shine_namespace_current (
|
||||
namespace, pda_address, namespace_type, min_localpart_len,
|
||||
registration_fee_lamports, registrar_pubkey, default_server_login,
|
||||
slot, last_tx_signature, raw_data_base64
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT (namespace) DO UPDATE SET
|
||||
slot=EXCLUDED.slot, last_tx_signature=EXCLUDED.last_tx_signature,
|
||||
raw_data_base64=EXCLUDED.raw_data_base64
|
||||
WHERE shine_namespace_current.pda_address=EXCLUDED.pda_address
|
||||
AND shine_namespace_current.raw_data_base64=EXCLUDED.raw_data_base64
|
||||
""";
|
||||
try (PreparedStatement ps = connection.prepareStatement(sql)) {
|
||||
for (ShineUsersCodec.NamespaceSnapshot ns : namespaces) {
|
||||
ps.setString(1, ns.namespace()); ps.setString(2, ns.pdaAddress());
|
||||
ps.setInt(3, ns.type()); ps.setInt(4, ns.minLocalpartLength());
|
||||
ps.setBigDecimal(5, new java.math.BigDecimal(ns.registrationFeeLamports()));
|
||||
ps.setString(6, ns.registrarPublicKey());
|
||||
ps.setString(7, ns.defaultServerLogin()); ps.setLong(8, ns.slot());
|
||||
ps.setString(9, ns.lastTxSignature()); ps.setString(10, ns.rawDataBase64());
|
||||
ps.addBatch();
|
||||
}
|
||||
ps.executeBatch();
|
||||
}
|
||||
// Namespace появляется после сервера, пересчитываем маршруты free пользователей.
|
||||
try (Statement st = connection.createStatement()) {
|
||||
st.execute("SELECT shine_refresh_user_access_servers_all()");
|
||||
}
|
||||
}
|
||||
|
||||
private void upsertCurrentSnapshots(
|
||||
Connection connection,
|
||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots
|
||||
@@ -1076,6 +1113,16 @@ public final class PostgresStorageRepository
|
||||
"ON user_access_servers_current(server_login)"
|
||||
);
|
||||
|
||||
// После PostgreSQL migration_v33 функции маршрутизации принадлежат
|
||||
// общему реестру логических identity, их нельзя перезаписывать
|
||||
// legacy Solana-only вариантом при старте sync.
|
||||
boolean hasIdentityTable;
|
||||
try (ResultSet check = statement.executeQuery(
|
||||
"SELECT to_regclass('user_identity_current') IS NOT NULL")) {
|
||||
check.next();
|
||||
hasIdentityTable = check.getBoolean(1);
|
||||
}
|
||||
if (!hasIdentityTable) {
|
||||
statement.execute(
|
||||
"""
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
||||
@@ -1260,6 +1307,8 @@ public final class PostgresStorageRepository
|
||||
"EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate()"
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
statement.execute("SELECT shine_refresh_user_access_servers_all()");
|
||||
}
|
||||
}
|
||||
|
||||
+21
@@ -61,6 +61,27 @@ public final class SolanaPdaUtil {
|
||||
);
|
||||
}
|
||||
|
||||
/** Новый v2 PDA. Старый двух-seed вариант оставлен только для legacy accounts. */
|
||||
public static String findUserPdaV2(String fullLogin, String programId) {
|
||||
if (fullLogin == null || !fullLogin.matches("[a-z0-9_]+@[a-z0-9_]+") || fullLogin.length() > 30) {
|
||||
throw new IllegalArgumentException("Invalid full login");
|
||||
}
|
||||
return findHashedPda("user_login=" + fullLogin, programId);
|
||||
}
|
||||
|
||||
public static String findNamespacePda(String namespace, String programId) {
|
||||
if (namespace == null || !namespace.matches("[a-z0-9_]+")) {
|
||||
throw new IllegalArgumentException("Invalid namespace");
|
||||
}
|
||||
return findHashedPda("namespace=" + namespace, programId);
|
||||
}
|
||||
|
||||
private static String findHashedPda(String preimage, String programId) {
|
||||
SHA256.Digest digest = new SHA256.Digest();
|
||||
byte[] seed = digest.digest(preimage.getBytes(StandardCharsets.UTF_8));
|
||||
return findProgramAddress(List.of(seed), programId);
|
||||
}
|
||||
|
||||
private static byte[] createProgramAddress(
|
||||
List<byte[]> seeds,
|
||||
byte[] programId
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package sync.codec;
|
||||
|
||||
import sync.util.SolanaPdaUtil;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
import java.util.Properties;
|
||||
|
||||
/** Отдельная offline-проверка, без RPC/DB; запуск через main(). */
|
||||
public final class NamespaceV2VectorCheck {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Properties p = new Properties();
|
||||
try (var stream = Files.newInputStream(Path.of(args[0]))) { p.load(stream); }
|
||||
String program = p.getProperty("program_id");
|
||||
if (!p.getProperty("namespace_free_pda").equals(SolanaPdaUtil.findNamespacePda("free", program)))
|
||||
throw new AssertionError("Namespace seed/PDA mismatch");
|
||||
if (!p.getProperty("user_bob_free_pda").equals(SolanaPdaUtil.findUserPdaV2("bob@free", program)))
|
||||
throw new AssertionError("User v2 seed/PDA mismatch");
|
||||
byte[] raw = HexFormat.of().parseHex(p.getProperty("namespace_free_bytes_hex"));
|
||||
var ns = ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
|
||||
42, Base64.getEncoder().encodeToString(raw), "test-signature", program);
|
||||
if (!"free".equals(ns.namespace()) || ns.type() != 2 ||
|
||||
ns.registrationFeeLamports().longValueExact() != 5_000_000L ||
|
||||
!"registrar@shine".equals(ns.defaultServerLogin()))
|
||||
throw new AssertionError("Namespace value mismatch");
|
||||
byte[] corrupt = raw.clone(); corrupt[6] ^= 1;
|
||||
try {
|
||||
ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
|
||||
42, Base64.getEncoder().encodeToString(corrupt), "test-signature", program);
|
||||
throw new AssertionError("Wrong PDA accepted");
|
||||
} catch (IllegalArgumentException expected) { }
|
||||
System.out.println("PASS: Java namespace decoder & SHA256 PDA test vectors");
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerI
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.archive.ArweaveBlockPublisherScheduler;
|
||||
import server.archive.registration.FreeRegistrationApiBootstrap;
|
||||
import server.archive.ArweaveBlockSyncScheduler;
|
||||
import server.debug.DebugApiConfigurator;
|
||||
import server.files.DmFileApiConfigurator;
|
||||
@@ -65,6 +66,7 @@ public final class WsServer {
|
||||
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
|
||||
|
||||
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
|
||||
FreeRegistrationApiBootstrap.startOrThrow();
|
||||
ArweaveBlockPublisherScheduler.startOrLog();
|
||||
ArweaveBlockSyncScheduler.startOrLog();
|
||||
KeyRotationRebuildScheduler.startOrLog();
|
||||
@@ -104,7 +106,7 @@ public final class WsServer {
|
||||
log.info("✅ WS сервер запущен на ws://localhost:{}/ws", port);
|
||||
ServerConnectionPool.getInstance().startOrLog();
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(
|
||||
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); },
|
||||
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); FreeRegistrationApiBootstrap.close(); },
|
||||
"server-connection-pool-shutdown"));
|
||||
PeriodicDmDeliveryService.startOrLog();
|
||||
server.join();
|
||||
|
||||
Reference in New Issue
Block a user