SHA256
Новый формат блоков CORE/CONTENT test5595
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.BchBlockEntry;
|
||||
import blockchain.CoreContentContainer;
|
||||
import blockchain.CoreContentTransport;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Thin adapter for the existing archive queues. No signing, state or independent retry. */
|
||||
final class ArchiveBlockPair {
|
||||
private ArchiveBlockPair() {}
|
||||
|
||||
@FunctionalInterface interface Upload<R> {
|
||||
R upload(byte[] raw, byte[] id) throws Exception;
|
||||
}
|
||||
@FunctionalInterface interface Download {
|
||||
byte[] download(byte[] id) throws Exception;
|
||||
}
|
||||
|
||||
/** Returns CORE acknowledgement only after both uploads succeed. */
|
||||
static <R> R publish(byte[] container, byte[] expectedCoreId, Upload<R> uploader) throws Exception {
|
||||
BchBlockEntry block = BchBlockEntry.fromCoreContent(container);
|
||||
Ans104DataItem core = block.getCoreDataItem(), content = block.getContentDataItem();
|
||||
if (!Arrays.equals(core.id32(), expectedCoreId)) throw new IllegalArgumentException("CORE id mismatch");
|
||||
uploader.upload(content.rawBytes(), content.id32());
|
||||
return uploader.upload(core.rawBytes(), core.id32());
|
||||
}
|
||||
|
||||
/** Download by signed reference, not by search tag or the CORE bundle location. */
|
||||
static byte[] download(byte[] coreRaw, byte[] expectedCoreId, Download downloader) throws Exception {
|
||||
Ans104DataItem core = new Ans104DataItem(coreRaw);
|
||||
var record = CoreContentTransport.verifyCore(core, core.owner32(), expectedCoreId, Instant.now().getEpochSecond());
|
||||
Ans104DataItem content = new Ans104DataItem(downloader.download(record.contentDataItemId32()));
|
||||
CoreContentTransport.verifyContent(record, content, core.owner32());
|
||||
return CoreContentContainer.pack(core, content);
|
||||
}
|
||||
}
|
||||
+7
-76
@@ -8,7 +8,6 @@ import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
||||
import server.sync.ArweavePublishSignal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
@@ -20,12 +19,11 @@ public final class ArweaveBlockPublisherService {
|
||||
private final ArweaveBlocksConfig cfg;
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
|
||||
private final ArweaveL1Uploader arweaveUploader;
|
||||
private final TurboDataItemUploader turboUploader;
|
||||
|
||||
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
|
||||
cfg.validatePublisher();
|
||||
this.cfg = cfg;
|
||||
this.arweaveUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.ARWEAVE ? new ArweaveL1Uploader(cfg) : null;
|
||||
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
|
||||
}
|
||||
|
||||
@@ -42,7 +40,7 @@ public final class ArweaveBlockPublisherService {
|
||||
if (entry == null) return true;
|
||||
byte[] raw = entry.getBlockBytes();
|
||||
if (raw == null || raw.length == 0) return false;
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
|
||||
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
|
||||
@@ -53,7 +51,7 @@ public final class ArweaveBlockPublisherService {
|
||||
if (entry == null) return true;
|
||||
byte[] raw = entry.getBlockBytes();
|
||||
if (raw == null || raw.length == 0) return false;
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
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());
|
||||
@@ -83,7 +81,7 @@ public final class ArweaveBlockPublisherService {
|
||||
attempted += rotationCandidates.size();
|
||||
published += switch (cfg.publishMode()) {
|
||||
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
|
||||
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates);
|
||||
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||
case NONE -> 0;
|
||||
};
|
||||
}
|
||||
@@ -96,7 +94,7 @@ public final class ArweaveBlockPublisherService {
|
||||
if (candidates.isEmpty()) return published;
|
||||
published += switch (cfg.publishMode()) {
|
||||
case TURBO -> publishTurbo(candidates, onPublished);
|
||||
case ARWEAVE -> publishDirectArweave(candidates);
|
||||
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||
case NONE -> 0;
|
||||
};
|
||||
return published;
|
||||
@@ -110,7 +108,7 @@ public final class ArweaveBlockPublisherService {
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
@@ -135,7 +133,7 @@ public final class ArweaveBlockPublisherService {
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
@@ -151,71 +149,4 @@ public final class ArweaveBlockPublisherService {
|
||||
return published;
|
||||
}
|
||||
|
||||
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
|
||||
List<byte[]> items = new ArrayList<>();
|
||||
List<byte[]> ids = new ArrayList<>();
|
||||
long estimated = 32;
|
||||
for (KeyRotationCandidateBlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
long next = estimated + 64L + raw.length;
|
||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
||||
if (next > cfg.publishMaxBundleBytes()) {
|
||||
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
||||
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
|
||||
continue;
|
||||
}
|
||||
items.add(raw);
|
||||
ids.add(id);
|
||||
estimated = next;
|
||||
}
|
||||
if (items.isEmpty()) return 0;
|
||||
|
||||
byte[] bundle = Ans104Bundle.write(items);
|
||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
||||
);
|
||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
||||
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
||||
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
||||
items.size(), result.txId(), bundle.length);
|
||||
return items.size();
|
||||
}
|
||||
|
||||
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
|
||||
List<byte[]> items = new ArrayList<>();
|
||||
List<byte[]> ids = new ArrayList<>();
|
||||
long estimated = 32;
|
||||
for (BlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
long next = estimated + 64L + raw.length;
|
||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
||||
if (next > cfg.publishMaxBundleBytes()) {
|
||||
log.error("One DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
||||
e.getBchName(), e.getBlockNumber(), raw.length);
|
||||
continue;
|
||||
}
|
||||
items.add(raw);
|
||||
ids.add(id);
|
||||
estimated = next;
|
||||
}
|
||||
if (items.isEmpty()) return 0;
|
||||
|
||||
byte[] bundle = Ans104Bundle.write(items);
|
||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
||||
);
|
||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
||||
blocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
||||
log.info("Published {} SHiNE test DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
||||
items.size(), result.txId(), bundle.length);
|
||||
return items.size();
|
||||
}
|
||||
}
|
||||
|
||||
+90
-24
@@ -10,6 +10,7 @@ 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;
|
||||
@@ -19,6 +20,7 @@ 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;
|
||||
|
||||
@@ -38,9 +40,8 @@ import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
||||
* or inside a direct server-created ANS-104 bundle.
|
||||
* 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);
|
||||
@@ -120,8 +121,8 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
|
||||
try {
|
||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
DownloadedEvent downloaded = downloadEvent(dataItemId);
|
||||
if (downloaded.registration()) {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
@@ -167,9 +168,9 @@ public final class ArweaveBlockSyncService {
|
||||
continue;
|
||||
}
|
||||
|
||||
DownloadedDataItem downloaded;
|
||||
DownloadedEvent downloaded;
|
||||
try {
|
||||
downloaded = downloadSignedDataItem(pending.dataItemId());
|
||||
downloaded = downloadEvent(pending.dataItemId());
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
@@ -183,7 +184,7 @@ public final class ArweaveBlockSyncService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
if (downloaded.registration()) {
|
||||
try {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
@@ -225,7 +226,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (pending.isEmpty()) break;
|
||||
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
||||
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
||||
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
|
||||
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
|
||||
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
||||
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -249,15 +250,16 @@ public final class ArweaveBlockSyncService {
|
||||
Ans104DataItem item;
|
||||
BchBlockEntry parsedBlock;
|
||||
try {
|
||||
item = new Ans104DataItem(q.rawDataItem());
|
||||
parsedBlock = new BchBlockEntry(q.rawDataItem());
|
||||
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 = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
||||
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
||||
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
||||
@@ -328,14 +330,11 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
try {
|
||||
// Metadata is trusted only after complete ANS-104 validation.
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
|
||||
Ans104DataItem item = b.getCoreDataItem();
|
||||
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
|
||||
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
|
||||
throw new IllegalArgumentException("bad App tag");
|
||||
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
|
||||
BchBlockEntry b = new BchBlockEntry(raw);
|
||||
|
||||
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
||||
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -352,7 +351,7 @@ public final class ArweaveBlockSyncService {
|
||||
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 = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
|
||||
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
|
||||
if (parent == null || parent.getBlockchainName() == null
|
||||
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
||||
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
||||
@@ -388,6 +387,61 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обычный пользователь подтверждается текущим 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);
|
||||
@@ -414,7 +468,7 @@ public final class ArweaveBlockSyncService {
|
||||
while(rs.next())logins.add(rs.getString(1));
|
||||
}
|
||||
for(String login:logins){
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
|
||||
if(u==null||u.getBlockchainName()==null)continue;
|
||||
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
||||
}
|
||||
@@ -467,7 +521,7 @@ public final class ArweaveBlockSyncService {
|
||||
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=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+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);
|
||||
@@ -477,7 +531,7 @@ public final class ArweaveBlockSyncService {
|
||||
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
||||
}
|
||||
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
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);
|
||||
@@ -485,9 +539,9 @@ public final class ArweaveBlockSyncService {
|
||||
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
|
||||
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=usersDAO.getByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
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;
|
||||
}}
|
||||
@@ -565,6 +619,17 @@ public final class ArweaveBlockSyncService {
|
||||
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);
|
||||
}
|
||||
@@ -763,6 +828,7 @@ public final class ArweaveBlockSyncService {
|
||||
|
||||
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 {
|
||||
|
||||
+3
-3
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
|
||||
}
|
||||
|
||||
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
|
||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE;
|
||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
|
||||
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
|
||||
|
||||
public static ArweaveBlocksConfig load() {
|
||||
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
|
||||
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
|
||||
|
||||
public void validatePublisher() {
|
||||
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) {
|
||||
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave");
|
||||
if (publishMode == PublishMode.ARWEAVE) {
|
||||
throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
|
||||
}
|
||||
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
|
||||
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
|
||||
|
||||
+1
-4
@@ -16,10 +16,7 @@ import java.util.Locale;
|
||||
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
|
||||
public final class FreeRegistrationCertificateV1 {
|
||||
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
|
||||
private static final List<Ans104DataItem.Tag> TAGS = List.of(
|
||||
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
|
||||
|
||||
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||
byte[] clientKey, byte[] innerSignature,
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ public final class FreeRegistrationCertificateV1Check {
|
||||
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
|
||||
" Alice.Example+Tag@Example.COM ", signer);
|
||||
var item = new Ans104DataItem(cert);
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE))
|
||||
throw new AssertionError("Current App tag missing");
|
||||
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|
||||
@@ -37,7 +37,7 @@ public final class FreeRegistrationCertificateV1Check {
|
||||
throw new AssertionError("Inner signature tampering accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
|
||||
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||
}
|
||||
}
|
||||
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Offline tests with real signed fixtures and fake upload/download callbacks (no network). */
|
||||
public final class M4ArchiveBlockPairCheck {
|
||||
private static int checks;
|
||||
private static final HexFormat HEX = HexFormat.of();
|
||||
@FunctionalInterface interface Action { void run() throws Exception; }
|
||||
private static void ok(boolean value) { checks++; if (!value) throw new AssertionError("check " + checks); }
|
||||
private static void reject(Class<? extends Exception> type, Action action) throws Exception {
|
||||
try { action.run(); } catch (Exception e) { ok(type.isInstance(e)); return; }
|
||||
throw new AssertionError("Expected " + type);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
var lines = Files.readAllLines(Path.of(args[0]));
|
||||
for (String line : lines.subList(1, lines.size())) {
|
||||
String[] v = line.split("\t");
|
||||
byte[] core = HEX.parseHex(v[6]), content = HEX.parseHex(v[8]);
|
||||
byte[] coreId = new Ans104DataItem(core).id32(), contentId = new Ans104DataItem(content).id32();
|
||||
byte[] pair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(content));
|
||||
List<byte[]> sent = new ArrayList<>();
|
||||
var ack = ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
ok(Arrays.equals(new Ans104DataItem(raw).id32(), id)); sent.add(raw); return HEX.formatHex(id);
|
||||
});
|
||||
ok(sent.size() == 2); ok(Arrays.equals(sent.get(0), content)); ok(Arrays.equals(sent.get(1), core));
|
||||
ok(ack.equals(HEX.formatHex(coreId)));
|
||||
sent.clear();
|
||||
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
sent.add(raw); throw new IOException("CONTENT not accepted");
|
||||
}));
|
||||
ok(sent.size() == 1); ok(Arrays.equals(sent.get(0), content));
|
||||
sent.clear();
|
||||
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
sent.add(raw); if (Arrays.equals(id, coreId)) throw new IOException("CORE not accepted"); return null;
|
||||
}));
|
||||
ok(sent.size() == 2);
|
||||
ArchiveBlockPair.publish(pair, coreId, (raw, id) -> { sent.add(raw); return null; });
|
||||
ok(sent.size() == 4); ok(Arrays.equals(sent.get(0), sent.get(2))); ok(Arrays.equals(sent.get(1), sent.get(3)));
|
||||
byte[] restored = ArchiveBlockPair.download(core, coreId, id -> { ok(Arrays.equals(id, contentId)); return content; });
|
||||
ok(Arrays.equals(restored, pair));
|
||||
reject(IOException.class, () -> ArchiveBlockPair.download(core, coreId, id -> { throw new IOException("CONTENT not visible yet"); }));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> core));
|
||||
byte[] damaged = content.clone(); damaged[damaged.length - 1] ^= 1;
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> damaged));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, contentId, id -> { throw new AssertionError("Unverified CORE requested CONTENT"); }));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(pair, contentId, (raw,id) -> { throw new AssertionError("Wrong CORE published"); }));
|
||||
byte[] badPair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(damaged));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(badPair, coreId, (raw,id) -> { throw new AssertionError("Invalid CONTENT published"); }));
|
||||
}
|
||||
System.out.println("PASS: " + checks + " archive pair checks (order, exact retry, missing CONTENT, wrong ID, signature/hash)");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user