SHA256
GPT: сгенерено и не проверено (смена ключей пользователя)
This commit is contained in:
@@ -42,6 +42,8 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_23 = 23;
|
||||
public static final int SCHEMA_VERSION_24 = 24;
|
||||
public static final int SCHEMA_VERSION_25 = 25;
|
||||
public static final int SCHEMA_VERSION_26 = 26;
|
||||
public static final int SCHEMA_VERSION_27 = 27;
|
||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V2_RESOURCE = "postgres/migration_v2.sql";
|
||||
public static final String POSTGRES_MIGRATION_V3_RESOURCE = "postgres/migration_v3.sql";
|
||||
@@ -67,6 +69,8 @@ public final class DatabaseInitializer {
|
||||
public static final String POSTGRES_MIGRATION_V23_RESOURCE = "postgres/migration_v23.sql";
|
||||
public static final String POSTGRES_MIGRATION_V24_RESOURCE = "postgres/migration_v24.sql";
|
||||
public static final String POSTGRES_MIGRATION_V25_RESOURCE = "postgres/migration_v25.sql";
|
||||
public static final String POSTGRES_MIGRATION_V26_RESOURCE = "postgres/migration_v26.sql";
|
||||
public static final String POSTGRES_MIGRATION_V27_RESOURCE = "postgres/migration_v27.sql";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -236,6 +240,14 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V25_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_25;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_26) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V26_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_26;
|
||||
}
|
||||
if (currentVersion < SCHEMA_VERSION_27) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V27_RESOURCE);
|
||||
currentVersion = SCHEMA_VERSION_27;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+94
@@ -127,6 +127,100 @@ public final class BlockchainResyncCleanupDAO {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* После смены fork обновляет только runtime-кэш физического blockchainName у логических target-ссылок.
|
||||
* Подписанная идентичность target уже задаётся login + blockNumber + blockHash; поэтому смена cache value
|
||||
* не меняет смысл ссылки и не требует переподписывать чужие блоки.
|
||||
*/
|
||||
public void refreshLogicalTargetBlockchainCache(String login, String oldBlockchainName, String newBlockchainName) throws SQLException {
|
||||
if (login == null || login.isBlank() || newBlockchainName == null || newBlockchainName.isBlank()) {
|
||||
throw new IllegalArgumentException("login/newBlockchainName are required");
|
||||
}
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
updateTargetCacheByLogin(c, "blocks", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "connections_state", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "reactions_state", login, newBlockchainName);
|
||||
updateTargetCacheByLogin(c, "message_stats", login, newBlockchainName);
|
||||
if (oldBlockchainName != null && !oldBlockchainName.isBlank()) {
|
||||
try (PreparedStatement ps = c.prepareStatement("UPDATE message_views_state SET to_bch_name=? WHERE to_bch_name=?")) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, oldBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("UPDATE channel_read_state SET owner_bch_name=? WHERE owner_bch_name=?")) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, oldBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
rebuildInboundMessageCounters(c, login, newBlockchainName);
|
||||
rebuildStatsState(c);
|
||||
c.commit();
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to refresh logical target blockchain cache for login=" + login, e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* После replay candidate-цепочки её собственные message_stats уже существуют, но входящие реакции/ответы
|
||||
* других пользователей были созданы раньше и не проходили триггеры повторно. Поэтому пересчитываем
|
||||
* агрегаты из исходных таблиц после перепривязки runtime to_bch_name cache.
|
||||
*/
|
||||
private void rebuildInboundMessageCounters(Connection c, String login, String newBlockchainName) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE message_stats ms
|
||||
SET likes_count = (
|
||||
SELECT COUNT(*)::INTEGER
|
||||
FROM reactions_state rs
|
||||
WHERE rs.reaction_type = ?
|
||||
AND rs.last_sub_type = ?
|
||||
AND LOWER(rs.to_login) = LOWER(ms.to_login)
|
||||
AND rs.to_bch_name = ms.to_bch_name
|
||||
AND rs.to_block_number = ms.to_block_number
|
||||
AND rs.to_block_hash = ms.to_block_hash
|
||||
),
|
||||
replies_count = (
|
||||
SELECT COUNT(*)::INTEGER
|
||||
FROM blocks b
|
||||
WHERE b.msg_type = 1
|
||||
AND b.msg_sub_type = ?
|
||||
AND LOWER(b.to_login) = LOWER(ms.to_login)
|
||||
AND b.to_bch_name = ms.to_bch_name
|
||||
AND b.to_block_number = ms.to_block_number
|
||||
AND b.to_block_hash = ms.to_block_hash
|
||||
)
|
||||
WHERE LOWER(ms.to_login) = LOWER(?)
|
||||
AND ms.to_bch_name = ?
|
||||
""")) {
|
||||
ps.setInt(1, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(2, DatabaseInitializer.REACTION_LIKE);
|
||||
ps.setInt(3, DatabaseInitializer.TEXT_REPLY);
|
||||
ps.setString(4, login);
|
||||
ps.setString(5, newBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private void updateTargetCacheByLogin(Connection c, String table, String login, String newBlockchainName) throws SQLException {
|
||||
String sql = "UPDATE " + table + " SET to_bch_name=? WHERE LOWER(to_login)=LOWER(?) AND to_bch_name IS DISTINCT FROM ?";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, newBlockchainName);
|
||||
ps.setString(2, login);
|
||||
ps.setString(3, newBlockchainName);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private String resolveLoginForCleanup(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
SELECT login
|
||||
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DbController;
|
||||
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/** Хранилище candidate-блоков будущего fork во время ротации ключей. */
|
||||
public final class KeyRotationCandidateBlocksDAO {
|
||||
private static volatile KeyRotationCandidateBlocksDAO instance;
|
||||
private final DbController db = DbController.getInstance();
|
||||
|
||||
private KeyRotationCandidateBlocksDAO() { }
|
||||
|
||||
public static KeyRotationCandidateBlocksDAO getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (KeyRotationCandidateBlocksDAO.class) {
|
||||
if (instance == null) instance = new KeyRotationCandidateBlocksDAO();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Идемпотентно сохраняет один candidate-блок.
|
||||
* Повтор того же blockNumber допустим только при полном совпадении hash и DataItem id.
|
||||
*/
|
||||
public KeyRotationCandidateBlockEntry insertOrGet(Connection c, KeyRotationCandidateBlockEntry entry) throws SQLException {
|
||||
KeyRotationCandidateBlockEntry existing = getByNumber(c, entry.getRotationSessionId(), entry.getBlockNumber());
|
||||
if (existing != null) {
|
||||
if (Arrays.equals(existing.getBlockHash(), entry.getBlockHash())
|
||||
&& Arrays.equals(existing.getDataItemId(), entry.getDataItemId())) {
|
||||
return existing;
|
||||
}
|
||||
throw new SQLException("Candidate block conflict at number=" + entry.getBlockNumber());
|
||||
}
|
||||
|
||||
String sql = """
|
||||
INSERT INTO key_rotation_candidate_blocks (
|
||||
rotation_session_id, login, candidate_blockchain_name,
|
||||
block_number, block_hash, data_item_id, block_bytes,
|
||||
arweave_publish_pending, arweave_published_at_ms, created_at_ms
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, NULL, ?)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
int i = 1;
|
||||
ps.setLong(i++, entry.getRotationSessionId());
|
||||
ps.setString(i++, entry.getLogin());
|
||||
ps.setString(i++, entry.getCandidateBlockchainName());
|
||||
ps.setInt(i++, entry.getBlockNumber());
|
||||
ps.setBytes(i++, entry.getBlockHash());
|
||||
ps.setBytes(i++, entry.getDataItemId());
|
||||
ps.setBytes(i++, entry.getBlockBytes());
|
||||
ps.setLong(i++, entry.getCreatedAtMs());
|
||||
ps.executeUpdate();
|
||||
try (ResultSet keys = ps.getGeneratedKeys()) {
|
||||
if (!keys.next()) throw new SQLException("candidate block insert returned no id");
|
||||
entry.setId(keys.getLong(1));
|
||||
}
|
||||
} catch (SQLException insertFailure) {
|
||||
// Конкурирующий повтор из другой сессии мог успеть вставиться между SELECT и INSERT.
|
||||
KeyRotationCandidateBlockEntry raced = getByNumber(c, entry.getRotationSessionId(), entry.getBlockNumber());
|
||||
if (raced != null
|
||||
&& Arrays.equals(raced.getBlockHash(), entry.getBlockHash())
|
||||
&& Arrays.equals(raced.getDataItemId(), entry.getDataItemId())) {
|
||||
return raced;
|
||||
}
|
||||
throw insertFailure;
|
||||
}
|
||||
entry.setArweavePublishPending(true);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public KeyRotationCandidateBlockEntry getByNumber(Connection c, long sessionId, int blockNumber) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT * FROM key_rotation_candidate_blocks
|
||||
WHERE rotation_session_id = ? AND block_number = ?
|
||||
""")) {
|
||||
ps.setLong(1, sessionId);
|
||||
ps.setInt(2, blockNumber);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? map(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int countStored(Connection c, long sessionId) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT COUNT(*) FROM key_rotation_candidate_blocks WHERE rotation_session_id = ?
|
||||
""")) {
|
||||
ps.setLong(1, sessionId);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public int countPublished(Connection c, long sessionId) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT COUNT(*) FROM key_rotation_candidate_blocks
|
||||
WHERE rotation_session_id = ? AND arweave_publish_pending = FALSE
|
||||
""")) {
|
||||
ps.setLong(1, sessionId);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
rs.next();
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Все candidate-блоки одной ротации в строгом порядке block_number. */
|
||||
public List<KeyRotationCandidateBlockEntry> listBySession(Connection c, long sessionId) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT * FROM key_rotation_candidate_blocks
|
||||
WHERE rotation_session_id = ?
|
||||
ORDER BY block_number
|
||||
""")) {
|
||||
ps.setLong(1, sessionId);
|
||||
List<KeyRotationCandidateBlockEntry> out = new ArrayList<>();
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) out.add(map(rs));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/** Candidate-блоки имеют приоритет перед обычной очередью publisher-а. */
|
||||
public List<KeyRotationCandidateBlockEntry> listPendingArweave(int limit) throws SQLException {
|
||||
if (limit <= 0) return List.of();
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT * FROM key_rotation_candidate_blocks
|
||||
WHERE arweave_publish_pending = TRUE
|
||||
ORDER BY id
|
||||
LIMIT ?
|
||||
""")) {
|
||||
ps.setInt(1, limit);
|
||||
List<KeyRotationCandidateBlockEntry> out = new ArrayList<>();
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) out.add(map(rs));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Помечает DataItem опубликованными и синхронизирует progress_current ротации
|
||||
* с реальным количеством DataItem, подтверждённых publisher-ом.
|
||||
*/
|
||||
public void markArweavePublished(List<byte[]> dataItemIds, long publishedAtMs) throws SQLException {
|
||||
if (dataItemIds == null || dataItemIds.isEmpty()) return;
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
java.util.Set<Long> sessions = new java.util.HashSet<>();
|
||||
try (PreparedStatement find = c.prepareStatement("""
|
||||
SELECT rotation_session_id
|
||||
FROM key_rotation_candidate_blocks
|
||||
WHERE data_item_id = ?
|
||||
""")) {
|
||||
for (byte[] id : dataItemIds) {
|
||||
find.setBytes(1, id);
|
||||
try (ResultSet rs = find.executeQuery()) {
|
||||
if (rs.next()) sessions.add(rs.getLong(1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_candidate_blocks
|
||||
SET arweave_publish_pending = FALSE,
|
||||
arweave_published_at_ms = COALESCE(arweave_published_at_ms, ?)
|
||||
WHERE data_item_id = ?
|
||||
""")) {
|
||||
for (byte[] id : dataItemIds) {
|
||||
ps.setLong(1, publishedAtMs);
|
||||
ps.setBytes(2, id);
|
||||
ps.addBatch();
|
||||
}
|
||||
ps.executeBatch();
|
||||
}
|
||||
|
||||
try (PreparedStatement progress = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions s
|
||||
SET progress_current = LEAST(s.progress_total, (
|
||||
SELECT COUNT(*)::INTEGER
|
||||
FROM key_rotation_candidate_blocks b
|
||||
WHERE b.rotation_session_id = s.id
|
||||
AND b.arweave_publish_pending = FALSE
|
||||
)),
|
||||
updated_at_ms = ?
|
||||
WHERE s.id = ? AND s.status = 'COPYING_CHAIN'
|
||||
""")) {
|
||||
for (Long sessionId : sessions) {
|
||||
progress.setLong(1, publishedAtMs);
|
||||
progress.setLong(2, sessionId);
|
||||
progress.addBatch();
|
||||
}
|
||||
progress.executeBatch();
|
||||
}
|
||||
c.commit();
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to mark candidate DataItems published", e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static KeyRotationCandidateBlockEntry map(ResultSet rs) throws SQLException {
|
||||
KeyRotationCandidateBlockEntry e = new KeyRotationCandidateBlockEntry();
|
||||
e.setId(rs.getLong("id"));
|
||||
e.setRotationSessionId(rs.getLong("rotation_session_id"));
|
||||
e.setLogin(rs.getString("login"));
|
||||
e.setCandidateBlockchainName(rs.getString("candidate_blockchain_name"));
|
||||
e.setBlockNumber(rs.getInt("block_number"));
|
||||
e.setBlockHash(rs.getBytes("block_hash"));
|
||||
e.setDataItemId(rs.getBytes("data_item_id"));
|
||||
e.setBlockBytes(rs.getBytes("block_bytes"));
|
||||
e.setArweavePublishPending(rs.getBoolean("arweave_publish_pending"));
|
||||
e.setArweavePublishedAtMs((Long) rs.getObject("arweave_published_at_ms"));
|
||||
e.setCreatedAtMs(rs.getLong("created_at_ms"));
|
||||
return e;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DbController;
|
||||
import shine.db.entities.KeyRotationSessionEntry;
|
||||
import shine.db.entities.KeyRotationStatus;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
|
||||
/**
|
||||
* DAO для серверной машины смены ключей.
|
||||
*
|
||||
* Все методы изменения статуса синхронно обновляют и key_rotation_sessions,
|
||||
* и solana_user_pda_current.rotation_status / rotation_session_id.
|
||||
*/
|
||||
public final class KeyRotationSessionsDAO {
|
||||
|
||||
private static volatile KeyRotationSessionsDAO instance;
|
||||
private final DbController db = DbController.getInstance();
|
||||
|
||||
private KeyRotationSessionsDAO() { }
|
||||
|
||||
public static KeyRotationSessionsDAO getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (KeyRotationSessionsDAO.class) {
|
||||
if (instance == null) instance = new KeyRotationSessionsDAO();
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Атомарно создаёт первую серверную запись ротации сразу в COPYING_CHAIN.
|
||||
* PREPARING в БД отсутствует: до этого момента всё является локальным UI-состоянием.
|
||||
*/
|
||||
public KeyRotationSessionEntry createCopyingSession(KeyRotationSessionEntry entry) throws SQLException {
|
||||
validateNewSession(entry);
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
KeyRotationSessionEntry created = createCopyingSession(c, entry);
|
||||
c.commit();
|
||||
return created;
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to create key rotation session", e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public KeyRotationSessionEntry createCopyingSession(Connection c, KeyRotationSessionEntry entry) throws SQLException {
|
||||
validateNewSession(entry);
|
||||
|
||||
String currentStatus;
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT rotation_status
|
||||
FROM solana_user_pda_current
|
||||
WHERE login = ?
|
||||
FOR UPDATE
|
||||
""")) {
|
||||
ps.setString(1, entry.getLogin());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) throw new SQLException("Unknown login for key rotation: " + entry.getLogin());
|
||||
currentStatus = rs.getString(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!KeyRotationStatus.NONE.name().equals(currentStatus)) {
|
||||
throw new SQLException("Key rotation already active for login=" + entry.getLogin() + ", status=" + currentStatus);
|
||||
}
|
||||
|
||||
long now = entry.getCreatedAtMs() > 0 ? entry.getCreatedAtMs() : System.currentTimeMillis();
|
||||
entry.setCreatedAtMs(now);
|
||||
entry.setUpdatedAtMs(now);
|
||||
entry.setStatus(KeyRotationStatus.COPYING_CHAIN);
|
||||
if (entry.getComment() == null) entry.setComment("");
|
||||
if (entry.getWalletMigrationStatus() == null) entry.setWalletMigrationStatus("PENDING");
|
||||
if (entry.getMessageMigrationStatus() == null) entry.setMessageMigrationStatus("PENDING");
|
||||
|
||||
String sql = """
|
||||
INSERT INTO key_rotation_sessions (
|
||||
login, status,
|
||||
source_blockchain_name, candidate_blockchain_name,
|
||||
old_root_key, old_blockchain_key, old_client_key,
|
||||
new_root_key, new_blockchain_key, new_client_key,
|
||||
fork_from_block, fork_from_hash,
|
||||
source_tip_block, source_tip_hash,
|
||||
reason_code, comment,
|
||||
progress_current, progress_total,
|
||||
pda_rotation_signature,
|
||||
wallet_migration_status, message_migration_status,
|
||||
last_error, last_error_at_ms, retry_count,
|
||||
created_at_ms, updated_at_ms, completed_at_ms, aborted_at_ms
|
||||
) VALUES (
|
||||
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
|
||||
)
|
||||
""";
|
||||
|
||||
long id;
|
||||
try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
|
||||
int i = 1;
|
||||
ps.setString(i++, entry.getLogin());
|
||||
ps.setString(i++, entry.getStatus().name());
|
||||
ps.setString(i++, entry.getSourceBlockchainName());
|
||||
ps.setString(i++, entry.getCandidateBlockchainName());
|
||||
ps.setString(i++, entry.getOldRootKey());
|
||||
ps.setString(i++, entry.getOldBlockchainKey());
|
||||
ps.setString(i++, entry.getOldClientKey());
|
||||
ps.setString(i++, entry.getNewRootKey());
|
||||
ps.setString(i++, entry.getNewBlockchainKey());
|
||||
ps.setString(i++, entry.getNewClientKey());
|
||||
ps.setInt(i++, entry.getForkFromBlock());
|
||||
ps.setBytes(i++, entry.getForkFromHash());
|
||||
ps.setInt(i++, entry.getSourceTipBlock());
|
||||
ps.setBytes(i++, entry.getSourceTipHash());
|
||||
ps.setShort(i++, entry.getReasonCode());
|
||||
ps.setString(i++, entry.getComment());
|
||||
ps.setInt(i++, entry.getProgressCurrent());
|
||||
ps.setInt(i++, entry.getProgressTotal());
|
||||
ps.setString(i++, entry.getPdaRotationSignature());
|
||||
ps.setString(i++, entry.getWalletMigrationStatus());
|
||||
ps.setString(i++, entry.getMessageMigrationStatus());
|
||||
ps.setString(i++, entry.getLastError());
|
||||
if (entry.getLastErrorAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getLastErrorAtMs());
|
||||
ps.setInt(i++, entry.getRetryCount());
|
||||
ps.setLong(i++, entry.getCreatedAtMs());
|
||||
ps.setLong(i++, entry.getUpdatedAtMs());
|
||||
if (entry.getCompletedAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getCompletedAtMs());
|
||||
if (entry.getAbortedAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getAbortedAtMs());
|
||||
ps.executeUpdate();
|
||||
try (ResultSet keys = ps.getGeneratedKeys()) {
|
||||
if (!keys.next()) throw new SQLException("key_rotation_sessions insert returned no id");
|
||||
id = keys.getLong(1);
|
||||
}
|
||||
}
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE solana_user_pda_current
|
||||
SET rotation_status = ?, rotation_session_id = ?
|
||||
WHERE login = ? AND rotation_status = 'NONE'
|
||||
""")) {
|
||||
ps.setString(1, KeyRotationStatus.COPYING_CHAIN.name());
|
||||
ps.setLong(2, id);
|
||||
ps.setString(3, entry.getLogin());
|
||||
if (ps.executeUpdate() != 1) {
|
||||
throw new SQLException("Failed to attach key rotation session to login=" + entry.getLogin());
|
||||
}
|
||||
}
|
||||
|
||||
entry.setId(id);
|
||||
return entry;
|
||||
}
|
||||
|
||||
public KeyRotationSessionEntry getById(long id) throws SQLException {
|
||||
try (Connection c = db.getConnection()) {
|
||||
return getById(c, id);
|
||||
}
|
||||
}
|
||||
|
||||
public KeyRotationSessionEntry getById(Connection c, long id) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement(selectBase() + " WHERE id = ?")) {
|
||||
ps.setLong(1, id);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public KeyRotationSessionEntry getActiveByLogin(String login) throws SQLException {
|
||||
try (Connection c = db.getConnection()) {
|
||||
return getActiveByLogin(c, login);
|
||||
}
|
||||
}
|
||||
|
||||
public KeyRotationSessionEntry getActiveByLogin(Connection c, String login) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement(selectBase() + """
|
||||
WHERE login = ?
|
||||
AND status NOT IN ('COMPLETE', 'ABORTED')
|
||||
ORDER BY id DESC
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Возвращает несколько сессий одного состояния для фоновых workers. */
|
||||
public java.util.List<KeyRotationSessionEntry> listByStatus(KeyRotationStatus status, int limit) throws SQLException {
|
||||
if (status == null || status == KeyRotationStatus.NONE) return java.util.List.of();
|
||||
int safeLimit = Math.max(1, Math.min(limit, 100));
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(selectBase() + """
|
||||
WHERE status = ?
|
||||
ORDER BY updated_at_ms, id
|
||||
LIMIT ?
|
||||
""")) {
|
||||
ps.setString(1, status.name());
|
||||
ps.setInt(2, safeLimit);
|
||||
java.util.List<KeyRotationSessionEntry> out = new java.util.ArrayList<>();
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) out.add(mapRow(rs));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Атомарный переход state machine. Смена статуса выполняется только из expected.
|
||||
*/
|
||||
public KeyRotationSessionEntry transition(long id,
|
||||
KeyRotationStatus expected,
|
||||
KeyRotationStatus next) throws SQLException {
|
||||
if (expected == null || next == null || !expected.canTransitionTo(next)) {
|
||||
throw new IllegalArgumentException("Forbidden key rotation transition: " + expected + " -> " + next);
|
||||
}
|
||||
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
|
||||
if (current == null) throw new SQLException("Unknown key rotation session id=" + id);
|
||||
if (current.getStatus() != expected) {
|
||||
throw new SQLException("Key rotation status mismatch: expected=" + expected + ", actual=" + current.getStatus());
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
Long completed = next == KeyRotationStatus.COMPLETE ? now : current.getCompletedAtMs();
|
||||
Long aborted = next == KeyRotationStatus.ABORTED ? now : current.getAbortedAtMs();
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET status = ?, updated_at_ms = ?, completed_at_ms = ?, aborted_at_ms = ?
|
||||
WHERE id = ? AND status = ?
|
||||
""")) {
|
||||
ps.setString(1, next.name());
|
||||
ps.setLong(2, now);
|
||||
if (completed == null) ps.setNull(3, java.sql.Types.BIGINT); else ps.setLong(3, completed);
|
||||
if (aborted == null) ps.setNull(4, java.sql.Types.BIGINT); else ps.setLong(4, aborted);
|
||||
ps.setLong(5, id);
|
||||
ps.setString(6, expected.name());
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent key rotation transition for id=" + id);
|
||||
}
|
||||
|
||||
KeyRotationStatus userStatus = next.userStatus();
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE solana_user_pda_current
|
||||
SET rotation_status = ?, rotation_session_id = ?
|
||||
WHERE login = ? AND rotation_session_id = ?
|
||||
""")) {
|
||||
ps.setString(1, userStatus.name());
|
||||
if (userStatus == KeyRotationStatus.NONE) ps.setNull(2, java.sql.Types.BIGINT); else ps.setLong(2, id);
|
||||
ps.setString(3, current.getLogin());
|
||||
ps.setLong(4, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to login=" + current.getLogin());
|
||||
}
|
||||
|
||||
// Candidate-копии нужны только пока ротация активна. В Arweave они уже опубликованы,
|
||||
// а в PostgreSQL после COMPLETE/ABORTED временные строки больше не нужны.
|
||||
if (next.isTerminalSessionStatus()) {
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"DELETE FROM key_rotation_candidate_blocks WHERE rotation_session_id = ?")) {
|
||||
ps.setLong(1, id);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
c.commit();
|
||||
current.setStatus(next);
|
||||
current.setUpdatedAtMs(now);
|
||||
current.setCompletedAtMs(completed);
|
||||
current.setAbortedAtMs(aborted);
|
||||
return current;
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed key rotation transition", e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void updateProgress(long id, int current, int total) throws SQLException {
|
||||
if (current < 0 || total < 0 || current > total) {
|
||||
throw new IllegalArgumentException("Invalid rotation progress: " + current + "/" + total);
|
||||
}
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET progress_current = ?, progress_total = ?, updated_at_ms = ?
|
||||
WHERE id = ? AND status = 'COPYING_CHAIN'
|
||||
""")) {
|
||||
ps.setInt(1, current);
|
||||
ps.setInt(2, total);
|
||||
ps.setLong(3, System.currentTimeMillis());
|
||||
ps.setLong(4, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Rotation progress can only be updated in COPYING_CHAIN, id=" + id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Атомарно фиксирует tx signature и переводит CHAIN_READY -> ROTATING_PDA.
|
||||
* Это точка, после которой Abort запрещён: отправленная Solana-транзакция может подтвердиться позже.
|
||||
*/
|
||||
public KeyRotationSessionEntry beginPdaRotation(long id, String signature) throws SQLException {
|
||||
if (signature == null || signature.isBlank()) throw new IllegalArgumentException("signature is empty");
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
|
||||
if (current == null) throw new SQLException("Unknown key rotation session id=" + id);
|
||||
if (current.getStatus() != KeyRotationStatus.CHAIN_READY) {
|
||||
throw new SQLException("PDA rotation requires CHAIN_READY, actual=" + current.getStatus());
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET status = 'ROTATING_PDA', pda_rotation_signature = ?, updated_at_ms = ?,
|
||||
last_error = NULL, last_error_at_ms = NULL
|
||||
WHERE id = ? AND status = 'CHAIN_READY'
|
||||
""")) {
|
||||
ps.setString(1, signature);
|
||||
ps.setLong(2, now);
|
||||
ps.setLong(3, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent PDA rotation start for id=" + id);
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE solana_user_pda_current
|
||||
SET rotation_status = 'ROTATING_PDA', rotation_session_id = ?
|
||||
WHERE login = ? AND rotation_session_id = ? AND rotation_status = 'CHAIN_READY'
|
||||
""")) {
|
||||
ps.setLong(1, id);
|
||||
ps.setString(2, current.getLogin());
|
||||
ps.setLong(3, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to login=" + current.getLogin());
|
||||
}
|
||||
c.commit();
|
||||
current.setStatus(KeyRotationStatus.ROTATING_PDA);
|
||||
current.setPdaRotationSignature(signature);
|
||||
current.setUpdatedAtMs(now);
|
||||
current.setLastError(null);
|
||||
current.setLastErrorAtMs(null);
|
||||
return current;
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to begin PDA rotation", e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Если Solana sync уже записал в current-PDA весь ожидаемый новый набор ключей,
|
||||
* атомарно переводит ROTATING_PDA -> PDA_ROTATED. Иначе возвращает null.
|
||||
*/
|
||||
public KeyRotationSessionEntry tryMarkPdaRotatedFromCurrentState(long id) throws SQLException {
|
||||
try (Connection c = db.getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
|
||||
if (current == null || current.getStatus() != KeyRotationStatus.ROTATING_PDA) {
|
||||
c.rollback();
|
||||
return current != null && current.getStatus() == KeyRotationStatus.PDA_ROTATED ? current : null;
|
||||
}
|
||||
|
||||
String root;
|
||||
String blockchain;
|
||||
String client;
|
||||
String blockchainName;
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT root_key, blockchain_key, client_key, blockchain_name
|
||||
FROM solana_user_pda_current
|
||||
WHERE login = ?
|
||||
FOR UPDATE
|
||||
""")) {
|
||||
ps.setString(1, current.getLogin());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) { c.rollback(); return null; }
|
||||
root = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("root_key"));
|
||||
blockchain = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("blockchain_key"));
|
||||
client = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("client_key"));
|
||||
blockchainName = rs.getString("blockchain_name");
|
||||
}
|
||||
}
|
||||
|
||||
if (!current.getNewRootKey().equals(root)
|
||||
|| !current.getNewBlockchainKey().equals(blockchain)
|
||||
|| !current.getNewClientKey().equals(client)
|
||||
|| !current.getCandidateBlockchainName().equals(blockchainName)) {
|
||||
c.rollback();
|
||||
return null;
|
||||
}
|
||||
|
||||
long now = System.currentTimeMillis();
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET status = 'PDA_ROTATED', updated_at_ms = ?, last_error = NULL, last_error_at_ms = NULL
|
||||
WHERE id = ? AND status = 'ROTATING_PDA'
|
||||
""")) {
|
||||
ps.setLong(1, now);
|
||||
ps.setLong(2, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent PDA rotation confirm for id=" + id);
|
||||
}
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE solana_user_pda_current
|
||||
SET rotation_status = 'PDA_ROTATED', rotation_session_id = ?
|
||||
WHERE login = ? AND rotation_session_id = ? AND rotation_status = 'ROTATING_PDA'
|
||||
""")) {
|
||||
ps.setLong(1, id);
|
||||
ps.setString(2, current.getLogin());
|
||||
ps.setLong(3, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to current PDA login=" + current.getLogin());
|
||||
}
|
||||
c.commit();
|
||||
current.setStatus(KeyRotationStatus.PDA_ROTATED);
|
||||
current.setUpdatedAtMs(now);
|
||||
current.setLastError(null);
|
||||
current.setLastErrorAtMs(null);
|
||||
return current;
|
||||
} catch (Exception e) {
|
||||
c.rollback();
|
||||
if (e instanceof SQLException sql) throw sql;
|
||||
throw new SQLException("Failed to confirm rotated PDA", e);
|
||||
} finally {
|
||||
c.setAutoCommit(oldAutoCommit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void setPdaRotationSignature(long id, String signature) throws SQLException {
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET pda_rotation_signature = ?, updated_at_ms = ?
|
||||
WHERE id = ? AND status = 'ROTATING_PDA'
|
||||
""")) {
|
||||
ps.setString(1, signature);
|
||||
ps.setLong(2, System.currentTimeMillis());
|
||||
ps.setLong(3, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("PDA signature requires ROTATING_PDA, id=" + id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Фиксирует результат необязательного этапа wallet/DM.
|
||||
* Имя колонки выбирается только из закрытого списка — внешние значения в SQL не подставляются.
|
||||
*/
|
||||
public void setMigrationSubStatus(long id, String column, String value) throws SQLException {
|
||||
String safeColumn = switch (String.valueOf(column)) {
|
||||
case "wallet_migration_status" -> "wallet_migration_status";
|
||||
case "message_migration_status" -> "message_migration_status";
|
||||
default -> throw new IllegalArgumentException("Unsupported migration status column: " + column);
|
||||
};
|
||||
String safeValue = switch (String.valueOf(value)) {
|
||||
case "PENDING", "COMPLETE", "SKIPPED", "NOT_IMPLEMENTED" -> String.valueOf(value);
|
||||
default -> throw new IllegalArgumentException("Unsupported migration status value: " + value);
|
||||
};
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"UPDATE key_rotation_sessions SET " + safeColumn + " = ?, updated_at_ms = ? WHERE id = ?")) {
|
||||
ps.setString(1, safeValue);
|
||||
ps.setLong(2, System.currentTimeMillis());
|
||||
ps.setLong(3, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Unknown key rotation session id=" + id);
|
||||
}
|
||||
}
|
||||
|
||||
public void recordError(long id, String error) throws SQLException {
|
||||
long now = System.currentTimeMillis();
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET last_error = ?, last_error_at_ms = ?, retry_count = retry_count + 1, updated_at_ms = ?
|
||||
WHERE id = ? AND status NOT IN ('COMPLETE', 'ABORTED')
|
||||
""")) {
|
||||
ps.setString(1, error);
|
||||
ps.setLong(2, now);
|
||||
ps.setLong(3, now);
|
||||
ps.setLong(4, id);
|
||||
if (ps.executeUpdate() != 1) throw new SQLException("Cannot record error for inactive rotation id=" + id);
|
||||
}
|
||||
}
|
||||
|
||||
public void clearError(long id) throws SQLException {
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE key_rotation_sessions
|
||||
SET last_error = NULL, last_error_at_ms = NULL, updated_at_ms = ?
|
||||
WHERE id = ?
|
||||
""")) {
|
||||
ps.setLong(1, System.currentTimeMillis());
|
||||
ps.setLong(2, id);
|
||||
ps.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
private KeyRotationSessionEntry getByIdForUpdate(Connection c, long id) throws SQLException {
|
||||
try (PreparedStatement ps = c.prepareStatement(selectBase() + " WHERE id = ? FOR UPDATE")) {
|
||||
ps.setLong(1, id);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? mapRow(rs) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static String selectBase() {
|
||||
return """
|
||||
SELECT
|
||||
id, login, status,
|
||||
source_blockchain_name, candidate_blockchain_name,
|
||||
old_root_key, old_blockchain_key, old_client_key,
|
||||
new_root_key, new_blockchain_key, new_client_key,
|
||||
fork_from_block, fork_from_hash,
|
||||
source_tip_block, source_tip_hash,
|
||||
reason_code, comment,
|
||||
progress_current, progress_total,
|
||||
pda_rotation_signature,
|
||||
wallet_migration_status, message_migration_status,
|
||||
last_error, last_error_at_ms, retry_count,
|
||||
created_at_ms, updated_at_ms, completed_at_ms, aborted_at_ms
|
||||
FROM key_rotation_sessions
|
||||
""";
|
||||
}
|
||||
|
||||
private static KeyRotationSessionEntry mapRow(ResultSet rs) throws SQLException {
|
||||
KeyRotationSessionEntry e = new KeyRotationSessionEntry();
|
||||
e.setId(rs.getLong("id"));
|
||||
e.setLogin(rs.getString("login"));
|
||||
e.setStatus(KeyRotationStatus.valueOf(rs.getString("status")));
|
||||
e.setSourceBlockchainName(rs.getString("source_blockchain_name"));
|
||||
e.setCandidateBlockchainName(rs.getString("candidate_blockchain_name"));
|
||||
e.setOldRootKey(rs.getString("old_root_key"));
|
||||
e.setOldBlockchainKey(rs.getString("old_blockchain_key"));
|
||||
e.setOldClientKey(rs.getString("old_client_key"));
|
||||
e.setNewRootKey(rs.getString("new_root_key"));
|
||||
e.setNewBlockchainKey(rs.getString("new_blockchain_key"));
|
||||
e.setNewClientKey(rs.getString("new_client_key"));
|
||||
e.setForkFromBlock(rs.getInt("fork_from_block"));
|
||||
e.setForkFromHash(rs.getBytes("fork_from_hash"));
|
||||
e.setSourceTipBlock(rs.getInt("source_tip_block"));
|
||||
e.setSourceTipHash(rs.getBytes("source_tip_hash"));
|
||||
e.setReasonCode(rs.getShort("reason_code"));
|
||||
e.setComment(rs.getString("comment"));
|
||||
e.setProgressCurrent(rs.getInt("progress_current"));
|
||||
e.setProgressTotal(rs.getInt("progress_total"));
|
||||
e.setPdaRotationSignature(rs.getString("pda_rotation_signature"));
|
||||
e.setWalletMigrationStatus(rs.getString("wallet_migration_status"));
|
||||
e.setMessageMigrationStatus(rs.getString("message_migration_status"));
|
||||
e.setLastError(rs.getString("last_error"));
|
||||
long lastErrorAt = rs.getLong("last_error_at_ms");
|
||||
e.setLastErrorAtMs(rs.wasNull() ? null : lastErrorAt);
|
||||
e.setRetryCount(rs.getInt("retry_count"));
|
||||
e.setCreatedAtMs(rs.getLong("created_at_ms"));
|
||||
e.setUpdatedAtMs(rs.getLong("updated_at_ms"));
|
||||
long completed = rs.getLong("completed_at_ms");
|
||||
e.setCompletedAtMs(rs.wasNull() ? null : completed);
|
||||
long aborted = rs.getLong("aborted_at_ms");
|
||||
e.setAbortedAtMs(rs.wasNull() ? null : aborted);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static void validateNewSession(KeyRotationSessionEntry e) {
|
||||
if (e == null) throw new IllegalArgumentException("entry is null");
|
||||
if (blank(e.getLogin())) throw new IllegalArgumentException("login is required");
|
||||
if (blank(e.getSourceBlockchainName()) || blank(e.getCandidateBlockchainName())) {
|
||||
throw new IllegalArgumentException("source/candidate blockchain names are required");
|
||||
}
|
||||
if (blank(e.getOldRootKey()) || blank(e.getOldBlockchainKey()) || blank(e.getOldClientKey())
|
||||
|| blank(e.getNewRootKey()) || blank(e.getNewBlockchainKey()) || blank(e.getNewClientKey())) {
|
||||
throw new IllegalArgumentException("all old/new public keys are required");
|
||||
}
|
||||
if (e.getForkFromHash() == null || e.getForkFromHash().length != 32) {
|
||||
throw new IllegalArgumentException("forkFromHash must be 32 bytes");
|
||||
}
|
||||
if (e.getSourceTipHash() == null || e.getSourceTipHash().length != 32) {
|
||||
throw new IllegalArgumentException("sourceTipHash must be 32 bytes");
|
||||
}
|
||||
if (e.getForkFromBlock() < 0 || e.getSourceTipBlock() < e.getForkFromBlock()) {
|
||||
throw new IllegalArgumentException("invalid fork/source tip block numbers");
|
||||
}
|
||||
if (e.getReasonCode() < 1 || e.getReasonCode() > 4) {
|
||||
throw new IllegalArgumentException("reasonCode must be 1..4");
|
||||
}
|
||||
String comment = e.getComment() == null ? "" : e.getComment();
|
||||
if (comment.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1024) {
|
||||
throw new IllegalArgumentException("comment must be <= 1024 UTF-8 bytes");
|
||||
}
|
||||
if (e.getProgressCurrent() < 0 || e.getProgressTotal() < e.getProgressCurrent()) {
|
||||
throw new IllegalArgumentException("invalid initial progress");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean blank(String value) {
|
||||
return value == null || value.isBlank();
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,27 @@ public final class SolanaUserPdaCurrentDAO {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public SolanaUserPdaCurrentEntry getByLogin(String login) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
login,
|
||||
blockchain_name,
|
||||
blockchain_key,
|
||||
paid_limit_bytes
|
||||
FROM solana_user_pda_current
|
||||
WHERE LOWER(login) = LOWER(?)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, login);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
return mapRow(rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public SolanaUserPdaCurrentEntry getByBlockchainName(Connection c, String blockchainName) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package shine.db.entities;
|
||||
|
||||
/**
|
||||
* Candidate-блок будущего fork во время смены ключей.
|
||||
*
|
||||
* Эти записи намеренно не попадают в обычную таблицу blocks и поэтому
|
||||
* не влияют на лайки, ответы, каналы и другие materialized state до
|
||||
* финального переключения активного fork.
|
||||
*/
|
||||
public final class KeyRotationCandidateBlockEntry {
|
||||
private long id;
|
||||
private long rotationSessionId;
|
||||
private String login;
|
||||
private String candidateBlockchainName;
|
||||
private int blockNumber;
|
||||
private byte[] blockHash;
|
||||
private byte[] dataItemId;
|
||||
private byte[] blockBytes;
|
||||
private boolean arweavePublishPending;
|
||||
private Long arweavePublishedAtMs;
|
||||
private long createdAtMs;
|
||||
|
||||
public long getId() { return id; }
|
||||
public void setId(long id) { this.id = id; }
|
||||
public long getRotationSessionId() { return rotationSessionId; }
|
||||
public void setRotationSessionId(long rotationSessionId) { this.rotationSessionId = rotationSessionId; }
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
public String getCandidateBlockchainName() { return candidateBlockchainName; }
|
||||
public void setCandidateBlockchainName(String candidateBlockchainName) { this.candidateBlockchainName = candidateBlockchainName; }
|
||||
public int getBlockNumber() { return blockNumber; }
|
||||
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
|
||||
public byte[] getBlockHash() { return blockHash; }
|
||||
public void setBlockHash(byte[] blockHash) { this.blockHash = blockHash; }
|
||||
public byte[] getDataItemId() { return dataItemId; }
|
||||
public void setDataItemId(byte[] dataItemId) { this.dataItemId = dataItemId; }
|
||||
public byte[] getBlockBytes() { return blockBytes; }
|
||||
public void setBlockBytes(byte[] blockBytes) { this.blockBytes = blockBytes; }
|
||||
public boolean isArweavePublishPending() { return arweavePublishPending; }
|
||||
public void setArweavePublishPending(boolean arweavePublishPending) { this.arweavePublishPending = arweavePublishPending; }
|
||||
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
|
||||
public void setArweavePublishedAtMs(Long arweavePublishedAtMs) { this.arweavePublishedAtMs = arweavePublishedAtMs; }
|
||||
public long getCreatedAtMs() { return createdAtMs; }
|
||||
public void setCreatedAtMs(long createdAtMs) { this.createdAtMs = createdAtMs; }
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package shine.db.entities;
|
||||
|
||||
/**
|
||||
* Публичное/runtime-состояние одной смены ключей.
|
||||
* Приватные ключи и пароли в этой сущности не хранятся никогда.
|
||||
*/
|
||||
public final class KeyRotationSessionEntry {
|
||||
private long id;
|
||||
private String login;
|
||||
private KeyRotationStatus status;
|
||||
private String sourceBlockchainName;
|
||||
private String candidateBlockchainName;
|
||||
private String oldRootKey;
|
||||
private String oldBlockchainKey;
|
||||
private String oldClientKey;
|
||||
private String newRootKey;
|
||||
private String newBlockchainKey;
|
||||
private String newClientKey;
|
||||
private int forkFromBlock;
|
||||
private byte[] forkFromHash;
|
||||
private int sourceTipBlock;
|
||||
private byte[] sourceTipHash;
|
||||
private short reasonCode;
|
||||
private String comment;
|
||||
private int progressCurrent;
|
||||
private int progressTotal;
|
||||
private String pdaRotationSignature;
|
||||
private String walletMigrationStatus;
|
||||
private String messageMigrationStatus;
|
||||
private String lastError;
|
||||
private Long lastErrorAtMs;
|
||||
private int retryCount;
|
||||
private long createdAtMs;
|
||||
private long updatedAtMs;
|
||||
private Long completedAtMs;
|
||||
private Long abortedAtMs;
|
||||
|
||||
public long getId() { return id; }
|
||||
public void setId(long id) { this.id = id; }
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String login) { this.login = login; }
|
||||
public KeyRotationStatus getStatus() { return status; }
|
||||
public void setStatus(KeyRotationStatus status) { this.status = status; }
|
||||
public String getSourceBlockchainName() { return sourceBlockchainName; }
|
||||
public void setSourceBlockchainName(String sourceBlockchainName) { this.sourceBlockchainName = sourceBlockchainName; }
|
||||
public String getCandidateBlockchainName() { return candidateBlockchainName; }
|
||||
public void setCandidateBlockchainName(String candidateBlockchainName) { this.candidateBlockchainName = candidateBlockchainName; }
|
||||
public String getOldRootKey() { return oldRootKey; }
|
||||
public void setOldRootKey(String oldRootKey) { this.oldRootKey = oldRootKey; }
|
||||
public String getOldBlockchainKey() { return oldBlockchainKey; }
|
||||
public void setOldBlockchainKey(String oldBlockchainKey) { this.oldBlockchainKey = oldBlockchainKey; }
|
||||
public String getOldClientKey() { return oldClientKey; }
|
||||
public void setOldClientKey(String oldClientKey) { this.oldClientKey = oldClientKey; }
|
||||
public String getNewRootKey() { return newRootKey; }
|
||||
public void setNewRootKey(String newRootKey) { this.newRootKey = newRootKey; }
|
||||
public String getNewBlockchainKey() { return newBlockchainKey; }
|
||||
public void setNewBlockchainKey(String newBlockchainKey) { this.newBlockchainKey = newBlockchainKey; }
|
||||
public String getNewClientKey() { return newClientKey; }
|
||||
public void setNewClientKey(String newClientKey) { this.newClientKey = newClientKey; }
|
||||
public int getForkFromBlock() { return forkFromBlock; }
|
||||
public void setForkFromBlock(int forkFromBlock) { this.forkFromBlock = forkFromBlock; }
|
||||
public byte[] getForkFromHash() { return forkFromHash; }
|
||||
public void setForkFromHash(byte[] forkFromHash) { this.forkFromHash = forkFromHash; }
|
||||
public int getSourceTipBlock() { return sourceTipBlock; }
|
||||
public void setSourceTipBlock(int sourceTipBlock) { this.sourceTipBlock = sourceTipBlock; }
|
||||
public byte[] getSourceTipHash() { return sourceTipHash; }
|
||||
public void setSourceTipHash(byte[] sourceTipHash) { this.sourceTipHash = sourceTipHash; }
|
||||
public short getReasonCode() { return reasonCode; }
|
||||
public void setReasonCode(short reasonCode) { this.reasonCode = reasonCode; }
|
||||
public String getComment() { return comment; }
|
||||
public void setComment(String comment) { this.comment = comment; }
|
||||
public int getProgressCurrent() { return progressCurrent; }
|
||||
public void setProgressCurrent(int progressCurrent) { this.progressCurrent = progressCurrent; }
|
||||
public int getProgressTotal() { return progressTotal; }
|
||||
public void setProgressTotal(int progressTotal) { this.progressTotal = progressTotal; }
|
||||
public String getPdaRotationSignature() { return pdaRotationSignature; }
|
||||
public void setPdaRotationSignature(String pdaRotationSignature) { this.pdaRotationSignature = pdaRotationSignature; }
|
||||
public String getWalletMigrationStatus() { return walletMigrationStatus; }
|
||||
public void setWalletMigrationStatus(String walletMigrationStatus) { this.walletMigrationStatus = walletMigrationStatus; }
|
||||
public String getMessageMigrationStatus() { return messageMigrationStatus; }
|
||||
public void setMessageMigrationStatus(String messageMigrationStatus) { this.messageMigrationStatus = messageMigrationStatus; }
|
||||
public String getLastError() { return lastError; }
|
||||
public void setLastError(String lastError) { this.lastError = lastError; }
|
||||
public Long getLastErrorAtMs() { return lastErrorAtMs; }
|
||||
public void setLastErrorAtMs(Long lastErrorAtMs) { this.lastErrorAtMs = lastErrorAtMs; }
|
||||
public int getRetryCount() { return retryCount; }
|
||||
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
|
||||
public long getCreatedAtMs() { return createdAtMs; }
|
||||
public void setCreatedAtMs(long createdAtMs) { this.createdAtMs = createdAtMs; }
|
||||
public long getUpdatedAtMs() { return updatedAtMs; }
|
||||
public void setUpdatedAtMs(long updatedAtMs) { this.updatedAtMs = updatedAtMs; }
|
||||
public Long getCompletedAtMs() { return completedAtMs; }
|
||||
public void setCompletedAtMs(Long completedAtMs) { this.completedAtMs = completedAtMs; }
|
||||
public Long getAbortedAtMs() { return abortedAtMs; }
|
||||
public void setAbortedAtMs(Long abortedAtMs) { this.abortedAtMs = abortedAtMs; }
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package shine.db.entities;
|
||||
|
||||
import java.util.EnumSet;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Состояния серверной машины смены ключей.
|
||||
*
|
||||
* NONE используется только в solana_user_pda_current.rotation_status.
|
||||
* COMPLETE/ABORTED остаются в истории key_rotation_sessions, после чего
|
||||
* пользователь снова получает rotation_status=NONE.
|
||||
*/
|
||||
public enum KeyRotationStatus {
|
||||
NONE,
|
||||
COPYING_CHAIN,
|
||||
CHAIN_READY,
|
||||
ROTATING_PDA,
|
||||
PDA_ROTATED,
|
||||
REBUILDING_SERVER,
|
||||
WALLET_MIGRATION,
|
||||
MESSAGE_MIGRATION,
|
||||
FINALIZING,
|
||||
COMPLETE,
|
||||
ABORTED;
|
||||
|
||||
public boolean isTerminalSessionStatus() {
|
||||
return this == COMPLETE || this == ABORTED;
|
||||
}
|
||||
|
||||
public boolean isUserActiveStatus() {
|
||||
return this != NONE && !isTerminalSessionStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* Допустимые переходы одной ротации.
|
||||
* Abort сознательно разрешён только до начала ROTATING_PDA: после отправки
|
||||
* Solana-транзакции нельзя надёжно знать, не будет ли она подтверждена позже.
|
||||
*/
|
||||
public boolean canTransitionTo(KeyRotationStatus next) {
|
||||
if (next == null) return false;
|
||||
return switch (this) {
|
||||
case COPYING_CHAIN -> EnumSet.of(CHAIN_READY, ABORTED).contains(next);
|
||||
case CHAIN_READY -> EnumSet.of(ROTATING_PDA, ABORTED).contains(next);
|
||||
case ROTATING_PDA -> next == PDA_ROTATED;
|
||||
case PDA_ROTATED -> next == REBUILDING_SERVER;
|
||||
case REBUILDING_SERVER -> next == WALLET_MIGRATION;
|
||||
case WALLET_MIGRATION -> next == MESSAGE_MIGRATION;
|
||||
case MESSAGE_MIGRATION -> next == FINALIZING;
|
||||
case FINALIZING -> next == COMPLETE;
|
||||
case NONE, COMPLETE, ABORTED -> false;
|
||||
};
|
||||
}
|
||||
|
||||
public static Set<KeyRotationStatus> activeStatuses() {
|
||||
return EnumSet.of(
|
||||
COPYING_CHAIN,
|
||||
CHAIN_READY,
|
||||
ROTATING_PDA,
|
||||
PDA_ROTATED,
|
||||
REBUILDING_SERVER,
|
||||
WALLET_MIGRATION,
|
||||
MESSAGE_MIGRATION,
|
||||
FINALIZING
|
||||
);
|
||||
}
|
||||
|
||||
/** Статус, который должен храниться у пользователя для данной session-state. */
|
||||
public KeyRotationStatus userStatus() {
|
||||
return isTerminalSessionStatus() ? NONE : this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
-- v26: серверная state machine смены ключей пользователя.
|
||||
--
|
||||
-- Важно:
|
||||
-- - rotation_status / rotation_session_id являются ЛОКАЛЬНЫМ runtime-состоянием сервера,
|
||||
-- а не полями Solana PDA;
|
||||
-- - Solana sync не должен перезаписывать эти колонки при upsert PDA;
|
||||
-- - приватные ключи здесь никогда не хранятся, только публичные ключи ротации.
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD COLUMN IF NOT EXISTS rotation_status TEXT NOT NULL DEFAULT 'NONE';
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD COLUMN IF NOT EXISTS rotation_session_id BIGINT;
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
DROP CONSTRAINT IF EXISTS chk_solana_user_pda_current_rotation_status;
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD CONSTRAINT chk_solana_user_pda_current_rotation_status CHECK (
|
||||
rotation_status IN (
|
||||
'NONE',
|
||||
'COPYING_CHAIN',
|
||||
'CHAIN_READY',
|
||||
'ROTATING_PDA',
|
||||
'PDA_ROTATED',
|
||||
'REBUILDING_SERVER',
|
||||
'WALLET_MIGRATION',
|
||||
'MESSAGE_MIGRATION',
|
||||
'FINALIZING'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_rotation_active
|
||||
ON solana_user_pda_current(rotation_status)
|
||||
WHERE rotation_status <> 'NONE';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS key_rotation_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL CHECK (
|
||||
status IN (
|
||||
'COPYING_CHAIN',
|
||||
'CHAIN_READY',
|
||||
'ROTATING_PDA',
|
||||
'PDA_ROTATED',
|
||||
'REBUILDING_SERVER',
|
||||
'WALLET_MIGRATION',
|
||||
'MESSAGE_MIGRATION',
|
||||
'FINALIZING',
|
||||
'COMPLETE',
|
||||
'ABORTED'
|
||||
)
|
||||
),
|
||||
|
||||
source_blockchain_name TEXT NOT NULL,
|
||||
candidate_blockchain_name TEXT NOT NULL,
|
||||
|
||||
old_root_key TEXT NOT NULL,
|
||||
old_blockchain_key TEXT NOT NULL,
|
||||
old_client_key TEXT NOT NULL,
|
||||
new_root_key TEXT NOT NULL,
|
||||
new_blockchain_key TEXT NOT NULL,
|
||||
new_client_key TEXT NOT NULL,
|
||||
|
||||
fork_from_block INTEGER NOT NULL CHECK (fork_from_block >= 0),
|
||||
fork_from_hash BYTEA NOT NULL CHECK (octet_length(fork_from_hash) = 32),
|
||||
source_tip_block INTEGER NOT NULL CHECK (source_tip_block >= 0),
|
||||
source_tip_hash BYTEA NOT NULL CHECK (octet_length(source_tip_hash) = 32),
|
||||
|
||||
reason_code SMALLINT NOT NULL CHECK (reason_code BETWEEN 1 AND 4),
|
||||
comment TEXT NOT NULL DEFAULT '' CHECK (octet_length(convert_to(comment, 'UTF8')) <= 1024),
|
||||
|
||||
progress_current INTEGER NOT NULL DEFAULT 0 CHECK (progress_current >= 0),
|
||||
progress_total INTEGER NOT NULL DEFAULT 0 CHECK (progress_total >= 0),
|
||||
|
||||
pda_rotation_signature TEXT,
|
||||
|
||||
wallet_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
|
||||
wallet_migration_status IN ('PENDING', 'COMPLETE', 'SKIPPED', 'NOT_IMPLEMENTED')
|
||||
),
|
||||
message_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
|
||||
message_migration_status IN ('PENDING', 'COMPLETE', 'SKIPPED', 'NOT_IMPLEMENTED')
|
||||
),
|
||||
|
||||
last_error TEXT,
|
||||
last_error_at_ms BIGINT,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
|
||||
|
||||
created_at_ms BIGINT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL,
|
||||
completed_at_ms BIGINT,
|
||||
aborted_at_ms BIGINT,
|
||||
|
||||
CHECK (progress_current <= progress_total),
|
||||
CHECK (fork_from_block <= source_tip_block)
|
||||
);
|
||||
|
||||
-- У одного login одновременно может существовать только одна незавершённая ротация.
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_key_rotation_sessions_active_login
|
||||
ON key_rotation_sessions(login)
|
||||
WHERE status NOT IN ('COMPLETE', 'ABORTED');
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_login_created
|
||||
ON key_rotation_sessions(login, created_at_ms DESC);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_status
|
||||
ON key_rotation_sessions(status);
|
||||
|
||||
-- Быстрый указатель из текущего пользователя на активную/последнюю runtime-сессию.
|
||||
-- FK добавляется после создания key_rotation_sessions, чтобы не создавать циклический DDL порядок.
|
||||
ALTER TABLE solana_user_pda_current
|
||||
DROP CONSTRAINT IF EXISTS fk_solana_user_pda_current_rotation_session;
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD CONSTRAINT fk_solana_user_pda_current_rotation_session
|
||||
FOREIGN KEY (rotation_session_id)
|
||||
REFERENCES key_rotation_sessions(id)
|
||||
ON DELETE SET NULL;
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version = 26,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
@@ -0,0 +1,31 @@
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS key_rotation_candidate_blocks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE,
|
||||
login TEXT NOT NULL,
|
||||
candidate_blockchain_name TEXT NOT NULL,
|
||||
block_number INTEGER NOT NULL CHECK (block_number >= 0),
|
||||
block_hash BYTEA NOT NULL CHECK (octet_length(block_hash) = 32),
|
||||
data_item_id BYTEA NOT NULL CHECK (octet_length(data_item_id) = 32),
|
||||
block_bytes BYTEA NOT NULL,
|
||||
arweave_publish_pending BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
arweave_published_at_ms BIGINT,
|
||||
created_at_ms BIGINT NOT NULL,
|
||||
UNIQUE (rotation_session_id, block_number),
|
||||
UNIQUE (rotation_session_id, data_item_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_pending
|
||||
ON key_rotation_candidate_blocks(id)
|
||||
WHERE arweave_publish_pending = TRUE;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_session
|
||||
ON key_rotation_candidate_blocks(rotation_session_id, block_number);
|
||||
|
||||
UPDATE db_schema_version
|
||||
SET schema_version = 27,
|
||||
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||
WHERE id = 1;
|
||||
|
||||
COMMIT;
|
||||
@@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS db_schema_version (
|
||||
);
|
||||
|
||||
INSERT INTO db_schema_version (id, schema_version, updated_at_ms)
|
||||
VALUES (1, 24, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
|
||||
VALUES (1, 26, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
schema_version = EXCLUDED.schema_version,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms;
|
||||
@@ -2081,8 +2081,111 @@ CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_archive_pending
|
||||
ON solana_user_pda_current(is_server, archive_imported)
|
||||
WHERE archive_head_tx_id <> '';
|
||||
|
||||
-- Server-local key rotation state machine (schema v26).
|
||||
-- Эти поля не являются частью Solana PDA и не перезаписываются Solana sync upsert-ом.
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD COLUMN IF NOT EXISTS rotation_status TEXT NOT NULL DEFAULT 'NONE';
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD COLUMN IF NOT EXISTS rotation_session_id BIGINT;
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
DROP CONSTRAINT IF EXISTS chk_solana_user_pda_current_rotation_status;
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD CONSTRAINT chk_solana_user_pda_current_rotation_status CHECK (
|
||||
rotation_status IN (
|
||||
'NONE','COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED',
|
||||
'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_rotation_active
|
||||
ON solana_user_pda_current(rotation_status)
|
||||
WHERE rotation_status <> 'NONE';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS key_rotation_sessions (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE,
|
||||
status TEXT NOT NULL CHECK (
|
||||
status IN (
|
||||
'COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED',
|
||||
'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING',
|
||||
'COMPLETE','ABORTED'
|
||||
)
|
||||
),
|
||||
source_blockchain_name TEXT NOT NULL,
|
||||
candidate_blockchain_name TEXT NOT NULL,
|
||||
old_root_key TEXT NOT NULL,
|
||||
old_blockchain_key TEXT NOT NULL,
|
||||
old_client_key TEXT NOT NULL,
|
||||
new_root_key TEXT NOT NULL,
|
||||
new_blockchain_key TEXT NOT NULL,
|
||||
new_client_key TEXT NOT NULL,
|
||||
fork_from_block INTEGER NOT NULL CHECK (fork_from_block >= 0),
|
||||
fork_from_hash BYTEA NOT NULL CHECK (octet_length(fork_from_hash) = 32),
|
||||
source_tip_block INTEGER NOT NULL CHECK (source_tip_block >= 0),
|
||||
source_tip_hash BYTEA NOT NULL CHECK (octet_length(source_tip_hash) = 32),
|
||||
reason_code SMALLINT NOT NULL CHECK (reason_code BETWEEN 1 AND 4),
|
||||
comment TEXT NOT NULL DEFAULT '' CHECK (octet_length(convert_to(comment, 'UTF8')) <= 1024),
|
||||
progress_current INTEGER NOT NULL DEFAULT 0 CHECK (progress_current >= 0),
|
||||
progress_total INTEGER NOT NULL DEFAULT 0 CHECK (progress_total >= 0),
|
||||
pda_rotation_signature TEXT,
|
||||
wallet_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
|
||||
wallet_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED')
|
||||
),
|
||||
message_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
|
||||
message_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED')
|
||||
),
|
||||
last_error TEXT,
|
||||
last_error_at_ms BIGINT,
|
||||
retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
|
||||
created_at_ms BIGINT NOT NULL,
|
||||
updated_at_ms BIGINT NOT NULL,
|
||||
completed_at_ms BIGINT,
|
||||
aborted_at_ms BIGINT,
|
||||
CHECK (progress_current <= progress_total),
|
||||
CHECK (fork_from_block <= source_tip_block)
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS uq_key_rotation_sessions_active_login
|
||||
ON key_rotation_sessions(login)
|
||||
WHERE status NOT IN ('COMPLETE','ABORTED');
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_login_created
|
||||
ON key_rotation_sessions(login, created_at_ms DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_status
|
||||
ON key_rotation_sessions(status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS key_rotation_candidate_blocks (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE,
|
||||
login TEXT NOT NULL,
|
||||
candidate_blockchain_name TEXT NOT NULL,
|
||||
block_number INTEGER NOT NULL CHECK (block_number >= 0),
|
||||
block_hash BYTEA NOT NULL CHECK (octet_length(block_hash) = 32),
|
||||
data_item_id BYTEA NOT NULL CHECK (octet_length(data_item_id) = 32),
|
||||
block_bytes BYTEA NOT NULL,
|
||||
arweave_publish_pending BOOLEAN NOT NULL DEFAULT TRUE,
|
||||
arweave_published_at_ms BIGINT,
|
||||
created_at_ms BIGINT NOT NULL,
|
||||
UNIQUE (rotation_session_id, block_number),
|
||||
UNIQUE (rotation_session_id, data_item_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_pending
|
||||
ON key_rotation_candidate_blocks(id)
|
||||
WHERE arweave_publish_pending = TRUE;
|
||||
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_session
|
||||
ON key_rotation_candidate_blocks(rotation_session_id, block_number);
|
||||
|
||||
ALTER TABLE solana_user_pda_current
|
||||
DROP CONSTRAINT IF EXISTS fk_solana_user_pda_current_rotation_session;
|
||||
ALTER TABLE solana_user_pda_current
|
||||
ADD CONSTRAINT fk_solana_user_pda_current_rotation_session
|
||||
FOREIGN KEY (rotation_session_id)
|
||||
REFERENCES key_rotation_sessions(id)
|
||||
ON DELETE SET NULL;
|
||||
|
||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms)
|
||||
VALUES(1,24,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
VALUES(1,27,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT))
|
||||
ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||
|
||||
COMMIT;
|
||||
|
||||
Reference in New Issue
Block a user