SHA256
Compare commits
4
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
5db3ad8a3e | ||
|
|
e556615fa9 | ||
|
|
790740cd56 | ||
|
|
d91e4a32df |
@@ -35,6 +35,7 @@ public final class DatabaseInitializer {
|
|||||||
public static final int SCHEMA_VERSION_42 = 42;
|
public static final int SCHEMA_VERSION_42 = 42;
|
||||||
public static final int SCHEMA_VERSION_43 = 43;
|
public static final int SCHEMA_VERSION_43 = 43;
|
||||||
public static final int SCHEMA_VERSION_44 = 44;
|
public static final int SCHEMA_VERSION_44 = 44;
|
||||||
|
public static final int SCHEMA_VERSION_45 = 45;
|
||||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
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_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||||
@@ -50,6 +51,7 @@ public final class DatabaseInitializer {
|
|||||||
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
|
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
|
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
|
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V45_RESOURCE = "postgres/migration_v45.sql";
|
||||||
|
|
||||||
private DatabaseInitializer() {}
|
private DatabaseInitializer() {}
|
||||||
|
|
||||||
@@ -197,9 +199,13 @@ public final class DatabaseInitializer {
|
|||||||
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
|
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
|
||||||
currentVersion = readCurrentSchemaVersion(conn);
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
}
|
}
|
||||||
if (currentVersion != SCHEMA_VERSION_44) {
|
if (currentVersion == SCHEMA_VERSION_44) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion != SCHEMA_VERSION_45) {
|
||||||
throw new SQLException(
|
throw new SQLException(
|
||||||
"Unsupported SHiNE DB v2 schema version: expected 44, found " + currentVersion);
|
"Unsupported SHiNE DB v2 schema version: expected 45, found " + currentVersion);
|
||||||
}
|
}
|
||||||
normalizeBlockchainStateKeysToBase64(conn);
|
normalizeBlockchainStateKeysToBase64(conn);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -73,6 +73,47 @@ public final class ChannelNameStateDAO {
|
|||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
bindInsert(ps, entry);
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Используется только при воспроизведении уже подписанной истории. В live AddBlock
|
||||||
|
* дубликат имени запрещён; при replay блок всё же нужно сохранить, иначе цепочка
|
||||||
|
* после него останется разорванной.
|
||||||
|
*/
|
||||||
|
public void insertOrReplaceWithNewerRoot(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||||
|
String sql = """
|
||||||
|
INSERT INTO channel_names_state (
|
||||||
|
slug, display_name, channel_description, owner_login, owner_bch_name,
|
||||||
|
channel_type_code, channel_type_version, channel_root_block_number,
|
||||||
|
channel_root_block_hash, created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (owner_bch_name, channel_type_code, slug) DO UPDATE SET
|
||||||
|
display_name = EXCLUDED.display_name,
|
||||||
|
channel_description = EXCLUDED.channel_description,
|
||||||
|
owner_login = EXCLUDED.owner_login,
|
||||||
|
channel_type_version = EXCLUDED.channel_type_version,
|
||||||
|
channel_root_block_number = EXCLUDED.channel_root_block_number,
|
||||||
|
channel_root_block_hash = EXCLUDED.channel_root_block_hash,
|
||||||
|
created_at_ms = EXCLUDED.created_at_ms,
|
||||||
|
ava_ar = EXCLUDED.ava_ar,
|
||||||
|
ava_pr = EXCLUDED.ava_pr,
|
||||||
|
ava_size = EXCLUDED.ava_size,
|
||||||
|
meta_updated_at_ms = EXCLUDED.meta_updated_at_ms,
|
||||||
|
is_deleted = FALSE,
|
||||||
|
deleted_at_ms = 0,
|
||||||
|
deleted_block_number = NULL
|
||||||
|
WHERE EXCLUDED.channel_root_block_number > channel_names_state.channel_root_block_number
|
||||||
|
""";
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
bindInsert(ps, entry);
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void bindInsert(PreparedStatement ps, ChannelNameStateEntry entry) throws SQLException {
|
||||||
ps.setString(1, entry.getSlug());
|
ps.setString(1, entry.getSlug());
|
||||||
ps.setString(2, entry.getDisplayName());
|
ps.setString(2, entry.getDisplayName());
|
||||||
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
||||||
@@ -87,8 +128,6 @@ public final class ChannelNameStateDAO {
|
|||||||
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
|
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
|
||||||
ps.setLong(13, Math.max(0L, entry.getAvaSize()));
|
ps.setLong(13, Math.max(0L, entry.getAvaSize()));
|
||||||
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
||||||
ps.executeUpdate();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
-- v45: FREE_CERT — полноценная identity без фиктивной Solana PDA.
|
||||||
|
-- Обычные проекции и чтение blockchain выбирают ветку по user_identity_current;
|
||||||
|
-- Solana PDA остаётся источником только Solana-специфичных данных.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_identity_active_fork(p_login TEXT)
|
||||||
|
RETURNS INTEGER
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
STABLE
|
||||||
|
AS $$
|
||||||
|
DECLARE
|
||||||
|
v_fork INTEGER;
|
||||||
|
BEGIN
|
||||||
|
SELECT substring(blockchain_name FROM '([0-9]{3})$')::INTEGER
|
||||||
|
INTO v_fork
|
||||||
|
FROM user_identity_current
|
||||||
|
WHERE LOWER(login) = LOWER(BTRIM(p_login))
|
||||||
|
LIMIT 1;
|
||||||
|
|
||||||
|
IF v_fork BETWEEN 1 AND 999 THEN
|
||||||
|
RETURN v_fork;
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
SELECT fork_number
|
||||||
|
INTO v_fork
|
||||||
|
FROM blockchain_state_store
|
||||||
|
WHERE LOWER(login) = LOWER(BTRIM(p_login))
|
||||||
|
ORDER BY updated_at_ms DESC, fork_number DESC
|
||||||
|
LIMIT 1;
|
||||||
|
|
||||||
|
RETURN COALESCE(v_fork, 1);
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_active_fork(p_login TEXT, p_block_number INTEGER)
|
||||||
|
RETURNS INTEGER
|
||||||
|
LANGUAGE sql
|
||||||
|
STABLE
|
||||||
|
AS $$
|
||||||
|
SELECT shine_canonical_fork(p_login, shine_identity_active_fork(p_login), p_block_number)
|
||||||
|
$$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_channel_names_state_refresh_owner_stats()
|
||||||
|
RETURNS TRIGGER
|
||||||
|
LANGUAGE plpgsql
|
||||||
|
AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'DELETE' THEN
|
||||||
|
PERFORM shine_refresh_user_stats(OLD.owner_login);
|
||||||
|
RETURN OLD;
|
||||||
|
END IF;
|
||||||
|
PERFORM shine_refresh_user_stats(NEW.owner_login);
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS trg_channel_names_state_refresh_owner_stats ON channel_names_state;
|
||||||
|
CREATE TRIGGER trg_channel_names_state_refresh_owner_stats
|
||||||
|
AFTER INSERT OR UPDATE OF owner_login, channel_type_code, is_deleted OR DELETE
|
||||||
|
ON channel_names_state
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_channel_names_state_refresh_owner_stats();
|
||||||
|
|
||||||
|
-- Исправить уже записанные FREE_CERT и paid identity одним пересчётом.
|
||||||
|
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
|
||||||
|
|
||||||
|
UPDATE db_schema_version
|
||||||
|
SET schema_version = 45,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
+1
-1
@@ -453,7 +453,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
|
if (!replayMode && channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
|
||||||
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
|
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
|||||||
+4
-1
@@ -79,7 +79,10 @@ public final class BlockchainWriter {
|
|||||||
blocksDAO.insert(c, be);
|
blocksDAO.insert(c, be);
|
||||||
|
|
||||||
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
|
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
|
||||||
if (channelNameStateEntry != null) channelNameStateDAO.insert(c, channelNameStateEntry);
|
if (channelNameStateEntry != null) {
|
||||||
|
if (replayMode) channelNameStateDAO.insertOrReplaceWithNewerRoot(c, channelNameStateEntry);
|
||||||
|
else channelNameStateDAO.insert(c, channelNameStateEntry);
|
||||||
|
}
|
||||||
if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry);
|
if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry);
|
||||||
if (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry);
|
if (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry);
|
||||||
|
|
||||||
|
|||||||
+45
-36
@@ -41,7 +41,8 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
private static void rebuildFromBlocksOrThrow() {
|
private static void rebuildFromBlocksOrThrow() {
|
||||||
ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance();
|
ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance();
|
||||||
List<ChannelNameStateEntry> entries = new ArrayList<>();
|
List<ChannelNameStateEntry> entries = new ArrayList<>();
|
||||||
Map<String, String> slugToIdentity = new LinkedHashMap<>();
|
Map<String, ChannelNameStateEntry> entriesByOwnerTypeSlug = new LinkedHashMap<>();
|
||||||
|
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots = new LinkedHashMap<>();
|
||||||
List<String> conflicts = new ArrayList<>();
|
List<String> conflicts = new ArrayList<>();
|
||||||
List<String> skipped = new ArrayList<>();
|
List<String> skipped = new ArrayList<>();
|
||||||
|
|
||||||
@@ -49,14 +50,7 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
SELECT login, bch_name, block_number, block_hash, block_bytes
|
SELECT login, bch_name, block_number, block_hash, block_bytes
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE msg_type = ? AND msg_sub_type = ?
|
WHERE msg_type = ? AND msg_sub_type = ?
|
||||||
AND fork_number=shine_canonical_fork(
|
AND fork_number=shine_active_fork(login, block_number)
|
||||||
login,
|
|
||||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
|
||||||
FROM solana_user_pda_current
|
|
||||||
WHERE LOWER(login)=LOWER(blocks.login)
|
|
||||||
LIMIT 1),
|
|
||||||
block_number
|
|
||||||
)
|
|
||||||
ORDER BY LOWER(login), block_number
|
ORDER BY LOWER(login), block_number
|
||||||
""";
|
""";
|
||||||
|
|
||||||
@@ -115,14 +109,6 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
String identity = ownerBch + "#" + blockNumber;
|
|
||||||
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
|
|
||||||
String existing = slugToIdentity.putIfAbsent(ownerTypeSlug, identity);
|
|
||||||
if (existing != null && !existing.equals(identity)) {
|
|
||||||
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: " + existing + " vs " + identity);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
ChannelNameStateEntry entry = new ChannelNameStateEntry();
|
ChannelNameStateEntry entry = new ChannelNameStateEntry();
|
||||||
entry.setSlug(slug);
|
entry.setSlug(slug);
|
||||||
entry.setDisplayName(displayName);
|
entry.setDisplayName(displayName);
|
||||||
@@ -138,18 +124,28 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
entry.setChannelRootBlockNumber(blockNumber);
|
entry.setChannelRootBlockNumber(blockNumber);
|
||||||
entry.setChannelRootBlockHash(blockHash);
|
entry.setChannelRootBlockHash(blockHash);
|
||||||
entry.setCreatedAtMs(parsed.timestamp * 1000L);
|
entry.setCreatedAtMs(parsed.timestamp * 1000L);
|
||||||
entries.add(entry);
|
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
|
||||||
|
ChannelNameStateEntry previous = entriesByOwnerTypeSlug.put(ownerTypeSlug, entry);
|
||||||
|
if (previous != null) {
|
||||||
|
replacedRoots.put(new ChannelRoot(previous.getOwnerBlockchainName(), previous.getChannelRootBlockNumber(), previous.getChannelRootBlockHash()), entry);
|
||||||
|
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: "
|
||||||
|
+ previous.getOwnerBlockchainName() + "#" + previous.getChannelRootBlockNumber()
|
||||||
|
+ " vs " + ownerBch + "#" + blockNumber + "; kept newest root");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
entries.addAll(entriesByOwnerTypeSlug.values());
|
||||||
|
|
||||||
dao.clearAll(c);
|
dao.clearAll(c);
|
||||||
dao.insertAll(c, entries);
|
dao.insertAll(c, entries);
|
||||||
|
redirectFollowedChannelRoots(c, replacedRoots);
|
||||||
|
|
||||||
applyMetaUpdates(c, dao, entries, skipped);
|
applyMetaUpdates(c, dao, entries, skipped);
|
||||||
applyDeletionStates(c, dao, skipped);
|
applyDeletionStates(c, dao, skipped);
|
||||||
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
|
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
|
||||||
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
|
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM user_identity_current")) {
|
||||||
ps.execute();
|
ps.execute();
|
||||||
}
|
}
|
||||||
try (PreparedStatement ps = c.prepareStatement("""
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
@@ -162,7 +158,7 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
c.commit();
|
c.commit();
|
||||||
log.info("channel_names_state bootstrapped: {}", entries.size());
|
log.info("channel_names_state bootstrapped: {}", entries.size());
|
||||||
if (!conflicts.isEmpty()) {
|
if (!conflicts.isEmpty()) {
|
||||||
log.warn("channel_names_state bootstrap detected {} slug conflicts (kept first occurrence)", conflicts.size());
|
log.warn("channel_names_state bootstrap detected {} slug conflicts (kept newest root)", conflicts.size());
|
||||||
int preview = Math.min(conflicts.size(), 10);
|
int preview = Math.min(conflicts.size(), 10);
|
||||||
for (int i = 0; i < preview; i++) {
|
for (int i = 0; i < preview; i++) {
|
||||||
log.warn("channel_names_state conflict: {}", conflicts.get(i));
|
log.warn("channel_names_state conflict: {}", conflicts.get(i));
|
||||||
@@ -192,19 +188,37 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Connections are a mutable projection. Keep follows on the current root when a legacy duplicate is replaced. */
|
||||||
|
private static void redirectFollowedChannelRoots(Connection c,
|
||||||
|
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots) throws Exception {
|
||||||
|
String sql = """
|
||||||
|
UPDATE connections_state
|
||||||
|
SET to_block_number = ?, to_block_hash = ?
|
||||||
|
WHERE LOWER(to_login) = LOWER(?)
|
||||||
|
AND to_block_number = ?
|
||||||
|
AND to_block_hash = ?
|
||||||
|
""";
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
for (Map.Entry<ChannelRoot, ChannelNameStateEntry> replacement : replacedRoots.entrySet()) {
|
||||||
|
ChannelRoot oldRoot = replacement.getKey();
|
||||||
|
ChannelNameStateEntry current = replacement.getValue();
|
||||||
|
ps.setInt(1, current.getChannelRootBlockNumber());
|
||||||
|
ps.setBytes(2, current.getChannelRootBlockHash());
|
||||||
|
ps.setString(3, current.getOwnerLogin());
|
||||||
|
ps.setInt(4, oldRoot.blockNumber());
|
||||||
|
ps.setBytes(5, oldRoot.blockHash());
|
||||||
|
ps.addBatch();
|
||||||
|
}
|
||||||
|
ps.executeBatch();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
|
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT bch_name, block_number, block_bytes, msg_sub_type
|
SELECT bch_name, block_number, block_bytes, msg_sub_type
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
|
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
|
||||||
AND fork_number=shine_canonical_fork(
|
AND fork_number=shine_active_fork(login, block_number)
|
||||||
login,
|
|
||||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
|
||||||
FROM solana_user_pda_current
|
|
||||||
WHERE LOWER(login)=LOWER(blocks.login)
|
|
||||||
LIMIT 1),
|
|
||||||
block_number
|
|
||||||
)
|
|
||||||
ORDER BY LOWER(login), block_number
|
ORDER BY LOWER(login), block_number
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -233,6 +247,8 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private record ChannelRoot(String ownerBlockchainName, int blockNumber, byte[] blockHash) {}
|
||||||
|
|
||||||
private static void applyMetaUpdates(Connection c,
|
private static void applyMetaUpdates(Connection c,
|
||||||
ChannelNameStateDAO dao,
|
ChannelNameStateDAO dao,
|
||||||
List<ChannelNameStateEntry> entries,
|
List<ChannelNameStateEntry> entries,
|
||||||
@@ -246,14 +262,7 @@ public final class ChannelNamesStateBootstrapper {
|
|||||||
SELECT login, bch_name, block_number, block_bytes
|
SELECT login, bch_name, block_number, block_bytes
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE msg_type = ? AND msg_sub_type = ?
|
WHERE msg_type = ? AND msg_sub_type = ?
|
||||||
AND fork_number=shine_canonical_fork(
|
AND fork_number=shine_active_fork(login, block_number)
|
||||||
login,
|
|
||||||
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
|
|
||||||
FROM solana_user_pda_current
|
|
||||||
WHERE LOWER(login)=LOWER(blocks.login)
|
|
||||||
LIMIT 1),
|
|
||||||
block_number
|
|
||||||
)
|
|
||||||
ORDER BY LOWER(login), block_number
|
ORDER BY LOWER(login), block_number
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
|||||||
+1
-2
@@ -158,14 +158,13 @@ public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
|
|||||||
String sql = """
|
String sql = """
|
||||||
SELECT login, bch_name, block_number, block_hash, block_bytes
|
SELECT login, bch_name, block_number, block_hash, block_bytes
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_active_fork(login,block_number)
|
||||||
ORDER BY block_number ASC
|
ORDER BY block_number ASC
|
||||||
""";
|
""";
|
||||||
List<MsgRow> out = new ArrayList<>();
|
List<MsgRow> out = new ArrayList<>();
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||||
ps.setInt(2, line);
|
ps.setInt(2, line);
|
||||||
ps.setString(3, ChannelsReadSupport.loginFromChainName(ownerBch));
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
MsgRow row = new MsgRow();
|
MsgRow row = new MsgRow();
|
||||||
|
|||||||
+5
-9
@@ -123,7 +123,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
|
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
|
||||||
OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?))
|
OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?))
|
||||||
)
|
)
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setInt(1, toBlockNumber);
|
ps.setInt(1, toBlockNumber);
|
||||||
@@ -155,14 +155,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, login);
|
ps.setString(1, login);
|
||||||
ps.setInt(2, blockNumber);
|
ps.setInt(2, blockNumber);
|
||||||
ps.setBytes(3, blockHash);
|
ps.setBytes(3, blockHash);
|
||||||
ps.setString(4, login);
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
return rs.next() ? mapRow(rs) : null;
|
return rs.next() ? mapRow(rs) : null;
|
||||||
}
|
}
|
||||||
@@ -174,14 +173,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
String login=ChannelsReadSupport.loginFromChainName(bchName);
|
String login=ChannelsReadSupport.loginFromChainName(bchName);
|
||||||
ps.setString(1, login);
|
ps.setString(1, login);
|
||||||
ps.setInt(2, blockNumber);
|
ps.setInt(2, blockNumber);
|
||||||
ps.setString(3, login);
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
return rs.next() ? mapRow(rs) : null;
|
return rs.next() ? mapRow(rs) : null;
|
||||||
}
|
}
|
||||||
@@ -193,7 +191,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
|
||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -201,7 +199,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
ps.setString(1, login);
|
ps.setString(1, login);
|
||||||
ps.setInt(2, blockNumber);
|
ps.setInt(2, blockNumber);
|
||||||
ps.setBytes(3, blockHash);
|
ps.setBytes(3, blockHash);
|
||||||
ps.setString(4, login);
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
return rs.next() ? mapRow(rs) : null;
|
return rs.next() ? mapRow(rs) : null;
|
||||||
}
|
}
|
||||||
@@ -321,7 +318,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
FROM blocks
|
FROM blocks
|
||||||
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
|
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
|
||||||
AND to_block_number=? AND to_block_hash=?
|
AND to_block_number=? AND to_block_hash=?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
ORDER BY block_number ASC
|
ORDER BY block_number ASC
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -330,7 +327,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
ps.setInt(2, subType);
|
ps.setInt(2, subType);
|
||||||
ps.setInt(3, targetBlock);
|
ps.setInt(3, targetBlock);
|
||||||
ps.setBytes(4, targetHash);
|
ps.setBytes(4, targetHash);
|
||||||
ps.setString(5, login);
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
List<PostRow> out = new ArrayList<>();
|
List<PostRow> out = new ArrayList<>();
|
||||||
while (rs.next()) out.add(mapRow(rs));
|
while (rs.next()) out.add(mapRow(rs));
|
||||||
|
|||||||
+2
-3
@@ -89,7 +89,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
|||||||
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
|
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
|
||||||
try (PreparedStatement ps = c.prepareStatement("""
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
SELECT blockchain_name
|
SELECT blockchain_name
|
||||||
FROM solana_user_pda_current
|
FROM user_identity_current
|
||||||
WHERE LOWER(login)=LOWER(?)
|
WHERE LOWER(login)=LOWER(?)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""")) {
|
""")) {
|
||||||
@@ -181,7 +181,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
|||||||
AND msg_sub_type = ?
|
AND msg_sub_type = ?
|
||||||
AND to_block_number = ?
|
AND to_block_number = ?
|
||||||
AND to_block_hash = ?
|
AND to_block_hash = ?
|
||||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
AND fork_number=shine_active_fork(login,block_number)
|
||||||
ORDER BY block_number ASC
|
ORDER BY block_number ASC
|
||||||
""")) {
|
""")) {
|
||||||
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
|
||||||
@@ -189,7 +189,6 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
|
|||||||
ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY);
|
ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY);
|
||||||
ps.setInt(4, originalBlockNumber);
|
ps.setInt(4, originalBlockNumber);
|
||||||
ps.setBytes(5, originalBlockHash);
|
ps.setBytes(5, originalBlockHash);
|
||||||
ps.setString(6, ChannelsReadSupport.loginFromChainName(ownerBch));
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
while (rs.next()) {
|
while (rs.next()) {
|
||||||
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
|
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
|
||||||
|
|||||||
+1
-1
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.20.67
|
client.version=1.20.67
|
||||||
server.version=1.16.33
|
server.version=1.16.38
|
||||||
|
|||||||
@@ -35,6 +35,7 @@
|
|||||||
- обязательный тестовый tag `App=test5592`;
|
- обязательный тестовый tag `App=test5592`;
|
||||||
- для channel block — `c=<canonical_channel_slug>`;
|
- для channel block — `c=<canonical_channel_slug>`;
|
||||||
- новый `CreateChannelBody`: техническое имя `channelName` должно быть длиной 4–32 символа (`A-Z`, `a-z`, `0-9`, `_`, `-`); для длины 1–3 возвращается `bad_channel_name`. Проверка выполняется на уровне body (`checkForCreate`) и бизнес-валидации `AddBlock`. Ранее подписанные блоки с именами короче 4 символов по-прежнему читаются и могут быть воспроизведены в архивном `replayMode` (но обычный `AddBlock` их отклоняет); бинарный формат v1 не изменён;
|
- новый `CreateChannelBody`: техническое имя `channelName` должно быть длиной 4–32 символа (`A-Z`, `a-z`, `0-9`, `_`, `-`); для длины 1–3 возвращается `bad_channel_name`. Проверка выполняется на уровне body (`checkForCreate`) и бизнес-валидации `AddBlock`. Ранее подписанные блоки с именами короче 4 символов по-прежнему читаются и могут быть воспроизведены в архивном `replayMode` (но обычный `AddBlock` их отклоняет); бинарный формат v1 не изменён;
|
||||||
|
- новый `CreateChannelBody` с тем же владельцем, типом и canonical slug отклоняется обычным `AddBlock` с `409 channel_name_already_exists`. При архивном `replayMode` исторический дубликат сохраняется только для непрерывности уже подписанной цепочки, а проекция выбирает корень с большим номером;
|
||||||
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
|
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
|
||||||
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
|
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
|
||||||
|
|
||||||
|
|||||||
@@ -48,9 +48,15 @@
|
|||||||
- `SolanaUsersSyncService` + `PostgresStorageRepository` создают/перезаписывают snapshots; не допустить, чтобы sync очищал доверенные free-сертификаты или создавал дубль при Solana upgrade.
|
- `SolanaUsersSyncService` + `PostgresStorageRepository` создают/перезаписывают snapshots; не допустить, чтобы sync очищал доверенные free-сертификаты или создавал дубль при Solana upgrade.
|
||||||
- `ArweaveBlockSyncService` читает `solana_user_pda_current` и blockchain-данные: восстановление free должно оставаться независимым от факта существования реального Solana PDA.
|
- `ArweaveBlockSyncService` читает `solana_user_pda_current` и blockchain-данные: восстановление free должно оставаться независимым от факта существования реального Solana PDA.
|
||||||
|
|
||||||
## Решение для этапа 5 — пока НЕ принято
|
## Принятое решение: единая identity без фиктивной PDA
|
||||||
|
|
||||||
Требование мастер-плана: одна логическая личность для `FREE_CERT` и `PAID_UPGRADED`; при free **нет on-chain PDA**, но сохраняются FK/индексы/функциональность сообщений, каналов, связей и сессий. Не вставлять фиктивный Solana snapshot со slot/signature только ради удовлетворения FK. Выбрать единый identity-index после проверки реальной схемы и протестировать:
|
Одна логическая личность существует для `FREE_CERT` и `PAID_UPGRADED`; при free **нет on-chain PDA**, но сохраняются FK/индексы/функциональность сообщений, каналов, связей и сессий. Не вставлять фиктивный Solana snapshot со slot/signature только ради удовлетворения FK.
|
||||||
|
|
||||||
|
Обычные серверные операции обязаны использовать `user_identity_current`: он содержит подтверждённые сертификатом Arweave login, blockchain name и публичные ключи free-пользователя. `solana_user_pda_current` допустимо использовать только для функций, которым действительно нужны on-chain сведения: платежи, Solana-ротация ключей, PDA и маршруты из Solana.
|
||||||
|
|
||||||
|
Для чтения блокчейна SQL-функции `shine_identity_active_fork(login)` и `shine_active_fork(login, block_number)` выбирают ветку по общей identity; при отсутствии PDA используется актуальная запись `blockchain_state_store`, а последним fallback служит fork `1`. Это обеспечивает одинаковую работу каналов и обсуждений у free и paid пользователей.
|
||||||
|
|
||||||
|
После миграции статистика free-пользователей пересчитывается из `channel_names_state` и `connections_state`. Проверить:
|
||||||
|
|
||||||
1. создание free до появления в Solana, работа всех 15 зависимых таблиц;
|
1. создание free до появления в Solana, работа всех 15 зависимых таблиц;
|
||||||
2. транзакционный upgrade без перегенерации root/blockchain/client и без переименования логина;
|
2. транзакционный upgrade без перегенерации root/blockchain/client и без переименования логина;
|
||||||
|
|||||||
Reference in New Issue
Block a user