Files
SHiNE-server/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlockSyncService.java
T

898 lines
52 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package server.archive;
import blockchain.Ans104DataItem;
import blockchain.BchBlockEntry;
import server.archive.registration.VerifiedFreeRegistrationImporter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard;
import shine.db.DbController;
import shine.db.KeyEncodingUtil;
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;
import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.RegistrationIdentityDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.*;
/**
* Discovers signed CORE items and registration certificates in the active App namespace.
* Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
*/
public final class ArweaveBlockSyncService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final Base64.Decoder B64URL = Base64.getUrlDecoder();
private final ArweaveBlocksConfig cfg;
private final HttpClient http = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(20))
.followRedirects(HttpClient.Redirect.NORMAL)
.build();
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
private final Net_AddBlock_Handler addBlock = new Net_AddBlock_Handler();
private final BlockchainForkSegmentsDAO segmentsDAO = BlockchainForkSegmentsDAO.getInstance();
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
private final BlockchainResyncCleanupDAO cleanupDAO = BlockchainResyncCleanupDAO.getInstance();
// DataItem уже виден через GraphQL, но его физические координаты внутри ANS-104 bundle
// ещё не появились у индексатора. Полный discovery остаётся редким, а эти ID ретраятся часто.
private final Map<String, PendingDownload> unresolvedDownloads = new LinkedHashMap<>();
public ArweaveBlockSyncService(ArweaveBlocksConfig cfg) { this.cfg = cfg; }
public void runCycle() throws Exception {
recoverInterruptedCanonicalRebuilds();
discover();
discoverFreeRegistrations();
drainQueue();
}
/** Быстрый retry только для уже обнаруженных DataItem, без повторного полного GraphQL discovery. */
public void runRetryCycle() throws Exception {
int queued = retryPendingDownloads();
if (queued > 0) drainQueue();
}
private void discover() throws Exception {
long stored = importDAO.getLastBlockHeight();
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
String cursor = null;
long maxHeight = minHeight;
long lowestRetryHeight = Long.MAX_VALUE;
int discovered = 0;
do {
JsonNode response = graphQlPage(minHeight, cursor);
JsonNode txs = response.path("data").path("transactions");
if (response.has("errors")) throw new IOException("Arweave GraphQL errors: " + response.path("errors"));
JsonNode edges = txs.path("edges");
if (!edges.isArray()) throw new IOException("Arweave GraphQL returned no transactions.edges");
String nextCursor = null;
for (JsonNode edge : edges) {
nextCursor = edge.path("cursor").asText(null);
JsonNode node = edge.path("node");
String dataItemId = node.path("id").asText("").trim();
long height = node.path("block").path("height").asLong(-1L);
if (dataItemId.isBlank() || height < 0) continue;
maxHeight = Math.max(maxHeight, height);
byte[] id32;
try {
id32 = B64URL.decode(dataItemId);
if (id32.length != 32) throw new IllegalArgumentException("id length=" + id32.length);
} catch (Exception e) {
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
continue;
}
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;
}
try {
DownloadedEvent downloaded = downloadEvent(dataItemId);
if (downloaded.registration()) {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(dataItemId);
continue; // Не парсить регистрацию как BchBlockEntry.
}
unresolvedDownloads.remove(dataItemId);
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
} catch (RetryableDataItemDownloadException e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
log.info("Signed DataItem {} visible at height {} but raw ANS-104 bytes are not ready yet; queued for fast retry: {}",
dataItemId, height, e.getMessage());
} catch (Exception e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
log.warn("Cannot retrieve signed DataItem {} at height {} yet: {}", dataItemId, height, e.getMessage());
}
}
boolean hasNext = txs.path("pageInfo").path("hasNextPage").asBoolean(false);
cursor = hasNext ? nextCursor : null;
if (hasNext && (cursor == null || cursor.isBlank())) throw new IOException("GraphQL hasNextPage without cursor");
} while (cursor != null);
// Keep inclusive overlap. If a gateway has indexed GraphQL before offsets, do not advance past that item.
long checkpoint = lowestRetryHeight == Long.MAX_VALUE ? maxHeight : Math.min(maxHeight, lowestRetryHeight);
importDAO.setLastBlockHeight(checkpoint, System.currentTimeMillis());
if (discovered > 0) {
log.info("Arweave discovery queued {} new SHiNE test DataItems; checkpoint={}", discovered, checkpoint);
}
}
private int retryPendingDownloads() throws Exception {
if (unresolvedDownloads.isEmpty()) return 0;
int queued = 0;
int attempted = 0;
List<PendingDownload> snapshot = new ArrayList<>(unresolvedDownloads.values());
for (PendingDownload pending : snapshot) {
if (attempted >= cfg.syncPageSize()) break;
attempted++;
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;
}
DownloadedEvent downloaded;
try {
downloaded = downloadEvent(pending.dataItemId());
} catch (RetryableDataItemDownloadException e) {
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
unresolvedDownloads.remove(pending.dataItemId());
unresolvedDownloads.put(pending.dataItemId(), pending);
log.debug("ANS-104 DataItem {} still waits for location/raw bytes: {}", pending.dataItemId(), e.getMessage());
continue;
} catch (Exception e) {
// Не долбим явно плохой ответ каждые 30 секунд. Полный discovery попробует его снова позднее.
unresolvedDownloads.remove(pending.dataItemId());
log.warn("Fast retry stopped for signed DataItem {} until next discovery: {}", pending.dataItemId(), e.getMessage());
continue;
}
if (downloaded.registration()) {
try {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(pending.dataItemId());
} catch (Exception e) {
unresolvedDownloads.remove(pending.dataItemId());
unresolvedDownloads.put(pending.dataItemId(), pending);
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
}
continue;
}
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
downloaded.rawDataItem(), System.currentTimeMillis())) {
queued++;
}
unresolvedDownloads.remove(pending.dataItemId());
}
if (queued > 0) {
log.info("Fast Arweave retry queued {} signed DataItems; {} still unresolved", queued, unresolvedDownloads.size());
}
return queued;
}
private void drainQueue() throws Exception {
int passes = 0;
int importedTotal = 0;
boolean progress;
Set<String> replayedLogins = new HashSet<>();
do {
progress = false;
// Phase 1 is global: validate every pending DataItem and discover all signed segment
// ancestry before any canonical/orphan decision is made.
prepareAllSegmentMetadata();
// Phase 2 is deterministic logical replay order, never Arweave height/order.
List<ArweaveBlockImportDAO.QueueItem> pending = importDAO.listPendingValidated(cfg.syncQueueBatchSize());
if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) {
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue;
}
int activeFork = forkOf(activeUser.getBlockchainName());
if (!isAncestryComplete(q.parsedLogin(), activeFork)) {
importDAO.setPendingError(q.dataItemId(), "ancestry_incomplete", System.currentTimeMillis());
continue;
}
int canonicalFork;
try (Connection cc = DbController.getInstance().getConnection()) {
canonicalFork = canonical.resolveFork(cc, q.parsedLogin(), activeFork, q.parsedBlockNumber());
}
if (canonicalFork != q.parsedForkNumber()) {
importDAO.reject(q.dataItemId(), "orphan_noncanonical", System.currentTimeMillis());
progress = true;
continue;
}
Ans104DataItem item;
BchBlockEntry parsedBlock;
try {
parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
item = parsedBlock.getCoreDataItem();
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
} catch (Exception e) {
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
progress = true;
continue;
}
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
importDAO.reject(q.dataItemId(), "validated_owner_mapping_changed", System.currentTimeMillis());
progress = true;
continue;
}
ensureState(physicalUser, parsedBlock);
Net_AddBlock_Handler.ArweaveImportResult result = addBlock.addBlockFromReplay(
physicalUser.getBlockchainName(), q.rawDataItem());
if (result.ok()) {
importDAO.delete(q.dataItemId());
importedTotal++;
replayedLogins.add(q.parsedLogin());
progress = true;
rebuildIfLocalOrphansExist(q.parsedLogin(), activeFork);
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)) {
importDAO.setPendingError(q.dataItemId(), reason, System.currentTimeMillis());
} else {
importDAO.reject(q.dataItemId(), reason, System.currentTimeMillis());
progress = true;
}
}
passes++;
} while (progress && passes < 1000);
// Replay deliberately suppresses live unread/push side effects. Recompute the server-owned
// unread projection from final canonical channel contents and preserved signed read_count.
if (!replayedLogins.isEmpty()) {
try (Connection c = DbController.getInstance().getConnection()) {
boolean ac = c.getAutoCommit(); c.setAutoCommit(false);
try {
for (String login : replayedLogins) {
ChannelReadStateDAO.getInstance().recalculateUnreadForOwnedChannels(c, login, System.currentTimeMillis());
}
c.commit();
} catch (Exception e) {
c.rollback(); throw e;
} finally { c.setAutoCommit(ac); }
}
}
if (importedTotal > 0) log.info("Imported {} SHiNE test DataItems from Arweave", importedTotal);
}
/**
* Phase 1 of Arweave recovery: scan the complete persistent PENDING queue and register only
* immutable segment ancestry metadata. No block is applied or rejected here.
*/
private void prepareAllSegmentMetadata() throws Exception {
String sql = "SELECT data_item_id,raw_data_item FROM arweave_block_import_queue WHERE status=? AND metadata_validated=FALSE ORDER BY block_height DESC, first_seen_at_ms DESC";
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ArweaveBlockImportDAO.STATUS_PENDING);
ps.setFetchSize(Math.max(100, cfg.syncQueueBatchSize()));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
byte[] id = rs.getBytes(1);
byte[] raw = rs.getBytes(2);
if (raw == null || raw.length == 0) {
importDAO.reject(id, "empty_data_item", System.currentTimeMillis());
continue;
}
try {
// Metadata is trusted only after complete ANS-104 validation.
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
Ans104DataItem item = b.getCoreDataItem();
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue;
}
int fork = forkOf(owner.getBlockchainName());
// Only signed structural anchor blocks can create/modify ancestry metadata.
if (fork == 1 && b.blockNumber == 0) {
if (!(b.body instanceof blockchain.body.HeaderBody))
throw new IllegalArgumentException("fork1 block #0 is not HEADER");
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
owner.getLogin(), 1, null, -1, null, 0, System.currentTimeMillis()));
} else if (b.body instanceof blockchain.body.ForkBody fb) {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
int parentFork = forkOf(parent.getBlockchainName());
if (parentFork >= fork) throw new IllegalArgumentException("TECH_FORK parent fork is not older");
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
owner.getLogin(), fork, parentFork,
fb.forkPointBlockNumber, fb.forkPointBlockHash32,
fb.forkPointBlockNumber + 1, System.currentTimeMillis()));
}
importDAO.markMetadataValidated(id, owner.getLogin(), fork, b.blockNumber, b.getHash32(), System.currentTimeMillis());
} catch (Exception e) {
importDAO.reject(id, "invalid_data_item: " + e.getMessage(), System.currentTimeMillis());
}
}
}
}
}
/** True only when rotation ancestry is known all the way back to fork1. */
private boolean isAncestryComplete(String login, int activeFork) throws Exception {
int f = activeFork;
Set<Integer> seen = new HashSet<>();
while (true) {
if (f < 1 || !seen.add(f)) return false;
BlockchainForkSegmentsDAO.Segment seg = segmentsDAO.get(login, f);
if (seg == null) return false;
if (seg.parentForkNumber() == null) {
return f == 1 && seg.firstPhysicalBlockNumber() == 0;
}
f = seg.parentForkNumber();
}
}
/**
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
*/
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
if (solana != null) return solana;
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
return null;
}
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
if (solana != null) return solana;
if (owner32 == null || owner32.length != 32) return null;
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT login, blockchain_key
FROM user_identity_current
WHERE registration_status='FREE_CERT' AND blockchain_key=?
LIMIT 1
""")) {
ps.setString(1, blockchainKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
}
}
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
if (solana != null) return solana;
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
String login = blockchainName.substring(0, blockchainName.length() - 4);
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
}
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
owner.setLogin(login);
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
owner.setPaidLimitBytes(0L);
return owner;
}
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
if(seg!=null&&seg.parentForkNumber()!=null){
s.setLastBlockNumber(seg.forkPointBlockNumber());s.setLastBlockHash(seg.forkPointBlockHash());
try(var c=shine.db.DbController.getInstance().getConnection();var ps=c.prepareStatement("SELECT COALESCE(SUM(octet_length(block_bytes)),0) FROM blocks_store WHERE LOWER(login)=LOWER(?) AND block_number<=? AND fork_number=shine_canonical_fork(?,?,block_number)")){
ps.setString(1,user.getLogin());ps.setInt(2,seg.forkPointBlockNumber());ps.setString(3,user.getLogin());ps.setInt(4,seg.parentForkNumber());try(var rs=ps.executeQuery()){if(rs.next())s.setFileSizeBytes(rs.getLong(1));}
}
} else{s.setLastBlockNumber(-1);s.setLastBlockHash(null);}
s.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(s);
if(existing!=null)stateDAO.upsert(s);
}
private static int forkOf(String n){int d=n.lastIndexOf('-');return Integer.parseInt(n.substring(d+1));}
/** Resume a durable canonical rebuild that was interrupted after staging/cleanup/replay. */
private void recoverInterruptedCanonicalRebuilds() throws Exception {
List<String> logins=new ArrayList<>();
try(Connection c=DbController.getInstance().getConnection();
PreparedStatement ps=c.prepareStatement("SELECT DISTINCT login FROM canonical_rebuild_staging ORDER BY login");
ResultSet rs=ps.executeQuery()){
while(rs.next())logins.add(rs.getString(1));
}
for(String login:logins){
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
}
}
/**
* A server may learn a deep fork only through Arweave after already materializing the old branch.
* If any local raw block is non-canonical under the current PDA fork, stage the canonical raw set
* and rebuild projections exactly like local key rotation does.
*/
private void rebuildIfLocalOrphansExist(String login,int activeFork)throws Exception{
if(!hasNonCanonicalLocalBlocks(login,activeFork))return;
if(!hasGenericStaging(login))stageLocalCanonicalBlocks(login,activeFork);
validateGenericStaging(login);
replayDurableCanonicalStaging(login,activeFork);
}
private boolean hasNonCanonicalLocalBlocks(String login,int activeFork)throws SQLException{
String sql="SELECT 1 FROM blocks_store b WHERE LOWER(b.login)=LOWER(?) AND b.fork_number<>shine_canonical_fork(?,?,b.block_number) LIMIT 1";
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);try(ResultSet rs=ps.executeQuery()){return rs.next();}
}
}
private boolean hasGenericStaging(String login)throws SQLException{
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT 1 FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) LIMIT 1")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){return rs.next();}
}
}
private void stageLocalCanonicalBlocks(String login,int activeFork)throws Exception{
try(Connection c=DbController.getInstance().getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
try(PreparedStatement d=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){d.setString(1,login);d.executeUpdate();}
String q="""
SELECT block_number,fork_number,block_bytes,block_hash
FROM blocks_store b
WHERE LOWER(login)=LOWER(?) AND fork_number=shine_canonical_fork(?,?,block_number)
ORDER BY block_number ASC
""";
String ins="INSERT INTO canonical_rebuild_staging(login,logical_block_number,physical_fork_number,block_bytes,block_hash) VALUES(?,?,?,?,?)";
try(PreparedStatement ps=c.prepareStatement(q);PreparedStatement out=c.prepareStatement(ins)){
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);
try(ResultSet rs=ps.executeQuery()){while(rs.next()){
out.setString(1,login);out.setInt(2,rs.getInt(1));out.setInt(3,rs.getInt(2));out.setBytes(4,rs.getBytes(3));out.setBytes(5,rs.getBytes(4));out.addBatch();
}}out.executeBatch();
}
c.commit();
}catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(ac);}}
}
private void validateGenericStaging(String login)throws Exception{
int expected=0,last=-1;byte[] previous=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
previous=hash;last=n;expected++;
}}
}
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
}
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{
validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login);
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}
}
cleanupDAO.finalizeCanonicalReplay(login);
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){ps.setString(1,login);ps.executeUpdate();}
}finally{BlockchainResyncGuard.end(activeName);}
}
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
private void discoverFreeRegistrations() throws Exception {
long stored;
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
ResultSet rs = ps.executeQuery()) {
stored = rs.next() ? rs.getLong(1) : 0;
}
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
long high = minHeight;
long retryFrom = Long.MAX_VALUE;
String cursor = null;
int count = 0;
do {
JsonNode response = graphQlPage(minHeight, cursor, true);
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
JsonNode txs = response.path("data").path("transactions");
JsonNode edges = txs.path("edges");
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
String next = null;
for (JsonNode edge : edges) {
next = edge.path("cursor").asText(null);
JsonNode node = edge.path("node");
String id = node.path("id").asText("").trim();
long height = node.path("block").path("height").asLong(-1);
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
high = Math.max(high, height);
try {
byte[] idBytes = B64URL.decode(id);
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
DownloadedDataItem item = downloadSignedDataItem(id);
if (!isRegistrationItem(item.rawDataItem()))
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
registrationImporter.importSigned(item.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
count++;
} catch (RetryableDataItemDownloadException e) {
retryFrom = Math.min(retryFrom, height);
log.debug("Registration DataItem {} is not downloadable yet", id);
} catch (IllegalArgumentException e) {
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
} catch (Exception e) {
retryFrom = Math.min(retryFrom, height);
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
}
}
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
throw new IOException("Registration GraphQL cursor missing");
} while (cursor != null);
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE free_registration_arweave_sync_state
SET last_block_height=?, updated_at_ms=? WHERE id=1
""")) {
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
}
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
}
private static boolean isRegistrationItem(byte[] raw) {
Ans104DataItem item = new Ans104DataItem(raw);
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
}
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
if (isRegistrationItem(first.rawDataItem())) {
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
}
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
return new DownloadedEvent(first.rootTxId(), container, false);
}
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
return graphQlPage(minHeight, cursor, false);
}
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
+ cfg.syncPageSize() + ", after:" + after
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
String body = MAPPER.writeValueAsString(Map.of("query", query));
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/graphql"))
.timeout(Duration.ofSeconds(60)).header("Content-Type","application/json").header("Accept","application/json")
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)).build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() < 200 || resp.statusCode() >= 300) throw new IOException("GraphQL HTTP " + resp.statusCode());
return MAPPER.readTree(resp.body());
}
/**
* Gateway по /{dataItemId} обычно отдаёт только payload. Для импорта SHiNE нужен полный
* подписанный ANS-104 DataItem, поэтому сначала резолвим rootTx + offset + size, а затем
* читаем точный range из root L1 transaction.
*/
private DownloadedDataItem downloadSignedDataItem(String dataItemId) throws Exception {
DataItemLocation location = resolveDataItemLocation(dataItemId);
long endInclusive = location.rootOffset() + location.size() - 1;
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/raw/" + location.rootTxId()))
.timeout(Duration.ofMinutes(2))
.header("Range", "bytes=" + location.rootOffset() + "-" + endInclusive)
.header("Accept", "application/octet-stream")
.GET().build();
HttpResponse<InputStream> resp = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
try (InputStream in = resp.body()) {
if (resp.statusCode() != 206) {
if (isRetryableHttpStatus(resp.statusCode())) {
throw new RetryableDataItemDownloadException(
"root range is temporarily unavailable via " + location.source() + ": HTTP " + resp.statusCode());
}
throw new IOException("Gateway ignored root range for DataItem " + dataItemId + ": HTTP " + resp.statusCode());
}
byte[] bytes = readExactlyBounded(in, Math.toIntExact(location.size()));
if (bytes.length != location.size()) {
throw new RetryableDataItemDownloadException(
"truncated DataItem range: expected=" + location.size() + " got=" + bytes.length);
}
Ans104DataItem parsed = new Ans104DataItem(bytes);
byte[] expectedId = B64URL.decode(dataItemId);
if (!Arrays.equals(parsed.id32(), expectedId)) {
throw new IOException("Range returned another ANS-104 DataItem for " + dataItemId);
}
return new DownloadedDataItem(location.rootTxId(), bytes);
}
}
/**
* Координаты считаются только подсказкой транспорта: источник может ошибиться, поэтому после
* range-read всё равно обязательно сверяется настоящий ANS-104 DataItem ID и затем подпись.
*/
private DataItemLocation resolveDataItemLocation(String dataItemId) throws Exception {
List<String> misses = new ArrayList<>(3);
try {
DataItemLocation location = getArIoIndexedLocation(dataItemId);
if (location != null) return location;
misses.add("ar-io=404");
} catch (Exception e) {
misses.add("ar-io=" + shortError(e));
}
try {
DataItemLocation location = getTurboLocation(dataItemId);
if (location != null) return location;
misses.add("turbo=404");
} catch (Exception e) {
misses.add("turbo=" + shortError(e));
}
try {
DataItemLocation location = getHeadLocation(dataItemId);
if (location != null) return location;
misses.add("head=no-location");
} catch (Exception e) {
misses.add("head=" + shortError(e));
}
throw new RetryableDataItemDownloadException(
"ANS-104 location not available yet (" + String.join(", ", misses) + ")");
}
/** Самый дешёвый путь: локальный индекс AR.IO gateway. */
private DataItemLocation getArIoIndexedLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/ar-io/offsets/" + dataItemId))
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
}
JsonNode offsets = MAPPER.readTree(resp.body());
return validateLocation("ar-io", dataItemId,
offsets.path("rootTxId").asText("").trim(),
offsets.path("rootOffset").asLong(-1L),
offsets.path("size").asLong(-1L));
}
/** Turbo часто знает координаты раньше общего gateway index. */
private DataItemLocation getTurboLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncTurboApiBase()) + "/tx/" + dataItemId + "/offsets"))
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
}
JsonNode offsets = MAPPER.readTree(resp.body());
return validateLocation("turbo", dataItemId,
offsets.path("rootBundleId").asText("").trim(),
offsets.path("startOffsetInRootBundle").asLong(-1L),
offsets.path("rawContentLength").asLong(-1L));
}
/**
* Последний fallback: успешный HEAD/GET AR.IO может вернуть координаты DataItem в headers.
* Поддерживаем несколько имён headers, чтобы пережить различия версий gateway.
*/
private DataItemLocation getHeadLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/" + dataItemId))
.timeout(Duration.ofSeconds(45))
.header("Accept", "application/octet-stream")
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode());
}
String rootTxId = firstHeader(resp, "X-AR-IO-Root-Transaction-Id");
long offset = firstLongHeader(resp,
"X-AR-IO-Root-Item-Offset",
"X-AR-IO-Root-Data-Item-Offset",
"X-AR-IO-Data-Item-Offset");
long size = firstLongHeader(resp,
"X-AR-IO-Root-Item-Size",
"X-AR-IO-Data-Item-Size");
if (rootTxId == null || offset < 0 || size <= 0) return null;
return validateLocation("head", dataItemId, rootTxId, offset, size);
}
private DataItemLocation validateLocation(String source, String dataItemId, String rootTxId, long rootOffset, long size)
throws IOException {
if (!isArweaveId(rootTxId) || rootOffset < 0 || size <= 0) {
throw new IOException("bad location for " + dataItemId + ": rootTxId=" + rootTxId
+ " offset=" + rootOffset + " size=" + size);
}
if (size > cfg.syncMaxDataItemBytes()) {
throw new IOException("DataItem exceeds syncMaxDataItemBytes: " + size);
}
if (size > Integer.MAX_VALUE) throw new IOException("DataItem is too large for in-memory import: " + size);
if (rootOffset > Long.MAX_VALUE - size) throw new IOException("DataItem offset overflow");
return new DataItemLocation(rootTxId, rootOffset, size, source);
}
private static String firstHeader(HttpResponse<?> response, String name) {
return response.headers().firstValue(name).map(String::trim).filter(v -> !v.isEmpty()).orElse(null);
}
private static long firstLongHeader(HttpResponse<?> response, String... names) {
for (String name : names) {
String value = firstHeader(response, name);
if (value == null) continue;
try { return Long.parseLong(value); }
catch (NumberFormatException ignored) { }
}
return -1L;
}
private static boolean isArweaveId(String value) {
if (value == null || value.length() != 43) return false;
try { return B64URL.decode(value).length == 32; }
catch (IllegalArgumentException e) { return false; }
}
private static boolean isRetryableHttpStatus(int status) {
return status == 404 || status == 408 || status == 425 || status == 429 || status >= 500;
}
private static String shortError(Exception e) {
String message = e.getMessage();
return safe(message == null || message.isBlank() ? e.getClass().getSimpleName() : message);
}
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
private static final class RetryableDataItemDownloadException extends IOException {
private RetryableDataItemDownloadException(String message) { super(message); }
}
private static byte[] readExactlyBounded(InputStream in, int expected) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(expected);
byte[] buf = new byte[Math.min(64 * 1024, Math.max(1024, expected))];
int remaining = expected;
while (remaining > 0) {
int n = in.read(buf, 0, Math.min(buf.length, remaining));
if (n < 0) break;
out.write(buf, 0, n);
remaining -= n;
}
return out.toByteArray();
}
private static String safe(String value) {
String v = value == null ? "" : value.replace('\n',' ').replace('\r',' ').trim();
return v.length() <= 500 ? v : v.substring(0, 500);
}
private static String trim(String s){return String.valueOf(s==null?"":s).trim().replaceAll("/+$","");}
private static String escapeGraphQl(String s){return s.replace("\\","\\\\").replace("\"","\\\"");}
}