SHA256
Исправить регистрацию free-пользователей без учёта регистра
НЕ ПРОВЕРЕНО: учтены логины с большими и маленькими буквами. Добавлен временный devnet-смарт-контракт для очистки тестового аккаунта от старых логинов; после сброса его необходимо удалить и восстановить штатный контракт.
This commit is contained in:
+1
-1
@@ -37,7 +37,7 @@ import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
||||
* or inside a direct server-created ANS-104 bundle.
|
||||
*/
|
||||
|
||||
+4
-3
@@ -1,6 +1,7 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.ShineProtocolTags;
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
@@ -16,7 +17,7 @@ import java.util.Locale;
|
||||
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(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
|
||||
@@ -27,8 +28,8 @@ public final class FreeRegistrationCertificateV1 {
|
||||
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");
|
||||
if (login == null || !login.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
|
||||
throw new IllegalArgumentException("Full login must use ASCII letters (any local-part case), lowercase namespace, <= 30 bytes");
|
||||
return login;
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ public final class FreeRegistrationIssuer {
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
|
||||
ps.setString(1, fullLogin);
|
||||
ps.setString(1, fullLogin.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
|
||||
+2
-2
@@ -65,7 +65,7 @@ public final class FreeRegistrationWorkflow {
|
||||
}
|
||||
}
|
||||
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
|
||||
p.setString(1, login);
|
||||
p.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee); }
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,7 @@ public final class FreeRegistrationWorkflow {
|
||||
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||
WHERE i.normalized_login=?
|
||||
""")) {
|
||||
p.setString(1,login);
|
||||
p.setString(1,login.toLowerCase(java.util.Locale.ROOT));
|
||||
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)),
|
||||
|
||||
+3
-3
@@ -25,7 +25,7 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
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);
|
||||
ps.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Login is already registered");
|
||||
@@ -96,11 +96,11 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
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(1, login); insert.setString(2, login.toLowerCase(java.util.Locale.ROOT)); 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.setString(8, login.toLowerCase(java.util.Locale.ROOT) + "-001"); insert.setLong(9, now); insert.setLong(10, now);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
|
||||
+27
-26
@@ -1,42 +1,43 @@
|
||||
package server.archive;
|
||||
|
||||
import server.archive.registration.*;
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.ShineProtocolTags;
|
||||
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 */
|
||||
/** Standalone test (no legacy signed fixture): certificate issue/verify for CURRENT App tag. */
|
||||
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");
|
||||
byte[] root = HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8");
|
||||
byte[] chain = HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7");
|
||||
byte[] client = HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d");
|
||||
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")))
|
||||
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
|
||||
" Alice.Example+Tag@Example.COM ", signer);
|
||||
var item = new Ans104DataItem(cert);
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
|
||||
throw new AssertionError("Current App tag missing");
|
||||
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|
||||
|| !Arrays.equals(result.blockchainKey(), chain) || !Arrays.equals(result.clientKey(), client))
|
||||
throw new AssertionError("Certificate identity corrupted");
|
||||
if (!Arrays.equals(result.emailSha256(), HEX.parseHex(
|
||||
"cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
|
||||
throw new AssertionError("Email normalization differs");
|
||||
byte[] bad = cert.clone(); bad[bad.length - 1] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||
throw new AssertionError("Email bit flip accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
bad = cert.clone(); bad[bad.length - 40] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||
throw new AssertionError("Inner signature tampering accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
System.out.println("PASS: Java registrar fixture, inner+outer Ed25519, email normalization, tamper rejection");
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
|
||||
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@ package blockchain;
|
||||
public final class ShineProtocolTags {
|
||||
private ShineProtocolTags() {}
|
||||
|
||||
public static final String NAMESPACE = "test5591";
|
||||
public static final String NAMESPACE = "test5592";
|
||||
public static final String APP_TAG_NAME = "App";
|
||||
public static final String APP_TAG_VALUE = NAMESPACE;
|
||||
public static final String CHANNEL_TAG_NAME = "c";
|
||||
|
||||
@@ -26,12 +26,14 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_33 = 33;
|
||||
public static final int SCHEMA_VERSION_34 = 34;
|
||||
public static final int SCHEMA_VERSION_35 = 35;
|
||||
public static final int SCHEMA_VERSION_36 = 36;
|
||||
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";
|
||||
public static final String POSTGRES_MIGRATION_V35_RESOURCE = "postgres/migration_v35.sql";
|
||||
public static final String POSTGRES_MIGRATION_V36_RESOURCE = "postgres/migration_v36.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -143,9 +145,13 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V35_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_35) {
|
||||
if (currentVersion == SCHEMA_VERSION_35) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V36_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_36) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 35, found " + currentVersion);
|
||||
"Unsupported SHiNE DB v2 schema version: expected 36, found " + currentVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,9 +164,9 @@ public final class ConnectionsStateDAO {
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, login);
|
||||
ps.setString(1, login.trim().toLowerCase(java.util.Locale.ROOT));
|
||||
ps.setInt(2, relType);
|
||||
ps.setString(3, toLogin);
|
||||
ps.setString(3, toLogin.trim().toLowerCase(java.util.Locale.ROOT));
|
||||
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
||||
ps.setBytes(5, toBlockHash);
|
||||
ps.executeUpdate();
|
||||
|
||||
@@ -111,7 +111,7 @@ public final class SubscriptionsDAO {
|
||||
FROM connections_state cs
|
||||
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
|
||||
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
|
||||
WHERE cs.login = ? AND cs.rel_type = ?
|
||||
WHERE LOWER(cs.login) = LOWER(?) AND cs.rel_type = ?
|
||||
|
||||
UNION
|
||||
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
-- v36: регистрационная запись хранит исходный регистр; все ссылки FK
|
||||
-- приводятся к её точному login. Исторические строки не мигрируются.
|
||||
-- На новой базе исходные имена PDA/сертификатов и FK согласованы.
|
||||
BEGIN;
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_canonicalize_identity_fk_login()
|
||||
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||
DECLARE
|
||||
field_name TEXT := TG_ARGV[0];
|
||||
requested_login TEXT;
|
||||
canonical_login TEXT;
|
||||
BEGIN
|
||||
requested_login := to_jsonb(NEW)->>field_name;
|
||||
IF requested_login IS NULL OR btrim(requested_login) = '' THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
SELECT i.login INTO canonical_login
|
||||
FROM user_identity_current i
|
||||
WHERE i.normalized_login = lower(btrim(requested_login))
|
||||
LIMIT 1;
|
||||
IF canonical_login IS NOT NULL THEN
|
||||
-- Меняем только проекцию/связь в SQL, никогда не байты подписанного блока.
|
||||
NEW := jsonb_populate_record(NEW, jsonb_build_object(field_name, canonical_login));
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
tab_name TEXT;
|
||||
col_name TEXT;
|
||||
spec TEXT;
|
||||
trigger_name TEXT;
|
||||
BEGIN
|
||||
FOREACH spec IN ARRAY ARRAY[
|
||||
'user_access_servers_current:user_login',
|
||||
'user_access_servers_current:server_login',
|
||||
'active_sessions:login',
|
||||
'esp_pairing_settings:login',
|
||||
'esp_pairing_requests:login',
|
||||
'users_params:login',
|
||||
'user_settings:login',
|
||||
'channel_read_state:viewer_login',
|
||||
'test_free_avatar_uploads:login',
|
||||
'blockchain_state:login',
|
||||
'user_stats_state:login',
|
||||
'user_push_tokens:login',
|
||||
'key_rotation_sessions:login'
|
||||
] LOOP
|
||||
tab_name := split_part(spec, ':', 1);
|
||||
col_name := split_part(spec, ':', 2);
|
||||
trigger_name := 'trg_canonical_identity_' || tab_name || '_' || col_name;
|
||||
EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I', trigger_name, tab_name);
|
||||
EXECUTE format(
|
||||
'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OF %I ON %I FOR EACH ROW EXECUTE FUNCTION shine_canonicalize_identity_fk_login(%L)',
|
||||
trigger_name, col_name, tab_name, col_name
|
||||
);
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
UPDATE db_schema_version SET schema_version = 36,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
COMMIT;
|
||||
@@ -2334,11 +2334,15 @@ CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_blo
|
||||
|
||||
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
||||
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
||||
v_canonical_login TEXT;
|
||||
BEGIN
|
||||
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
||||
-- В FK остаётся исходный регистр владельца, но поиск/сопоставления регистронезависимы.
|
||||
SELECT login INTO v_canonical_login FROM user_identity_current WHERE normalized_login=lower(btrim(p_login)) LIMIT 1;
|
||||
IF v_canonical_login IS NULL THEN RETURN; END IF;
|
||||
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
||||
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
||||
SELECT p_login,
|
||||
SELECT v_canonical_login,
|
||||
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
||||
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||
@@ -2485,15 +2489,15 @@ DECLARE positive_rel_type INTEGER; channel_bch TEXT;
|
||||
BEGIN
|
||||
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
|
||||
DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=NEW.msg_sub_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
|
||||
VALUES(NEW.login,NEW.msg_sub_type,NEW.to_login,NEW.to_block_number,NEW.to_block_hash);
|
||||
VALUES(lower(NEW.login),NEW.msg_sub_type,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash);
|
||||
ELSE
|
||||
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
|
||||
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
||||
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=positive_rel_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
||||
END IF;
|
||||
PERFORM shine_refresh_user_stats(NEW.login);
|
||||
PERFORM shine_refresh_user_stats(NEW.to_login);
|
||||
PERFORM shine_refresh_user_stats(lower(NEW.login));
|
||||
PERFORM shine_refresh_user_stats(lower(NEW.to_login));
|
||||
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
|
||||
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
|
||||
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
|
||||
@@ -2506,22 +2510,22 @@ DECLARE previous_sub_type INTEGER;
|
||||
BEGIN
|
||||
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
|
||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash)
|
||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash)
|
||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
|
||||
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=NEW.login AND reaction_type=1 AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
||||
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=lower(NEW.login) AND reaction_type=1 AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
||||
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
|
||||
UPDATE message_stats SET likes_count=likes_count+1,
|
||||
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
|
||||
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
|
||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
|
||||
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
|
||||
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
|
||||
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
|
||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||
END IF;
|
||||
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
|
||||
VALUES(NEW.login,1,NEW.to_login,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
||||
VALUES(lower(NEW.login),1,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
||||
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
@@ -2532,7 +2536,7 @@ BEGIN
|
||||
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
|
||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
|
||||
VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash,1)
|
||||
VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,1)
|
||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
@@ -30,6 +30,7 @@ dependencies {
|
||||
|
||||
implementation project(':shine-server-crypto') // модуль сервера для работы с криптографией
|
||||
implementation project(':shine-server-blockchain') // модуль для работы с блокчейном
|
||||
implementation project(':shine-server-solana-users-sync') // Нормализованный адрес PDA
|
||||
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
||||
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
||||
|
||||
|
||||
+17
-37
@@ -108,54 +108,34 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
private static byte[] fetchRawUserPda(String login) throws Exception {
|
||||
String loginB58 = toBase58(login.getBytes(StandardCharsets.UTF_8));
|
||||
String lenB58 = toBase58(new byte[]{(byte) login.length()});
|
||||
|
||||
String reqJson = """
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"method":"getProgramAccounts",
|
||||
"params":[
|
||||
"%s",
|
||||
{
|
||||
"encoding":"base64",
|
||||
"filters":[
|
||||
{"memcmp":{"offset":61,"bytes":"%s"}},
|
||||
{"memcmp":{"offset":62,"bytes":"%s"}}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID, lenB58, loginB58);
|
||||
|
||||
// Запись хранит исходный регистр, но адрес PDA зависит только от lowercase.
|
||||
String address = sync.util.SolanaPdaUtil.findUserPdaV2(login, SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID);
|
||||
String reqJson = MAPPER.writeValueAsString(Map.of(
|
||||
"jsonrpc", "2.0", "id", 1,
|
||||
"method", "getAccountInfo",
|
||||
"params", List.of(address, Map.of("encoding", "base64", "commitment", "confirmed"))));
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(SolanaProgramsConfig.SOLANA_RPC_URL))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(reqJson))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||
throw new IllegalStateException("Solana RPC HTTP status=" + resp.statusCode());
|
||||
}
|
||||
|
||||
JsonNode root = MAPPER.readTree(resp.body());
|
||||
if (root.hasNonNull("error")) {
|
||||
throw new IllegalStateException("Solana RPC error: " + root.get("error").toString());
|
||||
throw new IllegalStateException("Solana RPC error: " + root.get("error"));
|
||||
}
|
||||
|
||||
JsonNode result = root.path("result");
|
||||
if (!result.isArray() || result.isEmpty()) return null;
|
||||
|
||||
for (JsonNode item : result) {
|
||||
JsonNode dataNode = item.path("account").path("data");
|
||||
if (!dataNode.isArray() || dataNode.size() < 1) continue;
|
||||
String b64 = dataNode.get(0).asText("");
|
||||
if (b64.isBlank()) continue;
|
||||
return Base64.getDecoder().decode(b64);
|
||||
JsonNode account = root.path("result").path("value");
|
||||
if (account.isMissingNode() || account.isNull()) return null;
|
||||
if (!SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID.equals(account.path("owner").asText())) {
|
||||
throw new IllegalStateException("PDA принадлежит другой программе");
|
||||
}
|
||||
return null;
|
||||
JsonNode data = account.path("data");
|
||||
if (!data.isArray() || data.isEmpty()) return null;
|
||||
String b64 = data.get(0).asText("");
|
||||
return b64.isBlank() ? null : Base64.getDecoder().decode(b64);
|
||||
}
|
||||
|
||||
private static ParsedSolanaUser parseUserPda(byte[] raw) {
|
||||
@@ -258,7 +238,7 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
|
||||
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||
String blockchainName = normalizeLogin(login) + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||
return new ParsedSolanaUser(
|
||||
login,
|
||||
blockchainName,
|
||||
@@ -365,7 +345,7 @@ public final class SolanaUserPdaImportService {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Нужен для memcmp.bytes в Solana RPC.
|
||||
// Вспомогательная base58-конверсия для других совместимых полей.
|
||||
private static String toBase58(byte[] input) {
|
||||
final char[] alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
int zeros = 0;
|
||||
|
||||
+1
-1
@@ -770,7 +770,7 @@ public final class ShineUsersCodec {
|
||||
if (type == 2) {
|
||||
registrarKey = Base58Util.encode(r.readFixed(32));
|
||||
serverLogin = r.readStringU8();
|
||||
if (!serverLogin.matches("[a-z0-9_]+@[a-z0-9_]+") || serverLogin.length() > 30) {
|
||||
if (!serverLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || serverLogin.length() > 30) {
|
||||
throw new IllegalArgumentException("Invalid access server login");
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -63,10 +63,10 @@ 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) {
|
||||
if (fullLogin == null || !fullLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || fullLogin.length() > 30) {
|
||||
throw new IllegalArgumentException("Invalid full login");
|
||||
}
|
||||
return findHashedPda("user_login=" + fullLogin, programId);
|
||||
return findHashedPda("user_login=" + fullLogin.toLowerCase(java.util.Locale.ROOT), programId);
|
||||
}
|
||||
|
||||
public static String findNamespacePda(String namespace, String programId) {
|
||||
|
||||
+9
@@ -24,4 +24,13 @@ class SolanaPdaUtilTest {
|
||||
pda
|
||||
);
|
||||
}
|
||||
@Test
|
||||
void mixedCaseUsesSamePdaButNamespaceMustRemainLowercase() {
|
||||
String program = "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6";
|
||||
String lower = SolanaPdaUtil.findUserPdaV2("superman@free", program);
|
||||
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SuperMan@free", program));
|
||||
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SUPERMAN@free", program));
|
||||
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
|
||||
() -> SolanaPdaUtil.findUserPdaV2("SuperMan@FREE", program));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ test.freeAvatar.walletJwkPath=
|
||||
|
||||
# ============================================================
|
||||
# Arweave per-user-block transport (ANS-104)
|
||||
# Test namespace: each user DataItem is signed with App=test5591.
|
||||
# Test namespace: each user DataItem is signed with App=test5592.
|
||||
# Channel DataItems additionally contain c=<canonical-channel-slug>.
|
||||
# ============================================================
|
||||
arweave.blocks.publish.enabled=false
|
||||
|
||||
Reference in New Issue
Block a user