Улучшить UI регистрации и связанные сценарии

This commit is contained in:
AidarKC
2026-11-08 18:04:06 +03:00
parent 9405f28525
commit 4068465ee6
66 changed files with 842 additions and 221 deletions
@@ -74,7 +74,7 @@ public final class FreeRegistrationApiBootstrap {
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()
"registrationFeeLamports",ns.priceLamports(), "currencyCode",ns.currencyCode(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
)).toList());
}
case "CheckRegistrationLogin" -> {
@@ -83,6 +83,7 @@ public final class FreeRegistrationApiBootstrap {
out.put("namespaceType",info.namespaceType());
out.put("minLocalLength",info.minLocalLength());
out.put("registrationFeeLamports",info.registrationFeeLamports());
out.put("currencyCode",info.currencyCode());
}
case "CheckRegistrationEmail" -> {
var check=w.checkEmail(req.getEmail());
@@ -15,9 +15,9 @@ 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 NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, int currencyCode, String serverLogin) {}
public record Availability(boolean nameFree, boolean emailHashFree) {}
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports) {}
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports, int currencyCode) {}
public record EmailCheck(boolean emailAvailable, String emailStatus) {}
public record Started(String challengeId, long expiresAtMs) {}
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
@@ -93,11 +93,11 @@ public final class FreeRegistrationWorkflow {
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
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,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)));
rs.getString(4),rs.getInt(5),rs.getString(6)));
}
return List.copyOf(result);
}
@@ -105,18 +105,19 @@ public final class FreeRegistrationWorkflow {
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=?")) {
int type, minimum, currencyCode; String fee;
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports,currency_code 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);
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
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.toLowerCase(java.util.Locale.ROOT));
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee); }
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee,currencyCode); }
}
}
}
@@ -37,6 +37,8 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
private static final byte[] ZERO32 = new byte[32];
// Минимум для создания нового канала; исторические блоки 1–3 символа читаются.
public static final int MIN_NAME_LENGTH_FOR_CREATE = 4;
private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
@@ -159,6 +161,20 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
return this;
}
/**
* Правило создания нового TECH_CREATE_CHANNEL (в отличие от чтения истории).
* check() намеренно принимает старые каналы с именами из 1–3 символов.
*/
public CreateChannelBody checkForCreate() {
check();
String normalizedName = normalizeDisplayName(channelName);
int length = normalizedName.codePointCount(0, normalizedName.length());
if (length < MIN_NAME_LENGTH_FOR_CREATE) {
throw new IllegalArgumentException("channelName length must be 4..32");
}
return this;
}
private static String normalizeDisplayName(String value) {
if (value == null) return "";
return value.trim().replaceAll("\\s+", " ");
@@ -171,6 +187,9 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
@Override
public byte[] toBytes() {
// Новые блоки кодируются только с именем от 4 символов.
// Исторические блоки при чтении разбираются без повторного кодирования.
checkForCreate();
byte[] nameUtf8 = normalizeDisplayName(channelName).getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("channelName utf8 len must be 1..255");
@@ -0,0 +1,68 @@
package blockchain;
import blockchain.body.CreateChannelBody;
import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.*;
final class CreateChannelBodyNameLengthTest {
private static CreateChannelBody newChannel(String name) {
return new CreateChannelBody(
0, 0, new byte[32], 1, name, "",
CreateChannelBody.CHANNEL_TYPE_PUBLIC,
CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT
);
}
@Test
void newChannelMustContainAtLeastFourCharacters() {
for (String name : new String[]{"a", "ab", "abc"}) {
CreateChannelBody body = newChannel(name);
assertDoesNotThrow(body::check, "Исторический декодер не должен блокировать: " + name);
assertThrows(IllegalArgumentException.class, body::checkForCreate, name);
assertThrows(IllegalArgumentException.class, body::toBytes, name);
}
}
@Test
void fourToThirtyTwoCharactersAreAccepted() {
for (String name : new String[]{"abcd", "tantra", "X".repeat(32)}) {
CreateChannelBody newBody = newChannel(name);
assertDoesNotThrow(newBody::checkForCreate, name);
CreateChannelBody fromHistory = assertInstanceOf(
CreateChannelBody.class,
BodyRecordParser.parse(CreateChannelBody.TYPE, CreateChannelBody.SUBTYPE,
CreateChannelBody.VER, newBody.toBytes())
);
assertEquals(name, fromHistory.channelName);
}
assertThrows(IllegalArgumentException.class, () -> newChannel("x".repeat(33)).toBytes());
}
@Test
void historicalThreeCharacterBlockStillDecodes() {
// Байт-в-байт существующий формат, без использования сериализатора новых блоков.
byte[] name = "abc".getBytes(StandardCharsets.UTF_8);
ByteBuffer raw = ByteBuffer.allocate(4 + 4 + 32 + 4 + 1 + name.length + 2 + 4)
.order(ByteOrder.BIG_ENDIAN);
raw.putInt(0).putInt(0).put(new byte[32]).putInt(1);
raw.put((byte) name.length).put(name);
raw.putShort((short) 0);
raw.putShort(CreateChannelBody.CHANNEL_TYPE_PUBLIC);
raw.putShort(CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT);
CreateChannelBody parsed = assertInstanceOf(
CreateChannelBody.class,
BodyRecordParser.parse(CreateChannelBody.TYPE, CreateChannelBody.SUBTYPE,
CreateChannelBody.VER, raw.array())
);
assertEquals("abc", parsed.channelName);
assertDoesNotThrow(parsed::check);
assertThrows(IllegalArgumentException.class, parsed::checkForCreate);
}
}
@@ -30,6 +30,7 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_37 = 37;
public static final int SCHEMA_VERSION_38 = 38;
public static final int SCHEMA_VERSION_39 = 39;
public static final int SCHEMA_VERSION_40 = 40;
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";
@@ -40,6 +41,7 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V37_RESOURCE = "postgres/migration_v37.sql";
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.sql";
public static final String POSTGRES_MIGRATION_V39_RESOURCE = "postgres/migration_v39.sql";
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
private DatabaseInitializer() {}
@@ -167,9 +169,13 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V39_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_39) {
if (currentVersion == SCHEMA_VERSION_39) {
runSqlScript(conn, POSTGRES_MIGRATION_V40_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_40) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 39, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 40, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
@@ -4,7 +4,7 @@ import java.util.Locale;
import java.util.regex.Pattern;
public final class ChannelNameRules {
private static final int MIN_DISPLAY_NAME_LENGTH = 3;
private static final int MIN_DISPLAY_NAME_LENGTH = 4;
private static final int MAX_DISPLAY_NAME_LENGTH = 32;
private static final Pattern DISPLAY_ALLOWED_PATTERN =
Pattern.compile("^[A-Za-z0-9_-]+$");
@@ -26,7 +26,7 @@ public final class ChannelNameRules {
int length = normalized.codePointCount(0, normalized.length());
if (length < MIN_DISPLAY_NAME_LENGTH || length > MAX_DISPLAY_NAME_LENGTH) {
throw new IllegalArgumentException("channelName length must be 3..32");
throw new IllegalArgumentException("channelName length must be 4..32");
}
if (!DISPLAY_ALLOWED_PATTERN.matcher(normalized).matches()) {
@@ -420,9 +420,20 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
final String normalizedName;
final String slug;
try {
normalizedName = channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_PERSONAL & 0xFFFF)
? ChannelNameRules.requireValidDisplayNameForCreate(createChannelBody.channelName)
: ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName);
String historicalName = ChannelNameRules.normalizeDisplayName(createChannelBody.channelName);
boolean legacyReplayName = replayMode
&& historicalName.codePointCount(0, historicalName.length())
< CreateChannelBody.MIN_NAME_LENGTH_FOR_CREATE;
if (legacyReplayName) {
// Только воспроизведение старых подписанных DataItem: не ломаем ресинк истории.
// Новый AddBlock (replayMode=false) обязательно проверяет минимум 4 символа.
normalizedName = historicalName;
} else {
createChannelBody.checkForCreate();
normalizedName = channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_PERSONAL & 0xFFFF)
? ChannelNameRules.requireValidDisplayNameForCreate(createChannelBody.channelName)
: ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName);
}
slug = ChannelNameRules.toCanonicalSlug(normalizedName);
} catch (IllegalArgumentException badName) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_name", serverLastNum, serverLastHashHex);
@@ -31,6 +31,7 @@ public final class ShineUsersCodec {
6;
public static final int IX_CREATE_NAMESPACE = 7;
public static final int IX_UPDATE_NAMESPACE_PRICE = 8;
public static final long START_REGISTRATION_FEE_LAMPORTS =
10_000_000L;
@@ -154,6 +155,16 @@ public final class ShineUsersCodec {
null
);
case IX_UPDATE_NAMESPACE_PRICE ->
new ParsedInstruction(
TxKind.UPDATE_NAMESPACE_PRICE,
true,
accountAt(accounts, 1),
null,
null,
null
);
case IX_CREATE_NAMESPACE ->
new ParsedInstruction(
TxKind.CREATE_NAMESPACE,
@@ -744,15 +755,16 @@ public final class ShineUsersCodec {
}
}
/** Строгий декодер бинарного namespace 1.0 с on-chain PDA address check. */
/** Строгий декодер бинарных namespace 1.0/1.1 с проверкой on-chain PDA. */
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");
if (bytes.length < 13 || bytes[0] != 1 || (bytes[1] != 0 && bytes[1] != 1)) {
throw new IllegalArgumentException("Not a namespace PDA 1.0/1.1");
}
int minor = bytes[1] & 0xFF;
Reader r = new Reader(bytes);
r.readU8(); r.readU8();
int type = r.readU8();
@@ -766,6 +778,8 @@ public final class ShineUsersCodec {
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);
int currencyCode = minor == 1 ? r.readU8() : 1;
if (currencyCode != 1) throw new IllegalArgumentException("Unsupported namespace currency code: " + currencyCode);
String registrarKey = null, serverLogin = null;
if (type == 2) {
registrarKey = Base58Util.encode(r.readFixed(32));
@@ -778,12 +792,12 @@ public final class ShineUsersCodec {
throw new IllegalArgumentException("Invalid namespace bytes or PDA address");
}
return new NamespaceSnapshot(namespace, pdaAddress, type, minLen,
fee, registrarKey, serverLogin, slot, lastTxSignature, rawDataBase64);
fee, currencyCode, registrarKey, serverLogin, slot, lastTxSignature, rawDataBase64);
}
public record NamespaceSnapshot(
String namespace, String pdaAddress, int type, int minLocalpartLength,
java.math.BigInteger registrationFeeLamports, String registrarPublicKey,
java.math.BigInteger registrationFeeLamports, int currencyCode, String registrarPublicKey,
String defaultServerLogin, long slot, String lastTxSignature,
String rawDataBase64
) {}
@@ -793,6 +807,7 @@ public final class ShineUsersCodec {
UPDATE_USERS_ECONOMY_CONFIG,
CREATE_USER_PDA,
CREATE_NAMESPACE,
UPDATE_NAMESPACE_PRICE,
UPDATE_USER_PDA,
CLOSE_LEGACY_USER_PDA,
OTHER
@@ -532,7 +532,7 @@ public final class SolanaUsersSyncService
for (ProgramAccountUpdate account : exactAccounts.updates()) {
String lastSignature = latestRelevantSignatureByPda.getOrDefault(account.address(), "");
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
if (firstBytes.length > 2 && firstBytes[0] == 1 && (firstBytes[1] == 0 || firstBytes[1] == 1)) {
var ns = ShineUsersCodec.parseNamespaceAccount(account.address(),
account.slot(), account.dataBase64(), lastSignature, config.programId());
namespacesToPersist.removeIf(existing -> existing.pdaAddress().equals(ns.pdaAddress()));
@@ -613,7 +613,7 @@ public final class SolanaUsersSyncService
try {
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
if (firstBytes.length > 2 && firstBytes[0] == 1 && (firstBytes[1] == 0 || firstBytes[1] == 1)) {
currentNamespaces.add(ShineUsersCodec.parseNamespaceAccount(
account.address(), account.slot(), account.dataBase64(), "", config.programId()));
} else {
@@ -469,23 +469,26 @@ public final class PostgresStorageRepository
String sql = """
INSERT INTO shine_namespace_current (
namespace, pda_address, namespace_type, min_localpart_len,
registration_fee_lamports, registrar_pubkey, default_server_login,
registration_fee_lamports, currency_code, registrar_pubkey, default_server_login,
slot, last_tx_signature, raw_data_base64
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (namespace) DO UPDATE SET
registration_fee_lamports=EXCLUDED.registration_fee_lamports,
currency_code=EXCLUDED.currency_code,
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
AND EXCLUDED.slot >= shine_namespace_current.slot
""";
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.setInt(6, ns.currencyCode());
ps.setString(7, ns.registrarPublicKey());
ps.setString(8, ns.defaultServerLogin()); ps.setLong(9, ns.slot());
ps.setString(10, ns.lastTxSignature()); ps.setString(11, ns.rawDataBase64());
ps.addBatch();
}
ps.executeBatch();
@@ -24,6 +24,22 @@ public final class NamespaceV2VectorCheck {
ns.registrationFeeLamports().longValueExact() != 5_000_000L ||
!"registrar@shine".equals(ns.defaultServerLogin()))
throw new AssertionError("Namespace value mismatch");
int currencyOffset = 5 + (raw[4] & 0xFF) + 8;
byte[] version11 = new byte[raw.length+1];
System.arraycopy(raw,0,version11,0,currencyOffset);
version11[1] = 1;
version11[currencyOffset] = 1;
System.arraycopy(raw,currencyOffset,version11,currencyOffset+1,raw.length-currencyOffset);
var upgraded = ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
43, Base64.getEncoder().encodeToString(version11), "update", program);
if (upgraded.currencyCode()!=1 || upgraded.registrationFeeLamports().longValueExact()!=5_000_000L)
throw new AssertionError("Namespace 1.1 decode mismatch");
version11[currencyOffset] = 2;
try {
ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
44, Base64.getEncoder().encodeToString(version11), "update", program);
throw new AssertionError("Reserved currency 2 accepted");
} catch (IllegalArgumentException expected) { }
byte[] corrupt = raw.clone(); corrupt[6] ^= 1;
try {
ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),