Регистрация V2: не проверено end-to-end

This commit is contained in:
AidarKC
2026-10-23 19:21:52 +03:00
parent 6c8159c5f7
commit cab26bbf41
95 changed files with 4469 additions and 1088 deletions
@@ -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));
@@ -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;}
};
}
}
@@ -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); }
}
}
@@ -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);
}
}
@@ -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);
}
}
@@ -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);
}
}
}
}
@@ -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;
}
}
@@ -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() {}
}
@@ -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
@@ -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");
}
}
@@ -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");
}
}