Смерджить свежий main в очередь выплат

Подтянуты изменения main до d9a91875 (аудит API, учёт публикации блоков,
доработки звонков и настроек). Конфликт только в VERSION.properties:
версии подняты выше main и прежних значений ветки — client 1.21.6,
server 1.17.4. Словари ru/en слились автоматически.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pixel
2026-12-01 20:54:08 +03:00
co-authored by Claude Opus 5.5
75 changed files with 1487 additions and 1150 deletions
@@ -14,8 +14,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
/**
* Publisher с двумя путями доставки:
* 1) Turbo — немедленная неблокирующая попытка для только что принятого блока;
* 2) плановый fixed-delay цикл — страховочная добивка только зависших pending-записей.
* Серверный Turbo publisher обслуживает candidate-блоки ротации ключей.
* Пользовательские CORE/CONTENT в режиме client_only загружает браузер.
*/
public final class ArweaveBlockPublisherScheduler {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
@@ -12,7 +12,7 @@ import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/** Publishes locally-created signed user DataItems through the configured transport. */
/** Серверный publisher candidate-блоков ротации; пользовательские пары ведёт браузер. */
public final class ArweaveBlockPublisherService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherService.class);
@@ -46,16 +46,7 @@ public final class ArweaveBlockPublisherService {
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
return true;
}
BlockEntry entry = blocksDAO.getPendingArweaveByDataItemId(id);
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
return true;
return false;
}
public int runCycle() throws Exception {
@@ -86,17 +77,7 @@ public final class ArweaveBlockPublisherService {
};
}
int remaining = Math.max(0, maxItems - attempted);
if (remaining == 0) return published;
List<BlockEntry> candidates = blocksDAO.listPendingArweave(remaining);
candidates = candidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0;
};
// Пользовательские блоки в режиме client_only публикует браузер.
return published;
}
@@ -15,6 +15,7 @@ import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.entities.BlockEntry;
import shine.db.dao.BlockchainForkSegmentsDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO;
@@ -115,7 +116,26 @@ public final class ArweaveBlockSyncService {
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
continue;
}
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) {
if (blocksDAO.existsByDataItemId(id32)) {
// Локально принятый блок должен получить подтверждение Arweave без повторного применения.
try {
DownloadedEvent published = downloadEvent(dataItemId);
BlockEntry local = blocksDAO.getByDataItemId(id32);
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
} else {
log.warn("Arweave DataItem {} differs from locally accepted bytes", dataItemId);
}
} catch (Exception e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
continue;
}
unresolvedDownloads.remove(dataItemId);
continue;
}
if (importDAO.exists(id32)) {
unresolvedDownloads.remove(dataItemId);
continue;
}
@@ -163,7 +183,19 @@ public final class ArweaveBlockSyncService {
if (attempted >= cfg.syncPageSize()) break;
attempted++;
if (blocksDAO.existsByDataItemId(pending.id32()) || importDAO.exists(pending.id32())) {
if (blocksDAO.existsByDataItemId(pending.id32())) {
try {
DownloadedEvent published = downloadEvent(pending.dataItemId());
BlockEntry local = blocksDAO.getByDataItemId(pending.id32());
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
unresolvedDownloads.remove(pending.dataItemId());
}
} catch (Exception e) { log.debug("Arweave pair {} still unavailable: {}", pending.dataItemId(), e.getMessage()); }
continue;
}
if (importDAO.exists(pending.id32())) {
unresolvedDownloads.remove(pending.dataItemId());
continue;
}
@@ -280,6 +312,14 @@ public final class ArweaveBlockSyncService {
continue;
}
String reason = result.reasonCode();
if ("bad_block_number".equals(reason)) {
BlockEntry existing = blocksDAO.getByNumber(physicalUser.getBlockchainName(), parsedBlock.blockNumber);
if (existing != null && !Arrays.equals(existing.getBlockBytes(), q.rawDataItem())) {
importDAO.reject(q.dataItemId(), "conflict_same_number_different_core", System.currentTimeMillis());
progress = true;
continue;
}
}
if ("bad_block_number".equals(reason) || "bad_prev_hash".equals(reason)
|| "prev_line_block_not_found".equals(reason) || "channel_not_found".equals(reason)
|| "chain_resync_in_progress".equals(reason)) {
@@ -0,0 +1,70 @@
package server.archive;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shine.db.dao.BlockPublicationsDAO;
import shine.db.dao.BlocksDAO;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** Проверяет Turbo без загрузки или переподписи пользовательских блоков. */
public final class BlockPublicationVerifierScheduler {
private static final Logger log = LoggerFactory.getLogger(BlockPublicationVerifierScheduler.class);
private static final ObjectMapper json = new ObjectMapper();
private static final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static ScheduledExecutorService executor;
private BlockPublicationVerifierScheduler() {}
public static synchronized void startOrLog() {
if (executor != null) return;
String base = ArweaveBlocksConfig.load().syncTurboApiBase().replaceAll("/+$", "");
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "shine-block-publication-verifier"); t.setDaemon(true); return t;
});
executor.scheduleWithFixedDelay(() -> {
try { verify(base); }
catch (Exception e) { log.warn("Cannot verify pending Turbo publications", e); }
}, 10, 30, TimeUnit.SECONDS);
}
private static void verify(String base) throws Exception {
BlockPublicationsDAO dao = BlockPublicationsDAO.getInstance();
long now = System.currentTimeMillis();
List<BlockPublicationsDAO.Row> rows = dao.due(100, now);
for (BlockPublicationsDAO.Row row : rows) {
try {
boolean content = row.contentConfirmed() || available(base, row.contentId());
boolean core = row.coreConfirmed() || available(base, row.coreId());
if (content || core) dao.verified(row, content, core, now);
else dao.attempted(row, "Turbo ещё не видит подписанную пару", now);
if (content && core) BlocksDAO.getInstance().markArweavePublished(
List.of(java.util.Base64.getUrlDecoder().decode(row.coreId())), now);
} catch (Exception e) { dao.attempted(row, e.getMessage(), now); }
}
}
private static boolean available(String base, String id) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/tx/" + id + "/status"))
.timeout(Duration.ofSeconds(15)).GET().build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 404) return false;
if (res.statusCode() != 200) throw new IllegalStateException("Turbo status HTTP " + res.statusCode());
JsonNode node = json.readTree(res.body());
String status = node.path("status").asText("");
return status.equals("PENDING") || status.equals("CONFIRMED") || status.equals("BUNDLED") || status.equals("FINALIZED");
}
public static synchronized void close() {
if (executor != null) executor.shutdownNow();
executor = null;
}
}
@@ -40,6 +40,7 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_47 = 47;
public static final int SCHEMA_VERSION_48 = 48;
public static final int SCHEMA_VERSION_49 = 49;
public static final int SCHEMA_VERSION_50 = 50;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -60,6 +61,7 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V47_RESOURCE = "postgres/migration_v47.sql";
public static final String POSTGRES_MIGRATION_V49_RESOURCE = "postgres/migration_v49.sql";
public static final String POSTGRES_MIGRATION_V48_RESOURCE = "postgres/migration_v48.sql";
public static final String POSTGRES_MIGRATION_V50_RESOURCE = "postgres/migration_v50.sql";
private DatabaseInitializer() {}
@@ -227,9 +229,13 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V49_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_49) {
if (currentVersion == SCHEMA_VERSION_49) {
runSqlScript(conn, POSTGRES_MIGRATION_V50_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_50) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 49, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 50, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
@@ -0,0 +1,119 @@
package shine.db.dao;
import shine.db.DbController;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/** Состояние внешней публикации не влияет на уже принятую цепочку. */
public final class BlockPublicationsDAO {
private static final BlockPublicationsDAO INSTANCE = new BlockPublicationsDAO();
private final DbController db = DbController.getInstance();
private BlockPublicationsDAO() {}
public static BlockPublicationsDAO getInstance() { return INSTANCE; }
public record Row(String login, int fork, int number, String coreId, String contentId,
byte[] coreHash, byte[] contentHash, String status, boolean contentConfirmed,
boolean coreConfirmed, long receivedAt, int attempts, String lastError) {}
private static Row row(ResultSet rs) throws SQLException {
return new Row(rs.getString("login"), rs.getInt("fork_number"), rs.getInt("block_number"),
rs.getString("core_id"), rs.getString("content_id"), rs.getBytes("core_hash"),
rs.getBytes("content_hash"), rs.getString("status"),
rs.getObject("content_confirmed_at_ms") != null, rs.getObject("core_confirmed_at_ms") != null,
rs.getLong("first_received_at_ms"), rs.getInt("attempts"), rs.getString("last_error"));
}
public Row get(String login, int fork, int number) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE login=? AND fork_number=? AND block_number=?")) {
ps.setString(1, login); ps.setInt(2, fork); ps.setInt(3, number);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? row(rs) : null; }
}
}
public List<Row> pending(String login, int fork, int limit) throws SQLException {
List<Row> out = new ArrayList<>();
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE login=? AND fork_number=? AND status <> 'ARWEAVE_CONFIRMED' AND status <> 'TURBO_CONFIRMED' ORDER BY block_number LIMIT ?")) {
ps.setString(1, login); ps.setInt(2, fork); ps.setInt(3, limit);
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(row(rs)); }
}
return out;
}
public List<Row> due(int limit, long now) throws SQLException {
List<Row> out = new ArrayList<>();
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE status <> 'ARWEAVE_CONFIRMED' AND status <> 'TURBO_CONFIRMED' AND (next_retry_at_ms IS NULL OR next_retry_at_ms<=?) ORDER BY first_received_at_ms LIMIT ?")) {
ps.setLong(1, now); ps.setInt(2, limit);
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(row(rs)); }
}
return out;
}
public void attempted(Row r, String error, long now) throws SQLException {
try (Connection c = db.getConnection()) {
c.setAutoCommit(false);
try (PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET attempts=attempts+1,last_attempt_at_ms=?,last_error=?,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status NOT IN ('TURBO_CONFIRMED','ARWEAVE_CONFIRMED')
""")) {
ps.setLong(1, now); ps.setString(2, error); ps.setLong(3, now + 30_000L);
ps.setString(4, r.login()); ps.setInt(5, r.fork()); ps.setInt(6, r.number()); ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("INSERT INTO block_publication_attempts(login,fork_number,block_number,attempted_at_ms,outcome) VALUES(?,?,?,?,?)")) {
ps.setString(1, r.login()); ps.setInt(2, r.fork()); ps.setInt(3, r.number()); ps.setLong(4, now);
ps.setString(5, error == null ? "client_report" : error); ps.executeUpdate();
}
c.commit();
}
}
public void clientReported(Row r, String error, long now) throws SQLException {
String status = error == null || error.isBlank() ? "TURBO_SUBMITTED" : "FAILED_RETRYABLE";
try (Connection c = db.getConnection()) {
c.setAutoCommit(false);
try (PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET status=?,attempts=attempts+1,last_attempt_at_ms=?,last_error=?,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status NOT IN ('TURBO_CONFIRMED','ARWEAVE_CONFIRMED')
""")) {
ps.setString(1, status); ps.setLong(2, now); ps.setString(3, error);
ps.setLong(4, now); ps.setString(5, r.login()); ps.setInt(6, r.fork()); ps.setInt(7, r.number());
ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("INSERT INTO block_publication_attempts(login,fork_number,block_number,attempted_at_ms,outcome) VALUES(?,?,?,?,?)")) {
ps.setString(1, r.login()); ps.setInt(2, r.fork()); ps.setInt(3, r.number()); ps.setLong(4, now);
ps.setString(5, status + (error == null || error.isBlank() ? "" : ": " + error)); ps.executeUpdate();
}
c.commit();
}
}
public void verified(Row r, boolean content, boolean core, long now) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET
content_confirmed_at_ms=CASE WHEN ? THEN COALESCE(content_confirmed_at_ms,?) ELSE content_confirmed_at_ms END,
core_confirmed_at_ms=CASE WHEN ? THEN COALESCE(core_confirmed_at_ms,?) ELSE core_confirmed_at_ms END,
status=CASE WHEN (content_confirmed_at_ms IS NOT NULL OR ?) AND (core_confirmed_at_ms IS NOT NULL OR ?)
THEN 'TURBO_CONFIRMED' ELSE 'PENDING_TURBO' END,
last_error=NULL,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status <> 'ARWEAVE_CONFIRMED'
""")) {
ps.setBoolean(1, content); ps.setLong(2, now); ps.setBoolean(3, core); ps.setLong(4, now);
ps.setBoolean(5, content); ps.setBoolean(6, core); ps.setLong(7, now + 30_000L);
ps.setString(8, r.login()); ps.setInt(9, r.fork()); ps.setInt(10, r.number()); ps.executeUpdate();
}
}
public void arweaveConfirmed(String login, int fork, int number, long now) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET status='ARWEAVE_CONFIRMED',arweave_confirmed_at_ms=?,
content_confirmed_at_ms=COALESCE(content_confirmed_at_ms,?),core_confirmed_at_ms=COALESCE(core_confirmed_at_ms,?)
WHERE login=? AND fork_number=? AND block_number=?
""")) {
ps.setLong(1, now); ps.setLong(2, now); ps.setLong(3, now);
ps.setString(4, login); ps.setInt(5, fork); ps.setInt(6, number); ps.executeUpdate();
}
}
}
@@ -70,6 +70,19 @@ public final class BlocksDAO {
public void insert(BlockEntry e) throws SQLException { try (Connection c = db.getConnection()) { insert(c, e); } }
public void insertPublication(Connection c, BlockEntry e, byte[] contentId, byte[] contentHash,
byte[] owner, byte[] prevCoreHash, long receivedAtMs) throws SQLException {
String sql = "INSERT INTO block_publications(login,fork_number,block_number,core_id,content_id,core_hash,content_hash,owner,prev_core_hash,first_received_at_ms) VALUES(?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, e.getLogin()); ps.setInt(2, e.getForkNumber()); ps.setInt(3, e.getBlockNumber());
ps.setString(4, java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(e.getDataItemId()));
ps.setString(5, java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(contentId));
ps.setBytes(6, e.getBlockHash()); ps.setBytes(7, contentHash);
ps.setBytes(8, owner); ps.setBytes(9, prevCoreHash); ps.setLong(10, receivedAtMs);
ps.executeUpdate();
}
}
public boolean existsByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return false;
try (Connection c = db.getConnection();
@@ -79,6 +92,14 @@ public final class BlocksDAO {
}
}
public BlockEntry getByDataItemId(byte[] id) throws SQLException {
String sql = baseSelect() + " WHERE data_item_id=? LIMIT 1";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBytes(1, id);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? mapRow(rs) : null; }
}
}
/** Возвращает ещё не опубликованный пользовательский DataItem для быстрой Turbo-попытки. */
public BlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return null;
@@ -0,0 +1,39 @@
CREATE TABLE IF NOT EXISTS block_publications (
login TEXT NOT NULL,
fork_number INTEGER NOT NULL,
block_number INTEGER NOT NULL,
core_id TEXT NOT NULL,
content_id TEXT NOT NULL,
core_hash BYTEA NOT NULL,
content_hash BYTEA NOT NULL,
owner BYTEA NOT NULL,
prev_core_hash BYTEA NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING_TURBO',
content_confirmed_at_ms BIGINT,
core_confirmed_at_ms BIGINT,
arweave_confirmed_at_ms BIGINT,
first_received_at_ms BIGINT NOT NULL,
last_attempt_at_ms BIGINT,
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
next_retry_at_ms BIGINT,
PRIMARY KEY (login, fork_number, block_number),
FOREIGN KEY (login, fork_number, block_number)
REFERENCES blocks_store(login, fork_number, block_number) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_block_publications_pending
ON block_publications(status, next_retry_at_ms) WHERE status <> 'ARWEAVE_CONFIRMED';
CREATE TABLE IF NOT EXISTS block_publication_attempts (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
login TEXT NOT NULL,
fork_number INTEGER NOT NULL,
block_number INTEGER NOT NULL,
attempted_at_ms BIGINT NOT NULL,
outcome TEXT,
FOREIGN KEY (login, fork_number, block_number)
REFERENCES block_publications(login, fork_number, block_number) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_block_publication_attempts_block
ON block_publication_attempts(login, fork_number, block_number, attempted_at_ms);
UPDATE db_schema_version SET schema_version=50,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
@@ -478,16 +478,6 @@ CREATE TABLE IF NOT EXISTS ip_geo_cache (
CREATE INDEX IF NOT EXISTS idx_ip_geo_cache_updated_at
ON ip_geo_cache(updated_at_ms);
CREATE TABLE IF NOT EXISTS test_free_avatar_uploads (
login TEXT PRIMARY KEY REFERENCES solana_user_pda_current(login),
used_count INTEGER NOT NULL DEFAULT 0,
updated_at_ms BIGINT NOT NULL,
last_tx_id TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated
ON test_free_avatar_uploads(updated_at_ms);
CREATE TABLE IF NOT EXISTS blockchain_state (
blockchain_name TEXT PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login),
@@ -43,6 +43,8 @@ import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_StartEspPairing_
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_UpsertEspPairingSettings_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_BlockPublication_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_BlockPublication_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetBlockchainBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetMyBlockchain_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
@@ -229,6 +231,7 @@ public final class JsonHandlerRegistry {
// --- blockchain ---
Map.entry("AddBlock", new Net_AddBlock_Handler()),
Map.entry("BlockPublication", new Net_BlockPublication_Handler()),
Map.entry("GetBlockchainBlock", new Net_GetBlockchainBlock_Handler()),
Map.entry("GetMyBlockchain", new Net_GetMyBlockchain_Handler()),
@@ -344,6 +347,7 @@ public final class JsonHandlerRegistry {
// --- blockchain ---
Map.entry("AddBlock", Net_AddBlock_Request.class),
Map.entry("BlockPublication", Net_BlockPublication_Request.class),
Map.entry("GetBlockchainBlock", Net_GetBlockchainBlock_Request.class),
Map.entry("GetMyBlockchain", Net_GetMyBlockchain_Request.class),
@@ -91,6 +91,19 @@ public final class JsonInboundProcessor {
op = getTextOrNull(root, "op");
requestId = getTextOrNull(root, "requestId");
if (requestId == null || requestId.isBlank()) {
log.error("JSON request rejected: missing or blank requestId (op={}, login={}, sessionId={})",
safe(op), ctxLogin, ctxSessionId);
Net_Exception_Response err = NetExceptionResponseFactory.error(
op,
requestId,
WireCodes.Status.BAD_REQUEST,
"MISSING_REQUEST_ID",
"Поле 'requestId' обязательно и не должно быть пустым"
);
return writeResponse(err);
}
if (op == null || op.isEmpty()) {
Net_Exception_Response err = NetExceptionResponseFactory.error(
null,
@@ -36,6 +36,7 @@ import server.sync.ArweavePublishSignal;
import shine.db.channels.ChannelNameRules;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.dao.BlockPublicationsDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.CurrentUsersDAO;
@@ -146,6 +147,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
resp.setReasonCode(null);
resp.setServerLastGlobalNumber(r.serverLastBlockNumber);
resp.setServerLastGlobalHash(r.serverLastBlockHashHex);
try {
int dash = blockchainName.lastIndexOf('-');
BlockPublicationsDAO.Row publication = BlockPublicationsDAO.getInstance().get(
blockchainName.substring(0, dash), Integer.parseInt(blockchainName.substring(dash + 1)), r.acceptedBlockNumber);
if (publication != null) {
resp.setBlockNumber(publication.number());
resp.setCoreHash(toHex(publication.coreHash()));
resp.setContentHash(toHex(publication.contentHash()));
resp.setPublicationStatus(publication.status());
}
resp.setAlreadyPresent(r.alreadyPresent);
} catch (Exception e) { log.warn("Cannot read publication status for accepted block", e); }
return resp;
}
@@ -177,6 +190,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// полезно клиенту для ресинка
resp.setServerLastGlobalNumber(serverLastNum);
resp.setServerLastGlobalHash(serverLastHashHex);
if ("pending_publication_limit".equals(reasonCode)) {
try {
String chain = req.getBlockchainName(); int dash = chain.lastIndexOf('-');
var pending = BlockPublicationsDAO.getInstance().pending(chain.substring(0,dash), Integer.parseInt(chain.substring(dash+1)), 1);
if (!pending.isEmpty()) {
resp.setMissingPublicationBlockNumber(pending.get(0).number());
resp.setMissingPublicationCoreHash(toHex(pending.get(0).coreHash()));
resp.setPublicationStatus(pending.get(0).status());
resp.setRetryAfter(30);
}
} catch (Exception e) { log.warn("Cannot read oldest pending publication", e); }
}
return resp;
}
@@ -208,6 +233,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "state_last_hash_invalid" -> "Повреждено состояние блокчейна: неверный last_block_hash";
case "bad_block_base64" -> "Некорректный base64 блока";
case "limit_exceeded" -> "Превышен лимит размера блокчейна";
case "pending_publication_limit" -> "Слишком много блоков ожидают публикации в Turbo";
case "block_number_conflict" -> "Номер блока уже занят другой подписанной парой";
case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "bad_block_format" -> "Некорректный формат блока";
case "bad_block_body" -> "Некорректное тело блока";
@@ -339,6 +366,22 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
login, blockchainName, globalNumberFromReq, e);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_base64", serverLastNum, serverLastHashHex);
}
if (publishToArweave && !replayMode && globalNumberFromReq >= 0 && globalNumberFromReq <= serverLastNum) {
try {
BlockEntry existing = blocksDAO.getByNumber(blockchainName, globalNumberFromReq);
if (existing != null && Arrays.equals(existing.getBlockBytes(), blockBytes)) {
return new AddBlockResult(200, null, serverLastNum, serverLastHashHex, globalNumberFromReq, true);
}
if (existing != null) return new AddBlockResult(409, "block_number_conflict", serverLastNum, serverLastHashHex);
} catch (Exception e) { return new AddBlockResult(500, "db_error", serverLastNum, serverLastHashHex); }
}
if (publishToArweave && !replayMode) {
try {
if (BlockPublicationsDAO.getInstance().pending(login, Integer.parseInt(blockchainName.substring(blockchainName.lastIndexOf('-') + 1)), 16).size() >= 16) {
return new AddBlockResult(429, "pending_publication_limit", serverLastNum, serverLastHashHex);
}
} catch (Exception e) { return new AddBlockResult(500, "db_error", serverLastNum, serverLastHashHex); }
}
// 3) лимит (оставляем как было)
try {
@@ -759,10 +802,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// Chat200 is legacy/non-working/unused. Do not create or mutate Chat200 projections.
// The historical helper code remains below only for archive compatibility and may be removed later.
if (publishToArweave) {
// Только ставим быструю публикацию в очередь: ответ клиенту не ждёт сеть Turbo/Arweave.
ArweavePublishSignal.userBlockAccepted(be.getDataItemId());
}
// Пользовательский DataItem публикует клиент; сервер сохраняет исходную пару.
} catch (Exception e) {
if (isChannelSlugConflict(e)) {
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
@@ -1290,6 +1330,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
public static final class AddBlockExceptionResponse extends Net_Exception_Response {
private Integer serverLastGlobalNumber;
private String serverLastGlobalHash;
private Integer missingPublicationBlockNumber;
private String missingPublicationCoreHash;
private String publicationStatus;
private Integer retryAfter;
public Integer getMissingPublicationBlockNumber() { return missingPublicationBlockNumber; }
public void setMissingPublicationBlockNumber(Integer v) { missingPublicationBlockNumber = v; }
public String getMissingPublicationCoreHash() { return missingPublicationCoreHash; }
public void setMissingPublicationCoreHash(String v) { missingPublicationCoreHash = v; }
public String getPublicationStatus() { return publicationStatus; }
public void setPublicationStatus(String v) { publicationStatus = v; }
public Integer getRetryAfter() { return retryAfter; }
public void setRetryAfter(Integer v) { retryAfter = v; }
public Integer getServerLastGlobalNumber() {
return serverLastGlobalNumber;
@@ -1313,12 +1365,21 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
final String reasonCode;
final int serverLastBlockNumber;
final String serverLastBlockHashHex;
final int acceptedBlockNumber;
final boolean alreadyPresent;
AddBlockResult(int httpStatus, String reasonCode, int serverLastBlockNumber, String serverLastBlockHashHex) {
this(httpStatus, reasonCode, serverLastBlockNumber, serverLastBlockHashHex, serverLastBlockNumber, false);
}
AddBlockResult(int httpStatus, String reasonCode, int serverLastBlockNumber, String serverLastBlockHashHex,
int acceptedBlockNumber, boolean alreadyPresent) {
this.httpStatus = httpStatus;
this.reasonCode = reasonCode;
this.serverLastBlockNumber = serverLastBlockNumber;
this.serverLastBlockHashHex = serverLastBlockHashHex;
this.acceptedBlockNumber = acceptedBlockNumber;
this.alreadyPresent = alreadyPresent;
}
boolean isOk() { return httpStatus == WireCodes.Status.OK; }
@@ -85,6 +85,16 @@ public final class BlockchainWriter {
} else {
blocksDAO.insert(c, be);
}
if (be.isArweavePublishPending() && block.isCoreContent()) {
byte[] contentHash;
try {
contentHash = java.security.MessageDigest.getInstance("SHA-256").digest(block.getContentDataItem().rawBytes());
} catch (java.security.NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
blocksDAO.insertPublication(c, be, block.getContentDataItem().id32(), contentHash,
block.getOwner32(), block.prevHash32, nowMs);
}
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
if (channelNameStateEntry != null) {
@@ -0,0 +1,65 @@
package server.logic.ws_protocol.JSON.handlers.blockchain;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_BlockPublication_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_BlockPublication_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.BlockPublicationsDAO;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
/** Очередь публикации и уведомление о результате загрузки клиентом. */
public final class Net_BlockPublication_Handler implements JsonMessageHandler {
private final BlockPublicationsDAO dao = BlockPublicationsDAO.getInstance();
@Override public Net_Response handle(Net_Request base, ConnectionContext ctx) {
Net_BlockPublication_Request req = (Net_BlockPublication_Request) base;
String chain = req.getBlockchainName();
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getCurrentUser() == null
|| chain == null || !chain.equals(ctx.getCurrentUser().getBlockchainName())) {
return NetExceptionResponseFactory.error(req, 403, "FORBIDDEN", "Недоступная цепочка");
}
int dash = chain.lastIndexOf('-');
if (dash < 0) return NetExceptionResponseFactory.error(req, 400, "BAD_CHAIN", "Некорректная цепочка");
String login = chain.substring(0, dash);
int fork;
try { fork = Integer.parseInt(chain.substring(dash + 1)); }
catch (NumberFormatException e) { return NetExceptionResponseFactory.error(req, 400, "BAD_CHAIN", "Некорректная цепочка"); }
try {
Net_BlockPublication_Response response = new Net_BlockPublication_Response();
response.setOp(req.getOp()); response.setRequestId(req.getRequestId()); response.setStatus(200);
if ("report".equals(req.getAction())) {
BlockPublicationsDAO.Row r = dao.get(login, fork, req.getBlockNumber());
if (r == null) return NetExceptionResponseFactory.error(req, 404, "BLOCK_NOT_FOUND", "Блок не найден");
if (!r.coreId().equals(req.getCoreId()) || !r.contentId().equals(req.getContentId())
|| !HexFormat.of().formatHex(r.coreHash()).equalsIgnoreCase(req.getCoreHash())
|| !HexFormat.of().formatHex(r.contentHash()).equalsIgnoreCase(req.getContentHash())) {
return NetExceptionResponseFactory.error(req, 409, "PUBLICATION_CONFLICT", "Другая подписанная пара");
}
dao.clientReported(r, req.getError() == null ? null : req.getError().substring(0, Math.min(500, req.getError().length())), System.currentTimeMillis());
response.setPublicationStatus("TURBO_CONFIRMED".equals(r.status()) || "ARWEAVE_CONFIRMED".equals(r.status())
? r.status() : req.getError() == null || req.getError().isBlank() ? "TURBO_SUBMITTED" : "FAILED_RETRYABLE");
return response;
}
if (!"list".equals(req.getAction())) return NetExceptionResponseFactory.error(req, 400, "BAD_ACTION", "Некорректное действие");
List<Map<String,Object>> out = new ArrayList<>();
for (BlockPublicationsDAO.Row r : dao.pending(login, fork, 16)) {
out.add(Map.of("blockNumber", r.number(),
"coreId", r.coreId(), "contentId", r.contentId(),
"coreHash", HexFormat.of().formatHex(r.coreHash()), "contentHash", HexFormat.of().formatHex(r.contentHash()),
"publicationStatus", r.status(), "contentConfirmed", r.contentConfirmed(), "coreConfirmed", r.coreConfirmed(),
"firstReceivedAt", r.receivedAt()));
}
response.setPendingBlocks(out);
return response;
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "PUBLICATION_DB_ERROR", "Не удалось прочитать публикации");
}
}
}
@@ -15,6 +15,21 @@ public final class Net_AddBlock_Response extends Net_Response {
/** что сервер считает последним по глобальной цепочке */
private int serverLastGlobalNumber;
private String serverLastGlobalHash;
private int blockNumber;
private String coreHash;
private String contentHash;
private String publicationStatus;
private boolean alreadyPresent;
public boolean isAlreadyPresent() { return alreadyPresent; }
public void setAlreadyPresent(boolean v) { alreadyPresent = v; }
public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int v) { blockNumber = v; }
public String getCoreHash() { return coreHash; }
public void setCoreHash(String v) { coreHash = v; }
public String getContentHash() { return contentHash; }
public void setContentHash(String v) { contentHash = v; }
public String getPublicationStatus() { return publicationStatus; }
public void setPublicationStatus(String v) { publicationStatus = v; }
public String getReasonCode() { return reasonCode; }
public void setReasonCode(String reasonCode) { this.reasonCode = reasonCode; }
@@ -24,4 +39,4 @@ public final class Net_AddBlock_Response extends Net_Response {
public String getServerLastGlobalHash() { return serverLastGlobalHash; }
public void setServerLastGlobalHash(String v) { this.serverLastGlobalHash = v; }
}
}
@@ -0,0 +1,30 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
public final class Net_BlockPublication_Request extends Net_Request {
private String blockchainName;
private String action;
private int blockNumber;
private String coreId;
private String contentId;
private String coreHash;
private String contentHash;
private String error;
public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String v) { blockchainName = v; }
public String getAction() { return action; }
public void setAction(String v) { action = v; }
public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int v) { blockNumber = v; }
public String getCoreId() { return coreId; }
public void setCoreId(String v) { coreId = v; }
public String getContentId() { return contentId; }
public void setContentId(String v) { contentId = v; }
public String getCoreHash() { return coreHash; }
public void setCoreHash(String v) { coreHash = v; }
public String getContentHash() { return contentHash; }
public void setContentHash(String v) { contentHash = v; }
public String getError() { return error; }
public void setError(String v) { error = v; }
}
@@ -0,0 +1,14 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import java.util.List;
import java.util.Map;
public final class Net_BlockPublication_Response extends Net_Response {
private List<Map<String,Object>> pendingBlocks = List.of();
private String publicationStatus;
public List<Map<String,Object>> getPendingBlocks() { return pendingBlocks; }
public void setPendingBlocks(List<Map<String,Object>> v) { pendingBlocks = v; }
public String getPublicationStatus() { return publicationStatus; }
public void setPublicationStatus(String v) { publicationStatus = v; }
}
@@ -36,7 +36,6 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
private static final String TARGET_MODE_SINGLE = "single_session";
private static final String TARGET_MODE_ALL = "all_sessions";
private static final long ALLOWED_SKEW_MS = 30_000L;
private static final long PUSH_CALL_TTL_MS = 10_000L;
private static final String SIGNAL_CALL_INVITE = "call_invite";
private static final String SIGNAL_CALL_ACCEPT = "call_accept";
private static final String SIGNAL_CALL_DECLINE_BUSY = "call_decline_busy";
@@ -120,13 +119,12 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
}
List<ConnectionContext> targets = resolveTargets(targetMode, toLogin, targetSessionId);
boolean isCallInviteAllSessions = TARGET_MODE_ALL.equals(targetMode) && SIGNAL_CALL_INVITE.equals(signalType);
boolean isCallAcceptSingleSession = TARGET_MODE_SINGLE.equals(targetMode) && SIGNAL_CALL_ACCEPT.equals(signalType);
boolean isCallTerminalSingleSession = TARGET_MODE_SINGLE.equals(targetMode)
&& (SIGNAL_CALL_DECLINE_BUSY.equals(signalType)
|| SIGNAL_CALL_TIMEOUT.equals(signalType)
|| SIGNAL_CALL_HANGUP.equals(signalType));
if (targets.isEmpty() && !isCallInviteAllSessions) {
if (targets.isEmpty()) {
String code = TARGET_MODE_SINGLE.equals(targetMode) ? "SESSION_NOT_FOUND" : "NO_TARGET_SESSIONS";
String msg = TARGET_MODE_SINGLE.equals(targetMode) ? "Целевая сессия не найдена" : "Нет активных сессий для доставки сигнала";
return NetExceptionResponseFactory.error(req, 404, code, msg);
@@ -154,18 +152,7 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
}
}
int webPushDelivered = 0;
if (isCallInviteAllSessions) {
webPushDelivered = sendIncomingCallPushToOfflineSessions(
toLogin,
fromLogin,
fromSessionId,
signalRequestId,
deliveredSessionIds
);
}
if (deliveredSessionIds.isEmpty() && webPushDelivered <= 0) {
if (deliveredSessionIds.isEmpty()) {
return NetExceptionResponseFactory.error(req, 404, "DELIVERY_FAILED", "Не удалось доставить сигнал ни в одну целевую сессию");
}
@@ -205,11 +192,11 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setDeliveredCount(deliveredSessionIds.size() + webPushDelivered);
resp.setDeliveredCount(deliveredSessionIds.size());
resp.setDeliveredSessionIds(deliveredSessionIds);
resp.setDeliveredWsSessions(deliveredSessionIds.size());
resp.setDeliveredFcmSessions(webPushDelivered);
resp.setDeliveredWebPushSessions(webPushDelivered);
resp.setDeliveredFcmSessions(0);
resp.setDeliveredWebPushSessions(0);
return resp;
}
@@ -292,49 +279,6 @@ public class Net_SendSignal_Handler implements JsonMessageHandler {
return targets;
}
private int sendIncomingCallPushToOfflineSessions(
String toLogin,
String fromLogin,
String fromSessionId,
String callId,
List<String> deliveredOnlineSessionIds
) throws Exception {
List<ActiveSessionEntry> persistedSessions = ActiveSessionsDAO.getInstance().getByLogin(toLogin);
long sentAtMs = System.currentTimeMillis();
long expiresAtMs = sentAtMs + PUSH_CALL_TTL_MS;
int delivered = 0;
for (ActiveSessionEntry session : persistedSessions) {
String sessionId = safe(session.getSessionId());
if (!sessionId.isBlank() && deliveredOnlineSessionIds.contains(sessionId)) {
continue;
}
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
continue;
}
String payload = "{\"kind\":\"incoming_call\""
+ ",\"title\":\"SHiNE: входящий звонок\""
+ ",\"text\":\"Вам звонит " + jsonEscape(fromLogin) + "\""
+ ",\"fromLogin\":\"" + jsonEscape(fromLogin) + "\""
+ ",\"fromSessionId\":\"" + jsonEscape(fromSessionId) + "\""
+ ",\"targetSessionId\":\"" + jsonEscape(sessionId) + "\""
+ ",\"toLogin\":\"" + jsonEscape(toLogin) + "\""
+ ",\"callId\":\"" + jsonEscape(callId) + "\""
+ ",\"sentAtMs\":" + sentAtMs
+ ",\"expiresAtMs\":" + expiresAtMs
+ "}";
boolean pushed = WebPushSender.sendBase64Payload(
session.getPushEndpoint(),
session.getPushP256dhKey(),
session.getPushAuthKey(),
payload
);
if (pushed) {
delivered++;
}
}
return delivered;
}
private void notifyStopOnOtherSessions(
String targetLogin,
String excludeSessionId,
@@ -11,6 +11,7 @@ import org.slf4j.LoggerFactory;
import server.archive.ArweaveBlockPublisherScheduler;
import server.archive.registration.FreeRegistrationApiBootstrap;
import server.archive.ArweaveBlockSyncScheduler;
import server.archive.BlockPublicationVerifierScheduler;
import server.debug.DebugApiConfigurator;
import server.files.DmFileApiConfigurator;
import server.files.PublicFileApiConfigurator;
@@ -62,6 +63,7 @@ public final class WsServer {
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
FreeRegistrationApiBootstrap.startOrThrow();
ArweaveBlockPublisherScheduler.startOrLog();
BlockPublicationVerifierScheduler.startOrLog();
ArweaveBlockSyncScheduler.startOrLog();
KeyRotationRebuildScheduler.startOrLog();
@@ -100,7 +102,7 @@ public final class WsServer {
log.info("✅ WS сервер запущен на ws://localhost:{}/ws", port);
ServerConnectionPool.getInstance().startOrLog();
Runtime.getRuntime().addShutdownHook(new Thread(
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); FreeRegistrationApiBootstrap.close(); },
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); BlockPublicationVerifierScheduler.close(); ArweaveBlockSyncScheduler.close(); FreeRegistrationApiBootstrap.close(); },
"server-connection-pool-shutdown"));
PeriodicDmDeliveryService.startOrLog();
server.join();