SHA256
Смерджить свежий main в голосовые сообщения
Подтянуты изменения main до d9a91875 (аудит API, учёт публикации блоков,
звонки и настройки). Конфликт только в VERSION.properties: client 1.21.7,
server 1.17.5 — выше main и PR очереди выплат.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+2
-2
@@ -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);
|
||||
|
||||
+3
-22
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
+42
-2
@@ -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)) {
|
||||
|
||||
+70
@@ -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;
|
||||
+4
@@ -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),
|
||||
|
||||
|
||||
+65
-4
@@ -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; }
|
||||
|
||||
+10
@@ -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) {
|
||||
|
||||
+65
@@ -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
@@ -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; }
|
||||
|
||||
+30
@@ -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; }
|
||||
}
|
||||
+14
@@ -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; }
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
client.version=1.21.4
|
||||
server.version=1.17.2
|
||||
client.version=1.21.7
|
||||
server.version=1.17.5
|
||||
|
||||
@@ -45,7 +45,7 @@
|
||||
| Домен | Логин сервера | Сервер | UI | Порт | systemd | PostgreSQL DB | PostgreSQL user |
|
||||
|---|---|---|---|---|---|---|---|
|
||||
| `t1.shineup.me` | `server_t1` | `/home/player/t1/server` | `/home/player/t1/UI` | `7101` | `shine-t1.service` | `shine_t1_db` | `shine_t1` |
|
||||
| `t2.shineup.me` | `server_t2` | `/home/player/t2/server` | `/home/player/t2/UI` | `7102` | `shine-t2.service` | `shine_t2_db` | `shine_t2` |
|
||||
| `t2.shineup.me` | `server_t2` | `/home/player/t2/server` | `/home/player/t2/UI` | `7102` | `shine-t2.service` | `shine_core_t2` | `shine_t2` |
|
||||
| `t3.shineup.me` | `server_t3` | `/home/player/t3/server` | `/home/player/t3/UI` | `7103` | `shine-t3.service` | `shine_t3_db` | `shine_t3` |
|
||||
| `test.shineup.me` | `test_server@shine` | `/home/player/t4/server` | `/home/player/t4/UI` | `7104` | `shine-test.service` | `shine_test_db` | `shine_t2` |
|
||||
|
||||
|
||||
@@ -46,6 +46,37 @@
|
||||
|
||||
## Storage / publish / GetBlockchainBlock
|
||||
|
||||
### Клиентская публикация
|
||||
|
||||
При успешном `AddBlock` сервер сохраняет исходные подписанные CORE/CONTENT и
|
||||
отдельное состояние `PENDING_TURBO`. Ответ дополнительно содержит `blockNumber`,
|
||||
`coreHash`, `contentHash`, `publicationStatus`. Сервер не загружает пользовательские
|
||||
блоки в Turbo. Браузер оплачивает загрузку своим Turbo-кошельком: CONTENT, затем
|
||||
CORE. Каждая повторная попытка использует байты из сохранённого контейнера.
|
||||
|
||||
Авторизованный владелец цепочки вызывает `BlockPublication` с
|
||||
`{"blockchainName":"alice-001","action":"list"}`. Ответ `pendingBlocks`
|
||||
содержит максимум 16 записей с номерами, ID, хешами, статусом и признаками
|
||||
подтверждения каждой части. Исходный контейнер каждой записи читается через
|
||||
`GetBlockchainBlock`; клиент сверяет хеш CORE. После попытки клиент вызывает
|
||||
`BlockPublication` с `action=report`, `blockNumber`, `contentId`, `coreId`,
|
||||
`contentHash`, `coreHash`, `error` (пустая строка при успехе). Несовпадение ID или
|
||||
хешей даёт `409 PUBLICATION_CONFLICT`; сообщение клиента само по себе не является
|
||||
подтверждением Turbo.
|
||||
|
||||
Фоновая проверка сервера запрашивает у Turbo статус обоих DataItem по сохранённым
|
||||
ID. Только доступность обеих частей переводит пару в `TURBO_CONFIRMED`.
|
||||
Импортёр позже скачивает и сравнивает точные bytes пары, после чего выставляет
|
||||
`ARWEAVE_CONFIRMED` без повторного применения блока. Принятая пара участвует
|
||||
в цепочке до Turbo-подтверждения. После 16 незавершённых публикаций новый
|
||||
`AddBlock` получает `429 pending_publication_limit` с номером и хешем первой
|
||||
незакрытой публикации, её статусом и `retryAfter` в секундах. Срок 30 минут
|
||||
не включает загрузку сервером: очередь хранится до подключения клиента.
|
||||
|
||||
Клиентская публикация этого этапа поддерживается браузерным UI. Тестовый
|
||||
издатель и remote AddBlock не участвуют в этом сценарии и считаются
|
||||
устаревшими путями; они не подтверждают внешнюю публикацию.
|
||||
|
||||
В существующем `blocks_store.block_bytes` хранится контейнер целиком; `block_hash`, `block_signature`, `data_item_id` — hash, подпись, ID CORE. Размер цепочки увеличивается на фактическую длину контейнера. Сохраняются существующая транзакция и очередь; локальный AddBlock ACK не равен Turbo ACK. Публикация CONTENT -> CORE и загрузка пары из Arweave реализованы; локальный ACK не подтверждает публикацию.
|
||||
|
||||
`GetBlockchainBlock` возвращает `blockHash` (хеш CORE) и исходный `blockBytesB64` из одной записи без переупаковки. `GetMyBlockchain` и чтение каналов извлекают смысловое тело CONTENT из пары. Старые JSON-поля и операции сохранены; GetMyBlockchain дополнительно возвращает thisLineNumber из существующей БД. Клиент понимает новый контейнер.
|
||||
|
||||
@@ -45,6 +45,7 @@
|
||||
| `CloseActiveSession` | [`03_Session_Management_API.md`](03_Session_Management_API.md) | закрытие активной сессии |
|
||||
| `CloseOtherSessions` | [`03_Session_Management_API.md`](03_Session_Management_API.md) | закрыть все остальные сессии текущего пользователя |
|
||||
| `AddBlock` | [`04_Add_Block_to_Blockchain_API.md`](04_Add_Block_to_Blockchain_API.md) | добавление пары CORE/CONTENT одним событием |
|
||||
| `BlockPublication` | [`04_Add_Block_to_Blockchain_API.md`](04_Add_Block_to_Blockchain_API.md) | список ожидающих Turbo публикаций и сообщение клиента о попытке |
|
||||
| `GetBlockchainBlock` | [`04_Add_Block_to_Blockchain_API.md`](04_Add_Block_to_Blockchain_API.md) | чтение одного события (контейнер двух DataItem) |
|
||||
| `KeyRotationStart` | [`19_Key_Rotation_API.md`](19_Key_Rotation_API.md) | начать смену ключей сразу в состоянии `COPYING_CHAIN` |
|
||||
| `KeyRotationStatus` | [`19_Key_Rotation_API.md`](19_Key_Rotation_API.md) | получить текущий этап и прогресс смены ключей |
|
||||
|
||||
@@ -28,7 +28,7 @@ flowchart LR
|
||||
## Основные потоки
|
||||
|
||||
1. **Регистрация и подключение.** Клиент взаимодействует с Solana PDA и сервером; серверный адрес публикуется в PDA серверного аккаунта. Детали регистрации и её текущий статус: `docs/Инициализация_Solana_регистрации/README.md`, `docs/registration-v2/README.md`.
|
||||
2. **Пользовательские блоки.** Клиент подписывает CONTENT, затем CORE — два ANS-104 DataItem одного события. Сервер проверяет пару при `AddBlock`, хранит локально в PostgreSQL и, в зависимости от режима публикации, передаёт в Turbo (CONTENT → CORE) для Arweave. Прямая публикация L1 планируется. Другие серверы могут импортировать опубликованные блоки. Точный формат и ограничения: `docs/Blockchain/README.md`.
|
||||
2. **Пользовательские блоки.** Клиент подписывает CONTENT, затем CORE — два ANS-104 DataItem одного события. Сервер проверяет пару при `AddBlock` и хранит локально в PostgreSQL. Браузер передаёт исходные CONTENT → CORE в Turbo; сервер проверяет обе части через Turbo API. Прямая публикация L1 планируется. Другие серверы могут импортировать опубликованные блоки. Точный формат и ограничения: `docs/Blockchain/README.md`.
|
||||
3. **Личные сообщения.** Клиент формирует зашифрованное сообщение; сервер обслуживает доставку и локальное хранение, не получая ключ содержимого. Точные правила, формат и доставка: `docs/Personal_Messages/README.md`.
|
||||
4. **Деплой.** Сборка основного сервера управляется корневым Gradle-проектом; эксплуатационные сценарии и отдельный Solana-модуль документированы раздельно: `deploy/README.md`, `shine-solana/shine/AGENTS.md`.
|
||||
|
||||
|
||||
@@ -8,15 +8,23 @@ CORE: `App=test5595`, `n=<blockNumber>` (каноничная десятична
|
||||
|
||||
## Режимы публикации
|
||||
|
||||
Для новых пользовательских блоков действует `client_only`: сервер после AddBlock
|
||||
сохраняет оригинальную пару и проверяет её публикацию, а загрузку CONTENT → CORE
|
||||
выполняет браузер владельца за его Turbo-кредиты. Старый серверный publisher
|
||||
продолжает обслуживать candidate-блоки ротации ключей; пользовательские пары
|
||||
он не отправляет. При недоступности браузера ожидающий блок остаётся в БД.
|
||||
Через 30 минут ожидания клиент по-прежнему получает его в очереди; серверный
|
||||
fallback в этом этапе не включён.
|
||||
|
||||
| `arweave.blocks.publish.mode` | Статус |
|
||||
|---|---|
|
||||
| `turbo` | Реализован для CORE/CONTENT |
|
||||
| `turbo` | Для новых пользовательских CORE/CONTENT сервер выполняет проверку статуса; загрузку выполняет браузер. Серверный uploader остаётся для ротации ключей. |
|
||||
| `none` | Реализован; локальное хранение без внешней публикации |
|
||||
| `arweave` | Планируется разработать прямую публикацию CORE/CONTENT на сервере в Arweave L1; сейчас не поддерживается активным протоколом |
|
||||
|
||||
Публикация через Turbo отправляет исходный подписанный CONTENT, затем CORE. Сервер не переподписывает их. Pending снимается только после успеха обеих загрузок; при сбое повторяются оригинальные bytes. Локальный ACK AddBlock, Turbo ACK и подтверждённое долговременное наличие в Arweave — разные состояния. Publisher и importer могут включаться независимо через `arweave.blocks.publish.enabled` и `arweave.blocks.sync.enabled`.
|
||||
|
||||
Плательщик Turbo: `arweave.blocks.publish.turbo.paidByAddress` или `arweave.blocks.publish.turbo.walletJwkPath` для получения публичного адреса. При платной загрузке чужих подписанных данных может требоваться Credit Share Approval; free tier не гарантирован, ошибка оплаты оставляет pending.
|
||||
Плательщик новых пользовательских блоков — кошелёк браузерного клиента. Параметры `paidByAddress` и `walletJwkPath` относятся к старому серверному uploader и ротации ключей. Free tier не гарантирован; ошибка оплаты оставляет пару в очереди.
|
||||
|
||||
## Импорт
|
||||
|
||||
@@ -26,4 +34,7 @@ Discovery ищет CORE по `App`/`n`/`l`/owner, не root bundle. По ID ск
|
||||
|
||||
`ArchiveBlockPair.download` проверяет CORE по ожидаемому ID, скачивает CONTENT по подписанной ссылке и проверяет пару. В `ArweaveBlockSyncService` сначала устанавливаются метаданные физического сегмента/предков, затем выбирается каноническая ветка по актуальной регистрации/PDA. Неканонические записи получают `orphan_noncanonical`. Replay выполняется в логическом порядке, не в порядке высоты Arweave. При `bad_block_number`, `bad_prev_hash`, `prev_line_block_not_found`, `channel_not_found`, `chain_resync_in_progress` запись остаётся pending; прочие ошибки применения переводятся в rejected. Ошибка загрузки/формата до очереди может завершить быстрый retry до следующего discovery. Это текущая модель очереди, а не четыре постоянных статуса CONTENT в основной БД.
|
||||
|
||||
Если номер уже занят другой подписанной парой, импортёр помечает кандидата
|
||||
`conflict_same_number_different_core` и не подменяет локальный канонический блок.
|
||||
|
||||
Прямая межсерверная репликация пользовательских блоков не используется. См. [синхронизация](sync-between-servers.md), [формат](01_Common_Block_Format.md), [AddBlock](../API/04_Add_Block_to_Blockchain_API.md).
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Одно событие — одна запись `blocks_store` и один проход существующей транзакции `BlockchainWriter`. `BchBlockEntry` предоставляет номер, время, prevHash/hash, подпись, owner и ID из CORE; type/subType/version/body из CONTENT. `toBytes()` возвращает внутренний контейнер. Внутренние адаптеры BodyHasLine не меняют подписанные bytes. Порядковый номер линии вычисляется при применении. Не создаётся второй социальный runtime.
|
||||
|
||||
Путь записи: клиент → AddBlock → проверка состояния и квоты → разбор пары и проверка подписей → семантические проверки, глобальный хвост, авторизация ключа и линейный хвост → транзакция PostgreSQL → асинхронный publisher. Путь чтения: GetBlockchainBlock возвращает оригинальный контейнер, GetMyBlockchain и каналы — смысловое тело и производные индексы. Snapshot использует локальный framing SHINECC2 + u32 length для каждой пары. `.shine-pair` не является ANS-104.
|
||||
Путь записи: клиент → AddBlock → проверка состояния и квоты → разбор пары и проверка подписей → семантические проверки, глобальный хвост, авторизация ключа и линейный хвост → транзакция PostgreSQL с состоянием публикации → браузерная загрузка CONTENT и CORE → серверная проверка Turbo. Путь чтения: GetBlockchainBlock возвращает оригинальный контейнер, GetMyBlockchain и каналы — смысловое тело и производные индексы. Snapshot использует локальный framing SHINECC2 + u32 length для каждой пары. `.shine-pair` не является ANS-104.
|
||||
|
||||
Публикация и восстановление: [транспорт](17_ANS104_Arweave_Transport.md). Для fork сохраняется исходный префикс в родительских сегментах; новый ключ подписывает TECH_FORK и новые блоки, а не весь префикс. После rollback/replay read_count ограничивается актуальным message_count, unread_count = max(0, message_count-read_count); при изменении сервером подпись значения инвалидируется, прежний timestamp сохраняется. [API ротации](../API/19_Key_Rotation_API.md).
|
||||
|
||||
|
||||
@@ -2,6 +2,12 @@
|
||||
|
||||
Записи ниже описывают состояние на указанную дату; старые Frame v1, теги и промежуточные стадии не являются текущей спецификацией. Действующий контракт: [Blockchain](README.md).
|
||||
|
||||
## 2026-12-01 — клиентская публикация блоков
|
||||
|
||||
- Добавлены серверная очередь публикации, `BlockPublication`, проверка двух DataItem через Turbo API и подтверждение Arweave после сравнения исходных bytes.
|
||||
- Браузер загружает CONTENT и CORE за счёт своего Turbo-кошелька. Серверный uploader пользовательских блоков отключён; candidate-блоки ротации остаются в прежнем пути.
|
||||
- Лимит: 16 ожидающих блоков на physical fork. Принятые блоки продолжают цепочку независимо от внешней публикации.
|
||||
|
||||
## 2026-11-29 — сверка документации с кодом (без изменения протокола)
|
||||
|
||||
- Уточнены CORE/CONTENT, двоичные body, шаги AddBlock, границы replay, квоты и ограничения архивного импорта.
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
## Поток события
|
||||
|
||||
Клиент подписывает CONTENT, затем CORE с его хешем и ID; передаёт пару через AddBlock. Сервер проверяет квоту, обе подписи, полномочия, семантику и хвосты, атомарно записывает одну пару и производные индексы. При Turbo-публикации сначала отправляется CONTENT, затем CORE; другие серверы импортируют полные пары из Arweave. `none` оставляет данные локально; прямой L1 publisher планируется. Хеш истории — SHA-256 CORE, namespace тестовой эпохи — `test5595`.
|
||||
Клиент подписывает CONTENT, затем CORE с его хешем и ID; передаёт пару через AddBlock. Сервер проверяет квоту, обе подписи, полномочия, семантику и хвосты, атомарно записывает одну пару и производные индексы. Браузер публикует CONTENT, затем CORE в Turbo; сервер проверяет доступность обеих частей, а другие серверы импортируют полные пары из Arweave. `none` оставляет данные локально; прямой L1 publisher планируется. Хеш истории — SHA-256 CORE, namespace тестовой эпохи — `test5595`.
|
||||
|
||||
Сертификаты `t=reg` — [отдельный протокол](../Протоколы/SHINE_FREE_REGISTRATION_CERTIFICATE_V1.md), не AddBlock. [Регистрация](../registration-v2/README.md). [Правила регистра логина](CASE_INSENSITIVE_LOGIN.md).
|
||||
|
||||
|
||||
@@ -43,6 +43,10 @@
|
||||
|
||||
Макеты намеренно изолированы от `shine-UI`: они не импортируют приложение и не участвуют в его сборке. Здесь допускаются экспериментальные компоненты; при переносе утверждённого дизайна нужно использовать существующие владельцы AppShell, TopBar, Dropdown, Avatar и Composer.
|
||||
|
||||
## Звонки
|
||||
|
||||
Во входящем звонке действия отображаются круглыми иконками: ответ — зелёной трубкой, отклонение — красной. При выключении видео собеседником видеотрек перестаёт передаваться, а интерфейс возвращается к обычному экрану звонка с аватаром и данными собеседника; чёрная заглушка вместо видео не используется.
|
||||
|
||||
## Проверка
|
||||
|
||||
Результаты проверки и ограничения приведены в [VALIDATION.md](VALIDATION.md). Визуальная проверка в браузере в текущей сессии недоступна: подключённых браузеров нет. Это рабочие HTML-макеты для обсуждения, не проверенная на устройствах реализация приложения.
|
||||
|
||||
@@ -4947,6 +4947,11 @@
|
||||
"wallet_hint": "🧪 Experimental SOL ↔ USDT swaps via Jupiter. Not recommended for real funds; please review the warnings before trying.",
|
||||
"wallet_button": "Swap · Jupiter β"
|
||||
},
|
||||
"block_publication": {
|
||||
"add_failed": "Could not add the block. Please try again later.",
|
||||
"insufficient_credits": "Block #{number} was accepted by the server, but there are not enough Turbo credits to publish it. Top up the Turbo wallet; the block is saved and upload will retry.",
|
||||
"upload_failed": "Block #{number} was accepted, but could not be uploaded to Turbo. Upload will retry automatically."
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Attachment metadata is invalid; the original block remains unchanged.",
|
||||
"title": "Blockchain data",
|
||||
|
||||
@@ -4947,6 +4947,11 @@
|
||||
"wallet_hint": "🧪 Тестовый обмен SOL ↔ USDT через Jupiter. Функция не рекомендована для реальных средств: откройте предупреждение перед использованием.",
|
||||
"wallet_button": "Обменять · Jupiter β"
|
||||
},
|
||||
"block_publication": {
|
||||
"add_failed": "Не получается добавить блок. Попробуйте ещё раз позже.",
|
||||
"insufficient_credits": "Блок №{number} принят сервером, но в Turbo недостаточно средств для публикации. Пополните Turbo-кошелёк; блок сохранён и загрузка повторится.",
|
||||
"upload_failed": "Блок №{number} принят, но не удалось опубликовать его в Turbo. Загрузка повторится автоматически."
|
||||
},
|
||||
"blockchain_details": {
|
||||
"invalid_attachment": "Вложение содержит некорректные метаданные; исходный блок сохранён без изменений.",
|
||||
"title": "Данные блокчейна",
|
||||
|
||||
@@ -41,6 +41,8 @@ import {
|
||||
saveSessionMaterial,
|
||||
} from './key-vault.js';
|
||||
import { signEventContainer, submitSignedEvent, readStoredLineMeta } from './core-content.js';
|
||||
import { showToast } from './channels-ux.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import { defaultServerWs } from '../deploy-config.js';
|
||||
import { readPendingHeaderIdentity, clearPendingHeaderIdentity } from './pending-header-identity.js';
|
||||
|
||||
@@ -1172,6 +1174,14 @@ export class AuthService {
|
||||
const connectionScope = String(createResp?.payload?.connectionScope || '').trim().toUpperCase();
|
||||
|
||||
const canonicalLogin = await this.resolveCanonicalDisplayLogin(cleanLogin);
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await this.getUser(canonicalLogin);
|
||||
const { publishPendingBlocks } = await import('./block-publication-service.js');
|
||||
await publishPendingBlocks({ ws: this.ws, login: canonicalLogin, storagePwd,
|
||||
blockchainName: String(user?.blockchainName || `${canonicalLogin}-${BCH_SUFFIX}`) });
|
||||
} catch (error) { console.warn('Block publication resume failed', error); }
|
||||
})();
|
||||
|
||||
return {
|
||||
login: canonicalLogin,
|
||||
@@ -1314,12 +1324,13 @@ export class AuthService {
|
||||
const cleanLogin = (login || '').trim();
|
||||
if (!cleanLogin) throw new Error('Нет login для авто-входа');
|
||||
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, targetSessionId);
|
||||
const requestedSessionId = String(preferredSessionId || '').trim();
|
||||
const sessionMaterial = await loadSessionMaterial(cleanLogin, requestedSessionId);
|
||||
if (!sessionMaterial?.sessionId || !sessionMaterial?.sessionKey || !sessionMaterial?.sessionPrivPkcs8) {
|
||||
throw new Error('На устройстве нет сохраненного ключа сессии');
|
||||
}
|
||||
|
||||
const targetSessionId = preferredSessionId || sessionMaterial.sessionId;
|
||||
const targetSessionId = requestedSessionId || sessionMaterial.sessionId;
|
||||
const privateKey = await importPkcs8Ed25519(sessionMaterial.sessionPrivPkcs8);
|
||||
|
||||
const challengeResp = await this.ws.request('SessionChallenge', { sessionId: targetSessionId });
|
||||
@@ -1349,6 +1360,14 @@ export class AuthService {
|
||||
const connectionScope = String(loginResp?.payload?.connectionScope || '').trim().toUpperCase();
|
||||
|
||||
const canonicalLogin = await this.resolveCanonicalDisplayLogin(cleanLogin);
|
||||
void (async () => {
|
||||
try {
|
||||
const user = await this.getUser(canonicalLogin);
|
||||
const { publishPendingBlocks } = await import('./block-publication-service.js');
|
||||
await publishPendingBlocks({ ws: this.ws, login: canonicalLogin, storagePwd,
|
||||
blockchainName: String(user?.blockchainName || `${canonicalLogin}-${BCH_SUFFIX}`) });
|
||||
} catch (error) { console.warn('Block publication resume failed', error); }
|
||||
})();
|
||||
|
||||
return {
|
||||
login: canonicalLogin,
|
||||
@@ -1722,26 +1741,34 @@ export class AuthService {
|
||||
}
|
||||
|
||||
async runAddBlockWithRetry({ login, storagePwd, resolveFreshState, event }) {
|
||||
const freshState = await resolveFreshState();
|
||||
const blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
|
||||
const tryAdd = cursor => this.submitPreparedAddBlock({ login, storagePwd, blockchainName,
|
||||
blockNumber: Number(cursor?.serverLastGlobalNumber ?? -1) + 1,
|
||||
prevBlockHash: normalizeHex32(cursor?.serverLastGlobalHash, ZERO64), event });
|
||||
let response = await tryAdd(freshState.cursor);
|
||||
// Only a definitive global cursor conflict allows a new signature. An ambiguous
|
||||
// delivery is handled by submitSignedEvent using the original signed bytes.
|
||||
const code = String(response?.payload?.code || response?.code || '').toLowerCase();
|
||||
if (response.status !== 200 && ['bad_block_number', 'bad_prev_hash'].includes(code)) {
|
||||
const refreshed = await resolveFreshState();
|
||||
if (refreshed.blockchainName !== blockchainName) throw new Error('Blockchain changed during AddBlock');
|
||||
// HEADER must never be recreated at a nonzero number.
|
||||
if (!(event.msgType === MSG_TYPE_TECH && event.msgSubType === MSG_SUBTYPE_TECH_HEADER)) {
|
||||
response = await tryAdd(refreshed.cursor);
|
||||
try {
|
||||
const freshState = await resolveFreshState();
|
||||
const blockchainName = String(freshState?.blockchainName || '').trim();
|
||||
if (!blockchainName) throw new Error('runAddBlockWithRetry: blockchainName is empty');
|
||||
const tryAdd = cursor => this.submitPreparedAddBlock({ login, storagePwd, blockchainName,
|
||||
blockNumber: Number(cursor?.serverLastGlobalNumber ?? -1) + 1,
|
||||
prevBlockHash: normalizeHex32(cursor?.serverLastGlobalHash, ZERO64), event });
|
||||
let response = await tryAdd(freshState.cursor);
|
||||
// Only a definitive global cursor conflict allows a new signature. An ambiguous
|
||||
// delivery is handled by submitSignedEvent using the original signed bytes.
|
||||
const code = String(response?.payload?.code || response?.code || '').toLowerCase();
|
||||
if (response.status !== 200 && ['bad_block_number', 'bad_prev_hash'].includes(code)) {
|
||||
const refreshed = await resolveFreshState();
|
||||
if (refreshed.blockchainName !== blockchainName) throw new Error('Blockchain changed during AddBlock');
|
||||
// HEADER must never be recreated at a nonzero number.
|
||||
if (!(event.msgType === MSG_TYPE_TECH && event.msgSubType === MSG_SUBTYPE_TECH_HEADER)) {
|
||||
response = await tryAdd(refreshed.cursor);
|
||||
}
|
||||
}
|
||||
if (response.status !== 200) throw opError('AddBlock', response);
|
||||
void import('./block-publication-service.js').then(({ publishPendingBlocks }) =>
|
||||
publishPendingBlocks({ ws: this.ws, login, storagePwd, blockchainName }))
|
||||
.catch(error => console.warn('Block publication start failed', error));
|
||||
return { response, blockchainName };
|
||||
} catch (error) {
|
||||
showToast(t('block_publication.add_failed'), { kind: 'error' });
|
||||
throw error;
|
||||
}
|
||||
if (response.status !== 200) throw opError('AddBlock', response);
|
||||
return { response, blockchainName };
|
||||
}
|
||||
|
||||
async addBlockSigned({ login, storagePwd, msgType, msgSubType, msgVersion = 1, bodyBytes, channelSlug = '', _skipHeaderEnsure = false }) {
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { base64ToBytes } from './crypto-utils.js';
|
||||
import { unpackCoreContent } from './core-content.js';
|
||||
import { uploadSignedBlockDataItem } from './turbo-upload-service.js';
|
||||
import { showToast } from './channels-ux.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
const running = new Set();
|
||||
const scheduled = new Map();
|
||||
const lastNotice = new Map();
|
||||
|
||||
/** После перезапуска браузер повторно получает подписанные bytes с сервера. */
|
||||
export async function publishPendingBlocks({ ws, login, storagePwd, blockchainName }) {
|
||||
if (!ws || !login || !storagePwd || !blockchainName || running.has(blockchainName)) return;
|
||||
running.add(blockchainName);
|
||||
let keepPolling = false;
|
||||
try {
|
||||
const response = await ws.request('BlockPublication', { action: 'list', blockchainName });
|
||||
if (response.status !== 200) return;
|
||||
keepPolling = true;
|
||||
for (const block of response.payload?.pendingBlocks || []) {
|
||||
const read = await ws.request('GetBlockchainBlock', { blockchainName, blockNumber: block.blockNumber });
|
||||
if (read.status !== 200 || String(read.payload?.blockHash || '').toLowerCase() !== block.coreHash) {
|
||||
throw new Error('Pending block bytes unavailable or changed');
|
||||
}
|
||||
const { contentDataItem, coreDataItem } = unpackCoreContent(base64ToBytes(read.payload.blockBytesB64));
|
||||
let uploadError = '';
|
||||
try {
|
||||
if (!block.contentConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: contentDataItem, expectedId: block.contentId });
|
||||
if (!block.coreConfirmed) await uploadSignedBlockDataItem({ login, storagePwd, bytes: coreDataItem, expectedId: block.coreId });
|
||||
} catch (error) {
|
||||
uploadError = String(error?.message || error);
|
||||
const insufficientCredits = /(?:\b402\b|insufficient (?:balance|funds|credits)|not enough (?:balance|funds|credits)|payment required|недостаточно (?:средств|кредитов))/i.test(uploadError);
|
||||
const noticeKey = `${blockchainName}:${block.blockNumber}`;
|
||||
if (Date.now() - (lastNotice.get(noticeKey) || 0) >= 30 * 60_000) {
|
||||
showToast(t(insufficientCredits ? 'block_publication.insufficient_credits' : 'block_publication.upload_failed',
|
||||
{ number: block.blockNumber }), { kind: 'error', timeoutMs: 7000 });
|
||||
lastNotice.set(noticeKey, Date.now());
|
||||
}
|
||||
}
|
||||
await ws.request('BlockPublication', {
|
||||
action: 'report', blockchainName, blockNumber: block.blockNumber,
|
||||
contentId: block.contentId, coreId: block.coreId,
|
||||
contentHash: block.contentHash, coreHash: block.coreHash, error: uploadError,
|
||||
});
|
||||
if (uploadError) break;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Block publication queue unavailable', error);
|
||||
} finally {
|
||||
running.delete(blockchainName);
|
||||
if (keepPolling && !scheduled.has(blockchainName)) {
|
||||
const timer = globalThis.setTimeout(() => {
|
||||
scheduled.delete(blockchainName);
|
||||
void publishPendingBlocks({ ws, login, storagePwd, blockchainName });
|
||||
}, 30_000);
|
||||
scheduled.set(blockchainName, timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2265,34 +2265,20 @@ async function applyCameraState(call) {
|
||||
videoTrack.enabled = true;
|
||||
}
|
||||
} else {
|
||||
const blackTrack = ensureBlackVideoTrack(call);
|
||||
if (hadSlotBefore) {
|
||||
if (call.localStream && blackTrack) {
|
||||
const existingVideoTracks = call.localStream.getVideoTracks?.() || [];
|
||||
existingVideoTracks.forEach((track) => {
|
||||
if (track.id !== blackTrack.id) {
|
||||
try { call.localStream.removeTrack(track); } catch {}
|
||||
}
|
||||
});
|
||||
if (!existingVideoTracks.some((track) => track.id === blackTrack.id)) {
|
||||
call.localStream.addTrack(blackTrack);
|
||||
}
|
||||
}
|
||||
try {
|
||||
if (videoTransceiver && videoTransceiver.direction !== 'sendrecv') {
|
||||
videoTransceiver.direction = 'sendrecv';
|
||||
}
|
||||
} catch {}
|
||||
if (videoTransceiver?.sender) {
|
||||
try { await videoTransceiver.sender.replaceTrack(blackTrack || null); } catch {}
|
||||
// A black placeholder is still an active video track for the peer and leaves
|
||||
// its call UI on a black screen. Removing the source makes the remote track
|
||||
// mute, which restores the regular avatar call stage until video returns.
|
||||
try { await videoTransceiver.sender.replaceTrack(null); } catch {}
|
||||
call.videoSender = videoTransceiver.sender;
|
||||
bindVideoSenderStream(call, videoTransceiver.sender);
|
||||
await applyVideoSenderEncodingProfile(videoTransceiver.sender, 'placeholder');
|
||||
}
|
||||
} else {
|
||||
if (call.localStream && blackTrack) {
|
||||
syncLocalStreamVideoTrack(call, blackTrack, { stopRemoved: false });
|
||||
}
|
||||
try {
|
||||
if (videoTransceiver && videoTransceiver.direction !== 'sendrecv') {
|
||||
videoTransceiver.direction = 'sendrecv';
|
||||
@@ -2301,8 +2287,6 @@ async function applyCameraState(call) {
|
||||
if (hadReservedBefore && videoTransceiver?.sender) {
|
||||
try { await videoTransceiver.sender.replaceTrack(null); } catch {}
|
||||
call.videoSender = videoTransceiver.sender;
|
||||
} else if (call.videoTransportMode === VIDEO_TRANSPORT_SLOT && blackTrack) {
|
||||
await ensureVideoSenderSlot(call, { sourceTrack: blackTrack, profile: 'placeholder' });
|
||||
}
|
||||
}
|
||||
await disableCameraTrack(call);
|
||||
|
||||
@@ -166,7 +166,10 @@ function getIconSvg(name) {
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><rect x="9" y="3.5" width="6" height="11" rx="3" fill="none" stroke="currentColor" stroke-width="1.8"/><path d="M6 11.5a6 6 0 0 0 7.2 5.88" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M12 17.5v3" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M8.5 20.5h7" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/><path d="M5 5l14 14" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/></svg>';
|
||||
}
|
||||
if (name === 'hangup') {
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7l10 10M17 7 7 17" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round"/></svg>';
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.1 8.5c3.8-3.1 10-3.1 13.8 0l-2 2.4a1.3 1.3 0 0 1-1.6.3l-1.6-.8a1.3 1.3 0 0 0-1.2 0l-1.6.8a1.3 1.3 0 0 1-1.6-.3z" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
||||
}
|
||||
if (name === 'answer') {
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5.1 8.5c3.8-3.1 10-3.1 13.8 0l-2 2.4a1.3 1.3 0 0 1-1.6.3l-1.6-.8a1.3 1.3 0 0 0-1.2 0l-1.6.8a1.3 1.3 0 0 1-1.6-.3z" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" transform="rotate(180 12 12)"/></svg>';
|
||||
}
|
||||
if (name === 'minimize') {
|
||||
return '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 6v12M7.5 10.5 12 6l4.5 4.5" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
|
||||
@@ -455,16 +458,16 @@ function ensureUi() {
|
||||
|
||||
acceptBtn = document.createElement('button');
|
||||
acceptBtn.type = 'button';
|
||||
acceptBtn.className = 'call-accept-btn';
|
||||
acceptBtn.textContent = t('remaining.call_ui.answer');
|
||||
acceptBtn.className = 'call-call-action-btn call-call-action-btn--accept';
|
||||
setButtonIcon(acceptBtn, 'answer', t('remaining.call_ui.answer'));
|
||||
acceptBtn.addEventListener('click', async () => {
|
||||
await acceptIncomingCall();
|
||||
});
|
||||
|
||||
declineBtn = document.createElement('button');
|
||||
declineBtn.type = 'button';
|
||||
declineBtn.className = 'destructive-btn call-decline-btn';
|
||||
declineBtn.textContent = t('remaining.call_ui.decline');
|
||||
declineBtn.className = 'call-call-action-btn call-call-action-btn--decline';
|
||||
setButtonIcon(declineBtn, 'hangup', t('remaining.call_ui.decline'));
|
||||
declineBtn.addEventListener('click', async () => {
|
||||
await declineIncomingCall();
|
||||
});
|
||||
|
||||
@@ -188,6 +188,39 @@ export async function uploadFileWithTurbo({
|
||||
};
|
||||
}
|
||||
|
||||
/** Загружает готовый подписанный DataItem, сохраняя исходные bytes и ID. */
|
||||
export async function uploadSignedBlockDataItem({ login, storagePwd, bytes, expectedId }) {
|
||||
if (!(bytes instanceof Uint8Array) || bytes.length === 0) throw new Error('Empty signed DataItem');
|
||||
const alreadyUploaded = async () => {
|
||||
try {
|
||||
const response = await fetch(`https://turbo.ardrive.io/tx/${encodeURIComponent(expectedId)}/status`);
|
||||
if (!response.ok) return false;
|
||||
const status = String((await response.json())?.status || '').toUpperCase();
|
||||
return ['PENDING', 'CONFIRMED', 'BUNDLED', 'FINALIZED'].includes(status);
|
||||
} catch { return false; }
|
||||
};
|
||||
if (await alreadyUploaded()) return { id: expectedId, alreadyUploaded: true };
|
||||
const { turbo } = await getTurboContextForStoredSolanaKey({ login, storagePwd });
|
||||
let result;
|
||||
try {
|
||||
result = await turbo.uploadSignedDataItem({
|
||||
dataItemStreamFactory: () => new ReadableStream({
|
||||
start(controller) { controller.enqueue(bytes); controller.close(); },
|
||||
}),
|
||||
dataItemSizeFactory: () => bytes.length,
|
||||
});
|
||||
} catch (error) {
|
||||
// Потерянный ответ Turbo или повтор того же DataItem не создаёт новый блок.
|
||||
if (await alreadyUploaded()) return { id: expectedId, alreadyUploaded: true };
|
||||
if (/data item exists|already exists/i.test(String(error?.message || error))) {
|
||||
return { id: expectedId, alreadyUploaded: true };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (String(result?.id || '') !== expectedId) throw new Error('Turbo returned another DataItem ID');
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function topUpTurboWithSolana({
|
||||
login,
|
||||
storagePwd,
|
||||
|
||||
@@ -407,8 +407,7 @@
|
||||
.call-overlay-controls--incoming[hidden],
|
||||
.call-overlay-controls--active[hidden],
|
||||
.call-icon-btn[hidden],
|
||||
.call-accept-btn[hidden],
|
||||
.call-decline-btn[hidden],
|
||||
.call-call-action-btn[hidden],
|
||||
.call-minimized-bar-actions[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -426,81 +425,54 @@
|
||||
|
||||
|
||||
|
||||
.call-decline-btn {
|
||||
min-width: 132px;
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn {
|
||||
min-width: 132px;
|
||||
min-height: 38px;
|
||||
padding: 9px 12px;
|
||||
.call-call-action-btn {
|
||||
width: 64px;
|
||||
min-width: 64px;
|
||||
height: 64px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: var(--radius-sm);
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
box-shadow: none;
|
||||
color: var(--text-primary);
|
||||
text-shadow: none;
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
font-weight: 700;
|
||||
border-radius: 50%;
|
||||
color: #fff;
|
||||
box-shadow: 0 10px 22px rgba(0, 0, 0, 0.28);
|
||||
cursor: pointer;
|
||||
transition: transform 90ms ease, box-shadow 90ms ease, background-color 90ms ease, filter 120ms ease;
|
||||
transition: transform 120ms ease, box-shadow 120ms ease, filter 120ms ease;
|
||||
}
|
||||
|
||||
.call-call-action-btn--accept {
|
||||
background: var(--success);
|
||||
}
|
||||
|
||||
.call-call-action-btn--decline {
|
||||
background: var(--danger);
|
||||
}
|
||||
|
||||
.call-call-action-btn svg {
|
||||
width: 31px;
|
||||
height: 31px;
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.call-accept-btn:hover {
|
||||
color: var(--text-primary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
transform: translateY(-1px);
|
||||
filter: brightness(1.12);
|
||||
.call-call-action-btn:hover {
|
||||
transform: translateY(-2px) scale(1.03);
|
||||
filter: brightness(1.08);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn:active {
|
||||
color: var(--text-primary);
|
||||
background: color-mix(in srgb, var(--surface) 12%, transparent);
|
||||
border: 0;
|
||||
box-shadow:
|
||||
inset 0 3px 8px rgba(0, 0, 0, 0.58),
|
||||
inset 0 -1px 2px color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
transform: translateY(1px) scale(0.97);
|
||||
.call-call-action-btn:active {
|
||||
transform: scale(0.94);
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn:disabled {
|
||||
opacity: 1;
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
border: 0;
|
||||
box-shadow: none;
|
||||
.call-call-action-btn:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
filter: none;
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn:focus-visible {
|
||||
outline: 2px solid var(--border-control);
|
||||
.call-call-action-btn:focus-visible {
|
||||
outline: 2px solid var(--text-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
|
||||
.call-accept-btn::before,
|
||||
.call-accept-btn::after {
|
||||
background: transparent;
|
||||
background-image: none;
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
|
||||
@media (max-width: 420px) {
|
||||
.call-overlay-controls {
|
||||
gap: 16px;
|
||||
@@ -516,8 +488,9 @@
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
.call-accept-btn,
|
||||
.call-decline-btn {
|
||||
min-width: 124px;
|
||||
.call-call-action-btn {
|
||||
width: 58px;
|
||||
min-width: 58px;
|
||||
height: 58px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
|
||||
const read = (relative) => fs.readFileSync(new URL(relative, import.meta.url), 'utf8');
|
||||
|
||||
test('входящий звонок использует зелёную и красную кнопки с иконками трубки', () => {
|
||||
const ui = read('../js/services/call-ui-service.js');
|
||||
const css = read('../styles/components/call-ui.css');
|
||||
assert.match(ui, /setButtonIcon\(acceptBtn, 'answer', t\('remaining\.call_ui\.answer'\)\)/);
|
||||
assert.match(ui, /setButtonIcon\(declineBtn, 'hangup', t\('remaining\.call_ui\.decline'\)\)/);
|
||||
assert.match(css, /\.call-call-action-btn--accept\s*\{\s*background: var\(--success\)/);
|
||||
assert.match(css, /\.call-call-action-btn--decline\s*\{\s*background: var\(--danger\)/);
|
||||
});
|
||||
|
||||
test('выключение камеры не передаёт чёрную видеозаглушку собеседнику', () => {
|
||||
const service = read('../js/services/call-service.js');
|
||||
const disabledSlot = service.slice(service.indexOf(' } else {\n if (hadSlotBefore)'), service.indexOf(' await disableCameraTrack(call);'));
|
||||
assert.match(disabledSlot, /videoTransceiver\.sender\.replaceTrack\(null\)/);
|
||||
assert.doesNotMatch(disabledSlot, /ensureBlackVideoTrack\(call\)/);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
|
||||
const auth = readFileSync(new URL('../js/services/auth-service.js', import.meta.url), 'utf8');
|
||||
|
||||
test('resumeSession загружает материал до вычисления targetSessionId и поддерживает выбранную сессию', () => {
|
||||
const method = auth.match(/async resumeSessionUnlocked\(login, preferredSessionId = ''\) \{[\s\S]*?\n \}/)?.[0] || '';
|
||||
assert.ok(method, 'метод resumeSessionUnlocked должен существовать');
|
||||
assert.match(method, /const requestedSessionId = String\(preferredSessionId \|\| ''\)\.trim\(\);/);
|
||||
assert.match(method, /loadSessionMaterial\(cleanLogin, requestedSessionId\)/);
|
||||
assert.match(method, /const targetSessionId = requestedSessionId \|\| sessionMaterial\.sessionId;/);
|
||||
assert.ok(
|
||||
method.indexOf('loadSessionMaterial(cleanLogin, requestedSessionId)')
|
||||
< method.indexOf('const targetSessionId = requestedSessionId || sessionMaterial.sessionId;'),
|
||||
'session material должен загружаться до вычисления targetSessionId',
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user