SHA256
613 lines
30 KiB
Java
613 lines
30 KiB
Java
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 = current.getCompletedAtMs();
|
||
if (next == KeyRotationStatus.COMPLETE) completed = now;
|
||
Long aborted = current.getAbortedAtMs();
|
||
if (next == KeyRotationStatus.ABORTED) aborted = now;
|
||
|
||
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();
|
||
}
|
||
}
|