Обновить shine-users и синхронизацию пользователей

This commit is contained in:
AidarKC
2026-11-18 15:28:07 +03:00
parent 780ca53931
commit 76bbc9d023
24 changed files with 503 additions and 278 deletions
@@ -390,7 +390,7 @@ public final class ArweaveBlockSyncService {
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
@@ -482,12 +482,12 @@ public final class ArweaveBlockSyncService {
try{
validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login);
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=usersDAO.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}
@@ -122,7 +122,7 @@ public final class VerifiedFreeRegistrationImporter {
INSERT INTO blockchain_state_store (
login, fork_number, blockchain_key, size_limit, file_size_bytes,
last_block_number, last_block_hash, updated_at_ms)
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
""")) {
insert.setString(1, login);
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
}
}
/** Change ONLY the quota projection; 0 means unbounded. */
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
ChainRef r = chainRef(blockchainName);
ps.setLong(1, limit);
ps.setLong(2, System.currentTimeMillis());
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.executeUpdate();
}
}
/**
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
*/
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
String sql = """
UPDATE blockchain_state_store
SET
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
updated_at_ms = ?
WHERE
LOWER(login) = LOWER(?) AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit
AND file_size_bytes <= 9223372036854775807 - ?
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.setLong(5, deltaBytes);
ps.setLong(6, deltaBytes);
return ps.executeUpdate() > 0;
}
}
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
}
return mapRow(rs);
if (rs.next()) return mapRow(rs);
}
}
// Old forks remain valid separate blockchains even after root rotation.
String forkSql = """
SELECT u.login,
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
f.value ->> 'blockchainKey' AS blockchain_key,
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
FROM solana_user_pda_current u
CROSS JOIN LATERAL jsonb_array_elements(
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
) AS f(value)
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseUserPdaV12(raw);
}
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseServerProfileV12(raw);
}
@@ -38,6 +38,8 @@ import shine.db.dao.BlocksDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.dao.UserNotificationsStateDAO;
import shine.db.dao.UserParamsDAO;
import shine.db.entities.BlockchainStateEntry;
@@ -53,6 +55,7 @@ import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
/**
@@ -67,6 +70,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
@@ -281,7 +289,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
recovered.setBlockchainName(user.getBlockchainName());
recovered.setLogin(user.getLogin());
recovered.setBlockchainKey(user.getBlockchainKey());
recovered.setSizeLimit(100_000L);
recovered.setSizeLimit(Math.max(0L, resolveChainLimit(user.getBlockchainName())));
recovered.setFileSizeBytes(0L);
recovered.setLastBlockNumber(-1);
recovered.setLastBlockHash(new byte[32]);
@@ -335,7 +343,12 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// 3) лимит (оставляем как было)
try {
long oldSize = st.getFileSizeBytes();
long limit = st.getSizeLimit();
// Current synced Solana PDA is authoritative; free users have no PDA.
long limit = resolveChainLimit(blockchainName);
if (limit != st.getSizeLimit()) {
stateDAO.updateSizeLimit(blockchainName, limit);
st.setSizeLimit(limit);
}
long newSize = safeAdd(oldSize, blockBytes.length);
if (limit > 0 && newSize > limit) {
@@ -13,6 +13,8 @@ import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.DbController;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.CurrentUserEntry;
@@ -26,6 +28,11 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
@@ -80,7 +87,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
st.setLastBlockNumber(-1);
st.setLastBlockHash(new byte[32]);
st.setFileSizeBytes(0);
st.setSizeLimit(1_000_000L);
st.setSizeLimit(Math.max(0L, resolveChainLimit(u.getBlockchainName())));
st.setUpdatedAtMs(System.currentTimeMillis());
stateDAO.upsert(st);
log.warn("GetUser: восстановлена запись blockchain_state для login={}, blockchainName={}",
@@ -142,20 +142,17 @@ public final class ShineUsersCodec {
null
);
case IX_UPDATE_USERS_ECONOMY_CONFIG ->
new ParsedInstruction(
TxKind.UPDATE_USERS_ECONOMY_CONFIG,
false,
null,
null,
new EconomyConfigState(
1,
reader.readU64(),
reader.readU64(),
reader.readU64()
),
null
);
case IX_UPDATE_USERS_ECONOMY_CONFIG -> {
// Historical v1 transactions contain three u64s, v2 only update fee.
int payloadBytes = reader.remaining();
EconomyConfigState economy = switch (payloadBytes) {
case 8 -> new EconomyConfigState(2, 0L, 0L, 0L, reader.readU64());
case 24 -> new EconomyConfigState(1, reader.readU64(), reader.readU64(), reader.readU64(), 20_000L);
default -> throw new IllegalArgumentException("Invalid economy config instruction length");
};
yield new ParsedInstruction(TxKind.UPDATE_USERS_ECONOMY_CONFIG,
false, null, null, economy, null);
}
case IX_UPDATE_NAMESPACE_PRICE ->
new ParsedInstruction(
@@ -260,7 +257,7 @@ public final class ShineUsersCodec {
if (formatMajor != 1) {
throw new IllegalArgumentException("Unsupported PDA format " + formatMajor + "." + formatMinor);
}
if (formatMinor == 2) {
if (formatMinor == 2 || formatMinor == 3) {
return parseUserPdaAccountV12(pdaAddress, slot, rawDataBase64, lastTxSignature, raw);
}
if (formatMinor == 0) {
@@ -862,17 +859,13 @@ public final class ShineUsersCodec {
public record EconomyConfigState(
int version,
long registrationFeeLamports,
long lamportsPerLimitStep,
long startBonusLimit
long registrationFeeLamports, // legacy v1 only
long lamportsPerLimitStep, // legacy v1 only
long startBonusLimit, // legacy v1 only
long updateFeeLamports // v2 (v1 fallback 20_000)
) {
public static EconomyConfigState initial() {
return new EconomyConfigState(
1,
START_REGISTRATION_FEE_LAMPORTS,
START_LAMPORTS_PER_LIMIT_STEP,
START_BONUS_LIMIT
);
return new EconomyConfigState(2, 0L, 0L, 0L, 20_000L);
}
}
@@ -63,7 +63,7 @@ public final class PostgresStorageRepository
"last_error, economy_config_version, " +
"registration_fee_lamports, " +
"lamports_per_limit_step, " +
"start_bonus_limit, updated_at_ms " +
"start_bonus_limit, update_fee_lamports, updated_at_ms " +
"FROM solana_sync_state WHERE id = 1"
);
ResultSet resultSet =
@@ -106,7 +106,8 @@ public final class PostgresStorageRepository
),
resultSet.getLong(
"start_bonus_limit"
)
),
resultSet.getLong("update_fee_lamports")
);
}
@@ -274,6 +275,7 @@ public final class PostgresStorageRepository
connection,
snapshots
);
syncBlockchainStateLimits(connection, snapshots);
reconcileConfirmedKeyRotations(
connection,
@@ -314,6 +316,7 @@ public final class PostgresStorageRepository
connection,
snapshots
);
syncBlockchainStateLimits(connection, snapshots);
reconcileConfirmedKeyRotations(
connection,
@@ -337,6 +340,36 @@ public final class PostgresStorageRepository
}
}
/** Copy on-chain fork limits into the server's runtime state. 0 = unbounded.
* Never touch block tips, used bytes, or keys. Works after PDA updates even
* when record_number remains unchanged (future system-only limit mutation).
*/
private void syncBlockchainStateLimits(Connection connection,
List<ShineUsersCodec.UserPdaSnapshot> snapshots) throws SQLException {
if (snapshots == null || snapshots.isEmpty()) return;
try (PreparedStatement exists = connection.prepareStatement("SELECT to_regclass('public.blockchain_state_store')")) {
try (ResultSet rs = exists.executeQuery()) {
if (!rs.next() || rs.getString(1) == null) return;
}
}
try (PreparedStatement stmt = connection.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
for (ShineUsersCodec.UserPdaSnapshot snapshot : snapshots) {
if (snapshot == null || snapshot.blockchainForks() == null) continue;
for (ShineUsersCodec.BlockchainForkSnapshot fork : snapshot.blockchainForks()) {
stmt.setLong(1, fork.paidLimitBytes());
stmt.setLong(2, System.currentTimeMillis());
stmt.setString(3, snapshot.login());
stmt.setInt(4, fork.forkIndex() + 1);
stmt.addBatch();
}
}
stmt.executeBatch();
}
}
private void upsertTxHistory(
Connection connection,
List<TxHistoryEntry> txEntries
@@ -862,8 +895,8 @@ public final class PostgresStorageRepository
"last_seen_slot, last_relevant_signature, " +
"last_relevant_slot, last_error, economy_config_version, " +
"registration_fee_lamports, lamports_per_limit_step, " +
"start_bonus_limit, updated_at_ms" +
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"start_bonus_limit, update_fee_lamports, updated_at_ms" +
") VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +
"ON CONFLICT (id) DO UPDATE SET " +
"status = EXCLUDED.status, " +
"ready = EXCLUDED.ready, " +
@@ -878,6 +911,7 @@ public final class PostgresStorageRepository
"registration_fee_lamports = EXCLUDED.registration_fee_lamports, " +
"lamports_per_limit_step = EXCLUDED.lamports_per_limit_step, " +
"start_bonus_limit = EXCLUDED.start_bonus_limit, " +
"update_fee_lamports = EXCLUDED.update_fee_lamports, " +
"updated_at_ms = EXCLUDED.updated_at_ms";
try (PreparedStatement statement =
@@ -898,14 +932,16 @@ public final class PostgresStorageRepository
statement.setNull(11, Types.BIGINT);
statement.setNull(12, Types.BIGINT);
statement.setNull(13, Types.BIGINT);
statement.setNull(14, Types.BIGINT);
} else {
statement.setInt(10, snapshot.economyConfigState().version());
statement.setLong(11, snapshot.economyConfigState().registrationFeeLamports());
statement.setLong(12, snapshot.economyConfigState().lamportsPerLimitStep());
statement.setLong(13, snapshot.economyConfigState().startBonusLimit());
statement.setLong(14, snapshot.economyConfigState().updateFeeLamports());
}
bindNullableLong(statement, 14, snapshot.updatedAtMs());
bindNullableLong(statement, 15, snapshot.updatedAtMs());
statement.executeUpdate();
}
}
@@ -934,10 +970,13 @@ public final class PostgresStorageRepository
"registration_fee_lamports BIGINT, " +
"lamports_per_limit_step BIGINT, " +
"start_bonus_limit BIGINT, " +
"update_fee_lamports BIGINT, " +
"updated_at_ms BIGINT" +
")"
);
statement.executeUpdate("ALTER TABLE solana_sync_state ADD COLUMN IF NOT EXISTS update_fee_lamports BIGINT");
statement.executeUpdate(
"INSERT INTO solana_sync_state (id, status, ready) " +
"VALUES (1, 'EMPTY', FALSE) " +
@@ -58,10 +58,10 @@ public final class KeyRotationRebuildService {
}
private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}}
private void replayStaging(KeyRotationSessionEntry s)throws Exception{
SolanaUserPdaCurrentEntry u=users.getByLogin(s.getLogin());long limit=u!=null&&u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L;long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
long cumulative=0;int currentFork=-1;int prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){ps.setLong(1,s.getId());try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);String key=rs.getString(3);byte[] raw=rs.getBytes(4),hash=rs.getBytes(5);String bch=s.getLogin()+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=users.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(s.getLogin());st.setBlockchainKey(key);st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());states.insertIfMissing(st);currentFork=f;}
String target=bch;BlockchainResyncGuard.withBypass(target,()->{Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(target,raw);if(!r.ok())throw new IllegalStateException("canonical replay rejected #"+n+": "+r.reasonCode());});
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}}
@@ -370,7 +370,7 @@ public final class PeriodicBlockchainSyncService {
state.setBlockchainName(currentUser.getBlockchainName());
state.setLogin(currentUser.getLogin());
state.setBlockchainKey(currentUser.getBlockchainKey());
state.setSizeLimit(currentUser.getPaidLimitBytes() > 0 ? currentUser.getPaidLimitBytes() : 100_000L);
state.setSizeLimit(currentUser.getPaidLimitBytes());
state.setFileSizeBytes(existingState == null ? 0L : existingState.getFileSizeBytes());
state.setLastBlockNumber(existingState == null ? -1 : existingState.getLastBlockNumber());
state.setLastBlockHash(existingState == null ? null : existingState.getLastBlockHash());