Compare commits

...
311 changed files with 19016 additions and 3822 deletions
+6
View File
@@ -1,3 +1,9 @@
# Актуальная ветка SHiNE — CORE/CONTENT Minimal (26.11.2026)
**Начать с [00_START_HERE.md](docs/CORE-CONTENT-MINIMAL/00_START_HERE.md).** Это единственный актуальный план перехода на новый формат. Рабочий код в корне — исходная версия 25.11.2026 с M1–M6: кодеки, AddBlock/read, client/registration, Turbo/Arweave import, FORK/rotation. Активный App=test5595. Автономные проверки PASS, полный Gradle/PG/E2E/firmware, живая ротация и Turbo NOT RUN; M6 offline завершён (viewer/test publisher адаптированы). Следующий шаг — M6_TEST_DEPLOY.md, интеграционная приёмка отдельного тестового стенда. Не деплоить в production. `reference/core-content-attempt-01/` — архив первой попытки, только донор. Инструкции, планы, статусы и AGENTS в reference не действуют. Не собирать и не деплоить reference, не переносить новый storage/социальный runtime. Прямая межсерверная синхронизация блокчейнов выведена из эксплуатации и исключена из плана. Не изменять независимые подсистемы или протокол без отдельного согласования. Старые правила ниже сохраняются, если не противоречат актуальным решениям Minimal.
---
# Инструкции для агентов SHiNE # Инструкции для агентов SHiNE
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке. Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
@@ -0,0 +1,83 @@
#pragma once
#include <cstdint>
#include <cstddef>
#include <vector>
#include <string>
#include <algorithm>
// Remote AddBlock body is the existing type/subtype/version + semantic body.
// This helper has no network/state dependencies; hashes and Ed25519 are supplied
// by the existing firmware crypto libraries (or the offline vector test).
namespace shine_core {
using Bytes = std::vector<uint8_t>;
using Hash = bool (*)(const uint8_t*, size_t, uint8_t*);
using Sign = bool (*)(const Bytes&, const uint8_t*, uint8_t*);
inline void putBE(Bytes& out, uint64_t n, unsigned count) {
for (unsigned i=count; i>0; --i) out.push_back(uint8_t(n >> ((i-1)*8)));
}
inline void putLE(Bytes& out, uint64_t n, unsigned count) {
for (unsigned i=0; i<count; ++i) out.push_back(uint8_t(n >> (i*8)));
}
inline uint32_t getBE(const uint8_t* p) {
return (uint32_t(p[0])<<24)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<8)|p[3];
}
inline Bytes text(const std::string& s) { return Bytes(s.begin(),s.end()); }
inline void avroLong(Bytes& out, size_t n) {
uint64_t x=uint64_t(n)*2;
while (x>=128) { out.push_back(uint8_t(x)|0x80); x>>=7; }
out.push_back(uint8_t(x));
}
inline void avroString(Bytes& out,const std::string& s) {
avroLong(out,s.size());out.insert(out.end(),s.begin(),s.end());
}
inline bool deepBlob(const Bytes& data,Hash sha384,uint8_t* out) {
Bytes tag=text("blob"+std::to_string(data.size()));uint8_t pair[96];
return sha384(tag.data(),tag.size(),pair)&&sha384(data.data(),data.size(),pair+48)&&sha384(pair,96,out);
}
inline bool makeItem(const Bytes& data,const Bytes& tags,size_t count,const uint8_t* owner,const uint8_t* secret,
Hash sha384,Sign sign,Bytes& out) {
const Bytes children[]={text("dataitem"),text("1"),text("2"),Bytes(owner,owner+32),Bytes(),Bytes(),tags,data};
const Bytes list=text("list8");uint8_t acc[48],pair[96],sig[64];
if(!sha384(list.data(),list.size(),acc))return false;
for(const Bytes& child:children){
std::copy(acc,acc+48,pair);
if(!deepBlob(child,sha384,pair+48)||!sha384(pair,96,acc))return false;
}
if(!sign(Bytes(acc,acc+48),secret,sig))return false;
out.clear();putLE(out,2,2);out.insert(out.end(),sig,sig+64);out.insert(out.end(),owner,owner+32);
out.push_back(0);out.push_back(0);putLE(out,count,8);putLE(out,tags.size(),8);
out.insert(out.end(),tags.begin(),tags.end());out.insert(out.end(),data.begin(),data.end());return true;
}
inline bool buildPair(uint16_t type,uint16_t subtype,uint16_t version,const Bytes& body,
uint32_t number,uint64_t timestamp,const uint8_t* prev,const uint8_t* owner,const uint8_t* secret,
const std::string& app,Hash sha256,Hash sha384,Sign sign,Bytes& out) {
constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647;
const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4;
const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130);
if((version!=1&&!(header&&(version==2||version==3)))||number>MAX_NUMBER||header!=(number==0)||(type==0&&!header&&!tech)||body.size()>8*1024*1024-124)return false;
if(header&&std::any_of(prev,prev+32,[](uint8_t b){return b!=0;}))return false;
const size_t prefix=fixed?40:(tech||channel?44:0),offset=fixed?0:4;
if(body.size()<prefix)return false;
uint32_t code=0,previous=0;
if(prefix){
if(tech&&getBE(body.data())!=0)return false;
code=type==3?CONNECTION:type==4?PROFILE:tech?TECH:getBE(body.data());
previous=getBE(body.data()+offset);
if(previous>=number||(channel&&(code>MAX_NUMBER||(code>0&&(code>=number||previous<code)))))return false;
}
Bytes content{1};putBE(content,type,2);putBE(content,subtype,2);putBE(content,version,2);
content.insert(content.end(),body.begin()+prefix,body.end());
Bytes contentItem,coreItem;uint8_t contentHash[32],contentId[32];
if(!makeItem(content,Bytes{0},0,owner,secret,sha384,sign,contentItem)||
!sha256(content.data(),content.size(),contentHash)||!sha256(contentItem.data()+2,64,contentId))return false;
Bytes core{1};core.insert(core.end(),prev,prev+32);putBE(core,number,4);putBE(core,timestamp,8);
core.insert(core.end(),contentHash,contentHash+32);core.insert(core.end(),contentId,contentId+32);
if(prefix){putBE(core,code,4);putBE(core,previous,4);core.insert(core.end(),body.begin()+offset+4,body.begin()+offset+36);}
Bytes tags;const size_t count=prefix?3:2;avroLong(tags,count);avroString(tags,"App");avroString(tags,app);
avroString(tags,"n");avroString(tags,std::to_string(number));
if(prefix){avroString(tags,"l");avroString(tags,code==PROFILE?"P":code==CONNECTION?"C":code==TECH?"T":std::to_string(code));}
tags.push_back(0);
if(!makeItem(core,tags,count,owner,secret,sha384,sign,coreItem))return false;
out.clear();putBE(out,coreItem.size(),4);out.insert(out.end(),coreItem.begin(),coreItem.end());out.insert(out.end(),contentItem.begin(),contentItem.end());return true;
}
} // namespace shine_core
@@ -9,6 +9,8 @@
#include <TouchDrvCSTXXX.hpp> #include <TouchDrvCSTXXX.hpp>
#include <mbedtls/gcm.h> #include <mbedtls/gcm.h>
#include <mbedtls/sha256.h> #include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
#include "shine_core_content.h"
#include <mbedtls/base64.h> #include <mbedtls/base64.h>
#include <Ed25519.h> #include <Ed25519.h>
#include <sodium.h> #include <sodium.h>
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
continue; continue;
} }
std::vector<uint8_t> preimage;
preimage.reserve(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
appendUint16BE(preimage, 0);
preimage.insert(preimage.end(), prevHash32, prevHash32 + 32);
int32_t blockSize = (int32_t)(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
appendInt32BE(preimage, blockSize);
appendInt32BE(preimage, nextBlockNumber);
appendInt64BE(preimage, (int64_t)(shineNowMs() / 1000ULL));
appendUint16BE(preimage, msgType);
appendUint16BE(preimage, msgSubType);
appendUint16BE(preimage, msgVersion);
preimage.insert(preimage.end(), bodyBytes.begin(), bodyBytes.end());
uint8_t blockchainSeed[32] = {}; uint8_t blockchainSeed[32] = {};
uint8_t blockchainPub[32] = {}; uint8_t blockchainPub[32] = {};
uint8_t blockchainSec[64] = {}; uint8_t blockchainSec[64] = {};
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
continue; continue;
} }
uint8_t hash32[32] = {}; std::vector<uint8_t> fullBlock;
sha256calc(preimage.data(), preimage.size(), hash32); const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
uint8_t signature[64] = {}; return mbedtls_sha256(data, len, out, 0) == 0;
if (!signMessageEd25519(std::vector<uint8_t>(hash32, hash32 + 32), blockchainSec, signature)) { };
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign AddBlock hash\",\"requestId\":\"") const auto hash384 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
uint8_t buffer[64] = {};
if (mbedtls_sha512(data, len, buffer, 1) != 0) return false;
memcpy(out, buffer, 48);
return true;
};
const auto sign = +[](const std::vector<uint8_t>& data, const uint8_t* key, uint8_t* sig) -> bool {
return signMessageEd25519(data, key, sig);
};
// Same semantic remote body and signal contract; only the signed wire bytes change.
if (resolvedBlockchainName != blockchainName || nextBlockNumber < 0 ||
!shine_core::buildPair(msgType, msgSubType, msgVersion, bodyBytes, (uint32_t)nextBlockNumber,
shineNowMs()/1000ULL, prevHash32, blockchainPub, blockchainSec,
"test5595", hash256, hash384, sign, fullBlock)) {
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign CORE/CONTENT pair\",\"requestId\":\"")
+ jsonEscape(item.signalRequestId) + "\"}"; + jsonEscape(item.signalRequestId) + "\"}";
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData); sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
continue; continue;
} }
std::vector<uint8_t> fullBlock = preimage;
fullBlock.push_back(0x01);
fullBlock.push_back(0x00);
fullBlock.insert(fullBlock.end(), signature, signature + 64);
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName) String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "\",\"blockNumber\":" + String((long long)nextBlockNumber)
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash) + ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}"; + "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
String addBlockResp; String addBlockResp;
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS); bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
const bool uncertain = !addBlockOk;
if (uncertain) {
// Retry the identical container, not the semantic request or a new timestamp.
addBlockResp = "";
addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
}
uint64_t statusCode = 0; uint64_t statusCode = 0;
jsonInt64Field(addBlockResp, "status", statusCode); jsonInt64Field(addBlockResp, "status", statusCode);
String serverLastHash; String serverLastHash;
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
jsonStringField(addBlockResp, "message", errorMessage); jsonStringField(addBlockResp, "message", errorMessage);
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber); jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
if (uncertain && (!addBlockOk || statusCode != 200)) {
const String readReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "}";
String readResp, readBytes;
uint64_t readStatus = 0;
if (shineWsRequest(gShineWs, "GetBlockchainBlock", readReq, readResp, SHINE_RPC_TIMEOUT_MS)) {
jsonInt64Field(readResp, "status", readStatus);
jsonStringField(readResp, "blockBytesB64", readBytes);
if (readStatus == 200 && readBytes == bytesToBase64String(fullBlock.data(), fullBlock.size())) {
jsonStringField(readResp, "blockHash", serverLastHash);
serverLastNumber = (uint64_t)nextBlockNumber;
addBlockOk = true;
statusCode = 200;
}
}
if (!addBlockOk || statusCode != 200) {
errorCode = "addblock_outcome_unknown";
errorMessage = "AddBlock outcome unknown; refresh history before retrying";
}
}
if (!addBlockOk || statusCode != 200) { if (!addBlockOk || statusCode != 200) {
if (errorCode.isEmpty()) { if (errorCode.isEmpty()) {
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed"; errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
+1 -1
View File
@@ -55,7 +55,7 @@ PDA 1.2 использует три постоянные роли ключей:
## Синхронизация пользовательских blockchain ## Синхронизация пользовательских blockchain
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync пока может оставаться как inert legacy, но не должен включаться в runtime. Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync удалён; не восстанавливать его. `ListBlockchainHeads` остаётся read-only API тестового издателя.
## Деплой ## Деплой
@@ -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);
}
}
@@ -8,7 +8,6 @@ import shine.db.entities.BlockEntry;
import shine.db.entities.KeyRotationCandidateBlockEntry; import shine.db.entities.KeyRotationCandidateBlockEntry;
import server.sync.ArweavePublishSignal; import server.sync.ArweavePublishSignal;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
@@ -20,12 +19,11 @@ public final class ArweaveBlockPublisherService {
private final ArweaveBlocksConfig cfg; private final ArweaveBlocksConfig cfg;
private final BlocksDAO blocksDAO = BlocksDAO.getInstance(); private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance(); private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
private final ArweaveL1Uploader arweaveUploader;
private final TurboDataItemUploader turboUploader; private final TurboDataItemUploader turboUploader;
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) { public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
cfg.validatePublisher();
this.cfg = cfg; 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; this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
} }
@@ -42,7 +40,7 @@ public final class ArweaveBlockPublisherService {
if (entry == null) return true; if (entry == null) return true;
byte[] raw = entry.getBlockBytes(); byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false; 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()); candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}", log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber()); result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
@@ -53,7 +51,7 @@ public final class ArweaveBlockPublisherService {
if (entry == null) return true; if (entry == null) return true;
byte[] raw = entry.getBlockBytes(); byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false; 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()); blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}", log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber()); result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
@@ -83,7 +81,7 @@ public final class ArweaveBlockPublisherService {
attempted += rotationCandidates.size(); attempted += rotationCandidates.size();
published += switch (cfg.publishMode()) { published += switch (cfg.publishMode()) {
case TURBO -> publishTurboRotation(rotationCandidates, onPublished); case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates); case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0; case NONE -> 0;
}; };
} }
@@ -96,7 +94,7 @@ public final class ArweaveBlockPublisherService {
if (candidates.isEmpty()) return published; if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) { published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished); case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> publishDirectArweave(candidates); case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0; case NONE -> 0;
}; };
return published; return published;
@@ -110,7 +108,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId(); byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue; if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try { try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id); TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis()); candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id); onPublished.accept(id);
published++; published++;
@@ -135,7 +133,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId(); byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue; if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try { try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id); TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis()); blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id); onPublished.accept(id);
published++; published++;
@@ -151,71 +149,4 @@ public final class ArweaveBlockPublisherService {
return published; 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();
}
} }
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard; import server.sync.BlockchainResyncGuard;
import shine.db.DbController; import shine.db.DbController;
import shine.db.KeyEncodingUtil;
import utils.config.AppConfig; import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO; import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO; import shine.db.dao.BlockchainStateDAO;
@@ -19,6 +20,7 @@ import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO; import shine.db.dao.ChannelReadStateDAO;
import shine.db.dao.BlockchainResyncCleanupDAO; import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO; import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.RegistrationIdentityDAO;
import shine.db.entities.BlockchainStateEntry; import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry; import shine.db.entities.SolanaUserPdaCurrentEntry;
@@ -38,9 +40,8 @@ import java.time.Duration;
import java.util.*; import java.util.*;
/** /**
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes. * Discovers signed CORE items and registration certificates in the active App namespace.
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo * Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
* or inside a direct server-created ANS-104 bundle.
*/ */
public final class ArweaveBlockSyncService { public final class ArweaveBlockSyncService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class); private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
@@ -120,8 +121,8 @@ public final class ArweaveBlockSyncService {
} }
try { try {
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId); DownloadedEvent downloaded = downloadEvent(dataItemId);
if (isRegistrationItem(downloaded.rawDataItem())) { if (downloaded.registration()) {
registrationImporter.importSigned(downloaded.rawDataItem(), registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED); VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(dataItemId); unresolvedDownloads.remove(dataItemId);
@@ -167,9 +168,9 @@ public final class ArweaveBlockSyncService {
continue; continue;
} }
DownloadedDataItem downloaded; DownloadedEvent downloaded;
try { try {
downloaded = downloadSignedDataItem(pending.dataItemId()); downloaded = downloadEvent(pending.dataItemId());
} catch (RetryableDataItemDownloadException e) { } catch (RetryableDataItemDownloadException e) {
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих. // Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
unresolvedDownloads.remove(pending.dataItemId()); unresolvedDownloads.remove(pending.dataItemId());
@@ -183,7 +184,7 @@ public final class ArweaveBlockSyncService {
continue; continue;
} }
if (isRegistrationItem(downloaded.rawDataItem())) { if (downloaded.registration()) {
try { try {
registrationImporter.importSigned(downloaded.rawDataItem(), registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED); VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
@@ -225,7 +226,7 @@ public final class ArweaveBlockSyncService {
if (pending.isEmpty()) break; if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) { for (ArweaveBlockImportDAO.QueueItem q : pending) {
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue; 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()) { if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis()); importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue; continue;
@@ -249,15 +250,16 @@ public final class ArweaveBlockSyncService {
Ans104DataItem item; Ans104DataItem item;
BchBlockEntry parsedBlock; BchBlockEntry parsedBlock;
try { try {
item = new Ans104DataItem(q.rawDataItem()); parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
parsedBlock = new BchBlockEntry(q.rawDataItem()); item = parsedBlock.getCoreDataItem();
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
} catch (Exception e) { } catch (Exception e) {
// Should be impossible after metadata validation, but never trust persisted bytes blindly. // Should be impossible after metadata validation, but never trust persisted bytes blindly.
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis()); importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
progress = true; progress = true;
continue; continue;
} }
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32()); SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin()) || !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) { || forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
@@ -328,14 +330,11 @@ public final class ArweaveBlockSyncService {
} }
try { try {
// Metadata is trusted only after complete ANS-104 validation. // 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 (!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) { if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis()); importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue; continue;
@@ -352,7 +351,7 @@ public final class ArweaveBlockSyncService {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1"); if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1) if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch"); 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 if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin())) || !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch"); 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 { private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry(); 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); 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)); while(rs.next())logins.add(rs.getString(1));
} }
for(String login:logins){ for(String login:logins){
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login); SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
if(u==null||u.getBlockchainName()==null)continue; if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName())); 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")){ 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()){ 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); 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&&!(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(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); 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); if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
} }
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{ 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); String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{ try{
validateGenericStaging(login); validateGenericStaging(login);
@@ -485,9 +539,9 @@ public final class ArweaveBlockSyncService {
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null; long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){ 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()){ 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); 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()); 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; cumulative+=raw.length;prevNumber=n;prevHash=hash;
}} }}
@@ -565,6 +619,17 @@ public final class ArweaveBlockSyncService {
return item.tags().contains(new Ans104DataItem.Tag("t", "reg")); 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 { private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
return graphQlPage(minHeight, cursor, false); return graphQlPage(minHeight, cursor, false);
} }
@@ -763,6 +828,7 @@ public final class ArweaveBlockSyncService {
private record PendingDownload(String dataItemId, byte[] id32, long height) {} private record PendingDownload(String dataItemId, byte[] id32, long height) {}
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {} 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 record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
private static final class RetryableDataItemDownloadException extends IOException { private static final class RetryableDataItemDownloadException extends IOException {
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
} }
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME; 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 final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
public static ArweaveBlocksConfig load() { public static ArweaveBlocksConfig load() {
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
public boolean publishEnabled() { return publishMode != PublishMode.NONE; } public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
public void validatePublisher() { public void validatePublisher() {
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) { if (publishMode == PublishMode.ARWEAVE) {
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave"); throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
} }
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) { if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo"); throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
@@ -16,10 +16,7 @@ import java.util.Locale;
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */ /** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
public final class FreeRegistrationCertificateV1 { public final class FreeRegistrationCertificateV1 {
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8); private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
private static final List<Ans104DataItem.Tag> TAGS = List.of( private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public record Verified(String login, byte[] rootKey, byte[] blockchainKey, public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
byte[] clientKey, byte[] innerSignature, byte[] clientKey, byte[] innerSignature,
@@ -19,7 +19,7 @@ public final class FreeRegistrationCertificateV1Check {
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client, byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
" Alice.Example+Tag@Example.COM ", signer); " Alice.Example+Tag@Example.COM ", signer);
var item = new Ans104DataItem(cert); 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"); throw new AssertionError("Current App tag missing");
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32()); var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root) 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"); } throw new AssertionError("Inner signature tampering accepted"); }
catch (IllegalArgumentException expected) {} 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"); + ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
} }
} }
@@ -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)");
}
}
@@ -56,7 +56,7 @@ public final class Ans104DataItem {
public Ans104DataItem(byte[] bytes) { public Ans104DataItem(byte[] bytes) {
Objects.requireNonNull(bytes, "bytes == null"); Objects.requireNonNull(bytes, "bytes == null");
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + 1) { if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8) {
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length); throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
} }
if (bytes.length > MAX_DATA_ITEM_BYTES) { if (bytes.length > MAX_DATA_ITEM_BYTES) {
@@ -126,7 +126,8 @@ public final class Ans104DataItem {
} }
public byte[] signingMessage() { public byte[] signingMessage() {
return buildSigningMessage(owner, target, anchor, tags, data); // Проверяем именно подписанные исходные байты, не повторную Avro-сериализацию.
return signingMessageRaw(owner, target, anchor, rawTags, data);
} }
/** /**
@@ -151,6 +152,10 @@ public final class Ans104DataItem {
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length); byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
byte[] rawTags = serializeAvroTags(safeTags); byte[] rawTags = serializeAvroTags(safeTags);
return signingMessageRaw(owner32, safeTarget, safeAnchor, rawTags, safeData);
}
private static byte[] signingMessageRaw(byte[] owner32, byte[] safeTarget, byte[] safeAnchor, byte[] rawTags, byte[] safeData) {
return deepHash(List.of( return deepHash(List.of(
utf8("dataitem"), utf8("dataitem"),
utf8("1"), utf8("1"),
@@ -270,15 +275,20 @@ public final class Ans104DataItem {
} }
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) { private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
if (raw.length == 0 && declaredCount == 0) return List.of();
AvroCursor c = new AvroCursor(raw); AvroCursor c = new AvroCursor(raw);
List<Tag> out = new ArrayList<>(); List<Tag> out = new ArrayList<>();
boolean terminated = false;
while (!c.eof()) { while (!c.eof()) {
long count = c.readLong(); long count = c.readLong();
if (count == 0) break; if (count == 0) { terminated = true; break; }
int blockEnd = -1;
if (count < 0) { if (count < 0) {
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
count = -count; count = -count;
long blockBytes = c.readLong(); long blockBytes = c.readLong();
if (blockBytes < 0) throw new IllegalArgumentException("Negative Avro tag block size"); if (blockBytes < 0 || blockBytes > raw.length - c.p) throw new IllegalArgumentException("Invalid Avro tag block size");
blockEnd = c.p + (int) blockBytes;
} }
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) { if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
throw new IllegalArgumentException("Too many Avro tags"); throw new IllegalArgumentException("Too many Avro tags");
@@ -291,7 +301,9 @@ public final class Ans104DataItem {
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes"); if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
out.add(new Tag(name, value)); out.add(new Tag(name, value));
} }
if (blockEnd != -1 && c.p != blockEnd) throw new IllegalArgumentException("Avro tag block size mismatch");
} }
if (!terminated) throw new IllegalArgumentException("Missing Avro array terminator");
if (!c.eof()) { if (!c.eof()) {
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags"); throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
} }
@@ -312,6 +324,7 @@ public final class Ans104DataItem {
while (true) { while (true) {
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long"); if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
int b = data[p++] & 0xff; int b = data[p++] & 0xff;
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
raw |= (long) (b & 0x7f) << shift; raw |= (long) (b & 0x7f) << shift;
if ((b & 0x80) == 0) break; if ((b & 0x80) == 0) break;
shift += 7; shift += 7;
@@ -324,7 +337,9 @@ public final class Ans104DataItem {
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) { if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
throw new IllegalArgumentException("Bad Avro string length: " + len); throw new IllegalArgumentException("Bad Avro string length: " + len);
} }
String s = new String(data, p, (int) len, StandardCharsets.UTF_8); String s;
try { s = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data, p, (int) len)).toString(); }
catch (java.nio.charset.CharacterCodingException e) { throw new IllegalArgumentException("Invalid UTF-8 Avro tag", e); }
p += (int) len; p += (int) len;
return s; return s;
} }
@@ -49,6 +49,9 @@ public final class BchBlockEntry {
public final BodyRecord body; public final BodyRecord body;
private final Ans104DataItem dataItem; private final Ans104DataItem dataItem;
private final Ans104DataItem contentItem;
private final CoreRecord coreRecord;
private final ContentRecord contentRecord;
private final byte[] frameBytes; private final byte[] frameBytes;
private final byte[] hash32; private final byte[] hash32;
@@ -56,6 +59,9 @@ public final class BchBlockEntry {
public BchBlockEntry(byte[] fullDataItemBytes) { public BchBlockEntry(byte[] fullDataItemBytes) {
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null"); Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
this.dataItem = new Ans104DataItem(fullDataItemBytes); this.dataItem = new Ans104DataItem(fullDataItemBytes);
this.contentItem = null;
this.coreRecord = null;
this.contentRecord = null;
this.frameBytes = dataItem.data(); this.frameBytes = dataItem.data();
if (frameBytes.length < FRAME_HEADER_SIZE) { if (frameBytes.length < FRAME_HEADER_SIZE) {
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length); throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
@@ -90,7 +96,57 @@ public final class BchBlockEntry {
this.hash32 = BchCryptoVerifier.sha256(frameBytes); this.hash32 = BchCryptoVerifier.sha256(frameBytes);
} }
public Ans104DataItem getDataItem() { return dataItem; } /** M1: явная точка входа для пары. Runtime переключается на неё в M2–M5. */
public static BchBlockEntry fromCoreContent(byte[] container) {
return new BchBlockEntry(CoreContentContainer.unpack(container));
}
private BchBlockEntry(CoreContentContainer.Parts pair) {
this.dataItem = pair.core();
this.contentItem = pair.content();
// Подписи и связь пары проверяются до предоставления смыслового тела.
// Owner здесь self-claimed; вызывающий код обязан проверить авторизованный ключ.
var verified = CoreContentTransport.verifyPair(dataItem, dataItem.id32(), contentItem,
dataItem.owner32(), Instant.now().getEpochSecond());
this.coreRecord = verified.core();
this.contentRecord = verified.content();
this.frameBytes = coreRecord.toBytes();
this.frameCode = CoreRecord.FRAME_CODE;
this.prevHash32 = coreRecord.prevCoreHash32();
this.back32Hash32 = null; // Отсутствует в протоколе; не синтезируем.
this.blockSize = frameBytes.length;
this.blockNumber = coreRecord.blockNumber();
this.timestamp = coreRecord.timestamp();
this.type = (short) contentRecord.type();
this.subType = (short) contentRecord.subType();
this.version = (short) contentRecord.version();
this.bodyBytes = contentRecord.bodyBytes();
this.body = ContentBodyParser.parseForCore(coreRecord, contentRecord);
this.hash32 = coreRecord.coreHash32();
}
public boolean isCoreContent() { return coreRecord != null; }
public CoreRecord getCoreRecord() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return coreRecord;
}
public ContentRecord getContentRecord() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return contentRecord;
}
public Ans104DataItem getCoreDataItem() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return dataItem;
}
public Ans104DataItem getContentDataItem() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return contentItem;
}
/** Legacy API: не позволяет принять одну подпись за проверку пары. */
public Ans104DataItem getDataItem() {
if (isCoreContent()) throw new IllegalStateException("Используйте явные CORE/CONTENT accessors");
return dataItem;
}
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); } public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
/** Kept as an alias for code/docs that called the old field preimage. */ /** Kept as an alias for code/docs that called the old field preimage. */
public byte[] getPreimageBytes() { return getFrameBytes(); } public byte[] getPreimageBytes() { return getFrameBytes(); }
@@ -98,8 +154,8 @@ public final class BchBlockEntry {
public byte[] getOwner32() { return dataItem.owner32(); } public byte[] getOwner32() { return dataItem.owner32(); }
public byte[] getDataItemId32() { return dataItem.id32(); } public byte[] getDataItemId32() { return dataItem.id32(); }
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); } public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
/** Full serialized ANS-104 DataItem. */ /** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
public byte[] toBytes() { return dataItem.rawBytes(); } public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
@Override @Override
public String toString() { public String toString() {
@@ -22,6 +22,13 @@ public final class BchCryptoVerifier {
Objects.requireNonNull(block, "block == null"); Objects.requireNonNull(block, "block == null");
Objects.requireNonNull(publicKey32, "publicKey32 == null"); Objects.requireNonNull(publicKey32, "publicKey32 == null");
if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32"); if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32");
if (block.isCoreContent()) {
try {
CoreContentTransport.verifyPair(block.getCoreDataItem(), block.getDataItemId32(),
block.getContentDataItem(), publicKey32, java.time.Instant.now().getEpochSecond());
return true;
} catch (IllegalArgumentException e) { return false; }
}
return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature(); return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature();
} }
} }
@@ -19,7 +19,7 @@ public final class BodyRecordParser {
// TECH supports Header v1 and CreateChannel current format (ver=1). // TECH supports Header v1 and CreateChannel current format (ver=1).
if (t == (CreateChannelBody.TYPE & 0xFFFF)) { if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_CC0 & 0xFFFF))) { && (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_LICENSE & 0xFFFF) || v == HeaderBody.VER_IDENTITY)) {
return new HeaderBody(subType, version, bodyBytes).check(); return new HeaderBody(subType, version, bodyBytes).check();
} }
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF) if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -0,0 +1,66 @@
package blockchain;
import blockchain.body.*;
/** Смысловой парсер новой эпохи. Не выполняет проверки существования целей и состояния БД. */
public final class ContentBodyParser {
private ContentBodyParser() {}
public static boolean isChannelText(int subType) {
return switch (subType) {
case MsgSubType.TEXT_POST, MsgSubType.TEXT_EDIT_POST, MsgSubType.TEXT_REPOST,
MsgSubType.TEXT_CHANNEL_META, MsgSubType.TEXT_CHANNEL_DELETE, MsgSubType.TEXT_ENTRYPOINT,
MsgSubType.TEXT_EXERCISE, MsgSubType.TEXT_SERVICE, MsgSubType.TEXT_COURSE -> true;
default -> false;
};
}
/** Проверяет соответствие линии, затем разбирает CONTENT без legacy-префикса. */
public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) {
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE");
boolean header = content.type() == 0 && content.subType() == MsgSubType.HEADER_COMPAT;
if (content.version() != 1 && !(header && (content.version() == HeaderBody.VER_LICENSE || content.version() == HeaderBody.VER_IDENTITY)))
throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
CoreRecord.Line line = core.line();
int expected = switch (content.type()) {
case 0 -> header ? -1 : CoreRecord.TECH;
case 1 -> isChannelText(content.subType()) ? -2 : -1;
case 3 -> CoreRecord.CONNECTION;
case 4 -> CoreRecord.PROFILE;
default -> -1;
};
boolean match = expected == -1 ? line == null : line != null &&
(expected == -2 ? LineIndex.isChannel(line.lineCode()) : line.lineCode() == expected);
if (!match) throw new IllegalArgumentException("CONTENT не соответствует линии CORE");
short s = (short) content.subType(), v = (short) content.version();
byte[] bytes = content.bodyBytes();
BodyRecord body = switch (content.type()) {
case 0 -> switch (s) {
case MsgSubType.HEADER_COMPAT -> new HeaderBody(s, v, bytes);
case MsgSubType.TECH_CREATE_CHANNEL -> new CreateChannelBody(s, v, bytes, line);
case MsgSubType.TECH_FORK -> new ForkBody(s, v, bytes, line);
default -> throw new IllegalArgumentException("Неизвестный TECH subtype");
};
case 1 -> {
if (isChannelText(content.subType())) yield new TextLineBody(s, v, bytes, line);
yield switch (s) {
case MsgSubType.TEXT_REPLY, MsgSubType.TEXT_EDIT_REPLY -> new TextReplyBody(s, v, bytes);
case MsgSubType.TEXT_RATING -> new TextRatingBody(s, v, bytes);
default -> throw new IllegalArgumentException("Неизвестный TEXT subtype");
};
}
case 2 -> new ReactionBody(s, v, bytes);
case 3 -> new ConnectionBody(s, v, bytes, line);
case 4 -> new UserParamBody(s, v, bytes, line);
case 5 -> new StatusActionBody(s, v, bytes);
default -> throw new IllegalArgumentException("Неизвестный CONTENT type");
};
return body.check();
}
/** Для нового события, в дополнение к проверкам БД и авторизации вызывающим кодом. */
public static BodyRecord parseForCreate(CoreRecord core, ContentRecord content) {
BodyRecord body = parseForCore(core, content);
if (body instanceof CreateChannelBody create) create.checkForCreate();
return body;
}
}
@@ -0,0 +1,36 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Objects;
/** Бинарный CONTENT v1. Неизвестные типы разбираются как raw envelope. */
public final class ContentRecord {
public static final int CONTENT_CODE = 1, HEADER_SIZE = 7;
// Верхняя граница payload; полный ANS-104 дополнительно ограничен собственным лимитом.
public static final int MAX_PAYLOAD_SIZE = Ans104DataItem.MAX_DATA_ITEM_BYTES - 117;
private final int type, subType, version;
private final byte[] body;
public ContentRecord(int type, int subType, int version, byte[] body) {
if ((type & ~0xffff) != 0 || (subType & ~0xffff) != 0 || (version & ~0xffff) != 0)
throw new IllegalArgumentException("Ожидается uint16");
Objects.requireNonNull(body);
if (body.length > MAX_PAYLOAD_SIZE - HEADER_SIZE) throw new IllegalArgumentException("CONTENT слишком большой");
this.type = type; this.subType = subType; this.version = version; this.body = body.clone();
}
public static ContentRecord parse(byte[] bytes) {
if (bytes == null || bytes.length < HEADER_SIZE || bytes.length > MAX_PAYLOAD_SIZE)
throw new IllegalArgumentException("Неверная длина CONTENT");
ByteBuffer b = ByteBuffer.wrap(bytes);
if (Byte.toUnsignedInt(b.get()) != CONTENT_CODE) throw new IllegalArgumentException("Неверный contentCode");
int t = Short.toUnsignedInt(b.getShort()), s = Short.toUnsignedInt(b.getShort()), v = Short.toUnsignedInt(b.getShort());
byte[] body = new byte[b.remaining()]; b.get(body);
return new ContentRecord(t, s, v, body);
}
public byte[] toBytes() { return ByteBuffer.allocate(HEADER_SIZE + body.length).put((byte) CONTENT_CODE)
.putShort((short) type).putShort((short) subType).putShort((short) version).put(body).array(); }
public int type() { return type; }
public int subType() { return subType; }
public int version() { return version; }
public byte[] bodyBytes() { return body.clone(); }
public byte[] contentHash32() { return ProtocolHash.sha256(toBytes()); }
}
@@ -0,0 +1,36 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Arrays;
/** Внутренний block_bytes: u32 BE размер CORE, затем два исходных ANS-104. Не DataItem. */
public final class CoreContentContainer {
private CoreContentContainer() {}
public static final int MAX_CORE_ITEM_BYTES = 65865;
public static final int MAX_CONTAINER_BYTES = 4 + MAX_CORE_ITEM_BYTES + Ans104DataItem.MAX_DATA_ITEM_BYTES;
private static final int MIN_ITEM_BYTES = 116;
public record Parts(Ans104DataItem core, Ans104DataItem content) {}
public static Parts unpack(byte[] bytes) {
if (bytes == null || bytes.length < 4 + 2 * MIN_ITEM_BYTES || bytes.length > MAX_CONTAINER_BYTES)
throw new IllegalArgumentException("Неверная длина контейнера CORE/CONTENT");
long n = Integer.toUnsignedLong(ByteBuffer.wrap(bytes).getInt());
long rest = bytes.length - 4L - n;
checkLengths(n, rest);
int end = 4 + (int) n;
return new Parts(new Ans104DataItem(Arrays.copyOfRange(bytes, 4, end)),
new Ans104DataItem(Arrays.copyOfRange(bytes, end, bytes.length)));
}
public static byte[] pack(Ans104DataItem core, Ans104DataItem content) {
byte[] c = core.rawBytes(), p = content.rawBytes();
checkLengths(c.length, p.length);
return ByteBuffer.allocate(4 + c.length + p.length).putInt(c.length).put(c).put(p).array();
}
private static void checkLengths(long core, long content) {
if (core < MIN_ITEM_BYTES || core > MAX_CORE_ITEM_BYTES || content < MIN_ITEM_BYTES || content > Ans104DataItem.MAX_DATA_ITEM_BYTES)
throw new IllegalArgumentException("Неверная длина CORE/CONTENT DataItem");
}
}
@@ -0,0 +1,73 @@
package blockchain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import utils.crypto.Ed25519Util;
/** Новый транспорт; не переключает существующий runtime Frame v1. */
public final class CoreContentTransport {
private CoreContentTransport() {}
public static List<Ans104DataItem.Tag> coreTags(CoreRecord core) {
var tags = new ArrayList<Ans104DataItem.Tag>();
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE));
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_NUMBER_TAG_NAME, Integer.toString(core.blockNumber())));
if (core.line() != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_LINE_TAG_NAME, lineTag(core.line().lineCode())));
return List.copyOf(tags);
}
public static String lineTag(int code) {
return switch (code) {
case CoreRecord.PROFILE -> "P";
case CoreRecord.CONNECTION -> "C";
case CoreRecord.TECH -> "T";
default -> {
if (code < 0 || code > CoreRecord.MAX_BLOCK_NUMBER) throw new IllegalArgumentException("Неизвестный системный тег линии");
yield Integer.toString(code);
}
};
}
private static void require(boolean ok, String message) { if (!ok) throw new IllegalArgumentException(message); }
private static void verify(Ans104DataItem item, byte[] expectedOwner, byte[] expectedId) {
require(item.ownerEquals(ProtocolHash.copy32(expectedOwner)), "Неавторизованный owner");
require(Arrays.equals(item.id32(), ProtocolHash.copy32(expectedId)), "DataItem ID не совпадает");
require(item.verifySignature(), "Неверная подпись ANS-104");
}
public static CoreRecord verifyCore(Ans104DataItem item, byte[] authorizedOwner, byte[] expectedId, long nowSeconds) {
verify(item, authorizedOwner, expectedId);
CoreRecord core = CoreRecord.parse(item.data()); core.checkTimestamp(nowSeconds);
List<Ans104DataItem.Tag> expected = coreTags(core);
for (String name : List.of("App", "n", "l")) {
var actual = item.tags().stream().filter(t -> t.name().equals(name)).toList();
var wanted = expected.stream().filter(t -> t.name().equals(name)).toList();
require(actual.equals(wanted), "Некорректный тег CORE: " + name);
}
require(item.tags().stream().noneMatch(t -> t.name().equals("t") || t.name().equals("c")), "Legacy теги CORE запрещены");
return core;
}
/** Только соответствие payload подписанному CORE; это не проверка собственной подписи CONTENT. */
public static ContentRecord verifyPayload(CoreRecord core, byte[] payload) {
require(payload != null && payload.length <= ContentRecord.MAX_PAYLOAD_SIZE, "Неверная длина CONTENT");
byte[] snapshot = payload.clone();
require(Arrays.equals(core.contentHash32(), ProtocolHash.sha256(snapshot)), "CONTENT hash не совпадает");
return ContentRecord.parse(snapshot);
}
/** authorizedOwner должен быть owner уже проверенного CORE, а не произвольный ключ CONTENT. */
public static ContentRecord verifyContent(CoreRecord core, Ans104DataItem item, byte[] authorizedOwner) {
verify(item, authorizedOwner, core.contentDataItemId32());
require(item.tags().stream().noneMatch(t -> List.of("App", "n", "l", "t", "c").contains(t.name())), "CONTENT не должен иметь поисковые теги SHiNE");
return verifyPayload(core, item.data());
}
public record VerifiedPair(CoreRecord core, ContentRecord content) {}
/** Криптографическая проверка пары; семантика проверяется ContentBodyParser отдельно. */
public static VerifiedPair verifyPair(Ans104DataItem coreItem, byte[] expectedCoreId, Ans104DataItem contentItem,
byte[] authorizedOwner, long nowSeconds) {
CoreRecord core = verifyCore(coreItem, authorizedOwner, expectedCoreId, nowSeconds);
return new VerifiedPair(core, verifyContent(core, contentItem, coreItem.owner32()));
}
/** Для локального тестового издателя; production сервер не получает приватный ключ пользователя. */
public static Ans104DataItem sign(byte[] payload, List<Ans104DataItem.Tag> tags, byte[] seed) {
byte[] owner = Ed25519Util.derivePublicKey(seed);
byte[] sig = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, payload), seed);
return new Ans104DataItem(Ans104DataItem.serializeEd25519(sig, owner, tags, payload));
}
}
@@ -0,0 +1,75 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Arrays;
/** Неизменяемый бинарный CORE v2; проверка ссылок на историю выполняется отдельно. */
public final class CoreRecord {
public static final int BASE_SIZE = 109, LINE_SIZE = 149, FRAME_CODE = 1;
public static final int MAX_BLOCK_NUMBER = Integer.MAX_VALUE - 1024;
public static final int PROFILE = Integer.MAX_VALUE - 2, CONNECTION = Integer.MAX_VALUE - 1, TECH = Integer.MAX_VALUE;
public static final long FUTURE_TOLERANCE_SECONDS = 60;
public record Line(int lineCode, int prevLineBlockNumber, byte[] prevLineCoreHash32) {
public Line {
if (lineCode < 0 || prevLineBlockNumber < 0 || prevLineBlockNumber > MAX_BLOCK_NUMBER)
throw new IllegalArgumentException("Неверный номер линии/предшественника");
prevLineCoreHash32 = ProtocolHash.copy32(prevLineCoreHash32);
}
@Override public byte[] prevLineCoreHash32() { return prevLineCoreHash32.clone(); }
@Override public boolean equals(Object other) {
return other instanceof Line l && lineCode == l.lineCode && prevLineBlockNumber == l.prevLineBlockNumber
&& Arrays.equals(prevLineCoreHash32, l.prevLineCoreHash32);
}
@Override public int hashCode() {
return 31 * (31 * lineCode + prevLineBlockNumber) + Arrays.hashCode(prevLineCoreHash32);
}
}
private final byte[] prevCoreHash32, contentHash32, contentDataItemId32;
private final int blockNumber;
private final long timestamp;
private final Line line;
public CoreRecord(byte[] prevCoreHash32, int blockNumber, long timestamp, byte[] contentHash32,
byte[] contentDataItemId32, Line line) {
this.prevCoreHash32 = ProtocolHash.copy32(prevCoreHash32);
this.contentHash32 = ProtocolHash.copy32(contentHash32);
this.contentDataItemId32 = ProtocolHash.copy32(contentDataItemId32);
this.blockNumber = blockNumber; this.timestamp = timestamp; this.line = line;
if (blockNumber < 0 || blockNumber > MAX_BLOCK_NUMBER || timestamp < 0)
throw new IllegalArgumentException("Неверный номер CORE или timestamp");
if (blockNumber == 0 && (line != null || !Arrays.equals(this.prevCoreHash32, new byte[32])))
throw new IllegalArgumentException("Неверный genesis CORE");
if (line != null && (line.prevLineBlockNumber() >= blockNumber ||
(line.lineCode() > 0 && line.lineCode() <= MAX_BLOCK_NUMBER &&
(line.lineCode() >= blockNumber || line.prevLineBlockNumber() < line.lineCode()))))
throw new IllegalArgumentException("Неверная ссылка линии");
}
public static CoreRecord parse(byte[] bytes) {
if (bytes == null || (bytes.length != BASE_SIZE && bytes.length != LINE_SIZE))
throw new IllegalArgumentException("CORE должен иметь 109 или 149 байт");
ByteBuffer b = ByteBuffer.wrap(bytes);
if (Byte.toUnsignedInt(b.get()) != FRAME_CODE) throw new IllegalArgumentException("Неверный frameCode");
byte[] prev = read32(b); int n = b.getInt(); long t = b.getLong();
byte[] content = read32(b), id = read32(b);
Line line = b.hasRemaining() ? new Line(b.getInt(), b.getInt(), read32(b)) : null;
return new CoreRecord(prev, n, t, content, id, line);
}
private static byte[] read32(ByteBuffer b) { byte[] v = new byte[32]; b.get(v); return v; }
public byte[] toBytes() {
ByteBuffer b = ByteBuffer.allocate(line == null ? BASE_SIZE : LINE_SIZE);
b.put((byte) FRAME_CODE).put(prevCoreHash32).putInt(blockNumber).putLong(timestamp).put(contentHash32).put(contentDataItemId32);
if (line != null) b.putInt(line.lineCode()).putInt(line.prevLineBlockNumber()).put(line.prevLineCoreHash32());
return b.array();
}
public void checkTimestamp(long nowSeconds) {
if (nowSeconds < 0 || (timestamp > nowSeconds && timestamp - nowSeconds > FUTURE_TOLERANCE_SECONDS))
throw new IllegalArgumentException("CORE timestamp в будущем");
}
public int blockNumber() { return blockNumber; }
public long timestamp() { return timestamp; }
public Line line() { return line; }
public byte[] prevCoreHash32() { return prevCoreHash32.clone(); }
public byte[] contentHash32() { return contentHash32.clone(); }
public byte[] contentDataItemId32() { return contentDataItemId32.clone(); }
public byte[] coreHash32() { return ProtocolHash.sha256(toBytes()); }
}
@@ -1,17 +1,12 @@
//package blockchain; package blockchain;
//
///** /** Канонические линии CORE v2; Frame v1 использует старую модель. */
// * LineIndex — канонические номера линий блокчейна. public final class LineIndex {
// * private LineIndex() {}
// * Линия = независимая последовательность блоков внутри одного блокчейна. public static final int DEFAULT_CHANNEL = 0;
// */ public static final int USER_PROFILE = CoreRecord.PROFILE;
//public final class LineIndex { public static final int CONNECTION = CoreRecord.CONNECTION;
// public static final int TECH = CoreRecord.TECH;
// private LineIndex() {} public static final int MAX_CHANNEL = CoreRecord.MAX_BLOCK_NUMBER;
// public static boolean isChannel(int code) { return code >= 0 && code <= MAX_CHANNEL; }
// public static final short HEADER = 0; // genesis / идентификация }
// public static final short TEXT = 1; // сообщения да надо
// public static final short REACTION = 2; // реакции не надо
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
//}
@@ -0,0 +1,26 @@
package blockchain;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HexFormat;
public final class ProtocolHash {
private ProtocolHash() {}
public static byte[] copy32(byte[] bytes) {
if (bytes == null || bytes.length != 32) throw new IllegalArgumentException("Ожидается 32 байта");
return bytes.clone();
}
public static byte[] sha256(byte[] bytes) {
try { return MessageDigest.getInstance("SHA-256").digest(bytes); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
public static String hex32(byte[] bytes) { return HexFormat.of().formatHex(copy32(bytes)); }
public static byte[] fromHex32(String value) { return copy32(HexFormat.of().parseHex(value)); }
public static String base64url32(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(copy32(bytes)); }
public static byte[] fromBase64url32(String value) {
byte[] result = copy32(Base64.getUrlDecoder().decode(value));
if (!base64url32(result).equals(value)) throw new IllegalArgumentException("Неканонический base64url");
return result;
}
}
@@ -9,6 +9,14 @@ package blockchain;
public final class ShineProtocolTags { public final class ShineProtocolTags {
private ShineProtocolTags() {} private ShineProtocolTags() {}
public static final String CORE_NAMESPACE = "test5595";
/** Новый регистрационный сертификат остаётся отдельным объектом; используется при переключении эпохи. */
public static final java.util.List<Ans104DataItem.Tag> CORE_REGISTRATION_TAGS = java.util.List.of(
new Ans104DataItem.Tag("App", CORE_NAMESPACE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public static final String CORE_NUMBER_TAG_NAME = "n";
public static final String CORE_LINE_TAG_NAME = "l";
public static final String NAMESPACE = "test5592"; public static final String NAMESPACE = "test5592";
public static final String APP_TAG_NAME = "App"; public static final String APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE; public static final String APP_TAG_VALUE = NAMESPACE;
@@ -21,6 +21,9 @@ package blockchain.body;
*/ */
public interface BodyHasLine { public interface BodyHasLine {
/** CORE не подписывает ordinal; до проверки канонического хвоста значение отсутствует. */
int UNRESOLVED_SEQUENCE = -1;
int lineCode(); int lineCode();
int prevLineBlockGlobalNumber(); int prevLineBlockGlobalNumber();
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -16,6 +17,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public static final short VER = 1; public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
public final int prevConnectionBlockNumber; public final int prevConnectionBlockNumber;
@@ -27,16 +29,28 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public final byte[] toBlockHash32; public final byte[] toBlockHash32;
public ConnectionBody(short subType, short version, byte[] bodyBytes) { public ConnectionBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public ConnectionBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header"); if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short"); BodyTargetSupport.ensureMin(bb, (4 + 32 + 4 + 1 + 1 + 2 + 4 + 32) - (contentOnly ? 40 : 0), "ConnectionBody too short");
if (contentOnly) {
this.prevConnectionBlockNumber = line.prevLineBlockNumber();
this.prevConnectionBlockHash32 = line.prevLineCoreHash32();
this.connectionSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.prevConnectionBlockNumber = bb.getInt(); this.prevConnectionBlockNumber = bb.getInt();
this.prevConnectionBlockHash32 = new byte[32]; this.prevConnectionBlockHash32 = new byte[32];
bb.get(this.prevConnectionBlockHash32); bb.get(this.prevConnectionBlockHash32);
this.connectionSequence = bb.getInt(); this.connectionSequence = bb.getInt();
}
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0); BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login(); this.toLogin = t.login();
this.toForkNumber = t.forkNumber(); this.toForkNumber = t.forkNumber();
@@ -47,6 +61,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType, public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) { String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
this.contentOnly = false;
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields"); if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
this.prevConnectionBlockNumber = prevConnectionBlockNumber; this.prevConnectionBlockNumber = prevConnectionBlockNumber;
@@ -64,15 +79,15 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields"); if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0"); if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid"); if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1"); if (!contentOnly && connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return this; return this;
} }
@Override public byte[] toBytes() { @Override public byte[] toBytes() {
check(); check();
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 40) + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence); if (!contentOnly) bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array(); return bb.array();
} }
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -42,6 +43,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
private static final int MAX_NAME_LENGTH = 32; private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048; public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -56,6 +58,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
public final short channelTypeVersion; public final short channelTypeVersion;
public CreateChannelBody(short subType, short version, byte[] bodyBytes) { public CreateChannelBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public CreateChannelBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
@@ -67,16 +75,23 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) { if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF)); throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
} }
if (bodyBytes.length < 4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) { if (bodyBytes.length < (4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) - (contentOnly ? 44 : 0)) {
throw new IllegalArgumentException("CreateChannelBody too short"); throw new IllegalArgumentException("CreateChannelBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.lineCode = 0;
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32); bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
int nameLen = Byte.toUnsignedInt(bb.get()); int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0"); if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
@@ -86,7 +101,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
byte[] nameBytes = new byte[nameLen]; byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes); bb.get(nameBytes);
this.channelName = new String(nameBytes, StandardCharsets.UTF_8); this.channelName = contentOnly ? BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName") : new String(nameBytes, StandardCharsets.UTF_8);
int descriptionLen = Short.toUnsignedInt(bb.getShort()); int descriptionLen = Short.toUnsignedInt(bb.getShort());
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) { if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
@@ -100,7 +115,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
} else { } else {
byte[] descriptionBytes = new byte[descriptionLen]; byte[] descriptionBytes = new byte[descriptionLen];
bb.get(descriptionBytes); bb.get(descriptionBytes);
this.channelDescription = normalizeDescription(new String(descriptionBytes, StandardCharsets.UTF_8)); this.channelDescription = normalizeDescription(contentOnly ? BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription") : new String(descriptionBytes, StandardCharsets.UTF_8));
} }
this.channelTypeCode = bb.getShort(); this.channelTypeCode = bb.getShort();
this.channelTypeVersion = bb.getShort(); this.channelTypeVersion = bb.getShort();
@@ -117,6 +132,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String channelDescription, String channelDescription,
short channelTypeCode, short channelTypeCode,
short channelTypeVersion) { short channelTypeVersion) {
this.contentOnly = false;
Objects.requireNonNull(channelName, "channelName == null"); Objects.requireNonNull(channelName, "channelName == null");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0"); if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
@@ -142,6 +158,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String normalizedName = normalizeDisplayName(channelName); String normalizedName = normalizeDisplayName(channelName);
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank"); if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
int cpLen = normalizedName.codePointCount(0, normalizedName.length()); int cpLen = normalizedName.codePointCount(0, normalizedName.length());
if (contentOnly && normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32"); if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
String normalizedDescription = normalizeDescription(channelDescription); String normalizedDescription = normalizeDescription(channelDescription);
@@ -157,7 +174,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody"); if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody");
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid"); if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody"); if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
return this; return this;
} }
@@ -199,12 +216,14 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048"); throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
} }
int cap = 4 + (4 + 32 + 4) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4; int cap = (contentOnly ? 0 : 44) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(lineCode); bb.putInt(lineCode);
bb.putInt(prevLineNumber); bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32)); bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber); bb.putInt(thisLineNumber);
}
bb.put((byte) nameUtf8.length); bb.put((byte) nameUtf8.length);
bb.put(nameUtf8); bb.put(nameUtf8);
bb.putShort((short) (descriptionUtf8.length & 0xFFFF)); bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -49,6 +50,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2; private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN; private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -69,6 +71,12 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public final String comment; public final String comment;
public ForkBody(short subType, short version, byte[] bodyBytes) { public ForkBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public ForkBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
@@ -79,16 +87,23 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
if ((version & 0xFFFF) != (VER & 0xFFFF)) { if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody version must be 1"); throw new IllegalArgumentException("ForkBody version must be 1");
} }
if (bodyBytes.length < FIXED_LEN) { if (bodyBytes.length < FIXED_LEN - (contentOnly ? LINE_PREFIX_LEN : 0)) {
throw new IllegalArgumentException("ForkBody too short"); throw new IllegalArgumentException("ForkBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.lineCode = 0;
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32); bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
this.parentBlockchainKey32 = new byte[32]; this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32); bb.get(this.parentBlockchainKey32);
@@ -111,7 +126,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
} }
byte[] commentBytes = new byte[commentLen]; byte[] commentBytes = new byte[commentLen];
bb.get(commentBytes); bb.get(commentBytes);
this.comment = new String(commentBytes, StandardCharsets.UTF_8); this.comment = contentOnly ? BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment") : new String(commentBytes, StandardCharsets.UTF_8);
} }
public ForkBody(int lineCode, public ForkBody(int lineCode,
@@ -128,6 +143,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
int discardedBlocksCount, int discardedBlocksCount,
int reasonCode, int reasonCode,
String comment) { String comment) {
this.contentOnly = false;
this.subType = SUBTYPE; this.subType = SUBTYPE;
this.version = VER; this.version = VER;
this.lineCode = lineCode; this.lineCode = lineCode;
@@ -157,7 +173,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0"); if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0"); if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
require32(prevLineHash32, "prevLineHash32"); require32(prevLineHash32, "prevLineHash32");
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1"); if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
require32(parentBlockchainKey32, "parentBlockchainKey32"); require32(parentBlockchainKey32, "parentBlockchainKey32");
require32(forkPointBlockHash32, "forkPointBlockHash32"); require32(forkPointBlockHash32, "forkPointBlockHash32");
@@ -186,11 +202,13 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public byte[] toBytes() { public byte[] toBytes() {
check(); check();
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8); byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? FIXED_PAYLOAD_LEN : FIXED_LEN) + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(lineCode); bb.putInt(lineCode);
bb.putInt(prevLineNumber); bb.putInt(prevLineNumber);
bb.put(prevLineHash32); bb.put(prevLineHash32);
bb.putInt(thisLineNumber); bb.putInt(thisLineNumber);
}
bb.put(parentBlockchainKey32); bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber); bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32); bb.put(forkPointBlockHash32);
@@ -9,13 +9,17 @@ import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
/** /**
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 CC0. * HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 license / version=3 identity.
* *
* bodyBytes (BigEndian): * bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII * [TAG_LEN] tag ASCII
* [1] loginLength (uint8) * [1] loginLength (uint8)
* [N] login UTF-8 * [N] login UTF-8
* [15] ASCII "license:CC0-1.0" (version=2 only) * [1] accountType (v3 only, 0 alternative / 1 primary)
* [2+N] previous accounts CSV (v3 primary only, u16 length)
* [1] licenseLength (uint8, version>=2)
* [M] license UTF-8 (version>=2)
* Historical v2: fixed ASCII "license:CC0-1.0" instead of length + text.
* [32] initialBlockchainKey32 * [32] initialBlockchainKey32
* *
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1. * initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
@@ -24,8 +28,11 @@ import java.util.Objects;
*/ */
public final class HeaderBody implements BodyRecord { public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0; public static final short TYPE = 0;
public static final short VER = 1; // Legacy, read-only for newly created chains public static final short VER = 1; // Legacy Frame v1 and new CONTENT v1 (without CC0)
public static final short VER_CC0 = 2; public static final short VER_LICENSE = 2;
public static final short VER_IDENTITY = 3;
public static final int ALTERNATIVE = 0, PRIMARY = 1;
public static final short VER_CC0 = VER_LICENSE; // historical source compatibility
public static final String LICENSE_CC0 = "CC0-1.0"; public static final String LICENSE_CC0 = "CC0-1.0";
public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0; public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0;
private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII); private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII);
@@ -41,15 +48,18 @@ public final class HeaderBody implements BodyRecord {
public final String tag; public final String tag;
public final String login; public final String login;
public final byte[] initialBlockchainKey32; public final byte[] initialBlockchainKey32;
public final Integer accountType; // null for legacy HEADER
public final java.util.List<String> previousAccounts;
public final String license; // null for legacy HEADER v1 public final String license; // null for legacy HEADER v1
private final boolean legacyCc0Encoding;
public HeaderBody(short subType, short version, byte[] bodyBytes) { public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("HeaderBody version must be 1 or 2"); if (version != VER && version != VER_CC0 && version != VER_IDENTITY) throw new IllegalArgumentException("HeaderBody version must be 1, 2 or 3");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)) if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_LICENSE ? 1 : 0))
throw new IllegalArgumentException("HeaderBody too short"); throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
@@ -60,17 +70,48 @@ public final class HeaderBody implements BodyRecord {
this.tag = parsedTag; this.tag = parsedTag;
int loginLen = Byte.toUnsignedInt(bb.get()); int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0 || bb.remaining() != loginLen + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)) if (loginLen <= 0 || bb.remaining() < loginLen + 32 + (version == VER_LICENSE ? 1 : 0))
throw new IllegalArgumentException("Bad HeaderBody login/key/license length"); throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
byte[] loginBytes = new byte[loginLen]; byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes); bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login"); this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
if (version == VER_CC0) { if (version == VER_IDENTITY) {
byte[] actual = new byte[LICENSE_BYTES.length]; if (bb.remaining() < 34) throw new IllegalArgumentException("Truncated HEADER identity");
bb.get(actual); this.accountType = Byte.toUnsignedInt(bb.get());
if (!Arrays.equals(actual, LICENSE_BYTES)) throw new IllegalArgumentException("Unsupported HEADER license"); if (accountType == PRIMARY) {
if (bb.remaining() < 35) throw new IllegalArgumentException("Truncated HEADER previous accounts");
int size = Short.toUnsignedInt(bb.getShort());
if (size > bb.remaining() - 33) throw new IllegalArgumentException("Bad HEADER previous accounts length");
byte[] previous = new byte[size]; bb.get(previous);
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
this.previousAccounts = csv.isEmpty() ? java.util.List.of() : java.util.List.of(csv.split(",", -1));
} else {
this.previousAccounts = java.util.List.of();
}
int size = Byte.toUnsignedInt(bb.get());
if (bb.remaining() != size + 32) throw new IllegalArgumentException("Bad HEADER license length");
byte[] field = new byte[size]; bb.get(field);
this.license = BodyTargetSupport.decodeStrictUtf8(field, "HEADER license");
this.legacyCc0Encoding = false;
} else if (version == VER_LICENSE) {
this.accountType = null;
this.previousAccounts = java.util.List.of();
int fieldLength = bb.remaining() - 32;
if (fieldLength > 256) throw new IllegalArgumentException("HEADER license too long");
byte[] field = new byte[fieldLength];
bb.get(field);
legacyCc0Encoding = Arrays.equals(field, LICENSE_BYTES);
if (legacyCc0Encoding) {
this.license = LICENSE_CC0; this.license = LICENSE_CC0;
} else { } else {
int length = Byte.toUnsignedInt(field[0]);
if (fieldLength != 1 + length) throw new IllegalArgumentException("Bad HEADER license length");
this.license = BodyTargetSupport.decodeStrictUtf8(Arrays.copyOfRange(field, 1, fieldLength), "HEADER license");
}
} else {
this.accountType = null;
this.previousAccounts = java.util.List.of();
legacyCc0Encoding = false;
this.license = null; this.license = null;
} }
this.initialBlockchainKey32 = new byte[32]; this.initialBlockchainKey32 = new byte[32];
@@ -81,14 +122,34 @@ public final class HeaderBody implements BodyRecord {
// Legacy constructor is kept for historical fixtures and importing v1 blocks. // Legacy constructor is kept for historical fixtures and importing v1 blocks.
public HeaderBody(String login, byte[] initialBlockchainKey32) { public HeaderBody(String login, byte[] initialBlockchainKey32) {
this(login, initialBlockchainKey32, VER); this(login, initialBlockchainKey32, VER, null, false);
}
/** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER, null, false);
} }
public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) { public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER_CC0); return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, LICENSE_CC0, true);
} }
private HeaderBody(String login, byte[] initialBlockchainKey32, short version) { /** Новый HEADER v2: произвольная строка лицензии, включая пустую. */
public static HeaderBody licensed(String login, byte[] initialBlockchainKey32, String license) {
return new HeaderBody(login, initialBlockchainKey32, VER_LICENSE, Objects.requireNonNull(license), false);
}
public static HeaderBody identity(String login, byte[] initialBlockchainKey32, String license,
int accountType, java.util.List<String> previousAccounts) {
return new HeaderBody(login, initialBlockchainKey32, VER_IDENTITY, license, false, accountType, previousAccounts);
}
private HeaderBody(String login, byte[] initialBlockchainKey32, short version, String license, boolean legacyCc0Encoding) {
this(login, initialBlockchainKey32, version, license, legacyCc0Encoding, null, java.util.List.of());
}
private HeaderBody(String login, byte[] initialBlockchainKey32, short version, String license, boolean legacyCc0Encoding,
Integer accountType, java.util.List<String> previousAccounts) {
Objects.requireNonNull(login, "login == null"); Objects.requireNonNull(login, "login == null");
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"); Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
this.subType = SUBTYPE_COMPAT; this.subType = SUBTYPE_COMPAT;
@@ -96,15 +157,20 @@ public final class HeaderBody implements BodyRecord {
this.tag = TAG; this.tag = TAG;
this.login = login; this.login = login;
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length); this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
this.license = version == VER_CC0 ? LICENSE_CC0 : null; this.license = license;
this.accountType = accountType;
this.previousAccounts = java.util.List.copyOf(previousAccounts);
this.legacyCc0Encoding = legacyCc0Encoding;
check(); check();
} }
@Override @Override
public HeaderBody check() { public HeaderBody check() {
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("Bad HeaderBody version"); if (version != VER && version != VER_CC0 && version != VER_IDENTITY) throw new IllegalArgumentException("Bad HeaderBody version");
if (version == VER_CC0 && !LICENSE_CC0.equals(license)) throw new IllegalArgumentException("Bad HEADER CC0 license"); if (version != VER && (license == null || !StandardCharsets.UTF_8.newEncoder().canEncode(license)
|| license.getBytes(StandardCharsets.UTF_8).length > 255))
throw new IllegalArgumentException("HEADER license must be 0..255 UTF-8 bytes");
if (version == VER && license != null) throw new IllegalArgumentException("Legacy HEADER must not contain a license"); if (version == VER && license != null) throw new IllegalArgumentException("Legacy HEADER must not contain a license");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank"); if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
@@ -116,6 +182,19 @@ public final class HeaderBody implements BodyRecord {
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)"); throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
} }
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255"); if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
if (version == VER_IDENTITY) {
if (accountType == null || (accountType != ALTERNATIVE && accountType != PRIMARY))
throw new IllegalArgumentException("Bad HEADER account type");
if (previousAccounts.size() > 10 || (accountType == ALTERNATIVE && !previousAccounts.isEmpty()))
throw new IllegalArgumentException("Bad HEADER previous account count");
java.util.Set<String> seen = new java.util.HashSet<>();
seen.add(login.toLowerCase(java.util.Locale.ROOT));
for (String prev : previousAccounts) {
if (!(prev.matches("^[A-Za-z0-9_]{1,255}$") || (prev.length() <= 30 && prev.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$")))
|| !seen.add(prev.toLowerCase(java.util.Locale.ROOT)))
throw new IllegalArgumentException("Bad, duplicate or self HEADER previous account");
}
}
requireNonZeroKey(initialBlockchainKey32); requireNonZeroKey(initialBlockchainKey32);
return this; return this;
} }
@@ -124,11 +203,22 @@ public final class HeaderBody implements BodyRecord {
public byte[] toBytes() { public byte[] toBytes() {
check(); check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)).order(ByteOrder.BIG_ENDIAN); byte[] licenseUtf8 = version != VER ? license.getBytes(StandardCharsets.UTF_8) : new byte[0];
int licenseSize = version != VER ? (legacyCc0Encoding ? LICENSE_BYTES.length : 1 + licenseUtf8.length) : 0;
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
int identitySize = version == VER_IDENTITY ? 1 + (accountType == PRIMARY ? 2 + previous.length : 0) : 0;
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + licenseSize + identitySize).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII); bb.put(TAG_ASCII);
bb.put((byte) loginUtf8.length); bb.put((byte) loginUtf8.length);
bb.put(loginUtf8); bb.put(loginUtf8);
if (version == VER_CC0) bb.put(LICENSE_BYTES); if (version == VER_IDENTITY) {
bb.put((byte)(int)accountType);
if (accountType == PRIMARY) bb.putShort((short)previous.length).put(previous);
}
if (version != VER) {
if (legacyCc0Encoding) bb.put(LICENSE_BYTES);
else bb.put((byte) licenseUtf8.length).put(licenseUtf8);
}
bb.put(initialBlockchainKey32); bb.put(initialBlockchainKey32);
return bb.array(); return bb.array();
} }
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -27,6 +28,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
public static final short VER = 1; public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
public final int lineCode; public final int lineCode;
@@ -40,17 +42,30 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
public final String message; public final String message;
public TextLineBody(short subType, short version, byte[] bodyBytes) { public TextLineBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public TextLineBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header"); if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 2, "TextLineBody too short"); BodyTargetSupport.ensureMin(bb, (4 + 4 + 32 + 4 + 2) - (contentOnly ? 44 : 0), "TextLineBody too short");
if (contentOnly) {
this.lineCode = line.lineCode();
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32); this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
int st = subType & 0xFFFF; int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) { if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
@@ -88,6 +103,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
Integer toBlockGlobalNumber, Integer toBlockGlobalNumber,
byte[] toBlockHash32, byte[] toBlockHash32,
String message) { String message) {
this.contentOnly = false;
Objects.requireNonNull(message, "message == null"); Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype"); if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0"); if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
@@ -144,8 +160,8 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32; if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin); else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 44) + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber); if (!contentOnly) bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) { if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber).put(toBlockHash32); bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) { } else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -35,6 +36,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -46,6 +48,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public final String paramValue; public final String paramValue;
public UserParamBody(short subType, short version, byte[] bodyBytes) { public UserParamBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public UserParamBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
@@ -59,16 +67,22 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
} }
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1) // prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
if (bodyBytes.length < 4 + 32 + 4 + 2 + 1 + 2 + 1) { if (bodyBytes.length < (4 + 32 + 4 + 2 + 1 + 2 + 1) - (contentOnly ? 40 : 0)) {
throw new IllegalArgumentException("UserParamBody too short"); throw new IllegalArgumentException("UserParamBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.prevProfileBlockNumber = line.prevLineBlockNumber();
this.prevProfileBlockHash32 = line.prevLineCoreHash32();
this.profileSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.prevProfileBlockNumber = bb.getInt(); this.prevProfileBlockNumber = bb.getInt();
this.prevProfileBlockHash32 = new byte[32]; this.prevProfileBlockHash32 = new byte[32];
bb.get(this.prevProfileBlockHash32); bb.get(this.prevProfileBlockHash32);
this.profileSequence = bb.getInt(); this.profileSequence = bb.getInt();
}
int keyLen = Short.toUnsignedInt(bb.getShort()); int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0"); if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
@@ -98,6 +112,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
int profileSequence, int profileSequence,
String paramKey, String paramKey,
String paramValue) { String paramValue) {
this.contentOnly = false;
Objects.requireNonNull(paramKey, "paramKey == null"); Objects.requireNonNull(paramKey, "paramKey == null");
Objects.requireNonNull(paramValue, "paramValue == null"); Objects.requireNonNull(paramValue, "paramValue == null");
@@ -123,7 +138,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
} }
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0"); if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid"); if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
if (profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1"); if (!contentOnly && profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank"); if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank"); if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
@@ -140,14 +155,16 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535"); if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535"); if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
int cap = 4 + 32 + 4 int cap = (contentOnly ? 0 : 40)
+ 2 + keyUtf8.length + 2 + keyUtf8.length
+ 2 + valUtf8.length; + 2 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(prevProfileBlockNumber); bb.putInt(prevProfileBlockNumber);
bb.put(prevProfileBlockHash32); bb.put(prevProfileBlockHash32);
bb.putInt(profileSequence); bb.putInt(profileSequence);
}
bb.putShort((short) keyUtf8.length); bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8); bb.put(keyUtf8);
bb.putShort((short) valUtf8.length); bb.putShort((short) valUtf8.length);
@@ -0,0 +1,334 @@
package blockchain;
import blockchain.body.*;
import utils.crypto.Ed25519Util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import static blockchain.MsgSubType.*;
/** Запускается и из Gradle/JUnit, и автономно через javac --release 17. */
public final class StageAProtocolChecks {
private static int count;
private static final byte[] ZERO = new byte[32], HASH = ProtocolHash.sha256(new byte[]{1});
private static final long NOW = 1700001000L;
private static final byte[] SEED = new byte[32];
static { for (int i=0;i<32;i++) SEED[i]=(byte)i; }
private static final byte[] OWNER = Ed25519Util.derivePublicKey(SEED);
private static final HexFormat HEX = HexFormat.of();
private static void ok(boolean condition, String label) {
if (!condition) throw new AssertionError(label);
count++;
}
private static void eq(byte[] a, byte[] b, String label) { ok(Arrays.equals(a,b), label); }
private static void bad(Runnable r, String label) {
try { r.run(); } catch (IllegalArgumentException expected) { count++; return; }
throw new AssertionError("Ожидался отказ: " + label);
}
private static CoreRecord core(int number, CoreRecord.Line line, ContentRecord content, byte[] id) {
return new CoreRecord(number == 0 ? ZERO : HASH, number, NOW, content.contentHash32(), id, line);
}
private static CoreRecord.Line line(int code) { return new CoreRecord.Line(code,0,HASH); }
private static Ans104DataItem sign(CoreRecord c, List<Ans104DataItem.Tag> tags) {
return CoreContentTransport.sign(c.toBytes(), tags, SEED);
}
private static void rejectTags(CoreRecord c, List<Ans104DataItem.Tag> tags) {
var i = sign(c,tags); bad(() -> CoreContentTransport.verifyCore(i,OWNER,i.id32(),NOW), "signed bad tags " + tags);
}
private static Ans104DataItem.Tag tag(String name,String value) { return new Ans104DataItem.Tag(name,value); }
private static void checkBodies() throws Exception {
var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
testBody(0,HEADER_COMPAT,header,null,0);
ok(header.license == null,"HEADER без CC0");
var old = HeaderBody.licensedCc0("Alice", OWNER);
eq(parseSemantic(new ContentRecord(0,0,2,old.toBytes())).toBytes(), old.toBytes(), "historical CC0 HEADER");
for (String license : new String[]{"", "CC0-1.0", "CC-BY-NC-4.0", "Лицензия 🌞", "x".repeat(255)}) {
var h = HeaderBody.licensed("Alice@shine", OWNER, license);
var c = new ContentRecord(0,0,2,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(license.equals(parsed.license), "arbitrary license");
eq(h.toBytes(), parsed.toBytes(), "HEADER v2 roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(), h.toBytes(), "HEADER v2 create");
var contentItem = CoreContentTransport.sign(c.toBytes(), List.of(), SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var coreItem = sign(coreRecord,CoreContentTransport.coreTags(coreRecord));
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(coreItem, contentItem));
ok(license.equals(((HeaderBody)pair.body).license), "signed HEADER v2 pair");
eq(pair.getContentRecord().bodyBytes(), h.toBytes(), "signed HEADER v2 exact bytes");
bad(() -> parseSemantic(new ContentRecord(0,0,2,Arrays.copyOf(h.toBytes(),h.toBytes().length-1))), "truncated HEADER v2");
}
bad(() -> HeaderBody.licensed("Alice",OWNER,"x".repeat(256)), "license too long");
byte[] invalidUtf8 = HeaderBody.licensed("Alice",OWNER,"x").toBytes();
invalidUtf8[12] = (byte)0xff;
bad(() -> parseSemantic(new ContentRecord(0,0,2,invalidUtf8)), "invalid license UTF8");
for (int type : new int[]{0,1}) {
for (List<String> prev : type == 0 ? List.of(List.<String>of()) : List.of(List.<String>of(), List.of("Bob@free", "Old@shine"), java.util.stream.IntStream.range(0,10).mapToObj(n -> "old"+n+"@free").toList())) {
var h = HeaderBody.identity("Alice@shine",OWNER,"Лицензия",type,prev);
var c = new ContentRecord(0,0,3,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(parsed.accountType == type && parsed.previousAccounts.equals(prev) && parsed.license.equals("Лицензия"), "HEADER v3 role and predecessors");
eq(parsed.toBytes(), h.toBytes(), "HEADER v3 byte roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(),h.toBytes(),"HEADER v3 create");
var contentItem = CoreContentTransport.sign(c.toBytes(),List.of(),SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(sign(coreRecord,CoreContentTransport.coreTags(coreRecord)),contentItem));
ok(((HeaderBody)pair.body).previousAccounts.equals(prev),"signed HEADER v3 pair");
for(int n=0;n<h.toBytes().length;n++) {
byte[] cut=Arrays.copyOf(h.toBytes(),n);
bad(()->parseSemantic(new ContentRecord(0,0,3,cut)),"truncated HEADER v3");
}
}
}
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",2,List.of()),"unknown type");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",0,List.of("Bob@free")),"alternative predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("alice@shine")),"self predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob@free","bob@free")),"duplicate predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob,old")),"comma in predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,java.util.stream.IntStream.range(0,11).mapToObj(n->"old"+n+"@free").toList()),"eleven predecessors");
byte[] invalidRole = HeaderBody.identity("Alice@shine",OWNER,"",0,List.of()).toBytes();
invalidRole[6+"Alice@shine".length()] = 2;
bad(()->parseSemantic(new ContentRecord(0,0,3,invalidRole)),"invalid parsed role");
var create=new CreateChannelContentBody("Новости","Описание",(short)1,(short)1);
testBody(0,TECH_CREATE_CHANNEL,create,line(CoreRecord.TECH),1);
eq(create.toBytes(),Arrays.copyOfRange(new CreateChannelBody(0,0,HASH,1,"Новости","Описание",(short)1,(short)1).toBytes(),44,
new CreateChannelBody(0,0,HASH,1,"Новости","Описание",(short)1,(short)1).toBytes().length),"CREATE_CHANNEL prefix removed");
var fork=new ForkContentBody(OWNER,0,HASH,123,1,HASH,234,1,1,"rotate");
testBody(0,TECH_FORK,fork,line(CoreRecord.TECH),2);
var oldFork=new ForkBody(0,0,HASH,1,OWNER,0,HASH,123,1,HASH,234,1,1,"rotate");
eq(fork.toBytes(),Arrays.copyOfRange(oldFork.toBytes(),44,oldFork.toBytes().length),"FORK prefix removed");
for(short s:new short[]{TEXT_POST,TEXT_EDIT_POST,TEXT_REPOST,TEXT_CHANNEL_META,TEXT_CHANNEL_DELETE,TEXT_ENTRYPOINT,TEXT_EXERCISE,TEXT_SERVICE,TEXT_COURSE}) {
boolean edit=s==TEXT_EDIT_POST, repost=s==TEXT_REPOST, target=edit||repost;
String msg=s==TEXT_CHANNEL_DELETE?"": "Тест 🌞";
var body=new TextLineContentBody(s,repost?"Bob":null,repost?1:null,target?0:null,target?HASH:null,msg);
testBody(1,s,body,line(0),2);
var legacy=new TextLineBody(0,0,HASH,1,s,repost?"Bob":null,repost?1:null,target?0:null,target?HASH:null,msg);
eq(body.toBytes(),Arrays.copyOfRange(legacy.toBytes(),44,legacy.toBytes().length),"TEXT prefix removed " + s);
bad(() -> parseSemantic(new ContentRecord(1,s,1,legacy.toBytes())),"old text prefix");
}
testBody(1,TEXT_REPLY,new TextReplyBody(TEXT_REPLY,"Bob",1,0,HASH,"ответ"),null,2);
testBody(1,TEXT_EDIT_REPLY,new TextReplyBody(TEXT_EDIT_REPLY,null,null,0,HASH,""),null,2);
testBody(1,TEXT_RATING,new TextRatingBody("Bob",1,0,HASH,"rating"),null,2);
for(short s: new short[]{REACTION_LIKE,REACTION_UNLIKE}) testBody(2,s,new ReactionBody(s,"Bob",1,0,HASH),null,2);
for(var field: MsgSubType.class.getFields()) {
if(field.getName().startsWith("CONNECTION_")) {
short s=field.getShort(null);
var body=new ConnectionContentBody(s,"Bob",1,0,HASH);
testBody(3,s,body,line(CoreRecord.CONNECTION),2);
var legacy=new ConnectionBody(0,HASH,1,s,"Bob",1,0,HASH);
eq(body.toBytes(),Arrays.copyOfRange(legacy.toBytes(),40,legacy.toBytes().length),"CONNECTION prefix removed " + s);
}
if(field.getName().startsWith("STATUS_")) {
short s=field.getShort(null);
testBody(5,s,new StatusActionBody(s,"Bob",1,0,HASH,""),null,2);
}
}
var profile=new UserParamContentBody("name","Алиса");
testBody(4,USER_PARAM_TEXT_TEXT,profile,line(CoreRecord.PROFILE),2);
var oldProfile=new UserParamBody(0,HASH,1,"name","Алиса");
eq(profile.toBytes(),Arrays.copyOfRange(oldProfile.toBytes(),40,oldProfile.toBytes().length),"PROFILE prefix removed");
bad(() -> parseSemantic(new ContentRecord(4,1,1,oldProfile.toBytes())),"old profile prefix");
bad(() -> parseSemantic(new ContentRecord(0,1,1,new byte[]{1,(byte)0xff,0,0,0,1,0,1})),"invalid channel UTF-8");
bad(() -> parseSemantic(new ContentRecord(1,TEXT_POST,1,new byte[]{0,1,(byte)0xff})),"invalid text UTF-8");
bad(() -> parseSemantic(new ContentRecord(65535,65535,1,new byte[0])),"unknown type");
bad(() -> parseSemantic(new ContentRecord(1,TEXT_POST,2,new byte[0])),"unknown version");
var shortName=new ContentRecord(0,1,1,new byte[]{1,'x',0,0,0,1,0,1});
var cc=core(1,line(CoreRecord.TECH),shortName,HASH);
ok(ContentBodyParser.parseForCore(cc,shortName) instanceof CreateChannelBody,"existing short name can be read");
bad(() -> ContentBodyParser.parseForCreate(cc,shortName),"new short name rejected");
}
// Для негативных тестов semantic parser строим корректный CORE вокруг испорченного тела.
private static BodyRecord parseSemantic(ContentRecord c) {
boolean header = c.type()==0 && c.subType()==HEADER_COMPAT;
CoreRecord.Line l = switch(c.type()) {
case 0 -> header ? null : line(CoreRecord.TECH);
case 1 -> ContentBodyParser.isChannelText(c.subType()) ? line(0) : null;
case 3 -> line(CoreRecord.CONNECTION);
case 4 -> line(CoreRecord.PROFILE);
default -> null;
};
return ContentBodyParser.parseForCore(core(header?0:2,l,c,HASH),c);
}
private static void testBody(int t, short s, BodyRecord body, CoreRecord.Line line, int n) {
byte[] raw=body.toBytes(); var content=new ContentRecord(t,s,1,raw); var c=core(n,line,content,HASH);
eq(ContentBodyParser.parseForCreate(c,content).toBytes(),raw,"roundtrip " + t + "/" + s);
for(int len=0;len<raw.length;len++) {
byte[] truncated=Arrays.copyOf(raw,len);
bad(() -> parseSemantic(new ContentRecord(t,s,1,truncated)),"truncated " + t + "/" + s + " len=" + len);
}
bad(() -> parseSemantic(new ContentRecord(t,s,1,Arrays.copyOf(raw,raw.length+1))),"body trailing bytes");
if(n==0) bad(() -> ContentBodyParser.parseForCore(core(1,null,content,HASH),content),"HEADER outside genesis");
else bad(() -> ContentBodyParser.parseForCore(core(n,line==null?line(0):null,content,HASH),content),"wrong line presence");
if(line!=null) {
int wrong=line.lineCode()==0?CoreRecord.PROFILE:0;
bad(() -> ContentBodyParser.parseForCore(core(n,line(wrong),content,HASH),content),"wrong line class");
}
}
private static void checkBinaryAndTransport() {
byte[] raw={0,5,'H','e','l','l','o'};
var content=new ContentRecord(1,TEXT_POST,1,raw);
raw[2]=0; ok(content.bodyBytes()[2]=='H',"immutable CONTENT input");
content.bodyBytes()[2]=0; ok(content.bodyBytes()[2]=='H',"immutable CONTENT output");
var item=CoreContentTransport.sign(content.toBytes(),List.of(),SEED);
var c=core(128,line(0),content,item.id32());
eq(c.toBytes(),CoreRecord.parse(c.toBytes()).toBytes(),"CORE roundtrip");
eq(content.toBytes(),ContentRecord.parse(content.toBytes()).toBytes(),"CONTENT roundtrip");
byte[] copy=c.prevCoreHash32(); copy[0]^=1; eq(c.prevCoreHash32(),HASH,"immutable CORE prev hash");
byte[] source=HASH.clone(); var l=new CoreRecord.Line(0,0,source); source[0]^=1; eq(l.prevLineCoreHash32(),HASH,"immutable Line input");
l.prevLineCoreHash32()[0]^=1; eq(l.prevLineCoreHash32(),HASH,"immutable Line output");
eq(ProtocolHash.fromHex32(ProtocolHash.hex32(HASH)),HASH,"hex");
eq(ProtocolHash.fromBase64url32(ProtocolHash.base64url32(HASH)),HASH,"base64url");
bad(() -> ProtocolHash.fromBase64url32(ProtocolHash.base64url32(HASH)+"="),"base64url padding");
for(int len:new int[]{0,108,110,148,150}) bad(() -> CoreRecord.parse(new byte[len]),"CORE length");
for(int len=0;len<7;len++) { int n=len; bad(() -> ContentRecord.parse(new byte[n]),"CONTENT length"); }
byte[] code=c.toBytes(); code[0]=2; bad(() -> CoreRecord.parse(code),"frameCode");
byte[] wrongContent=content.toBytes(); wrongContent[0]=2; bad(() -> ContentRecord.parse(wrongContent),"contentCode");
byte[] le=c.toBytes(); ByteBuffer.wrap(le).order(ByteOrder.LITTLE_ENDIAN).putInt(33,128); bad(() -> CoreRecord.parse(le),"wrong endian number");
bad(() -> core(-1,null,content,HASH),"negative global");
bad(() -> core(CoreRecord.MAX_BLOCK_NUMBER+1,null,content,HASH),"reserved global");
bad(() -> core(0,line(0),content,HASH),"genesis line");
bad(() -> new CoreRecord(HASH,0,NOW,HASH,HASH,null),"genesis nonzero prev");
bad(() -> core(1,new CoreRecord.Line(0,1,HASH),content,HASH),"line predecessor same number");
bad(() -> core(1,new CoreRecord.Line(1,0,HASH),content,HASH),"channel not created yet");
bad(() -> core(5,new CoreRecord.Line(3,2,HASH),content,HASH),"line pred before root");
new CoreRecord(HASH,1,NOW+60,HASH,HASH,null).checkTimestamp(NOW); count++;
bad(() -> new CoreRecord(HASH,1,NOW+61,HASH,HASH,null).checkTimestamp(NOW),"timestamp +61");
bad(() -> new CoreRecord(HASH,1,-1,HASH,HASH,null),"negative timestamp");
var signed=sign(c,CoreContentTransport.coreTags(c));
eq(CoreContentTransport.verifyPair(signed,signed.id32(),item,OWNER,NOW).content().toBytes(),content.toBytes(),"pair verify");
eq(CoreContentTransport.verifyCore(signed,OWNER,signed.id32(),NOW).toBytes(),c.toBytes(),"CORE only");
eq(CoreContentTransport.verifyPayload(c,item.data()).toBytes(),content.toBytes(),"payload only");
bad(() -> CoreContentTransport.verifyCore(signed,OWNER,HASH,NOW),"core ID mismatch");
byte[] altered=item.data(); altered[altered.length-1]^=1;
bad(() -> CoreContentTransport.verifyPayload(c,altered),"content hash mismatch");
byte[] signature=signed.rawBytes(); signature[2]^=1; var tampered=new Ans104DataItem(signature);
bad(() -> CoreContentTransport.verifyCore(tampered,OWNER,tampered.id32(),NOW),"bad signature with new ID");
byte[] secondSeed=SEED.clone(); secondSeed[0]^=1;
var other=CoreContentTransport.sign(content.toBytes(),List.of(),secondSeed);
var foreignCore=core(128,line(0),content,other.id32()); var foreign=sign(foreignCore,CoreContentTransport.coreTags(foreignCore));
bad(() -> CoreContentTransport.verifyPair(foreign,foreign.id32(),other,OWNER,NOW),"different owner with matching content ID");
bad(() -> CoreContentTransport.verifyContent(c,other,other.owner32()),"wrong content ID");
var tagged=CoreContentTransport.sign(content.toBytes(),List.of(tag("App","test5595"),tag("n","128")),SEED);
bad(() -> CoreContentTransport.verifyContent(core(128,line(0),content,tagged.id32()),tagged,OWNER),"tagged CONTENT");
rejectTags(c,List.of(tag("App","test5592"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","0128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","129"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128"),tag("l","P")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128")));
rejectTags(c,List.of(tag("App","test5595"),tag("App","test5595"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128"),tag("l","0"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128"),tag("l","0"),tag("c","news")));
rejectTags(c,List.of(tag("App","test5595"),tag("n","128"),tag("l","0"),tag("t","tech")));
rejectTags(core(128,null,content,item.id32()),List.of(tag("App","test5595"),tag("n","128"),tag("l","0")));
rejectTags(core(128,line(CoreRecord.TECH),content,item.id32()),List.of(tag("App","test5595"),tag("n","128"),tag("l",Integer.toString(CoreRecord.TECH))));
ok(ShineProtocolTags.CORE_REGISTRATION_TAGS.equals(List.of(tag("App","test5595"), tag("t","reg"), tag("Protocol","SHiNE-Free-Registration-V1"))), "separate registration tags");
rejectTags(core(128,null,content,item.id32()),ShineProtocolTags.CORE_REGISTRATION_TAGS);
var oldFrame=new byte[109]; oldFrame[1]=1;
bad(() -> CoreRecord.parse(oldFrame),"old Frame v1");
var unsignedUnknown=new ContentRecord(65535,65535,65535,new byte[0]);
ok(ContentRecord.parse(unsignedUnknown.toBytes()).type()==65535,"raw unknown unsigned type");
bad(() -> new ContentRecord(65536,0,0,new byte[0]),"uint16 overflow");
}
// ANS-104 подписывает исходные Avro-байты, а не декодированный список тегов.
private static byte[] replaceRawTags(Ans104DataItem item, byte[] rawTags) {
// Тестовые оболочки без target/anchor: tags_size расположен по смещению 108.
byte[] old = item.rawBytes(), data = item.data();
byte[] result = Arrays.copyOf(old, 116 + rawTags.length + data.length);
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).putLong(108, rawTags.length);
System.arraycopy(rawTags,0,result,116,rawTags.length);
System.arraycopy(data,0,result,116+rawTags.length,data.length);
return result;
}
private static void checkRawTagSignatures() {
var original = CoreContentTransport.sign(new byte[]{7},List.of(tag("App","test5595")),SEED);
byte[] raw = original.rawTags();
// Эквивалентный Avro-массив с отрицательным count и явным размером блока.
byte[] alternative = new byte[raw.length+1];
alternative[0]=1; // zigzag(-1)
alternative[1]=(byte)((raw.length-2)*2);
System.arraycopy(raw,1,alternative,2,raw.length-1);
byte[] replaced=replaceRawTags(original,alternative);
var changed = new Ans104DataItem(replaced);
ok(changed.tags().equals(original.tags()),"same decoded tags");
ok(!changed.verifySignature(),"modified raw tags must invalidate original signature");
ok(!Arrays.equals(changed.signingMessage(),original.signingMessage()),"raw encoding is part of deep hash");
byte[] sig=Ed25519Util.sign(changed.signingMessage(),SEED);
System.arraycopy(sig,0,replaced,2,64);
ok(new Ans104DataItem(replaced).verifySignature(),"genuinely signed alternative Avro encoding");
byte[] wrongSize=alternative.clone(); wrongSize[1]-=2;
bad(() -> new Ans104DataItem(replaceRawTags(original,wrongSize)),"wrong Avro block size");
bad(() -> new Ans104DataItem(replaceRawTags(original,Arrays.copyOf(raw,raw.length-1))),"missing Avro terminator");
byte[] invalidUtf8=raw.clone(); invalidUtf8[2]=(byte)0xff;
bad(() -> new Ans104DataItem(replaceRawTags(original,invalidUtf8)),"invalid UTF-8 in tags");
var empty=CoreContentTransport.sign(new byte[]{7},List.of(),SEED);
byte[] emptyRaw=replaceRawTags(empty,new byte[0]);
var unsigned=new Ans104DataItem(emptyRaw);
ok(!unsigned.verifySignature(),"zero-length Avro differs from encoded empty array");
System.arraycopy(Ed25519Util.sign(unsigned.signingMessage(),SEED),0,emptyRaw,2,64);
ok(new Ans104DataItem(emptyRaw).verifySignature(),"signed zero-length tag section");
}
private static Path vectorsPath() {
for(Path p=Path.of("").toAbsolutePath();p!=null;p=p.getParent()) {
Path f=p.resolve("docs/Blockchain/vectors/core-content-v1.tsv"); if(Files.isRegularFile(f))return f;
}
throw new IllegalStateException("Не найдены golden vectors");
}
private static void checkVectors() throws Exception {
var rows=Files.readAllLines(vectorsPath()); var history=new ArrayList<CoreRecord>();
for(String row:rows.subList(1,rows.size())) {
String[] f=row.split("\t"); byte[] owner=HEX.parseHex(f[1]); byte[] c=HEX.parseHex(f[2]), h=HEX.parseHex(f[3]), p=HEX.parseHex(f[4]);
var ci=new Ans104DataItem(HEX.parseHex(f[6])); var pi=new Ans104DataItem(HEX.parseHex(f[8]));
var pair=CoreContentTransport.verifyPair(ci,HEX.parseHex(f[7]),pi,owner,NOW);
eq(pair.core().toBytes(),c,"golden CORE " + f[0]); eq(pair.core().coreHash32(),h,"golden CORE hash");
eq(pair.content().toBytes(),p,"golden CONTENT"); eq(pair.content().contentHash32(),HEX.parseHex(f[5]),"golden CONTENT hash");
eq(pi.id32(),HEX.parseHex(f[9]),"golden CONTENT ID");
eq(CoreContentTransport.sign(c,CoreContentTransport.coreTags(pair.core()),SEED).rawBytes(),ci.rawBytes(),"independent CORE signing");
eq(CoreContentTransport.sign(p,List.of(),SEED).rawBytes(),pi.rawBytes(),"independent CONTENT signing");
ContentBodyParser.parseForCreate(pair.core(),pair.content()); count++;
var core=pair.core(); eq(core.prevCoreHash32(),history.isEmpty()?ZERO:history.get(history.size()-1).coreHash32(),"global hash link");
if(core.line()!=null) eq(core.line().prevLineCoreHash32(),history.get(core.line().prevLineBlockNumber()).coreHash32(),"line hash link");
history.add(core);
}
}
private static void checkContainer() throws Exception {
var rows=Files.readAllLines(vectorsPath());
for (String row: rows.subList(1,rows.size())) {
String[] f=row.split("\t");
var ci=new Ans104DataItem(HEX.parseHex(f[6])); var pi=new Ans104DataItem(HEX.parseHex(f[8]));
byte[] raw=CoreContentContainer.pack(ci,pi);
var entry=BchBlockEntry.fromCoreContent(raw);
ok(entry.isCoreContent(),"pair entry");
eq(entry.toBytes(),raw,"container byte-identical");
eq(entry.getFrameBytes(),HEX.parseHex(f[2]),"CORE payload");
eq(entry.getHash32(),HEX.parseHex(f[3]),"CORE hash");
eq(entry.getDataItemId32(),HEX.parseHex(f[7]),"CORE ID");
eq(entry.getContentDataItem().rawBytes(),pi.rawBytes(),"signed CONTENT");
eq(entry.body.toBytes(),entry.getContentRecord().bodyBytes(),"concrete body roundtrip");
ok(entry.back32Hash32==null,"no back32");
ok(BchCryptoVerifier.verifyBlock(entry,OWNER),"pair authorized");
ok(!BchCryptoVerifier.verifyBlock(entry,new byte[32]),"wrong owner");
try { entry.getDataItem(); throw new AssertionError("legacy accessor must refuse pair"); }
catch (IllegalStateException expected) { count++; }
if(entry.body instanceof BodyHasLine l) {
int signed=entry.getCoreRecord().line().lineCode();
ok(l.lineCode()==(LineIndex.isChannel(signed)?signed:0),"internal line mapping");
ok(l.lineSeq()==BodyHasLine.UNRESOLVED_SEQUENCE,"no fabricated sequence");
eq(l.prevLineBlockHash32(),entry.getCoreRecord().line().prevLineCoreHash32(),"previous line hash");
}
byte[] badLen=raw.clone(); ByteBuffer.wrap(badLen).putInt(-1);
bad(()->BchBlockEntry.fromCoreContent(badLen),"unsigned length overflow");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,4+ci.rawBytes().length)),"missing CONTENT");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,raw.length-1)),"truncated CONTENT");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,raw.length+1)),"extra CONTENT byte");
byte[] changed=raw.clone(); changed[4+2]^=1;
bad(()->BchBlockEntry.fromCoreContent(changed),"CORE signature tamper");
byte[] changedContent=raw.clone(); changedContent[4+ci.rawBytes().length+2]^=1;
bad(()->BchBlockEntry.fromCoreContent(changedContent),"CONTENT signature tamper");
}
bad(()->BchBlockEntry.fromCoreContent(new byte[CoreContentContainer.MAX_CONTAINER_BYTES+1]),"oversize");
}
public static int runAll() throws Exception { count=0; checkContainer(); checkBinaryAndTransport(); checkRawTagSignatures(); checkBodies(); checkVectors(); return count; }
public static void main(String[] args) throws Exception { System.out.println("Stage A assertions passed: " + runAll()); }
}
@@ -0,0 +1,10 @@
package blockchain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StageAProtocolTest {
@Test void coreContentProtocol() throws Exception {
assertTrue(StageAProtocolChecks.runAll() > 0);
}
}
@@ -0,0 +1,83 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class ConnectionContentBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 3;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public ConnectionContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 1 + 1 + 2 + 4 + 32, "ConnectionContentBody too short");
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected ConnectionContentBody tail");
}
public ConnectionContentBody(short subType,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
this.subType = subType;
this.version = VER;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
}
@Override public ConnectionContentBody check() {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return this;
}
@Override public byte[] toBytes() {
check();
ByteBuffer bb = ByteBuffer.allocate(BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array();
}
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static boolean isValidSubType(short st) {
int v = st & 0xFFFF;
return v == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCLOSE_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CONTACT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCONTACT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FOLLOW & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SPOUSE & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSPOUSE & 0xFFFF)
|| v == (MsgSubType.CONNECTION_PARENT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNPARENT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CHILD & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCHILD & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SIBLING & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSIBLING & 0xFFFF)
|| v == (MsgSubType.CONNECTION_KNOWN_PERSON & 0xFFFF) || v == (MsgSubType.CONNECTION_UNKNOWN_PERSON & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNCONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_SEEN & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNSEEN & 0xFFFF)
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
}
}
@@ -0,0 +1,176 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class CreateChannelContentBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final short SUBTYPE = MsgSubType.TECH_CREATE_CHANNEL;
public static final short CHANNEL_TYPE_STORIES = 0;
public static final short CHANNEL_TYPE_PUBLIC = 1;
public static final short CHANNEL_TYPE_PERSONAL = 100;
public static final short CHANNEL_TYPE_GROUP = 200;
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
// Минимум для создания нового канала; исторические блоки 1–3 символа читаются.
public static final int MIN_NAME_LENGTH_FOR_CREATE = 4;
private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
public final short subType;
public final short version;
public final String channelName;
public final String channelDescription;
public final short channelTypeCode;
public final short channelTypeVersion;
public CreateChannelContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
int ver = this.version & 0xFFFF;
if (ver != (VER & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody version must be 1, got=" + ver);
}
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
}
if (bodyBytes.length < 1 + 1 + 2 + 4) {
throw new IllegalArgumentException("CreateChannelContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
if (bb.remaining() < nameLen + 2 + 4) {
throw new IllegalArgumentException("CreateChannelContentBody tail mismatch: remaining=" + bb.remaining() + " nameLen=" + nameLen);
}
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.channelName = BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName");
int descriptionLen = Short.toUnsignedInt(bb.getShort());
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
if (bb.remaining() != descriptionLen + 4) {
throw new IllegalArgumentException("CreateChannelContentBody tail mismatch: remaining=" + bb.remaining() + " descriptionLen=" + descriptionLen);
}
if (descriptionLen == 0) {
this.channelDescription = "";
} else {
byte[] descriptionBytes = new byte[descriptionLen];
bb.get(descriptionBytes);
this.channelDescription = normalizeDescription(BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription"));
}
this.channelTypeCode = bb.getShort();
this.channelTypeVersion = bb.getShort();
if (bb.remaining() != 0) {
throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
}
}
public CreateChannelContentBody(String channelName,
String channelDescription,
short channelTypeCode,
short channelTypeVersion) {
Objects.requireNonNull(channelName, "channelName == null");
this.subType = SUBTYPE;
this.version = VER;
this.channelName = channelName;
this.channelDescription = channelDescription == null ? "" : channelDescription;
this.channelTypeCode = channelTypeCode;
this.channelTypeVersion = channelTypeVersion;
}
@Override
public CreateChannelContentBody check() {
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody subType must be TECH_CREATE_CHANNEL(1)");
}
String normalizedName = normalizeDisplayName(channelName);
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
int cpLen = normalizedName.codePointCount(0, normalizedName.length());
if (normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
String normalizedDescription = normalizeDescription(channelDescription);
byte[] descUtf8 = normalizedDescription.getBytes(StandardCharsets.UTF_8);
if (descUtf8.length > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
int typeCode = Short.toUnsignedInt(channelTypeCode);
int typeVer = Short.toUnsignedInt(channelTypeVersion);
if (typeCode < 0 || typeCode > 0xFFFF) throw new IllegalArgumentException("channelTypeCode invalid");
if (typeVer < 0 || typeVer > 0xFFFF) throw new IllegalArgumentException("channelTypeVersion invalid");
return this;
}
/**
* Правило создания нового TECH_CREATE_CHANNEL (в отличие от чтения истории).
* check() намеренно принимает старые каналы с именами из 1–3 символов.
*/
public CreateChannelContentBody checkForCreate() {
check();
String normalizedName = normalizeDisplayName(channelName);
int length = normalizedName.codePointCount(0, normalizedName.length());
if (length < MIN_NAME_LENGTH_FOR_CREATE) {
throw new IllegalArgumentException("channelName length must be 4..32");
}
return this;
}
private static String normalizeDisplayName(String value) {
if (value == null) return "";
return value.trim().replaceAll("\\s+", " ");
}
private static String normalizeDescription(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
@Override
public byte[] toBytes() {
// Новые блоки кодируются только с именем от 4 символов.
// Исторические блоки при чтении разбираются без повторного кодирования.
checkForCreate();
byte[] nameUtf8 = normalizeDisplayName(channelName).getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("channelName utf8 len must be 1..255");
}
byte[] descriptionUtf8 = normalizeDescription(channelDescription).getBytes(StandardCharsets.UTF_8);
if (descriptionUtf8.length > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
int cap = 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
if (descriptionUtf8.length > 0) bb.put(descriptionUtf8);
bb.putShort(channelTypeCode);
bb.putShort(channelTypeVersion);
return bb.array();
}
}
@@ -0,0 +1,182 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class ForkContentBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
public static final short SUBTYPE = MsgSubType.TECH_FORK;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final int REASON_ROUTINE_ROTATION = 1;
public static final int REASON_POSSIBLE_COMPROMISE = 2;
public static final int REASON_CONFIRMED_COMPROMISE_ROLLBACK = 3;
public static final int REASON_RECOVERY = 4;
public static final int MAX_COMMENT_UTF8_LEN = 1024;
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
private static final int FIXED_LEN = FIXED_PAYLOAD_LEN;
public final short subType;
public final short version;
public final byte[] parentBlockchainKey32;
public final int forkPointBlockNumber;
public final byte[] forkPointBlockHash32;
public final long forkPointTimestampMs;
public final int parentTipBlockNumber;
public final byte[] parentTipBlockHash32;
public final long parentTipTimestampMs;
public final int discardedBlocksCount;
public final int reasonCode;
public final String comment;
public ForkContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody version must be 1");
}
if (bodyBytes.length < FIXED_LEN) {
throw new IllegalArgumentException("ForkContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32);
this.forkPointBlockNumber = bb.getInt();
this.forkPointBlockHash32 = new byte[32];
bb.get(this.forkPointBlockHash32);
this.forkPointTimestampMs = bb.getLong();
this.parentTipBlockNumber = bb.getInt();
this.parentTipBlockHash32 = new byte[32];
bb.get(this.parentTipBlockHash32);
this.parentTipTimestampMs = bb.getLong();
this.discardedBlocksCount = bb.getInt();
this.reasonCode = Byte.toUnsignedInt(bb.get());
int commentLen = Short.toUnsignedInt(bb.getShort());
if (commentLen > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkContentBody comment utf8 len must be <=1024");
}
if (bb.remaining() != commentLen) {
throw new IllegalArgumentException("ForkContentBody tail mismatch: remaining=" + bb.remaining() + " commentLen=" + commentLen);
}
byte[] commentBytes = new byte[commentLen];
bb.get(commentBytes);
this.comment = BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment");
}
public ForkContentBody(byte[] parentBlockchainKey32,
int forkPointBlockNumber,
byte[] forkPointBlockHash32,
long forkPointTimestampMs,
int parentTipBlockNumber,
byte[] parentTipBlockHash32,
long parentTipTimestampMs,
int discardedBlocksCount,
int reasonCode,
String comment) {
this.subType = SUBTYPE;
this.version = VER;
this.parentBlockchainKey32 = copy32(parentBlockchainKey32, "parentBlockchainKey32");
this.forkPointBlockNumber = forkPointBlockNumber;
this.forkPointBlockHash32 = copy32(forkPointBlockHash32, "forkPointBlockHash32");
this.forkPointTimestampMs = forkPointTimestampMs;
this.parentTipBlockNumber = parentTipBlockNumber;
this.parentTipBlockHash32 = copy32(parentTipBlockHash32, "parentTipBlockHash32");
this.parentTipTimestampMs = parentTipTimestampMs;
this.discardedBlocksCount = discardedBlocksCount;
this.reasonCode = reasonCode;
this.comment = normalizeComment(comment);
}
@Override
public ForkContentBody check() {
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody version must be 1");
}
require32(parentBlockchainKey32, "parentBlockchainKey32");
require32(forkPointBlockHash32, "forkPointBlockHash32");
require32(parentTipBlockHash32, "parentTipBlockHash32");
if (forkPointBlockNumber < 0) throw new IllegalArgumentException("forkPointBlockNumber < 0");
if (parentTipBlockNumber < forkPointBlockNumber) {
throw new IllegalArgumentException("parentTipBlockNumber < forkPointBlockNumber");
}
if (forkPointTimestampMs < 0) throw new IllegalArgumentException("forkPointTimestampMs < 0");
if (parentTipTimestampMs < 0) throw new IllegalArgumentException("parentTipTimestampMs < 0");
int expectedDiscarded = parentTipBlockNumber - forkPointBlockNumber;
if (discardedBlocksCount != expectedDiscarded) {
throw new IllegalArgumentException("discardedBlocksCount must equal parentTipBlockNumber - forkPointBlockNumber");
}
if (!isReasonSupported(reasonCode)) {
throw new IllegalArgumentException("Unsupported fork reasonCode=" + reasonCode);
}
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
if (commentUtf8.length > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkContentBody comment utf8 len must be <=1024");
}
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32);
bb.putLong(forkPointTimestampMs);
bb.putInt(parentTipBlockNumber);
bb.put(parentTipBlockHash32);
bb.putLong(parentTipTimestampMs);
bb.putInt(discardedBlocksCount);
bb.put((byte) reasonCode);
bb.putShort((short) commentUtf8.length);
bb.put(commentUtf8);
return bb.array();
}
public static boolean isReasonSupported(int code) {
return code == REASON_ROUTINE_ROTATION
|| code == REASON_POSSIBLE_COMPROMISE
|| code == REASON_CONFIRMED_COMPROMISE_ROLLBACK
|| code == REASON_RECOVERY;
}
private static byte[] copy32(byte[] value, String name) {
require32(value, name);
return Arrays.copyOf(value, 32);
}
private static void require32(byte[] value, String name) {
if (value == null || value.length != 32) {
throw new IllegalArgumentException(name + " must be 32 bytes");
}
}
private static String normalizeComment(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
}
@@ -0,0 +1,152 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class TextLineContentBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toLogin;
public final Integer toForkNumber;
public final Integer toBlockGlobalNumber;
public final byte[] toBlockHash32;
public final String message;
public TextLineContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 2, "TextLineContentBody too short");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
BodyTargetSupport.ensureMin(bb, 4 + 32 + 2, "EDIT_POST target missing");
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32]; bb.get(this.toBlockHash32);
BodyTargetSupport.validateCompact(this.toBlockGlobalNumber, this.toBlockHash32, "EDIT_POST");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "REPOST", 2);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
} else {
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
}
boolean allowEmpty = st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
this.message = readText(bb, allowEmpty);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextLineContentBody tail");
}
public TextLineContentBody(short subType,
String toLogin,
Integer toForkNumber,
Integer toBlockGlobalNumber,
byte[] toBlockHash32,
String message) {
Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody subtype");
this.subType = subType;
this.version = VER;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = toBlockHash32 == null ? null : blockchain.ProtocolHash.copy32(toBlockHash32);
this.message = message;
check();
}
@Override public TextLineContentBody check() {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody subtype");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (toLogin != null || toForkNumber != null) throw new IllegalArgumentException("EDIT_POST must not contain login/fork target");
BodyTargetSupport.validateCompact(toBlockGlobalNumber, toBlockHash32, "EDIT_POST");
if (message == null) throw new IllegalArgumentException("EDIT_POST message is null");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
if (message == null || message.isBlank()) throw new IllegalArgumentException("REPOST message is blank");
} else {
if (toLogin != null || toForkNumber != null || toBlockGlobalNumber != null || toBlockHash32 != null) {
throw new IllegalArgumentException("Non-target text body must not contain target fields");
}
if (st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
if (message == null) throw new IllegalArgumentException("CHANNEL_META message is null");
} else if (st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
if (message == null || !message.isEmpty()) throw new IllegalArgumentException("CHANNEL_DELETE message must be empty");
} else if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Text message is blank");
}
}
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
int st = subType & 0xFFFF;
int targetSize = 0;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
ByteBuffer bb = ByteBuffer.allocate(targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
}
bb.putShort((short) text.length).put(text);
return bb.array();
}
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32 == null ? null : Arrays.copyOf(toBlockHash32, 32); }
public boolean isEditPost() { return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_POST & 0xFFFF); }
private static boolean isSupportedSubType(short subType) {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF) || st == (MsgSubType.TEXT_COURSE & 0xFFFF);
}
private static String readText(ByteBuffer bb, boolean allowEmpty) {
if (bb.remaining() < 2) throw new IllegalArgumentException("Text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (len == 0) { if (allowEmpty) return ""; throw new IllegalArgumentException("Text is empty"); }
if (bb.remaining() < len) throw new IllegalArgumentException("Text payload too short");
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { String s = dec.decode(ByteBuffer.wrap(bytes)).toString(); if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException("Text blank"); return s; }
catch (CharacterCodingException e) { throw new IllegalArgumentException("Text invalid UTF-8", e); }
}
}
@@ -0,0 +1,133 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class UserParamContentBody implements BodyRecord {
public static final short TYPE = 4;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String paramKey;
public final String paramValue;
public UserParamContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("UserParamContentBody version must be 1, got=" + (this.version & 0xFFFF));
}
if ((this.subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
throw new IllegalArgumentException("Bad UserParam subType: " + (this.subType & 0xFFFF));
}
if (bodyBytes.length < 2 + 1 + 2 + 1) {
throw new IllegalArgumentException("UserParamContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
if (bb.remaining() < keyLen + 2) throw new IllegalArgumentException("UserParam key payload too short");
byte[] keyBytes = new byte[keyLen];
bb.get(keyBytes);
int valLen = Short.toUnsignedInt(bb.getShort());
if (valLen <= 0) throw new IllegalArgumentException("paramValueLen is 0");
if (bb.remaining() < valLen) throw new IllegalArgumentException("UserParam value payload too short");
byte[] valBytes = new byte[valLen];
bb.get(valBytes);
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
this.paramKey = strictUtf8(keyBytes, "paramKey");
this.paramValue = strictUtf8(valBytes, "paramValue");
if (this.paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (this.paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
}
public UserParamContentBody(String paramKey,
String paramValue) {
Objects.requireNonNull(paramKey, "paramKey == null");
Objects.requireNonNull(paramValue, "paramValue == null");
this.subType = MsgSubType.USER_PARAM_TEXT_TEXT;
this.version = VER;
if (paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
this.paramKey = paramKey;
this.paramValue = paramValue;
}
@Override
public UserParamContentBody check() {
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
throw new IllegalArgumentException("Bad UserParam subType: " + (subType & 0xFFFF));
}
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
if (paramKey.getBytes(StandardCharsets.UTF_8).length > 65535 || paramValue.getBytes(StandardCharsets.UTF_8).length > 65535)
throw new IllegalArgumentException("Profile key/value too long");
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] keyUtf8 = paramKey.getBytes(StandardCharsets.UTF_8);
byte[] valUtf8 = paramValue.getBytes(StandardCharsets.UTF_8);
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
int cap = 2 + keyUtf8.length
+ 2 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8);
bb.putShort((short) valUtf8.length);
bb.put(valUtf8);
return bb.array();
}
private static String strictUtf8(byte[] bytes, String fieldName) {
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return decoder.decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
}
@@ -35,6 +35,11 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_42 = 42; public static final int SCHEMA_VERSION_42 = 42;
public static final int SCHEMA_VERSION_43 = 43; public static final int SCHEMA_VERSION_43 = 43;
public static final int SCHEMA_VERSION_44 = 44; public static final int SCHEMA_VERSION_44 = 44;
public static final int SCHEMA_VERSION_45 = 45;
public static final int SCHEMA_VERSION_46 = 46;
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 String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql"; 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_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql"; public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -50,6 +55,11 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql"; public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql"; public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql"; public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
public static final String POSTGRES_MIGRATION_V45_RESOURCE = "postgres/migration_v45.sql";
public static final String POSTGRES_MIGRATION_V46_RESOURCE = "postgres/migration_v46.sql";
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";
private DatabaseInitializer() {} private DatabaseInitializer() {}
@@ -197,9 +207,29 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE); runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn); currentVersion = readCurrentSchemaVersion(conn);
} }
if (currentVersion != SCHEMA_VERSION_44) { if (currentVersion == SCHEMA_VERSION_44) {
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_45) {
runSqlScript(conn, POSTGRES_MIGRATION_V46_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_46) {
runSqlScript(conn, POSTGRES_MIGRATION_V47_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_47) {
runSqlScript(conn, POSTGRES_MIGRATION_V48_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_48) {
runSqlScript(conn, POSTGRES_MIGRATION_V49_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_49) {
throw new SQLException( throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 44, found " + currentVersion); "Unsupported SHiNE DB v2 schema version: expected 49, found " + currentVersion);
} }
normalizeBlockchainStateKeysToBase64(conn); normalizeBlockchainStateKeysToBase64(conn);
} }
@@ -87,6 +87,7 @@ public final class BlockchainResyncCleanupDAO {
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){ try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate(); ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
} }
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,ref.login());ps.execute();}
c.commit(); c.commit();
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState); return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); } }catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
@@ -214,6 +215,7 @@ public final class BlockchainResyncCleanupDAO {
) )
""")){ps.setString(1,login);ps.executeUpdate();} """)){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,login);ps.execute();}
// Recompute all message aggregates whose target belongs to this user. This also fixes // Recompute all message aggregates whose target belongs to this user. This also fixes
// external reactions/replies that intentionally survive this user's rebuild. // external reactions/replies that intentionally survive this user's rebuild.
try(PreparedStatement ps=c.prepareStatement(""" try(PreparedStatement ps=c.prepareStatement("""
@@ -9,7 +9,7 @@ import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** DAO for SHiNE Frame v1 blocks. block_bytes contains the complete ANS-104 DataItem. */ /** DAO for SHiNE blocks. block_bytes contains the complete signed CORE/CONTENT container. */
public final class BlocksDAO { public final class BlocksDAO {
private static volatile BlocksDAO instance; private static volatile BlocksDAO instance;
private final DbController db = DbController.getInstance(); private final DbController db = DbController.getInstance();
@@ -22,14 +22,19 @@ public final class BlocksDAO {
} }
public void insert(Connection c, BlockEntry e) throws SQLException { public void insert(Connection c, BlockEntry e) throws SQLException {
insert(c, e, null, null);
}
public void insert(Connection c, BlockEntry e, Integer accountType, List<String> previousAccounts) throws SQLException {
String sql = """ String sql = """
INSERT INTO blocks_store ( INSERT INTO blocks_store (
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes, login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash, to_login,to_fork_number,to_block_number,to_block_hash,
block_hash,block_signature,data_item_id, block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms, arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number,
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) header_account_type,header_previous_accounts
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1; int i = 1;
@@ -53,6 +58,12 @@ public final class BlocksDAO {
setNullableInt(ps, i++, e.getPrevLineNumber()); setNullableInt(ps, i++, e.getPrevLineNumber());
setNullableBytes(ps, i++, e.getPrevLineHash()); setNullableBytes(ps, i++, e.getPrevLineHash());
setNullableInt(ps, i++, e.getThisLineNumber()); setNullableInt(ps, i++, e.getThisLineNumber());
if (accountType == null) {
ps.setNull(i++, Types.SMALLINT); ps.setNull(i, Types.ARRAY);
} else {
ps.setInt(i++, accountType);
ps.setArray(i, c.createArrayOf("text", previousAccounts.toArray(String[]::new)));
}
ps.executeUpdate(); ps.executeUpdate();
} }
} }
@@ -73,6 +73,47 @@ public final class ChannelNameStateDAO {
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
bindInsert(ps, entry);
ps.executeUpdate();
}
}
/**
* Используется только при воспроизведении уже подписанной истории. В live AddBlock
* дубликат имени запрещён; при replay блок всё же нужно сохранить, иначе цепочка
* после него останется разорванной.
*/
public void insertOrReplaceWithNewerRoot(Connection c, ChannelNameStateEntry entry) throws SQLException {
String sql = """
INSERT INTO channel_names_state (
slug, display_name, channel_description, owner_login, owner_bch_name,
channel_type_code, channel_type_version, channel_root_block_number,
channel_root_block_hash, created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (owner_bch_name, channel_type_code, slug) DO UPDATE SET
display_name = EXCLUDED.display_name,
channel_description = EXCLUDED.channel_description,
owner_login = EXCLUDED.owner_login,
channel_type_version = EXCLUDED.channel_type_version,
channel_root_block_number = EXCLUDED.channel_root_block_number,
channel_root_block_hash = EXCLUDED.channel_root_block_hash,
created_at_ms = EXCLUDED.created_at_ms,
ava_ar = EXCLUDED.ava_ar,
ava_pr = EXCLUDED.ava_pr,
ava_size = EXCLUDED.ava_size,
meta_updated_at_ms = EXCLUDED.meta_updated_at_ms,
is_deleted = FALSE,
deleted_at_ms = 0,
deleted_block_number = NULL
WHERE EXCLUDED.channel_root_block_number > channel_names_state.channel_root_block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
bindInsert(ps, entry);
ps.executeUpdate();
}
}
private static void bindInsert(PreparedStatement ps, ChannelNameStateEntry entry) throws SQLException {
ps.setString(1, entry.getSlug()); ps.setString(1, entry.getSlug());
ps.setString(2, entry.getDisplayName()); ps.setString(2, entry.getDisplayName());
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription()); ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
@@ -87,8 +128,6 @@ public final class ChannelNameStateDAO {
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr()); ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
ps.setLong(13, Math.max(0L, entry.getAvaSize())); ps.setLong(13, Math.max(0L, entry.getAvaSize()));
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs())); ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.executeUpdate();
}
} }
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException { public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
@@ -21,6 +21,16 @@ public final class ChannelReadStateDAO {
private ChannelReadStateDAO() {} private ChannelReadStateDAO() {}
// Корневой канал существует виртуально даже до появления Header. Никаких записей CreateChannel.
private static final String PUBLIC_CHANNELS = """
public_channels AS (
SELECT owner_login, slug, channel_root_block_number, channel_root_block_hash, is_deleted
FROM channel_names_state WHERE channel_type_code=1 AND slug<>'stories'
UNION ALL
SELECT login, 'stories', 0, NULL::bytea, FALSE FROM user_identity_current
)
""";
public static ChannelReadStateDAO getInstance() { public static ChannelReadStateDAO getInstance() {
if (instance == null) { if (instance == null) {
synchronized (ChannelReadStateDAO.class) { synchronized (ChannelReadStateDAO.class) {
@@ -64,22 +74,21 @@ public final class ChannelReadStateDAO {
} }
public long sumUnreadCount(Connection c, String viewerLogin) throws SQLException { public long sumUnreadCount(Connection c, String viewerLogin) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT COALESCE(SUM(crs.unread_count),0) SELECT COALESCE(SUM(crs.unread_count),0)
FROM channel_read_state crs FROM channel_read_state crs
WHERE LOWER(crs.viewer_login)=LOWER(?) WHERE LOWER(crs.viewer_login)=LOWER(?)
AND EXISTS ( AND EXISTS (
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login) ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=30 AND cs.rel_type=30
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login) WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
AND NOT cns.is_deleted AND NOT cns.is_deleted
) )
"""; """;
@@ -96,18 +105,17 @@ public final class ChannelReadStateDAO {
*/ */
public boolean hasActiveSubscription(Connection c, String viewerLogin, String ownerBchName, String channelName, public boolean hasActiveSubscription(Connection c, String viewerLogin, String ownerBchName, String channelName,
int followRelType) throws SQLException { int followRelType) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(?) ON LOWER(cs.login)=LOWER(?)
AND cs.rel_type=? AND cs.rel_type=?
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(?) WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.slug=? AND cns.slug=?
AND cns.channel_type_code=1
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -122,10 +130,10 @@ public final class ChannelReadStateDAO {
} }
public String resolvePublicChannelNameByRoot(Connection c, String ownerBchName, int rootBlockNumber) throws SQLException { public String resolvePublicChannelNameByRoot(Connection c, String ownerBchName, int rootBlockNumber) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT slug SELECT slug
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -139,10 +147,10 @@ public final class ChannelReadStateDAO {
public Integer resolvePublicChannelRootByName(Connection c, String ownerBchName, String channelName) throws SQLException { public Integer resolvePublicChannelRootByName(Connection c, String ownerBchName, String channelName) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT channel_root_block_number SELECT channel_root_block_number
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND slug=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -155,10 +163,10 @@ public final class ChannelReadStateDAO {
} }
public String resolveOwnerLogin(Connection c, String ownerBchName, String channelName) throws SQLException { public String resolveOwnerLogin(Connection c, String ownerBchName, String channelName) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT owner_login SELECT owner_login
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND slug=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -242,7 +250,7 @@ public final class ChannelReadStateDAO {
String channelName, String channelName,
int followRelType, int followRelType,
long nowMs) throws SQLException { long nowMs) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
UPDATE channel_read_state crs UPDATE channel_read_state crs
SET unread_count = crs.unread_count + 1, SET unread_count = crs.unread_count + 1,
updated_at_ms = ? updated_at_ms = ?
@@ -251,16 +259,15 @@ public final class ChannelReadStateDAO {
AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login) AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login)
AND EXISTS ( AND EXISTS (
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login) ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=? AND cs.rel_type=?
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login) WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
) )
RETURNING viewer_login RETURNING viewer_login
"""; """;
@@ -280,15 +287,14 @@ public final class ChannelReadStateDAO {
/** Delete the projection row when a channel FOLLOW is explicitly removed. */ /** Delete the projection row when a channel FOLLOW is explicitly removed. */
public boolean deleteForUnfollowTarget(Connection c, String viewerLogin, String ownerBchName, public boolean deleteForUnfollowTarget(Connection c, String viewerLogin, String ownerBchName,
int rootBlockNumber) throws SQLException { int rootBlockNumber) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
DELETE FROM channel_read_state crs DELETE FROM channel_read_state crs
USING channel_names_state cns USING public_channels cns
WHERE LOWER(crs.viewer_login)=LOWER(?) WHERE LOWER(crs.viewer_login)=LOWER(?)
AND LOWER(crs.owner_login)=LOWER(?) AND LOWER(crs.owner_login)=LOWER(?)
AND LOWER(cns.owner_login)=LOWER(crs.owner_login) AND LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_root_block_number=? AND cns.channel_root_block_number=?
AND cns.channel_type_code=1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin); ps.setString(1, viewerLogin);
@@ -299,24 +305,27 @@ public final class ChannelReadStateDAO {
} }
/** /**
* Recomputes server-owned unread counters for all public channels owned by one logical login. * Recomputes server-owned unread counters for all public channels owned by one logical login.
* Signed read_count/read signature fields are preserved exactly. Safe to call repeatedly after replay. * Clamp the effective read_count to the rebuilt history; invalidate a signature
* when its stored count changes. Keep the last accepted timestamp to reject stale requests.
*/ */
public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException { public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + ", " + """
WITH counts AS ( counts AS (
SELECT cns.owner_login, cns.slug, COUNT(b.block_number)::BIGINT AS message_count SELECT cns.owner_login, cns.slug, COUNT(b.block_number)::BIGINT AS message_count
FROM channel_names_state cns FROM public_channels cns
LEFT JOIN blocks_store b LEFT JOIN blocks_store b
ON LOWER(b.login)=LOWER(cns.owner_login) ON LOWER(b.login)=LOWER(cns.owner_login)
AND b.line_code=cns.channel_root_block_number AND b.line_code=cns.channel_root_block_number
AND b.msg_type=1 AND b.msg_type=1
AND b.msg_sub_type IN (10,50,100,110,120,130) AND b.msg_sub_type IN (10,50,100,110,120,130)
AND b.fork_number=shine_active_fork(b.login,b.block_number)
WHERE LOWER(cns.owner_login)=LOWER(?) WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.channel_type_code=1
GROUP BY cns.owner_login,cns.slug GROUP BY cns.owner_login,cns.slug
) )
UPDATE channel_read_state crs UPDATE channel_read_state crs
SET unread_count=GREATEST(0, counts.message_count-crs.read_count), SET unread_count=GREATEST(0, counts.message_count-crs.read_count),
read_count=LEAST(crs.read_count, counts.message_count),
read_signature=CASE WHEN crs.read_count>counts.message_count THEN '' ELSE crs.read_signature END,
updated_at_ms=? updated_at_ms=?
FROM counts FROM counts
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login) WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
@@ -1,104 +0,0 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.entities.SyncServerEntry;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* DAO локальной таблицы серверов-партнёров для будущей межсерверной синхронизации.
*/
public final class SyncServersDAO {
private static volatile SyncServersDAO instance;
private final DbController db = DbController.getInstance();
private SyncServersDAO() {}
public static SyncServersDAO getInstance() {
if (instance == null) {
synchronized (SyncServersDAO.class) {
if (instance == null) instance = new SyncServersDAO();
}
}
return instance;
}
public List<SyncServerEntry> listAll() throws SQLException {
try (Connection c = db.getConnection()) {
return listAll(c);
}
}
public List<SyncServerEntry> listAll(Connection c) throws SQLException {
String sql = """
SELECT login, server_address, updated_at_ms
FROM sync_servers
ORDER BY login
""";
List<SyncServerEntry> result = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(mapRow(rs));
}
}
return result;
}
/**
* Полностью заменяет список партнёров актуальным снимком из Solana PDA.
*/
public void replaceAll(List<SyncServerEntry> entries) throws SQLException {
try (Connection c = db.getConnection()) {
replaceAll(c, entries);
}
}
public void replaceAll(Connection c, List<SyncServerEntry> entries) throws SQLException {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try (Statement st = c.createStatement()) {
st.executeUpdate("DELETE FROM sync_servers");
String sql = """
INSERT INTO sync_servers (
login, server_address, updated_at_ms
) VALUES (?, ?, ?)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
for (SyncServerEntry entry : entries) {
ps.setString(1, entry.getLogin());
ps.setString(2, safe(entry.getServerAddress()));
ps.setLong(3, entry.getUpdatedAtMs());
ps.addBatch();
}
ps.executeBatch();
}
c.commit();
} catch (Exception e) {
try { c.rollback(); } catch (Exception ignored) {}
if (e instanceof SQLException sqlEx) throw sqlEx;
throw new SQLException("Не удалось обновить таблицу sync_servers", e);
} finally {
try { c.setAutoCommit(oldAutoCommit); } catch (Exception ignored) {}
}
}
private SyncServerEntry mapRow(ResultSet rs) throws SQLException {
SyncServerEntry entry = new SyncServerEntry();
entry.setLogin(rs.getString("login"));
entry.setServerAddress(rs.getString("server_address"));
entry.setUpdatedAtMs(rs.getLong("updated_at_ms"));
return entry;
}
private static String safe(String value) {
return value == null ? "" : value;
}
}
@@ -37,6 +37,8 @@ public final class UserParamsDAO {
// -------------------- UPSERT (IF NEWER) -------------------- // -------------------- UPSERT (IF NEWER) --------------------
public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException { public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException {
if ("gender".equalsIgnoreCase(e.getParam())) return 0;
if ("account_role".equalsIgnoreCase(e.getParam()) && hasDeclaredIdentity(c, e.getLogin())) return 0;
String sql = """ String sql = """
INSERT INTO users_params ( INSERT INTO users_params (
login, login,
@@ -108,9 +110,17 @@ public final class UserParamsDAO {
} }
} }
public static boolean hasDeclaredIdentity(Connection c, String login) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM account_identity_state WHERE login=LOWER(?)")) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) { return rs.next(); }
}
}
// -------------------- SELECT -------------------- // -------------------- SELECT --------------------
public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException { public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException {
if ("gender".equalsIgnoreCase(param)) return null;
String sql = """ String sql = """
SELECT SELECT
login, login,
@@ -151,7 +161,7 @@ public final class UserParamsDAO {
client_key, client_key,
signature signature
FROM users_params FROM users_params
WHERE LOWER(login) = LOWER(?) WHERE LOWER(login) = LOWER(?) AND LOWER(param) <> 'gender'
ORDER BY time_ms DESC ORDER BY time_ms DESC
"""; """;
@@ -61,10 +61,10 @@ public final class UserProfileStateDAO {
String where = switch (String.valueOf(listType)) { String where = switch (String.valueOf(listType)) {
case "friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(cs.login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)"; case "friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(cs.login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)";
case "close_friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=10"; case "close_friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=10";
case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)"; case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)"; case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)"; case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)"; case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
default -> throw new IllegalArgumentException("Unsupported listType: " + listType); default -> throw new IllegalArgumentException("Unsupported listType: " + listType);
}; };
boolean received = "primary_received".equals(listType) || "shine_received".equals(listType); boolean received = "primary_received".equals(listType) || "shine_received".equals(listType);
@@ -77,9 +77,9 @@ public final class UserProfileStateDAO {
COALESCE(up.ava_ar,'') AS ava_ar, COALESCE(up.ava_ar,'') AS ava_ar,
up.account_role, up.shine_status, up.account_role, up.shine_status,
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=80 EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=80
AND shine_is_primary(x.login) AND shine_target_accepts_primary_confirmation(x.to_login)) AS primary_confirmed, AND shine_can_confirm_primary(x.login,x.to_login)) AS primary_confirmed,
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=70 EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=70
AND shine_is_primary(x.login) AND shine_is_shining(x.login) AND shine_target_accepts_shine_confirmation(x.to_login)) AS shine_confirmed, AND shine_can_confirm_shine(x.login,x.to_login)) AS shine_confirmed,
CASE CASE
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=10) THEN 'close_friend' WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=10) THEN 'close_friend'
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=14) THEN 'friend' WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=14) THEN 'friend'
@@ -113,27 +113,39 @@ public final class UserProfileStateDAO {
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException { public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException {
int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset); int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset);
String virtualChannels = """
WITH public_channels AS (
SELECT owner_login, slug, display_name, ava_ar, ava_pr, owner_bch_name,
channel_root_block_number, channel_root_block_hash, is_deleted, deleted_at_ms, deleted_block_number
FROM channel_names_state WHERE channel_type_code=1
UNION ALL
SELECT u.login, 'stories', COALESCE(NULLIF(TRIM(CONCAT_WS(' ', p.first_name, p.last_name)), ''), u.login),
COALESCE(p.ava_ar,''), '', u.blockchain_name, 0, NULL::bytea, FALSE, 0::bigint, NULL::integer
FROM user_identity_current u LEFT JOIN user_profile_state p ON LOWER(p.login)=LOWER(u.login)
)
""";
String sql; String sql;
if ("owned".equals(mode)) { if ("owned".equals(mode)) {
sql=""" sql=virtualChannels+"""
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name, SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM channel_names_state cn FROM public_channels cn
WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted) WHERE LOWER(cn.owner_login)=LOWER(?) AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ? ORDER BY CASE WHEN cn.channel_root_block_number=0 THEN 0 ELSE 1 END, cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else if ("following".equals(mode)) { } else if ("following".equals(mode)) {
sql=""" sql=virtualChannels+"""
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name, SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM connections_state cs FROM public_channels cn
JOIN channel_names_state cn WHERE EXISTS (SELECT 1 FROM connections_state cs
ON LOWER(cn.owner_login)=LOWER(cs.to_login) WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30
AND cn.channel_root_block_number=cs.to_block_number AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cn.channel_root_block_hash=cs.to_block_hash AND cs.to_block_number=cn.channel_root_block_number
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30 AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted) AND (cn.channel_root_block_number=0 OR cs.to_block_hash=cn.channel_root_block_hash))
AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ? ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else throw new IllegalArgumentException("Unsupported channel mode: "+mode); } else throw new IllegalArgumentException("Unsupported channel mode: "+mode);
@@ -143,7 +155,7 @@ public final class UserProfileStateDAO {
try(ResultSet rs=ps.executeQuery()){ try(ResultSet rs=ps.executeQuery()){
while(rs.next()) out.add(new ChannelCard( while(rs.next()) out.add(new ChannelCard(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_pr"), rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_pr"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getString("root_hash"), rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getInt("channel_root_block_number") == 0 ? publicationsHash(c, rs.getString("owner_bch_name")) : rs.getString("root_hash"),
rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number") rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number")
)); ));
} }
@@ -151,6 +163,11 @@ public final class UserProfileStateDAO {
return out; return out;
} }
private static String publicationsHash(Connection c, String ownerBch) throws SQLException {
byte[] hash=CanonicalChainResolver.getInstance().getHash(c,ownerBch,0);
return java.util.HexFormat.of().formatHex(hash == null ? new byte[32] : hash);
}
private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));} private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));}
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){} public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){} public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
@@ -6,9 +6,9 @@ package shine.db.entities;
* Храним: * Храним:
* - login + fork_number (physical fork identity; bch_name is derived only for display/API) * - login + fork_number (physical fork identity; bch_name is derived only for display/API)
* - block_number (глобальный номер в этой цепочке) * - block_number (глобальный номер в этой цепочке)
* - block_bytes (полный блок: preimage + signature) * - block_bytes (контейнер двух оригинальных подписанных ANS-104)
* - block_hash (32 байта вычисленный SHA-256(preimage)) * - block_hash (32 байта вычисленный SHA-256(CORE payload))
* - block_signature (64 байта) * - block_signature (64 байта, подпись CORE)
* *
* Опционально: * Опционально:
* - line_code / prev_line_number / prev_line_hash / this_line_number * - line_code / prev_line_number / prev_line_hash / this_line_number
@@ -1,43 +0,0 @@
package shine.db.entities;
/**
* Запись о сервере-партнёре, с которым текущий сервер должен синхронизироваться.
*/
public class SyncServerEntry {
private String login;
private String serverAddress;
private long updatedAtMs;
public SyncServerEntry() {}
public SyncServerEntry(String login, String serverAddress, long updatedAtMs) {
this.login = login;
this.serverAddress = serverAddress;
this.updatedAtMs = updatedAtMs;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getServerAddress() {
return serverAddress;
}
public void setServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
}
public long getUpdatedAtMs() {
return updatedAtMs;
}
public void setUpdatedAtMs(long updatedAtMs) {
this.updatedAtMs = updatedAtMs;
}
}
@@ -0,0 +1,68 @@
-- v45: FREE_CERT — полноценная identity без фиктивной Solana PDA.
-- Обычные проекции и чтение blockchain выбирают ветку по user_identity_current;
-- Solana PDA остаётся источником только Solana-специфичных данных.
BEGIN;
CREATE OR REPLACE FUNCTION shine_identity_active_fork(p_login TEXT)
RETURNS INTEGER
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_fork INTEGER;
BEGIN
SELECT substring(blockchain_name FROM '([0-9]{3})$')::INTEGER
INTO v_fork
FROM user_identity_current
WHERE LOWER(login) = LOWER(BTRIM(p_login))
LIMIT 1;
IF v_fork BETWEEN 1 AND 999 THEN
RETURN v_fork;
END IF;
SELECT fork_number
INTO v_fork
FROM blockchain_state_store
WHERE LOWER(login) = LOWER(BTRIM(p_login))
ORDER BY updated_at_ms DESC, fork_number DESC
LIMIT 1;
RETURN COALESCE(v_fork, 1);
END $$;
CREATE OR REPLACE FUNCTION shine_active_fork(p_login TEXT, p_block_number INTEGER)
RETURNS INTEGER
LANGUAGE sql
STABLE
AS $$
SELECT shine_canonical_fork(p_login, shine_identity_active_fork(p_login), p_block_number)
$$;
CREATE OR REPLACE FUNCTION shine_channel_names_state_refresh_owner_stats()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
PERFORM shine_refresh_user_stats(OLD.owner_login);
RETURN OLD;
END IF;
PERFORM shine_refresh_user_stats(NEW.owner_login);
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS trg_channel_names_state_refresh_owner_stats ON channel_names_state;
CREATE TRIGGER trg_channel_names_state_refresh_owner_stats
AFTER INSERT OR UPDATE OF owner_login, channel_type_code, is_deleted OR DELETE
ON channel_names_state
FOR EACH ROW EXECUTE FUNCTION shine_channel_names_state_refresh_owner_stats();
-- Исправить уже записанные FREE_CERT и paid identity одним пересчётом.
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
UPDATE db_schema_version
SET schema_version = 45,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,77 @@
-- HEADER V3: производные данные хранятся рядом с физическим блоком #0.
-- V1/V2: NULL, прежняя логика профиля. Указанные аккаунты не меняют никакие голоса.
BEGIN;
ALTER TABLE blocks_store ADD COLUMN header_account_type SMALLINT;
ALTER TABLE blocks_store ADD COLUMN header_previous_accounts TEXT[];
ALTER TABLE blocks_store ADD CONSTRAINT chk_header_identity CHECK (
(header_account_type IS NULL AND header_previous_accounts IS NULL) OR
(block_number=0 AND msg_type=0 AND msg_sub_type=0
AND header_account_type IS NOT NULL AND header_account_type IN (0,1)
AND header_previous_accounts IS NOT NULL AND cardinality(header_previous_accounts)<=10
AND (header_account_type=1 OR cardinality(header_previous_accounts)=0)));
CREATE VIEW account_identity_state AS
SELECT LOWER(b.login) AS login, b.header_account_type AS account_type,
3 AS header_version, b.block_hash AS header_hash, b.header_previous_accounts AS previous_accounts
FROM blocks_store b
WHERE b.block_number=0 AND b.header_account_type IS NOT NULL
AND b.fork_number=shine_active_fork(b.login,0);
CREATE VIEW account_predecessors AS
SELECT i.login, p.previous_login
FROM account_identity_state i CROSS JOIN LATERAL unnest(i.previous_accounts) AS p(previous_login);
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'account_role'),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
v_account_role := COALESCE(
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login = LOWER(p_login)),
LOWER(BTRIM(COALESCE(v_account_role, ''))));
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
-- Вызывать после записи HEADER и при завершении восстановления канонической цепи.
CREATE OR REPLACE FUNCTION shine_refresh_header_identity(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
BEGIN
PERFORM shine_refresh_user_profile(p_login);
PERFORM shine_refresh_related_user_stats(p_login);
PERFORM shine_refresh_message_qualified_likes_for_actor(p_login);
END $$;
UPDATE db_schema_version SET schema_version=46,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,82 @@
-- Official = signed canonical HEADER V3 / account_type=1. Legacy USER_PARAM is not proof.
BEGIN;
CREATE OR REPLACE FUNCTION shine_is_primary(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT EXISTS (SELECT 1 FROM account_identity_state
WHERE login=LOWER(p_login) AND account_type=1)
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'account_role'),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
v_account_role := COALESCE(
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login = LOWER(p_login)),
CASE WHEN LOWER(BTRIM(COALESCE(v_account_role, ''))) = 'non_voting'
THEN 'non_voting' ELSE NULL END);
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
-- Remove obsolete legacy Primary projections, leaving the original signed history intact.
-- The shared predicate also serves social graph confirmations; refresh affected projections.
DO $$
DECLARE r RECORD;
BEGIN
FOR r IN
UPDATE user_profile_state ups SET account_role=NULL
WHERE ups.account_role='primary' AND NOT shine_is_primary(ups.login)
RETURNING login
LOOP
PERFORM shine_refresh_related_user_stats(r.login);
END LOOP;
END $$;
-- Recalculate both qualified counters, not the all-accounts count.
-- The aggregate returns zeros even if no qualifying reaction exists.
UPDATE message_stats ms SET (primary_likes_count, shining_likes_count) = (
SELECT COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login))::INTEGER,
COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))::INTEGER
FROM reactions_state rs
WHERE rs.reaction_type=1 AND rs.last_sub_type=1
AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number
AND rs.to_block_hash=ms.to_block_hash
);
UPDATE db_schema_version SET schema_version=47,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,109 @@
-- Только канонический HEADER V3 определяет Primary. История не меняется.
BEGIN;
CREATE OR REPLACE FUNCTION shine_target_accepts_primary_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT shine_is_primary(p_login)
$$;
CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT shine_is_primary(p_login) AND NOT EXISTS (
SELECT 1 FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) AND shine_status='not_interested')
$$;
CREATE OR REPLACE FUNCTION shine_can_confirm_primary(p_actor TEXT,p_target TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
AND shine_is_primary(p_actor) AND shine_target_accepts_primary_confirmation(p_target),FALSE)
$$;
CREATE OR REPLACE FUNCTION shine_can_confirm_shine(p_actor TEXT,p_target TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
AND shine_is_primary(p_actor) AND shine_is_shining(p_actor)
AND shine_target_accepts_shine_confirmation(p_target),FALSE)
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
INTO v_account_role FROM account_identity_state WHERE login = LOWER(p_login);
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
-- Архивная связь может прийти до регистрации цели в локальном каталоге.
-- Не создавать строку статистики без владельца FK, но сохранить подписанную связь.
SELECT i.login INTO p_login FROM user_identity_current i WHERE i.normalized_login=LOWER(p_login);
IF p_login IS NULL THEN RETURN; END IF;
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(p_login,cs.to_login)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(p_login,cs.to_login)),v_now
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
-- Обновить роль в существующих карточках; не переписывать исходные параметры/блоки.
UPDATE user_profile_state ups SET account_role = (
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login=LOWER(ups.login))
WHERE account_role IS DISTINCT FROM (
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login=LOWER(ups.login));
-- У аккаунтов с HEADER, но без параметров, также должна существовать карточка.
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT login FROM account_identity_state i
WHERE NOT EXISTS (SELECT 1 FROM user_profile_state p WHERE LOWER(p.login)=i.login)
LOOP PERFORM shine_refresh_user_profile(r.login); END LOOP;
-- Все старые участники подтверждений, в том числе с устаревшими ненулевыми счётчиками.
FOR r IN SELECT login FROM user_stats_state
UNION SELECT login FROM connections_state WHERE rel_type IN (70,80)
UNION SELECT to_login FROM connections_state WHERE rel_type IN (70,80)
LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP;
END $$;
UPDATE db_schema_version SET schema_version=48,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,13 @@
-- Only self-declared shining accounts may receive shine confirmations.
BEGIN;
CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT shine_is_shining(p_login) $$;
-- Existing signed relations stay intact; qualification is evaluated dynamically.
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT login FROM user_stats_state
UNION SELECT login FROM connections_state WHERE rel_type=70
UNION SELECT to_login FROM connections_state WHERE rel_type=70
LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP;
END $$;
UPDATE db_schema_version SET schema_version=49, updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -488,15 +488,6 @@ CREATE TABLE IF NOT EXISTS test_free_avatar_uploads (
CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated
ON test_free_avatar_uploads(updated_at_ms); ON test_free_avatar_uploads(updated_at_ms);
CREATE TABLE IF NOT EXISTS sync_servers (
login TEXT PRIMARY KEY,
server_address TEXT NOT NULL DEFAULT '',
updated_at_ms BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sync_servers_updated
ON sync_servers(updated_at_ms);
CREATE TABLE IF NOT EXISTS blockchain_state ( CREATE TABLE IF NOT EXISTS blockchain_state (
blockchain_name TEXT PRIMARY KEY, blockchain_name TEXT PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login), login TEXT NOT NULL REFERENCES solana_user_pda_current(login),
@@ -0,0 +1,36 @@
-- Запускать psql -v ON_ERROR_STOP=1 -f <этот файл> на отдельной тестовой БД после миграции 48.
-- Фикстуры временные; проверяются действующие SQL-функции, изменения откатываются.
BEGIN;
SET LOCAL search_path TO pg_temp, public;
CREATE TEMP TABLE account_identity_state(login TEXT PRIMARY KEY,account_type SMALLINT);
CREATE TEMP TABLE user_profile_state (LIKE public.user_profile_state INCLUDING ALL);
CREATE TEMP TABLE user_stats_state (LIKE public.user_stats_state INCLUDING ALL);
CREATE TEMP TABLE user_identity_current(login TEXT PRIMARY KEY,normalized_login TEXT UNIQUE);
CREATE TEMP TABLE users_params(login TEXT,param TEXT,value TEXT,time_ms BIGINT);
CREATE TEMP TABLE connections_state(login TEXT,rel_type INTEGER,to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA);
CREATE TEMP TABLE channel_names_state(owner_login TEXT,channel_type_code INTEGER,is_deleted BOOLEAN,channel_root_block_number INTEGER,channel_root_block_hash BYTEA);
INSERT INTO account_identity_state VALUES ('alice@free',1),('bob@free',1),('alt@free',0),('optout@free',1);
INSERT INTO user_identity_current SELECT login,lower(login) FROM account_identity_state;
INSERT INTO user_identity_current VALUES ('legacy@free','legacy@free');
INSERT INTO users_params VALUES ('alice@free','shine','shining',1),('alt@free','shine','shining',1),('legacy@free','account_role','primary',1),('optout@free','shine','not_interested',1);
SELECT shine_refresh_user_profile(login) FROM user_identity_current;
DO $$ BEGIN
IF NOT shine_can_confirm_primary('ALICE@FREE','bob@free') OR NOT shine_can_confirm_shine('alice@free','bob@free') THEN RAISE EXCEPTION 'Primary pair rejected'; END IF;
IF shine_can_confirm_primary('alice@free','alt@free') OR shine_can_confirm_primary('alt@free','alice@free') OR shine_can_confirm_primary('legacy@free','alice@free') OR shine_can_confirm_primary('alice@free','legacy@free') OR shine_can_confirm_primary('alice@free','missing@free') OR shine_can_confirm_primary('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid primary pair accepted'; END IF;
IF shine_can_confirm_shine('alice@free','alt@free') OR shine_can_confirm_shine('alt@free','alice@free') OR shine_can_confirm_shine('bob@free','alice@free') OR shine_can_confirm_shine('alice@free','optout@free') OR shine_can_confirm_shine('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid shine pair accepted'; END IF;
IF (SELECT account_role FROM user_profile_state WHERE login='legacy@free') IS NOT NULL THEN RAISE EXCEPTION 'Legacy role leaked into profile'; END IF;
END $$;
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES
('alice@free',80,'bob@free',0,'\x00'),('alice@free',70,'bob@free',0,'\x00'),
('alice@free',80,'alt@free',0,'\x00'),('alice@free',70,'alt@free',0,'\x00'),
('alt@free',80,'bob@free',0,'\x00'),('alt@free',70,'bob@free',0,'\x00'),
('legacy@free',80,'bob@free',0,'\x00'),('alice@free',80,'alice@free',0,'\x00');
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
SELECT shine_refresh_user_stats('missing@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='bob@free' AND primary_confirmations_received_count=1 AND shine_confirmations_received_count=1) THEN RAISE EXCEPTION 'Wrong Bob counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND primary_confirmations_given_count=1 AND shine_confirmations_given_count=1 AND primary_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Alice counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alt@free' AND primary_confirmations_received_count=0 AND primary_confirmations_given_count=0 AND shine_confirmations_received_count=0 AND shine_confirmations_given_count=0) THEN RAISE EXCEPTION 'Alternative counters not zero'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
ROLLBACK;
@@ -0,0 +1,61 @@
-- Запускать psql -v ON_ERROR_STOP=1 -f <этот файл> на отдельной тестовой БД после миграции 49.
-- Фикстуры временные; проверяются действующие SQL-функции, изменения откатываются.
BEGIN;
SET LOCAL search_path TO pg_temp, public;
CREATE TEMP TABLE account_identity_state(login TEXT PRIMARY KEY,account_type SMALLINT);
CREATE TEMP TABLE user_profile_state (LIKE public.user_profile_state INCLUDING ALL);
CREATE TEMP TABLE user_stats_state (LIKE public.user_stats_state INCLUDING ALL);
CREATE TEMP TABLE user_identity_current(login TEXT PRIMARY KEY,normalized_login TEXT UNIQUE);
CREATE TEMP TABLE users_params(login TEXT,param TEXT,value TEXT,time_ms BIGINT);
CREATE TEMP TABLE connections_state(login TEXT,rel_type INTEGER,to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA);
CREATE TEMP TABLE channel_names_state(owner_login TEXT,channel_type_code INTEGER,is_deleted BOOLEAN,channel_root_block_number INTEGER,channel_root_block_hash BYTEA);
INSERT INTO account_identity_state VALUES ('alice@free',1),('bob@free',1),('alt@free',0),('optout@free',1);
INSERT INTO user_identity_current SELECT login,lower(login) FROM account_identity_state;
INSERT INTO user_identity_current VALUES ('legacy@free','legacy@free');
INSERT INTO users_params VALUES ('alice@free','shine','shining',1),('alt@free','shine','shining',1),('legacy@free','account_role','primary',1),('optout@free','shine','not_interested',1);
SELECT shine_refresh_user_profile(login) FROM user_identity_current;
DO $$ BEGIN
IF NOT shine_can_confirm_primary('ALICE@FREE','bob@free') OR shine_can_confirm_shine('alice@free','bob@free') THEN RAISE EXCEPTION 'Primary pair rejected'; END IF;
IF shine_can_confirm_primary('alice@free','alt@free') OR shine_can_confirm_primary('alt@free','alice@free') OR shine_can_confirm_primary('legacy@free','alice@free') OR shine_can_confirm_primary('alice@free','legacy@free') OR shine_can_confirm_primary('alice@free','missing@free') OR shine_can_confirm_primary('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid primary pair accepted'; END IF;
IF NOT shine_can_confirm_shine('alice@free','alt@free') OR shine_can_confirm_shine('alt@free','alice@free') OR shine_can_confirm_shine('bob@free','alice@free') OR shine_can_confirm_shine('alice@free','optout@free') OR shine_can_confirm_shine('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid shine pair accepted'; END IF;
IF (SELECT account_role FROM user_profile_state WHERE login='legacy@free') IS NOT NULL THEN RAISE EXCEPTION 'Legacy role leaked into profile'; END IF;
END $$;
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES
('alice@free',80,'bob@free',0,'\x00'),('alice@free',70,'bob@free',0,'\x00'),
('alice@free',80,'alt@free',0,'\x00'),('alice@free',70,'alt@free',0,'\x00'),
('alt@free',80,'bob@free',0,'\x00'),('alt@free',70,'bob@free',0,'\x00'),
('legacy@free',80,'bob@free',0,'\x00'),('alice@free',80,'alice@free',0,'\x00');
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
SELECT shine_refresh_user_stats('missing@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='bob@free' AND primary_confirmations_received_count=1 AND shine_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Bob counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND primary_confirmations_given_count=1 AND shine_confirmations_given_count=1 AND primary_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Alice counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alt@free' AND primary_confirmations_received_count=0 AND primary_confirmations_given_count=0 AND shine_confirmations_received_count=1 AND shine_confirmations_given_count=0) THEN RAISE EXCEPTION 'Alternative counters incorrect'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
-- Existing declarations must become inactive when either end stops shining,
-- and become effective again without writing a new connection block.
UPDATE user_profile_state SET shine_status='shining' WHERE login='bob@free';
SELECT shine_refresh_related_user_stats('bob@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=2) THEN RAISE EXCEPTION 'Bob opt-in did not activate old relation'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='unknown' WHERE login='alice@free';
SELECT shine_refresh_related_user_stats('alice@free');
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM user_stats_state WHERE login IN ('bob@free','alt@free') AND shine_confirmations_received_count<>0) THEN RAISE EXCEPTION 'Actor opt-out failed'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='shining' WHERE login='alice@free';
SELECT shine_refresh_related_user_stats('alice@free');
UPDATE user_profile_state SET shine_status='unknown' WHERE login='alt@free';
SELECT shine_refresh_related_user_stats('alt@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=1) THEN RAISE EXCEPTION 'Target opt-out failed'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='shining' WHERE login='alt@free';
SELECT shine_refresh_related_user_stats('alt@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=2) THEN RAISE EXCEPTION 'Target opt-in failed'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
ROLLBACK;
@@ -158,7 +158,6 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_UpsertPushToken_Reque
// --- NEW: Ping --- // --- NEW: Ping ---
import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_GetCallIceConfig_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_GetCallIceConfig_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_GetSyncUserProfile_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientErrorLog_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ClientErrorLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_Handler;
@@ -170,7 +169,6 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientErrorLog
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetServerInfo_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetServerInfo_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchainHeads_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchainHeads_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
@@ -295,7 +293,6 @@ public final class JsonHandlerRegistry {
Map.entry("Ping", new Net_Ping_Handler()), Map.entry("Ping", new Net_Ping_Handler()),
Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()), Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()),
Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()), Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()),
Map.entry("GetSyncUserProfile", new Net_GetSyncUserProfile_Handler()),
Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()), Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()),
Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()), Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()),
Map.entry("ClientDebugLog", new Net_ClientDebugLog_Handler()), Map.entry("ClientDebugLog", new Net_ClientDebugLog_Handler()),
@@ -411,7 +408,6 @@ public final class JsonHandlerRegistry {
Map.entry("Ping", Net_Ping_Request.class), Map.entry("Ping", Net_Ping_Request.class),
Map.entry("GetServerInfo", Net_GetServerInfo_Request.class), Map.entry("GetServerInfo", Net_GetServerInfo_Request.class),
Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_Request.class), Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_Request.class),
Map.entry("GetSyncUserProfile", Net_GetSyncUserProfile_Request.class),
Map.entry("GetCallIceConfig", Net_GetCallIceConfig_Request.class), Map.entry("GetCallIceConfig", Net_GetCallIceConfig_Request.class),
Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class), Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class),
Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class), Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class),
@@ -3,7 +3,7 @@ package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier; import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.ShineProtocolTags; import blockchain.CoreContentContainer;
import blockchain.body.BodyHasLine; import blockchain.body.BodyHasLine;
import blockchain.body.BodyHasTarget; import blockchain.body.BodyHasTarget;
import blockchain.body.ConnectionBody; import blockchain.body.ConnectionBody;
@@ -25,6 +25,7 @@ import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks;
import server.sync.BlockchainResyncGuard; import server.sync.BlockchainResyncGuard;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainWriter; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainWriter;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.LineContinuity;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request; import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response; import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response;
import server.logic.ws_protocol.JSON.handlers.channels.ChannelMetaTextParser; import server.logic.ws_protocol.JSON.handlers.channels.ChannelMetaTextParser;
@@ -209,18 +210,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "limit_exceeded" -> "Превышен лимит размера блокчейна"; case "limit_exceeded" -> "Превышен лимит размера блокчейна";
case "limit_check_failed" -> "Ошибка проверки лимита размера"; case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "bad_block_format" -> "Некорректный формат блока"; case "bad_block_format" -> "Некорректный формат блока";
case "bad_app_tag" -> "Некорректный тестовый тег ANS-104";
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
case "bad_block_body" -> "Некорректное тело блока"; case "bad_block_body" -> "Некорректное тело блока";
case "header_v3_required" -> "Для нового блокчейна требуется HEADER V3 с типом аккаунта";
case "previous_account_not_found" -> "Указанный предыдущий аккаунт не найден";
case "primary_vote_not_allowed" -> "Подтверждать официальность могут только разные основные аккаунты";
case "shine_vote_not_allowed" -> "Подтверждать сияние может только сияющий основной аккаунт другого основного аккаунта, принимающего подтверждения";
case "account_type_immutable" -> "Тип аккаунта зафиксирован в HEADER и не может быть изменён";
case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации"; case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER"; case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
case "bad_channel_name" -> "Некорректное название канала"; case "bad_channel_name" -> "Некорректное название канала";
case "bad_block_number" -> "Некорректный номер блока"; case "bad_block_number" -> "Некорректный номер блока";
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке"; case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
case "bad_prev_hash" -> "Некорректный prevHash (цепочка не совпадает)"; case "bad_prev_hash" -> "Некорректный prevHash (цепочка не совпадает)";
case "bad_back32_hash" -> "Некорректный back32Hash (резервная ссылка N-32 не совпадает)";
case "db_error_back32_check" -> "Ошибка БД при проверке back32Hash";
case "bad_blockchain_key_len" -> "Некорректный ключ блокчейна в состоянии (ожидалось 32 байта)"; case "bad_blockchain_key_len" -> "Некорректный ключ блокчейна в состоянии (ожидалось 32 байта)";
case "signature_verify_failed" -> "Ошибка проверки подписи блока"; case "signature_verify_failed" -> "Ошибка проверки подписи блока";
case "bad_signature" -> "Некорректная подпись блока"; case "bad_signature" -> "Некорректная подпись блока";
@@ -230,7 +231,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "bad_line_state" -> "Повреждено состояние логической линии"; case "bad_line_state" -> "Повреждено состояние логической линии";
case "bad_prev_line_number" -> "Блок не продолжает текущий хвост логической линии"; case "bad_prev_line_number" -> "Блок не продолжает текущий хвост логической линии";
case "bad_prev_line_hash" -> "Некорректный prevLineHash"; case "bad_prev_line_hash" -> "Некорректный prevLineHash";
case "bad_line_sequence" -> "Некорректный порядковый номер логической линии";
case "unsupported_line_body" -> "Этот body не поддерживает логическую линию"; case "unsupported_line_body" -> "Этот body не поддерживает логическую линию";
case "db_error_prev_line_check", "db_error_line_check" -> "Ошибка БД при проверке логической линии"; case "db_error_prev_line_check", "db_error_line_check" -> "Ошибка БД при проверке логической линии";
case "channel_name_already_exists" -> "Такое название канала уже занято"; case "channel_name_already_exists" -> "Такое название канала уже занято";
@@ -364,27 +364,14 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// 4) parse block // 4) parse block
final BchBlockEntry block; final BchBlockEntry block;
try { try {
block = new BchBlockEntry(blockBytes); block = BchBlockEntry.fromCoreContent(blockBytes);
} catch (Exception e) { } catch (Exception e) {
log.warn("AddBlock: не удалось распарсить BchBlockEntry (login={}, blockchainName={}, bytesLen={})", log.warn("AddBlock: не удалось распарсить BchBlockEntry (login={}, blockchainName={}, bytesLen={})",
login, blockchainName, blockBytes.length, e); login, blockchainName, blockBytes.length, e);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_format", serverLastNum, serverLastHashHex); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_format", serverLastNum, serverLastHashHex);
} }
if (!block.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) { // Подписанные App/n/l и обе подписи уже проверены парсером пары.
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_app_tag", serverLastNum, serverLastHashHex);
}
// Signed secondary index for the fixed SHiNE streams.
String expectedTypeTag = expectedTypeTag(block);
String actualTypeTag = block.getDataItem().tagValue(ShineProtocolTags.TYPE_TAG_NAME);
if (expectedTypeTag != null) {
if (!expectedTypeTag.equals(actualTypeTag)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
}
} else if (actualTypeTag != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
}
// body.check() // body.check()
try { try {
@@ -403,6 +390,15 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки. // HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя. // Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
try { try {
// Исторические V1/V2 принимаются при импорте; новый прямой AddBlock требует V3.
if (publishToArweave && headerBody.version != HeaderBody.VER_IDENTITY)
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_v3_required", serverLastNum, serverLastHashHex);
if (publishToArweave) {
for (String previous : headerBody.previousAccounts) {
if (currentUsersDAO.getByLogin(previous) == null)
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "previous_account_not_found", serverLastNum, serverLastHashHex);
}
}
CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login); CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin()) if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) { || !login.equalsIgnoreCase(registeredOwner.getLogin())) {
@@ -448,12 +444,15 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
: ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName); : ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName);
} }
slug = ChannelNameRules.toCanonicalSlug(normalizedName); slug = ChannelNameRules.toCanonicalSlug(normalizedName);
if (!replayMode && "stories".equals(slug)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "reserved_channel_name", serverLastNum, serverLastHashHex);
}
} catch (IllegalArgumentException badName) { } catch (IllegalArgumentException badName) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_name", serverLastNum, serverLastHashHex); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_name", serverLastNum, serverLastHashHex);
} }
try { try {
if (channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) { if (!replayMode && channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex); return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
} }
} catch (Exception e) { } catch (Exception e) {
@@ -537,20 +536,10 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
channelMetaUpdateEntry.setMetaUpdatedAtMs(block.timestamp * 1000L); channelMetaUpdateEntry.setMetaUpdatedAtMs(block.timestamp * 1000L);
} }
// Channel DataItems are indexed by a signed canonical channel slug tag: c=<slug>. if ((block.type & 0xFFFF) == 1
try { && (block.subType & 0xFFFF) == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)
String expectedChannelSlug = expectedChannelSlug(blockchainName, block, channelNameStateEntry); && block.body instanceof TextLineBody deleteBody && deleteBody.lineCode() == 0 && !replayMode) {
String actualChannelSlug = block.getDataItem().tagValue(ShineProtocolTags.CHANNEL_TAG_NAME); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "cannot_delete_publications", serverLastNum, serverLastHashHex);
if (expectedChannelSlug != null) {
if (!expectedChannelSlug.equals(actualChannelSlug)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_tag", serverLastNum, serverLastHashHex);
}
} else if (actualChannelSlug != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_tag", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.warn("AddBlock: cannot validate channel tag blockchainName={} block={}", blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_tag", serverLastNum, serverLastHashHex);
} }
if ((block.type & 0xFFFF) == 1 if ((block.type & 0xFFFF) == 1
@@ -616,29 +605,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_prev_hash", serverLastNum, serverLastHashHex); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_prev_hash", serverLastNum, serverLastHashHex);
} }
// 4.4) резервная глобальная ссылка: N<32 -> ZERO32, иначе hash блока N-32.
try {
byte[] expectedBack32 = new byte[32];
if (block.blockNumber >= 32) {
byte[] storedBack32 = canonicalChain.getHash(blockchainName, block.blockNumber - 32);
if (storedBack32 == null || storedBack32.length != 32) {
log.error("AddBlock: missing N-32 block for back32 validation (blockchainName={}, blockNumber={}, target={})",
blockchainName, block.blockNumber, block.blockNumber - 32);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_back32_check", serverLastNum, serverLastHashHex);
}
expectedBack32 = storedBack32;
}
if (!Arrays.equals(block.back32Hash32, expectedBack32)) {
log.warn("AddBlock: bad_back32_hash (login={}, blockchainName={}, blockNumber={}, clientBack32={}, expectedBack32={})",
login, blockchainName, block.blockNumber, toHex(block.back32Hash32), toHex(expectedBack32));
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_back32_hash", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: db_error_back32_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_back32_check", serverLastNum, serverLastHashHex);
}
// 5) pubKey // 5) pubKey
final byte[] pubKey32 = st.getBlockchainKeyBytes(); final byte[] pubKey32 = st.getBlockchainKeyBytes();
if (pubKey32 == null || pubKey32.length != 32) { if (pubKey32 == null || pubKey32.length != 32) {
@@ -678,15 +644,16 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
lineCode = bl.lineCode(); lineCode = bl.lineCode();
prevLineNumber = bl.prevLineBlockGlobalNumber(); prevLineNumber = bl.prevLineBlockGlobalNumber();
prevLineHash32 = bl.prevLineBlockHash32(); prevLineHash32 = bl.prevLineBlockHash32();
thisLineNumber = bl.lineSeq();
try { try {
String lineError = validateLineContinuity(blockchainName, block, bl); LineContinuity.Result lineResult = validateLineContinuity(blockchainName, block, bl);
String lineError = lineResult.error();
if (lineError != null) { if (lineError != null) {
log.warn("AddBlock: {} (login={}, blockchainName={}, blockNumber={}, lineCode={}, prevLineNumber={}, lineSeq={})", log.warn("AddBlock: {} (login={}, blockchainName={}, blockNumber={}, lineCode={}, prevLineNumber={}, lineSeq={})",
lineError, login, blockchainName, block.blockNumber, lineCode, prevLineNumber, thisLineNumber); lineError, login, blockchainName, block.blockNumber, lineCode, prevLineNumber, bl.lineSeq());
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, lineError, serverLastNum, serverLastHashHex); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, lineError, serverLastNum, serverLastHashHex);
} }
thisLineNumber = lineResult.sequence();
} catch (Exception e) { } catch (Exception e) {
log.error("AddBlock: db_error_line_check (login={}, blockchainName={}, blockNumber={})", log.error("AddBlock: db_error_line_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e); login, blockchainName, block.blockNumber, e);
@@ -748,7 +715,9 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
be.setEditedByBlockNumber(be.getToBlockNumber()); be.setEditedByBlockNumber(be.getToBlockNumber());
} }
if (block.body instanceof ConnectionBody connectionBody) { // Архивные блоки уже подписаны; их допустимость для текущего рейтинга
// определяет проекция, а не порядок восстановления разных пользователей.
if (publishToArweave && block.body instanceof ConnectionBody connectionBody) {
String votingError = validateConnectionVotingRights(login, block.subType & 0xFFFF, connectionBody.toLogin()); String votingError = validateConnectionVotingRights(login, block.subType & 0xFFFF, connectionBody.toLogin());
if (votingError != null) { if (votingError != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, votingError, serverLastNum, serverLastHashHex); return new AddBlockResult(WireCodes.Status.BAD_REQUEST, votingError, serverLastNum, serverLastHashHex);
@@ -757,10 +726,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
UserParamEntry upsertedParam = null; UserParamEntry upsertedParam = null;
if (block.body instanceof UserParamBody upBody) { if (block.body instanceof UserParamBody upBody) {
if (publishToArweave && ("account_role".equalsIgnoreCase(upBody.paramKey.strip())
|| "official".equalsIgnoreCase(upBody.paramKey.strip()))) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "account_type_immutable", serverLastNum, serverLastHashHex);
}
if (publishToArweave && "gender".equalsIgnoreCase(upBody.paramKey.strip())) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "gender_disabled", serverLastNum, serverLastHashHex);
}
String effectiveLogin = (st.getLogin() != null && !st.getLogin().isBlank()) String effectiveLogin = (st.getLogin() != null && !st.getLogin().isBlank())
? st.getLogin() ? st.getLogin()
: login; : login;
upsertedParam = new UserParamEntry( if (!"gender".equalsIgnoreCase(upBody.paramKey.strip())) upsertedParam = new UserParamEntry(
effectiveLogin, effectiveLogin,
upBody.paramKey, upBody.paramKey,
block.timestamp * 1000L, block.timestamp * 1000L,
@@ -821,29 +797,34 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
} }
private ArweaveImportResult addBlockFromStoredBytes(String blockchainName, byte[] rawBlockBytes, boolean replayMode) { private ArweaveImportResult addBlockFromStoredBytes(String blockchainName, byte[] rawBlockBytes, boolean replayMode) {
if (BlockchainNameUtil.forkNumberFromBlockchainName(blockchainName) == null)
return new ArweaveImportResult(false, "bad_blockchain_name", -1, "");
if (!replayMode && BlockchainResyncGuard.isBlockedForExternalAddBlock(blockchainName)) { if (!replayMode && BlockchainResyncGuard.isBlockedForExternalAddBlock(blockchainName)) {
return new ArweaveImportResult(false, "chain_resync_in_progress", -1, ""); return new ArweaveImportResult(false, "chain_resync_in_progress", -1, "");
} }
if (rawBlockBytes == null || rawBlockBytes.length == 0) { if (rawBlockBytes == null || rawBlockBytes.length == 0) {
return new ArweaveImportResult(false, "empty_block", -1, ""); return new ArweaveImportResult(false, "empty_block", -1, "");
} }
try {
BchBlockEntry probe = new BchBlockEntry(rawBlockBytes);
if (blocksDAO.existsByDataItemId(probe.getDataItemId32())) {
return new ArweaveImportResult(true, "already_present", probe.blockNumber, toHex(probe.getHash32()));
}
} catch (Exception ignored) {
// Parsed again below to return the canonical bad_block_format result.
}
final BchBlockEntry parsed; final BchBlockEntry parsed;
try { try {
parsed = new BchBlockEntry(rawBlockBytes); parsed = BchBlockEntry.fromCoreContent(rawBlockBytes);
} catch (Exception e) { } catch (Exception e) {
return new ArweaveImportResult(false, "bad_block_format", -1, ""); return new ArweaveImportResult(false, "bad_block_format", -1, "");
} }
ReentrantLock lock = BlockchainLocks.lockFor(blockchainName); ReentrantLock lock = BlockchainLocks.lockFor(blockchainName);
lock.lock(); lock.lock();
try { try {
// Повтор импорта должен относиться именно к выбранной канонической цепочке.
// Наличие того же ID в произвольной ветке не означает успешный импорт сюда.
try {
BlockEntry existing = canonicalChain.getBlock(blockchainName, parsed.blockNumber);
if (existing != null && Arrays.equals(existing.getDataItemId(), parsed.getDataItemId32())
&& Arrays.equals(existing.getBlockBytes(), rawBlockBytes)) {
return new ArweaveImportResult(true, "already_present", parsed.blockNumber, toHex(parsed.getHash32()));
}
} catch (SQLException e) {
return new ArweaveImportResult(false, "db_error", -1, "");
}
AddBlockResult r = addBlock( AddBlockResult r = addBlock(
blockchainName, blockchainName,
parsed.blockNumber, parsed.blockNumber,
@@ -865,56 +846,46 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
/* ====================== Helpers ====================================== */ /* ====================== Helpers ====================================== */
/* ===================================================================== */ /* ===================================================================== */
private static String expectedTypeTag(BchBlockEntry block) {
int type = block.type & 0xffff;
return switch (type) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
/** /**
* Проверяет не просто существование prev-блока, а именно продолжение текущего хвоста линии. * Проверяет не просто существование prev-блока, а именно продолжение текущего хвоста линии.
* Это запрещает боковые ветки линии и гарантирует монотонный sequence. * Это запрещает боковые ветки линии и гарантирует монотонный sequence.
*/ */
private String validateLineContinuity(String blockchainName, BchBlockEntry block, BodyHasLine line) throws Exception { private LineContinuity.Result validateLineContinuity(String blockchainName, BchBlockEntry block, BodyHasLine line) throws Exception {
int type = block.type & 0xffff; int type = block.type & 0xffff;
int lineCode = line.lineCode(); int lineCode = line.lineCode();
int rootBlockNumber; int rootBlockNumber;
int firstSequence; int firstSequence;
if (block.body instanceof UserParamBody || block.body instanceof ConnectionBody) { if (block.body instanceof UserParamBody || block.body instanceof ConnectionBody) {
if (lineCode != 0) return "bad_line_code"; if (lineCode != 0) return LineContinuity.Result.rejected("bad_line_code");
rootBlockNumber = 0; rootBlockNumber = 0;
firstSequence = 1; firstSequence = 1;
} else if (block.body instanceof CreateChannelBody || block.body instanceof ForkBody) { } else if (block.body instanceof CreateChannelBody || block.body instanceof ForkBody) {
if (lineCode != 0) return "bad_line_code"; if (lineCode != 0) return LineContinuity.Result.rejected("bad_line_code");
rootBlockNumber = 0; rootBlockNumber = 0;
firstSequence = 1; firstSequence = 1;
} else if (block.body instanceof TextLineBody) { } else if (block.body instanceof TextLineBody) {
if (lineCode < 0) return "bad_line_code"; if (lineCode < 0) return LineContinuity.Result.rejected("bad_line_code");
rootBlockNumber = lineCode; rootBlockNumber = lineCode;
// Channel sequence is zero-based after its root anchor. // Channel sequence is zero-based after its root anchor.
firstSequence = 0; firstSequence = 0;
} else { } else {
return "unsupported_line_body"; return LineContinuity.Result.rejected("unsupported_line_body");
} }
BlockEntry root = canonicalChain.getBlock(blockchainName, rootBlockNumber); BlockEntry root = canonicalChain.getBlock(blockchainName, rootBlockNumber);
if (root == null) return "line_root_not_found"; if (root == null) return LineContinuity.Result.rejected("line_root_not_found");
if (rootBlockNumber == 0) { if (rootBlockNumber == 0) {
try { try {
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof HeaderBody)) return "bad_line_root"; if (!(BchBlockEntry.fromCoreContent(root.getBlockBytes()).body instanceof HeaderBody)) return LineContinuity.Result.rejected("bad_line_root");
} catch (Exception e) { } catch (Exception e) {
return "bad_line_root"; return LineContinuity.Result.rejected("bad_line_root");
} }
} else { } else {
try { try {
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof CreateChannelBody)) return "bad_line_root"; if (!(BchBlockEntry.fromCoreContent(root.getBlockBytes()).body instanceof CreateChannelBody)) return LineContinuity.Result.rejected("bad_line_root");
} catch (Exception e) { } catch (Exception e) {
return "bad_line_root"; return LineContinuity.Result.rejected("bad_line_root");
} }
} }
@@ -922,64 +893,23 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
try (Connection resolverConnection = shine.db.DbController.getInstance().getConnection()) { try (Connection resolverConnection = shine.db.DbController.getInstance().getConnection()) {
tail = canonicalChain.getLastLineBlock(resolverConnection, blockchainName, type, lineCode, block.blockNumber); tail = canonicalChain.getLastLineBlock(resolverConnection, blockchainName, type, lineCode, block.blockNumber);
} }
int expectedPrevNumber; return LineContinuity.resolve(line, rootBlockNumber, firstSequence, root, tail);
byte[] expectedPrevHash;
int expectedSequence;
if (tail == null) {
expectedPrevNumber = rootBlockNumber;
expectedPrevHash = root.getBlockHash();
expectedSequence = firstSequence;
} else {
if (tail.getThisLineNumber() == null) return "bad_line_state";
expectedPrevNumber = tail.getBlockNumber();
expectedPrevHash = tail.getBlockHash();
expectedSequence = Math.addExact(tail.getThisLineNumber(), 1);
}
if (line.prevLineBlockGlobalNumber() != expectedPrevNumber) return "bad_prev_line_number";
byte[] suppliedPrevHash = require32OrThrow(line.prevLineBlockHash32(), "prevLineHash32 invalid");
if (!Arrays.equals(expectedPrevHash, suppliedPrevHash)) return "bad_prev_line_hash";
if (line.lineSeq() != expectedSequence) return "bad_line_sequence";
return null;
}
private String expectedChannelSlug(String blockchainName, BchBlockEntry block, ChannelNameStateEntry justCreated) throws Exception {
if (block.body instanceof CreateChannelBody) {
return justCreated == null ? null : justCreated.getSlug();
}
int type = block.type & 0xffff;
int sub = block.subType & 0xffff;
boolean channelBlock = type == 1 && (
sub == (MsgSubType.TEXT_POST & 0xffff)
|| sub == (MsgSubType.TEXT_REPOST & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_META & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_DELETE & 0xffff)
|| sub == (MsgSubType.TEXT_ENTRYPOINT & 0xffff)
|| sub == (MsgSubType.TEXT_EXERCISE & 0xffff)
|| sub == (MsgSubType.TEXT_SERVICE & 0xffff)
|| sub == (MsgSubType.TEXT_COURSE & 0xffff)
|| sub == (MsgSubType.TEXT_EDIT_POST & 0xffff));
if (!channelBlock || !(block.body instanceof BodyHasLine line) || line.lineCode() <= 0) return null;
return channelNameStateDAO.getSlugByOwnerAndRoot(blockchainName, line.lineCode());
} }
private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) { private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) {
if (subType != (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) if (subType != (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
&& subType != (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)) return null; && subType != (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)) return null;
if (targetLogin == null || targetLogin.isBlank()) return "bad_connection_target"; if (targetLogin == null || targetLogin.isBlank() || targetLogin.equalsIgnoreCase(actorLogin))
String sql = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) return "bad_connection_target";
? "SELECT shine_is_primary(?), shine_target_accepts_primary_confirmation(?)" boolean primary = subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF);
: "SELECT (shine_is_primary(?) AND shine_is_shining(?)), shine_target_accepts_shine_confirmation(?)"; String sql = primary
? "SELECT shine_can_confirm_primary(?,?)"
: "SELECT shine_can_confirm_shine(?,?)";
try (Connection c = shine.db.DbController.getInstance().getConnection(); try (Connection c = shine.db.DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(sql)) { PreparedStatement ps = c.prepareStatement(sql)) {
if (subType == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)) {
ps.setString(1, actorLogin); ps.setString(2, targetLogin); ps.setString(1, actorLogin); ps.setString(2, targetLogin);
} else {
ps.setString(1, actorLogin); ps.setString(2, actorLogin); ps.setString(3, targetLogin);
}
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (!rs.next() || !rs.getBoolean(1)) return subType == 80 ? "primary_vote_not_allowed" : "shine_vote_not_allowed"; if (!rs.next() || !rs.getBoolean(1)) return primary ? "primary_vote_not_allowed" : "shine_vote_not_allowed";
if (!rs.getBoolean(2)) return subType == 80 ? "target_non_voting" : "target_shine_not_interested";
} }
return null; return null;
} catch (Exception e) { } catch (Exception e) {
@@ -990,7 +920,13 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static byte[] decodeBase64(String b64) { private static byte[] decodeBase64(String b64) {
if (b64 == null) throw new IllegalArgumentException("blockBytesB64 == null"); if (b64 == null) throw new IllegalArgumentException("blockBytesB64 == null");
return Base64Ws.decode(b64); String value = b64.trim();
long maxEncoded = 4L * ((CoreContentContainer.MAX_CONTAINER_BYTES + 2L) / 3L);
if (value.length() > maxEncoded) throw new IllegalArgumentException("blockBytesB64 too large");
byte[] decoded = Base64Ws.decode(value);
if (decoded.length > CoreContentContainer.MAX_CONTAINER_BYTES)
throw new IllegalArgumentException("CORE/CONTENT container too large");
return decoded;
} }
private static boolean isChannelSlugConflict(Throwable throwable) { private static boolean isChannelSlugConflict(Throwable throwable) {
@@ -1,6 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils; package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.body.HeaderBody;
import shine.db.dao.BlockchainStateDAO; import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO; import shine.db.dao.BlocksDAO;
import shine.db.dao.ChannelNameStateDAO; import shine.db.dao.ChannelNameStateDAO;
@@ -21,7 +22,7 @@ import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
/** Stores the complete ANS-104 DataItem and all derived SHiNE state atomically in PostgreSQL. /** Stores the complete CORE/CONTENT container and all derived SHiNE state atomically in PostgreSQL.
* Local .bch/tmp/marker files are intentionally not used. * Local .bch/tmp/marker files are intentionally not used.
*/ */
public final class BlockchainWriter { public final class BlockchainWriter {
@@ -47,7 +48,7 @@ public final class BlockchainWriter {
} }
/** /**
* Stores the complete ANS-104 DataItem and all SQL projections in one DB transaction. * Stores the complete CORE/CONTENT container and all SQL projections in one DB transaction.
* There is intentionally no .bch/tmp/marker file layer anymore. * There is intentionally no .bch/tmp/marker file layer anymore.
*/ */
public List<String> appendBlockAndState(String blockchainName, public List<String> appendBlockAndState(String blockchainName,
@@ -61,7 +62,7 @@ public final class BlockchainWriter {
boolean replayMode) throws SQLException { boolean replayMode) throws SQLException {
long nowMs = System.currentTimeMillis(); long nowMs = System.currentTimeMillis();
byte[] rawDataItem = block.toBytes(); byte[] rawBlock = block.toBytes();
Set<String> counterChangedLogins = new LinkedHashSet<>(); Set<String> counterChangedLogins = new LinkedHashSet<>();
try (Connection c = shine.db.DbController.getInstance().getConnection()) { try (Connection c = shine.db.DbController.getInstance().getConnection()) {
c.setAutoCommit(false); c.setAutoCommit(false);
@@ -72,14 +73,24 @@ public final class BlockchainWriter {
// самый первый HEADER ранее импортированной цепочки. // самый первый HEADER ранее импортированной цепочки.
st.setLastBlockNumber(block.blockNumber); st.setLastBlockNumber(block.blockNumber);
st.setLastBlockHash(block.getHash32()); st.setLastBlockHash(block.getHash32());
st.setFileSizeBytes(st.getFileSizeBytes() + rawDataItem.length); st.setFileSizeBytes(st.getFileSizeBytes() + rawBlock.length);
st.setUpdatedAtMs(nowMs); st.setUpdatedAtMs(nowMs);
stateDAO.upsert(c, st); stateDAO.upsert(c, st);
if (block.body instanceof HeaderBody header && header.accountType != null) {
blocksDAO.insert(c, be, header.accountType, header.previousAccounts);
try (var ps = c.prepareStatement("SELECT shine_refresh_header_identity(?)")) {
ps.setString(1, be.getLogin()); ps.execute();
}
} else {
blocksDAO.insert(c, be); blocksDAO.insert(c, be);
}
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry); if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
if (channelNameStateEntry != null) channelNameStateDAO.insert(c, channelNameStateEntry); if (channelNameStateEntry != null) {
if (replayMode) channelNameStateDAO.insertOrReplaceWithNewerRoot(c, channelNameStateEntry);
else channelNameStateDAO.insert(c, channelNameStateEntry);
}
if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry); if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry);
if (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry); if (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry);
@@ -97,7 +108,7 @@ public final class BlockchainWriter {
} }
if (channelVisibilityChanged) counterChangedLogins.addAll(refreshChannelVisibilityStats(c, blockchainName, lineCode)); if (channelVisibilityChanged) counterChangedLogins.addAll(refreshChannelVisibilityStats(c, blockchainName, lineCode));
} }
if (!replayMode && isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode > 0) { if (!replayMode && isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode >= 0) {
String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode); String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode);
if (channelName != null && !channelName.isBlank()) { if (channelName != null && !channelName.isBlank()) {
counterChangedLogins.addAll(channelReadStateDAO.incrementUnreadForSubscribers( counterChangedLogins.addAll(channelReadStateDAO.incrementUnreadForSubscribers(
@@ -108,7 +119,7 @@ public final class BlockchainWriter {
if (!replayMode && msgType == 3 if (!replayMode && msgType == 3
&& msgSubType == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF) && msgSubType == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
&& be.getToBchName() != null && !be.getToBchName().isBlank() && be.getToBchName() != null && !be.getToBchName().isBlank()
&& be.getToBlockNumber() != null && be.getToBlockNumber() > 0) { && be.getToBlockNumber() != null && be.getToBlockNumber() >= 0) {
if (channelReadStateDAO.deleteForUnfollowTarget( if (channelReadStateDAO.deleteForUnfollowTarget(
c, be.getLogin(), be.getToBchName(), be.getToBlockNumber())) { c, be.getLogin(), be.getToBchName(), be.getToBlockNumber())) {
counterChangedLogins.add(be.getLogin()); counterChangedLogins.add(be.getLogin());
@@ -0,0 +1,28 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils;
import blockchain.body.BodyHasLine;
import shine.db.entities.BlockEntry;
import java.util.Arrays;
/** Вычисляет прежний SQL ordinal из уже найденного канонического хвоста. */
public final class LineContinuity {
private LineContinuity() {}
public record Result(String error, Integer sequence) {
public static Result rejected(String error) { return new Result(error, null); }
}
public static Result resolve(BodyHasLine line, int rootNumber, int firstSequence,
BlockEntry root, BlockEntry tail) {
if (root == null) return Result.rejected("line_root_not_found");
if (tail != null && (tail.getThisLineNumber() == null || tail.getThisLineNumber() < firstSequence
|| tail.getThisLineNumber() == Integer.MAX_VALUE)) return Result.rejected("bad_line_state");
int expectedNumber = tail == null ? rootNumber : tail.getBlockNumber();
byte[] expectedHash = (tail == null ? root : tail).getBlockHash();
int sequence = tail == null ? firstSequence : tail.getThisLineNumber() + 1;
if (expectedHash == null || expectedHash.length != 32) return Result.rejected("bad_line_state");
if (line.prevLineBlockGlobalNumber() != expectedNumber) return Result.rejected("bad_prev_line_number");
if (!Arrays.equals(expectedHash, line.prevLineBlockHash32())) return Result.rejected("bad_prev_line_hash");
return new Result(null, sequence);
}
}
@@ -62,7 +62,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
} }
List<Net_GetMyBlockchain_Response.BlockItem> items = new ArrayList<>(rows.size()); List<Net_GetMyBlockchain_Response.BlockItem> items = new ArrayList<>(rows.size());
for (BlockEntry row : rows) { for (BlockEntry row : rows) {
BchBlockEntry parsed = new BchBlockEntry(row.getBlockBytes()); BchBlockEntry parsed = BchBlockEntry.fromCoreContent(row.getBlockBytes());
Net_GetMyBlockchain_Response.BlockItem item = new Net_GetMyBlockchain_Response.BlockItem(); Net_GetMyBlockchain_Response.BlockItem item = new Net_GetMyBlockchain_Response.BlockItem();
item.setBlockNumber(row.getBlockNumber()); item.setBlockNumber(row.getBlockNumber());
item.setBlockHash(hex(row.getBlockHash())); item.setBlockHash(hex(row.getBlockHash()));
@@ -71,6 +71,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
item.setMsgType(Short.toUnsignedInt(parsed.type)); item.setMsgType(Short.toUnsignedInt(parsed.type));
item.setMsgSubType(Short.toUnsignedInt(parsed.subType)); item.setMsgSubType(Short.toUnsignedInt(parsed.subType));
item.setMsgVersion(Short.toUnsignedInt(parsed.version)); item.setMsgVersion(Short.toUnsignedInt(parsed.version));
item.setThisLineNumber(row.getThisLineNumber());
if (parsed.body instanceof BodyHasTarget target) { if (parsed.body instanceof BodyHasTarget target) {
item.setToLogin(target.toLogin()); item.setToLogin(target.toLogin());
item.setToForkNumber(target.toForkNumber()); item.setToForkNumber(target.toForkNumber());
@@ -7,7 +7,7 @@ public final class Net_AddBlock_Request extends Net_Request {
private String blockchainName; // обязателен private String blockchainName; // обязателен
private int blockNumber; // обязателен private int blockNumber; // обязателен
private String prevBlockHash; // HEX(64) или "" для нулевого private String prevBlockHash; // HEX(64) или "" для нулевого
private String blockBytesB64; // байты FULL-блока (raw+sig+hash) в Base64 private String blockBytesB64; // контейнер двух подписанных DataItem в Base64
public String getBlockchainName() { return blockchainName; } public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; } public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
@@ -38,6 +38,7 @@ public final class Net_GetMyBlockchain_Response extends Net_Response {
private Integer toBlockNumber; private Integer toBlockNumber;
private String toBlockHash; private String toBlockHash;
private String blockBytesB64; private String blockBytesB64;
private Integer thisLineNumber;
public int getBlockNumber() { return blockNumber; } public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; } public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
@@ -61,6 +62,8 @@ public final class Net_GetMyBlockchain_Response extends Net_Response {
public void setToBlockNumber(Integer toBlockNumber) { this.toBlockNumber = toBlockNumber; } public void setToBlockNumber(Integer toBlockNumber) { this.toBlockNumber = toBlockNumber; }
public String getToBlockHash() { return toBlockHash; } public String getToBlockHash() { return toBlockHash; }
public void setToBlockHash(String toBlockHash) { this.toBlockHash = toBlockHash; } public void setToBlockHash(String toBlockHash) { this.toBlockHash = toBlockHash; }
public Integer getThisLineNumber() { return thisLineNumber; }
public void setThisLineNumber(Integer value) { thisLineNumber = value; }
public String getBlockBytesB64() { return blockBytesB64; } public String getBlockBytesB64() { return blockBytesB64; }
public void setBlockBytesB64(String blockBytesB64) { this.blockBytesB64 = blockBytesB64; } public void setBlockBytesB64(String blockBytesB64) { this.blockBytesB64 = blockBytesB64; }
} }
@@ -41,7 +41,8 @@ public final class ChannelNamesStateBootstrapper {
private static void rebuildFromBlocksOrThrow() { private static void rebuildFromBlocksOrThrow() {
ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance(); ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance();
List<ChannelNameStateEntry> entries = new ArrayList<>(); List<ChannelNameStateEntry> entries = new ArrayList<>();
Map<String, String> slugToIdentity = new LinkedHashMap<>(); Map<String, ChannelNameStateEntry> entriesByOwnerTypeSlug = new LinkedHashMap<>();
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots = new LinkedHashMap<>();
List<String> conflicts = new ArrayList<>(); List<String> conflicts = new ArrayList<>();
List<String> skipped = new ArrayList<>(); List<String> skipped = new ArrayList<>();
@@ -49,14 +50,7 @@ public final class ChannelNamesStateBootstrapper {
SELECT login, bch_name, block_number, block_hash, block_bytes SELECT login, bch_name, block_number, block_hash, block_bytes
FROM blocks FROM blocks
WHERE msg_type = ? AND msg_sub_type = ? WHERE msg_type = ? AND msg_sub_type = ?
AND fork_number=shine_canonical_fork( AND fork_number=shine_active_fork(login, block_number)
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number ORDER BY LOWER(login), block_number
"""; """;
@@ -78,7 +72,7 @@ public final class ChannelNamesStateBootstrapper {
final BchBlockEntry parsed; final BchBlockEntry parsed;
final CreateChannelBody createChannelBody; final CreateChannelBody createChannelBody;
try { try {
parsed = new BchBlockEntry(blockBytes); parsed = BchBlockEntry.fromCoreContent(blockBytes);
if (!(parsed.body instanceof CreateChannelBody ccb)) continue; if (!(parsed.body instanceof CreateChannelBody ccb)) continue;
createChannelBody = ccb; createChannelBody = ccb;
} catch (Exception parseError) { } catch (Exception parseError) {
@@ -115,14 +109,6 @@ public final class ChannelNamesStateBootstrapper {
continue; continue;
} }
String identity = ownerBch + "#" + blockNumber;
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
String existing = slugToIdentity.putIfAbsent(ownerTypeSlug, identity);
if (existing != null && !existing.equals(identity)) {
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: " + existing + " vs " + identity);
continue;
}
ChannelNameStateEntry entry = new ChannelNameStateEntry(); ChannelNameStateEntry entry = new ChannelNameStateEntry();
entry.setSlug(slug); entry.setSlug(slug);
entry.setDisplayName(displayName); entry.setDisplayName(displayName);
@@ -138,18 +124,28 @@ public final class ChannelNamesStateBootstrapper {
entry.setChannelRootBlockNumber(blockNumber); entry.setChannelRootBlockNumber(blockNumber);
entry.setChannelRootBlockHash(blockHash); entry.setChannelRootBlockHash(blockHash);
entry.setCreatedAtMs(parsed.timestamp * 1000L); entry.setCreatedAtMs(parsed.timestamp * 1000L);
entries.add(entry); String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
ChannelNameStateEntry previous = entriesByOwnerTypeSlug.put(ownerTypeSlug, entry);
if (previous != null) {
replacedRoots.put(new ChannelRoot(previous.getOwnerBlockchainName(), previous.getChannelRootBlockNumber(), previous.getChannelRootBlockHash()), entry);
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: "
+ previous.getOwnerBlockchainName() + "#" + previous.getChannelRootBlockNumber()
+ " vs " + ownerBch + "#" + blockNumber + "; kept newest root");
}
} }
} }
} }
entries.addAll(entriesByOwnerTypeSlug.values());
dao.clearAll(c); dao.clearAll(c);
dao.insertAll(c, entries); dao.insertAll(c, entries);
redirectFollowedChannelRoots(c, replacedRoots);
applyMetaUpdates(c, dao, entries, skipped); applyMetaUpdates(c, dao, entries, skipped);
applyDeletionStates(c, dao, skipped); applyDeletionStates(c, dao, skipped);
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap. // v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) { try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM user_identity_current")) {
ps.execute(); ps.execute();
} }
try (PreparedStatement ps = c.prepareStatement(""" try (PreparedStatement ps = c.prepareStatement("""
@@ -162,7 +158,7 @@ public final class ChannelNamesStateBootstrapper {
c.commit(); c.commit();
log.info("channel_names_state bootstrapped: {}", entries.size()); log.info("channel_names_state bootstrapped: {}", entries.size());
if (!conflicts.isEmpty()) { if (!conflicts.isEmpty()) {
log.warn("channel_names_state bootstrap detected {} slug conflicts (kept first occurrence)", conflicts.size()); log.warn("channel_names_state bootstrap detected {} slug conflicts (kept newest root)", conflicts.size());
int preview = Math.min(conflicts.size(), 10); int preview = Math.min(conflicts.size(), 10);
for (int i = 0; i < preview; i++) { for (int i = 0; i < preview; i++) {
log.warn("channel_names_state conflict: {}", conflicts.get(i)); log.warn("channel_names_state conflict: {}", conflicts.get(i));
@@ -192,19 +188,37 @@ public final class ChannelNamesStateBootstrapper {
} }
} }
/** Connections are a mutable projection. Keep follows on the current root when a legacy duplicate is replaced. */
private static void redirectFollowedChannelRoots(Connection c,
Map<ChannelRoot, ChannelNameStateEntry> replacedRoots) throws Exception {
String sql = """
UPDATE connections_state
SET to_block_number = ?, to_block_hash = ?
WHERE LOWER(to_login) = LOWER(?)
AND to_block_number = ?
AND to_block_hash = ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
for (Map.Entry<ChannelRoot, ChannelNameStateEntry> replacement : replacedRoots.entrySet()) {
ChannelRoot oldRoot = replacement.getKey();
ChannelNameStateEntry current = replacement.getValue();
ps.setInt(1, current.getChannelRootBlockNumber());
ps.setBytes(2, current.getChannelRootBlockHash());
ps.setString(3, current.getOwnerLogin());
ps.setInt(4, oldRoot.blockNumber());
ps.setBytes(5, oldRoot.blockHash());
ps.addBatch();
}
ps.executeBatch();
}
}
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception { private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
String sql = """ String sql = """
SELECT bch_name, block_number, block_bytes, msg_sub_type SELECT bch_name, block_number, block_bytes, msg_sub_type
FROM blocks FROM blocks
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?) WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
AND fork_number=shine_canonical_fork( AND fork_number=shine_active_fork(login, block_number)
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number ORDER BY LOWER(login), block_number
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -221,7 +235,7 @@ public final class ChannelNamesStateBootstrapper {
String ownerBch = rs.getString("bch_name"); String ownerBch = rs.getString("bch_name");
int blockNumber = rs.getInt("block_number"); int blockNumber = rs.getInt("block_number");
try { try {
BchBlockEntry parsed = new BchBlockEntry(rs.getBytes("block_bytes")); BchBlockEntry parsed = BchBlockEntry.fromCoreContent(rs.getBytes("block_bytes"));
if (!(parsed.body instanceof TextLineBody body) || body.lineCode() <= 0) continue; if (!(parsed.body instanceof TextLineBody body) || body.lineCode() <= 0) continue;
boolean deleted = rs.getInt("msg_sub_type") == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF); boolean deleted = rs.getInt("msg_sub_type") == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
dao.updateDeletedState(c, ownerBch, body.lineCode(), deleted, deleted ? parsed.timestamp * 1000L : 0L, deleted ? blockNumber : null); dao.updateDeletedState(c, ownerBch, body.lineCode(), deleted, deleted ? parsed.timestamp * 1000L : 0L, deleted ? blockNumber : null);
@@ -233,6 +247,8 @@ public final class ChannelNamesStateBootstrapper {
} }
} }
private record ChannelRoot(String ownerBlockchainName, int blockNumber, byte[] blockHash) {}
private static void applyMetaUpdates(Connection c, private static void applyMetaUpdates(Connection c,
ChannelNameStateDAO dao, ChannelNameStateDAO dao,
List<ChannelNameStateEntry> entries, List<ChannelNameStateEntry> entries,
@@ -246,14 +262,7 @@ public final class ChannelNamesStateBootstrapper {
SELECT login, bch_name, block_number, block_bytes SELECT login, bch_name, block_number, block_bytes
FROM blocks FROM blocks
WHERE msg_type = ? AND msg_sub_type = ? WHERE msg_type = ? AND msg_sub_type = ?
AND fork_number=shine_canonical_fork( AND fork_number=shine_active_fork(login, block_number)
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number ORDER BY LOWER(login), block_number
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -266,7 +275,7 @@ public final class ChannelNamesStateBootstrapper {
int blockNumber = rs.getInt("block_number"); int blockNumber = rs.getInt("block_number");
byte[] blockBytes = rs.getBytes("block_bytes"); byte[] blockBytes = rs.getBytes("block_bytes");
try { try {
BchBlockEntry parsed = new BchBlockEntry(blockBytes); BchBlockEntry parsed = BchBlockEntry.fromCoreContent(blockBytes);
if (!(parsed.body instanceof TextLineBody metaBody)) continue; if (!(parsed.body instanceof TextLineBody metaBody)) continue;
int lineCode = metaBody.lineCode(); int lineCode = metaBody.lineCode();
String fallbackTitle = fallbackTitles.get(ownerLogin.toLowerCase() + "#" + lineCode); String fallbackTitle = fallbackTitles.get(ownerLogin.toLowerCase() + "#" + lineCode);
@@ -55,6 +55,11 @@ final class ChannelsReadSupport {
return value; return value;
} }
static byte[] publicationsRootHash(Connection c, String ownerBch) throws SQLException {
byte[] hash = shine.db.dao.CanonicalChainResolver.getInstance().getHash(c, ownerBch, 0);
return hash == null ? new byte[32] : hash;
}
static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException { static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException {
ChannelMeta meta = new ChannelMeta(); ChannelMeta meta = new ChannelMeta();
meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF; meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF;
@@ -64,6 +69,24 @@ final class ChannelsReadSupport {
meta.displayName = STORIES_CHANNEL_NAME; meta.displayName = STORIES_CHANNEL_NAME;
meta.channelDescription = ""; meta.channelDescription = "";
meta.channelTypeCode = CreateChannelBody.CHANNEL_TYPE_STORIES & 0xFFFF; meta.channelTypeCode = CreateChannelBody.CHANNEL_TYPE_STORIES & 0xFFFF;
String ownerLogin = loginFromChainName(ownerBch);
meta.displayName = ownerLogin;
try (PreparedStatement ps = c.prepareStatement("""
SELECT first_name,last_name,ava_ar,updated_at_ms FROM user_profile_state WHERE LOWER(login)=LOWER(?) LIMIT 1
""")) {
ps.setString(1, ownerLogin);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
String name = (rs.getString("first_name") + " " + rs.getString("last_name")).trim();
if (!name.isBlank()) meta.displayName = name;
var avatar = server.logic.ws_protocol.JSON.handlers.profile.AvatarValueParser.parse(rs.getString("ava_ar"));
meta.avaAr = avatar.ar();
meta.avaPr = avatar.pr();
meta.avaSize = avatar.size();
meta.metaUpdatedAtMs = rs.getLong("updated_at_ms");
}
}
}
return meta; return meta;
} }
@@ -118,7 +141,7 @@ final class ChannelsReadSupport {
return meta; return meta;
} }
byte[] bytes = rs.getBytes("block_bytes"); byte[] bytes = rs.getBytes("block_bytes");
BchBlockEntry e = new BchBlockEntry(bytes); BchBlockEntry e = BchBlockEntry.fromCoreContent(bytes);
BodyRecord body = e.body; BodyRecord body = e.body;
if (body instanceof CreateChannelBody ccb) { if (body instanceof CreateChannelBody ccb) {
meta.channelName = ccb.channelName; meta.channelName = ccb.channelName;
@@ -215,7 +238,7 @@ final class ChannelsReadSupport {
static TextInfo parseTextAndTime(byte[] blockBytes) { static TextInfo parseTextAndTime(byte[] blockBytes) {
try { try {
BchBlockEntry e = new BchBlockEntry(blockBytes); BchBlockEntry e = BchBlockEntry.fromCoreContent(blockBytes);
TextInfo ti = new TextInfo(); TextInfo ti = new TextInfo();
ti.createdAtMs = e.timestamp * 1000L; ti.createdAtMs = e.timestamp * 1000L;
if (e.body instanceof TextLineBody tlb) { if (e.body instanceof TextLineBody tlb) {
@@ -409,7 +432,7 @@ final class ChannelsReadSupport {
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return ""; if (!rs.next()) return "";
byte[] bytes = rs.getBytes("block_bytes"); byte[] bytes = rs.getBytes("block_bytes");
BchBlockEntry e = new BchBlockEntry(bytes); BchBlockEntry e = BchBlockEntry.fromCoreContent(bytes);
BodyRecord body = e.body; BodyRecord body = e.body;
if (body instanceof CreateChannelBody ccb) { if (body instanceof CreateChannelBody ccb) {
return ccb.channelDescription == null ? "" : ccb.channelDescription; return ccb.channelDescription == null ? "" : ccb.channelDescription;
@@ -495,7 +518,7 @@ final class ChannelsReadSupport {
event.blockHash = rs.getBytes("block_hash"); event.blockHash = rs.getBytes("block_hash");
event.lineStep = null; event.lineStep = null;
try { try {
BchBlockEntry entry = new BchBlockEntry(rs.getBytes("block_bytes")); BchBlockEntry entry = BchBlockEntry.fromCoreContent(rs.getBytes("block_bytes"));
event.createdAtMs = entry.timestamp * 1000L; event.createdAtMs = entry.timestamp * 1000L;
if (entry.body instanceof CreateChannelBody ccb) { if (entry.body instanceof CreateChannelBody ccb) {
event.title = ccb.channelName; event.title = ccb.channelName;
@@ -585,7 +608,7 @@ final class ChannelsReadSupport {
event.blockNumber = rs.getInt("block_number"); event.blockNumber = rs.getInt("block_number");
event.blockHash = rs.getBytes("block_hash"); event.blockHash = rs.getBytes("block_hash");
event.lineStep = (Integer) rs.getObject("this_line_number"); event.lineStep = (Integer) rs.getObject("this_line_number");
try { event.createdAtMs = new BchBlockEntry(rs.getBytes("block_bytes")).timestamp * 1000L; } try { event.createdAtMs = BchBlockEntry.fromCoreContent(rs.getBytes("block_bytes")).timestamp * 1000L; }
catch (Exception ignored) { event.createdAtMs = 0L; } catch (Exception ignored) { event.createdAtMs = 0L; }
out.add(event); out.add(event);
} }
@@ -79,7 +79,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
channel.setDeletedBlockNumber(meta.deletedBlockNumber); channel.setDeletedBlockNumber(meta.deletedBlockNumber);
Net_GetChannelMessages_Response.BlockRef rootRef = new Net_GetChannelMessages_Response.BlockRef(); Net_GetChannelMessages_Response.BlockRef rootRef = new Net_GetChannelMessages_Response.BlockRef();
rootRef.setBlockNumber(lineCode); rootRef.setBlockNumber(lineCode);
rootRef.setBlockHash(req.getChannel().getChannelRootBlockHash()); rootRef.setBlockHash(lineCode == 0 ? ChannelsReadSupport.toHex(ChannelsReadSupport.publicationsRootHash(c, ownerBch)) : req.getChannel().getChannelRootBlockHash());
channel.setChannelRoot(rootRef); channel.setChannelRoot(rootRef);
resp.setChannel(channel); resp.setChannel(channel);
@@ -205,6 +205,15 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
} }
private static int loadSubscribersCount(Connection c, String ownerBch, int rootNumber, int channelTypeCode) { private static int loadSubscribersCount(Connection c, String ownerBch, int rootNumber, int channelTypeCode) {
if (rootNumber == 0) {
try (PreparedStatement ps = c.prepareStatement("SELECT COUNT(DISTINCT LOWER(login)) FROM connections_state WHERE LOWER(to_login)=LOWER(?) AND rel_type=30 AND to_block_number=0")) {
ps.setString(1, BlockchainNameUtil.loginFromBlockchainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getInt(1) : 0; }
} catch (Exception e) {
log.warn("GetChannelMessages: не удалось загрузить подписчиков публикаций {}", ownerBch, e);
return 0;
}
}
if (channelTypeCode != (CreateChannelBody.CHANNEL_TYPE_PUBLIC & 0xFFFF)) { if (channelTypeCode != (CreateChannelBody.CHANNEL_TYPE_PUBLIC & 0xFFFF)) {
return 0; return 0;
} }
@@ -50,7 +50,8 @@ public class Net_GetChannelsCounters_Handler implements JsonMessageHandler {
private int countFeed(Connection c, String login) throws Exception { private int countFeed(Connection c, String login) throws Exception {
String sql = """ String sql = """
SELECT COUNT(*) SELECT COUNT(DISTINCT (LOWER(to_login), COALESCE(to_block_number,0),
CASE WHEN COALESCE(to_block_number,0)=0 THEN NULL ELSE to_block_hash END))
FROM connections_state FROM connections_state
WHERE LOWER(login) = LOWER(?) WHERE LOWER(login) = LOWER(?)
AND rel_type = ? AND rel_type = ?
@@ -81,7 +82,7 @@ public class Net_GetChannelsCounters_Handler implements JsonMessageHandler {
} }
private int countMyChannels(Connection c, String login) throws Exception { private int countMyChannels(Connection c, String login) throws Exception {
String bchCountSql = "SELECT COUNT(*) FROM blockchain_state WHERE LOWER(login) = LOWER(?)"; String bchCountSql = "SELECT COUNT(*) FROM user_identity_current WHERE LOWER(login) = LOWER(?)";
int stories = 0; int stories = 0;
try (PreparedStatement ps = c.prepareStatement(bchCountSql)) { try (PreparedStatement ps = c.prepareStatement(bchCountSql)) {
ps.setString(1, login); ps.setString(1, login);
@@ -158,14 +158,13 @@ public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
String sql = """ String sql = """
SELECT login, bch_name, block_number, block_hash, block_bytes SELECT login, bch_name, block_number, block_hash, block_bytes
FROM blocks FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_active_fork(login,block_number)
ORDER BY block_number ASC ORDER BY block_number ASC
"""; """;
List<MsgRow> out = new ArrayList<>(); List<MsgRow> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch)); ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
ps.setInt(2, line); ps.setInt(2, line);
ps.setString(3, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { while (rs.next()) {
MsgRow row = new MsgRow(); MsgRow row = new MsgRow();
@@ -48,7 +48,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
COALESCE(ups.first_name, '') AS first_name, COALESCE(ups.first_name, '') AS first_name,
COALESCE(ups.last_name, '') AS last_name, COALESCE(ups.last_name, '') AS last_name,
COALESCE(ups.ava_ar, '') AS avatar_ar, COALESCE(ups.ava_ar, '') AS avatar_ar,
COALESCE(ups.account_role, 'unknown') AS account_role, shine_is_primary(rs.from_login) AS is_primary,
COALESCE(ups.shine_status, 'unknown') AS shine_status COALESCE(ups.shine_status, 'unknown') AS shine_status
FROM reactions_state rs FROM reactions_state rs
LEFT JOIN user_profile_state ups ON LOWER(ups.login) = LOWER(rs.from_login) LEFT JOIN user_profile_state ups ON LOWER(ups.login) = LOWER(rs.from_login)
@@ -77,7 +77,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
user.setAvatarAr(avatar.ar()); user.setAvatarAr(avatar.ar());
user.setAvatarPr(avatar.pr()); user.setAvatarPr(avatar.pr());
boolean isOfficial = "primary".equalsIgnoreCase(rs.getString("account_role")); boolean isOfficial = rs.getBoolean("is_primary");
boolean isShining = "shining".equalsIgnoreCase(rs.getString("shine_status")); boolean isShining = "shining".equalsIgnoreCase(rs.getString("shine_status"));
if (isOfficial && isShining) shining.add(user); if (isOfficial && isShining) shining.add(user);
else if (isOfficial) official.add(user); else if (isOfficial) official.add(user);
@@ -123,7 +123,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?)) (msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?)) OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?))
) )
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, toBlockNumber); ps.setInt(1, toBlockNumber);
@@ -155,14 +155,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=? WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login); ps.setString(1, login);
ps.setInt(2, blockNumber); ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash); ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null; return rs.next() ? mapRow(rs) : null;
} }
@@ -174,14 +173,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=? WHERE LOWER(login)=LOWER(?) AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
String login=ChannelsReadSupport.loginFromChainName(bchName); String login=ChannelsReadSupport.loginFromChainName(bchName);
ps.setString(1, login); ps.setString(1, login);
ps.setInt(2, blockNumber); ps.setInt(2, blockNumber);
ps.setString(3, login);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null; return rs.next() ? mapRow(rs) : null;
} }
@@ -193,7 +191,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=? WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -201,7 +199,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
ps.setString(1, login); ps.setString(1, login);
ps.setInt(2, blockNumber); ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash); ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null; return rs.next() ? mapRow(rs) : null;
} }
@@ -321,7 +318,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
FROM blocks FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=? WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=? AND to_block_number=? AND to_block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
ORDER BY block_number ASC ORDER BY block_number ASC
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -330,7 +327,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
ps.setInt(2, subType); ps.setInt(2, subType);
ps.setInt(3, targetBlock); ps.setInt(3, targetBlock);
ps.setBytes(4, targetHash); ps.setBytes(4, targetHash);
ps.setString(5, login);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
List<PostRow> out = new ArrayList<>(); List<PostRow> out = new ArrayList<>();
while (rs.next()) out.add(mapRow(rs)); while (rs.next()) out.add(mapRow(rs));
@@ -89,7 +89,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception { private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
try (PreparedStatement ps = c.prepareStatement(""" try (PreparedStatement ps = c.prepareStatement("""
SELECT blockchain_name SELECT blockchain_name
FROM solana_user_pda_current FROM user_identity_current
WHERE LOWER(login)=LOWER(?) WHERE LOWER(login)=LOWER(?)
LIMIT 1 LIMIT 1
""")) { """)) {
@@ -116,7 +116,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { while (rs.next()) {
byte[] blockBytes = rs.getBytes("block_bytes"); byte[] blockBytes = rs.getBytes("block_bytes");
BchBlockEntry entry = new BchBlockEntry(blockBytes); BchBlockEntry entry = BchBlockEntry.fromCoreContent(blockBytes);
if (!(entry.body instanceof StatusActionBody statusBody)) continue; if (!(entry.body instanceof StatusActionBody statusBody)) continue;
Net_GetChannelMessages_Response.MessageItem item = new Net_GetChannelMessages_Response.MessageItem(); Net_GetChannelMessages_Response.MessageItem item = new Net_GetChannelMessages_Response.MessageItem();
@@ -181,7 +181,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
AND msg_sub_type = ? AND msg_sub_type = ?
AND to_block_number = ? AND to_block_number = ?
AND to_block_hash = ? AND to_block_hash = ?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number) AND fork_number=shine_active_fork(login,block_number)
ORDER BY block_number ASC ORDER BY block_number ASC
""")) { """)) {
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch)); ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
@@ -189,7 +189,6 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY); ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY);
ps.setInt(4, originalBlockNumber); ps.setInt(4, originalBlockNumber);
ps.setBytes(5, originalBlockHash); ps.setBytes(5, originalBlockHash);
ps.setString(6, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) { while (rs.next()) {
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes")); ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
@@ -84,7 +84,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
Net_ListSubscriptionsFeed_Response.BlockRef rootRef = new Net_ListSubscriptionsFeed_Response.BlockRef(); Net_ListSubscriptionsFeed_Response.BlockRef rootRef = new Net_ListSubscriptionsFeed_Response.BlockRef();
rootRef.setBlockNumber(key.rootNumber); rootRef.setBlockNumber(key.rootNumber);
rootRef.setBlockHash(ChannelsReadSupport.toHex(key.rootHash)); rootRef.setBlockHash(ChannelsReadSupport.toHex(key.rootNumber == 0 && key.ownerLogin.equalsIgnoreCase(viewerLogin) ? ChannelsReadSupport.publicationsRootHash(c, key.ownerBch) : key.rootHash));
channelRef.setChannelRoot(rootRef); channelRef.setChannelRoot(rootRef);
row.setChannel(channelRef); row.setChannel(channelRef);
@@ -155,6 +155,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
int rootNumber = rs.getInt("root_number"); int rootNumber = rs.getInt("root_number");
if (onlyUserRoots && rootNumber != 0) continue; if (onlyUserRoots && rootNumber != 0) continue;
if (!onlyUserRoots && rootNumber == 0) continue; if (!onlyUserRoots && rootNumber == 0) continue;
if (rs.getString("to_bch_name") == null) continue;
out.add(new ChannelKey( out.add(new ChannelKey(
rs.getString("to_login"), rs.getString("to_login"),
rs.getString("to_bch_name"), rs.getString("to_bch_name"),
@@ -130,26 +130,24 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
sql = outgoing ? """ sql = outgoing ? """
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=80
AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login) AND shine_can_confirm_primary(cs.login,cs.to_login)
ORDER BY peer ORDER BY peer
""" : """ """ : """
SELECT DISTINCT cs.login AS peer FROM connections_state cs SELECT DISTINCT cs.login AS peer FROM connections_state cs
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80
AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login) AND shine_can_confirm_primary(cs.login,cs.to_login)
ORDER BY peer ORDER BY peer
"""; """;
} else { } else {
sql = outgoing ? """ sql = outgoing ? """
SELECT DISTINCT cs.to_login AS peer FROM connections_state cs SELECT DISTINCT cs.to_login AS peer FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=70
AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_can_confirm_shine(cs.login,cs.to_login)
AND shine_target_accepts_shine_confirmation(cs.to_login)
ORDER BY peer ORDER BY peer
""" : """ """ : """
SELECT DISTINCT cs.login AS peer FROM connections_state cs SELECT DISTINCT cs.login AS peer FROM connections_state cs
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70
AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_can_confirm_shine(cs.login,cs.to_login)
AND shine_target_accepts_shine_confirmation(cs.to_login)
ORDER BY peer ORDER BY peer
"""; """;
} }
@@ -216,12 +214,10 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
COALESCE(ups.last_name,'') last_name, COALESCE(ups.last_name,'') last_name,
ups.account_role, ups.shine_status, COALESCE(ups.ava_ar,'') avatar_value, ups.account_role, ups.shine_status, COALESCE(ups.ava_ar,'') avatar_value,
COALESCE(ust.primary_confirmations_received_count,0) primary_confirmations_count, COALESCE(ust.primary_confirmations_received_count,0) primary_confirmations_count,
COALESCE(ust.shine_confirmations_received_count,0) shine_confirmations_count, COALESCE(ust.shine_confirmations_received_count,0) shine_confirmations_count
MAX(CASE WHEN up.param='gender' THEN up.value END) gender_value
FROM %s FROM %s
LEFT JOIN user_profile_state ups ON LOWER(ups.login)=LOWER(su.login) LEFT JOIN user_profile_state ups ON LOWER(ups.login)=LOWER(su.login)
LEFT JOIN user_stats_state ust ON LOWER(ust.login)=LOWER(su.login) LEFT JOIN user_stats_state ust ON LOWER(ust.login)=LOWER(su.login)
LEFT JOIN users_params up ON LOWER(up.login)=LOWER(su.login) AND up.param='gender'
WHERE LOWER(su.login) IN (%s) WHERE LOWER(su.login) IN (%s)
GROUP BY su.login, ups.first_name, ups.last_name, ups.account_role, ups.shine_status, ups.ava_ar, GROUP BY su.login, ups.first_name, ups.last_name, ups.account_role, ups.shine_status, ups.ava_ar,
ust.primary_confirmations_received_count, ust.shine_confirmations_received_count ust.primary_confirmations_received_count, ust.shine_confirmations_received_count
@@ -233,7 +229,7 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
String login=rs.getString("login"); if(login==null||login.isBlank()) continue; String login=rs.getString("login"); if(login==null||login.isBlank()) continue;
UserMeta meta=new UserMeta(); meta.firstName=rs.getString("first_name"); meta.lastName=rs.getString("last_name"); UserMeta meta=new UserMeta(); meta.firstName=rs.getString("first_name"); meta.lastName=rs.getString("last_name");
meta.accountRole=rs.getString("account_role"); meta.shineStatus=rs.getString("shine_status"); meta.accountRole=rs.getString("account_role"); meta.shineStatus=rs.getString("shine_status");
meta.gender=normalizeGender(rs.getString("gender_value")); meta.official="primary".equals(meta.accountRole); meta.shine="shining".equals(meta.shineStatus); meta.official="primary".equals(meta.accountRole); meta.shine="shining".equals(meta.shineStatus);
meta.primaryConfirmationsCount=rs.getInt("primary_confirmations_count"); meta.shineConfirmationsCount=rs.getInt("shine_confirmations_count"); meta.primaryConfirmationsCount=rs.getInt("primary_confirmations_count"); meta.shineConfirmationsCount=rs.getInt("shine_confirmations_count");
meta.avatarValue=String.valueOf(rs.getString("avatar_value") == null ? "" : rs.getString("avatar_value")); out.put(normKey(login),meta); meta.avatarValue=String.valueOf(rs.getString("avatar_value") == null ? "" : rs.getString("avatar_value")); out.put(normKey(login),meta);
}} }}
@@ -261,19 +257,6 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
return "1".equals(v) || "yes".equals(v) || "true".equals(v) || "on".equals(v); return "1".equals(v) || "yes".equals(v) || "true".equals(v) || "on".equals(v);
} }
private String normalizeGender(String rawValue) {
String v = String.valueOf(rawValue == null ? "" : rawValue).trim().toLowerCase();
if ("male".equals(v)) return "male";
if ("female".equals(v)) return "female";
return "unknown";
}
private String genderLabel(String gender) {
if ("male".equals(gender)) return "мужчина";
if ("female".equals(gender)) return "женщина";
return "не указан";
}
private String extractArAvatarTxId(String rawValue) { private String extractArAvatarTxId(String rawValue) {
String value = String.valueOf(rawValue == null ? "" : rawValue).trim(); String value = String.valueOf(rawValue == null ? "" : rawValue).trim();
if (value.isEmpty()) return null; if (value.isEmpty()) return null;
@@ -311,12 +294,9 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
String clean = (login == null) ? "" : login.trim(); String clean = (login == null) ? "" : login.trim();
if (clean.isEmpty()) continue; if (clean.isEmpty()) continue;
UserMeta meta = metaByLogin.get(normKey(clean)); UserMeta meta = metaByLogin.get(normKey(clean));
String gender = (meta == null) ? "unknown" : meta.gender;
Net_GetUserConnectionsGraph_Response.RelativeItem it = new Net_GetUserConnectionsGraph_Response.RelativeItem(); Net_GetUserConnectionsGraph_Response.RelativeItem it = new Net_GetUserConnectionsGraph_Response.RelativeItem();
it.setLogin(clean); it.setLogin(clean);
it.setGender(gender);
it.setGenderLabel(genderLabel(gender));
it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarValue)); it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarValue));
items.add(it); items.add(it);
} }
@@ -363,7 +343,6 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
} }
private static final class UserMeta { private static final class UserMeta {
private String gender = "unknown";
private String firstName = ""; private String firstName = "";
private String lastName = ""; private String lastName = "";
private String accountRole = null; private String accountRole = null;
@@ -49,16 +49,10 @@ public class Net_GetUserConnectionsGraph_Response extends Net_Response {
public static class RelativeItem { public static class RelativeItem {
private String login; private String login;
private String gender;
private String genderLabel;
private AvatarItem avatar; private AvatarItem avatar;
public String getLogin() { return login; } public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; } public void setLogin(String login) { this.login = login; }
public String getGender() { return gender; }
public void setGender(String gender) { this.gender = gender; }
public String getGenderLabel() { return genderLabel; }
public void setGenderLabel(String genderLabel) { this.genderLabel = genderLabel; }
public AvatarItem getAvatar() { return avatar; } public AvatarItem getAvatar() { return avatar; }
public void setAvatar(AvatarItem avatar) { this.avatar = avatar; } public void setAvatar(AvatarItem avatar) { this.avatar = avatar; }
} }
@@ -3,7 +3,6 @@ package server.logic.ws_protocol.JSON.handlers.keyRotation;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier; import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.ForkBody; import blockchain.body.ForkBody;
import server.logic.ws_protocol.Base64Ws; import server.logic.ws_protocol.Base64Ws;
import server.logic.ws_protocol.JSON.ConnectionContext; import server.logic.ws_protocol.JSON.ConnectionContext;
@@ -74,9 +73,9 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
KeyRotationCandidateBlockEntry existing = candidates.getByNumber(c, session.getId(), req.getBlockNumber()); KeyRotationCandidateBlockEntry existing = candidates.getByNumber(c, session.getId(), req.getBlockNumber());
if (existing != null) { if (existing != null) {
BchBlockEntry repeated; BchBlockEntry repeated;
try { repeated = new BchBlockEntry(Base64Ws.decode(req.getBlockBytesB64())); } try { repeated = BchBlockEntry.fromCoreContent(Base64Ws.decode(req.getBlockBytesB64())); }
catch (Exception e) { return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Не удалось распарсить DataItem"); } catch (Exception e) { return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Не удалось распарсить DataItem"); }
if (!Arrays.equals(existing.getBlockHash(), repeated.getHash32()) || !Arrays.equals(existing.getDataItemId(), repeated.getDataItemId32())) { if (!Arrays.equals(existing.getBlockHash(), repeated.getHash32()) || !Arrays.equals(existing.getDataItemId(), repeated.getDataItemId32()) || !Arrays.equals(existing.getBlockBytes(), repeated.toBytes())) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BLOCK_CONFLICT", "TECH_FORK уже сохранён с другим содержимым"); return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BLOCK_CONFLICT", "TECH_FORK уже сохранён с другим содержимым");
} }
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), session); return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), session);
@@ -92,7 +91,7 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
final BchBlockEntry block; final BchBlockEntry block;
try { try {
raw = Base64Ws.decode(req.getBlockBytesB64()); raw = Base64Ws.decode(req.getBlockBytesB64());
block = new BchBlockEntry(raw); block = BchBlockEntry.fromCoreContent(raw);
block.body.check(); block.body.check();
} catch (Exception e) { } catch (Exception e) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Некорректный SHiNE/ANS-104 блок"); return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Некорректный SHiNE/ANS-104 блок");
@@ -100,28 +99,9 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
if (block.blockNumber != req.getBlockNumber()) { if (block.blockNumber != req.getBlockNumber()) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BLOCK_NUMBER_MISMATCH", "blockNumber запроса не совпадает с блоком"); return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BLOCK_NUMBER_MISMATCH", "blockNumber запроса не совпадает с блоком");
} }
if (!block.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_APP_TAG", "Отсутствует App=" + ShineProtocolTags.APP_TAG_VALUE);
}
String expectedTypeTag = expectedTypeTag(block);
String actualTypeTag = block.getDataItem().tagValue(ShineProtocolTags.TYPE_TAG_NAME);
if (expectedTypeTag != null ? !expectedTypeTag.equals(actualTypeTag) : actualTypeTag != null) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_TYPE_TAG", "Некорректный t-тег candidate DataItem");
}
if (!requestPrevHashMatches(req.getPrevBlockHash(), block.prevHash32)) { if (!requestPrevHashMatches(req.getPrevBlockHash(), block.prevHash32)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_PREV_HASH_MISMATCH", "prevBlockHash запроса не совпадает с блоком"); return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_PREV_HASH_MISMATCH", "prevBlockHash запроса не совпадает с блоком");
} }
byte[] expectedBack32 = new byte[32];
if (block.blockNumber >= 32) {
expectedBack32 = canonicalChain.getHash(c, session.getSourceBlockchainName(), block.blockNumber - 32);
if (expectedBack32 == null || expectedBack32.length != 32) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BACK32_SOURCE_MISSING", "Нет канонического блока N-32 для проверки back32Hash");
}
}
if (!Arrays.equals(block.back32Hash32, expectedBack32)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BACK32_HASH_MISMATCH", "back32Hash candidate-блока не совпадает с N-32");
}
byte[] newBlockchainKey; byte[] newBlockchainKey;
try { try {
newBlockchainKey = Base64.getDecoder().decode(session.getNewBlockchainKey()); newBlockchainKey = Base64.getDecoder().decode(session.getNewBlockchainKey());
@@ -188,11 +168,15 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
} }
if (!Arrays.equals(candidate.prevHash32, session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_PREV_HASH"; if (!Arrays.equals(candidate.prevHash32, session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_PREV_HASH";
BlockEntry techTail = canonicalChain.getLastLineBlock(c, session.getSourceBlockchainName(), 0, 0, candidate.blockNumber);
if (techTail == null) techTail = canonicalChain.getBlock(c, session.getSourceBlockchainName(), 0);
if (techTail == null || fork.prevLineNumber != techTail.getBlockNumber()
|| !Arrays.equals(fork.prevLineHash32, techTail.getBlockHash())) return "KEY_ROTATION_TECH_FORK_LINE";
BlockEntry forkSourceEntry = canonicalChain.getBlock(c, session.getSourceBlockchainName(), session.getForkFromBlock()); BlockEntry forkSourceEntry = canonicalChain.getBlock(c, session.getSourceBlockchainName(), session.getForkFromBlock());
BlockEntry tipSourceEntry = blocks.getByNumber(c, session.getSourceBlockchainName(), session.getSourceTipBlock()); BlockEntry tipSourceEntry = blocks.getByNumber(c, session.getSourceBlockchainName(), session.getSourceTipBlock());
if (forkSourceEntry == null || tipSourceEntry == null) return "KEY_ROTATION_SOURCE_BLOCK_MISSING"; if (forkSourceEntry == null || tipSourceEntry == null) return "KEY_ROTATION_SOURCE_BLOCK_MISSING";
BchBlockEntry forkSource = new BchBlockEntry(forkSourceEntry.getBlockBytes()); BchBlockEntry forkSource = BchBlockEntry.fromCoreContent(forkSourceEntry.getBlockBytes());
BchBlockEntry tipSource = new BchBlockEntry(tipSourceEntry.getBlockBytes()); BchBlockEntry tipSource = BchBlockEntry.fromCoreContent(tipSourceEntry.getBlockBytes());
byte[] oldBlockchain = Base64.getDecoder().decode(session.getOldBlockchainKey()); byte[] oldBlockchain = Base64.getDecoder().decode(session.getOldBlockchainKey());
if (!Arrays.equals(fork.parentBlockchainKey32, oldBlockchain)) return "KEY_ROTATION_TECH_FORK_PARENT_KEY"; if (!Arrays.equals(fork.parentBlockchainKey32, oldBlockchain)) return "KEY_ROTATION_TECH_FORK_PARENT_KEY";
@@ -229,14 +213,4 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
if (value == null) return ""; if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n'); return value.trim().replace("\r\n", "\n").replace('\r', '\n');
} }
private static String expectedTypeTag(BchBlockEntry block) {
int type = block.type & 0xffff;
return switch (type) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
} }
@@ -3,7 +3,6 @@ package server.logic.ws_protocol.JSON.handlers.keyRotation;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier; import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.ForkBody; import blockchain.body.ForkBody;
import server.logic.ws_protocol.JSON.ConnectionContext; import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request; import server.logic.ws_protocol.JSON.entyties.Net_Request;
@@ -133,19 +132,13 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
if(stored.getBlockNumber()!=expectedNumber) return "KEY_ROTATION_CANDIDATE_GAP"; if(stored.getBlockNumber()!=expectedNumber) return "KEY_ROTATION_CANDIDATE_GAP";
if(stored.isArweavePublishPending() || stored.getArweavePublishedAtMs()==null) return "KEY_ROTATION_CHAIN_NOT_PUBLISHED"; if(stored.isArweavePublishPending() || stored.getArweavePublishedAtMs()==null) return "KEY_ROTATION_CHAIN_NOT_PUBLISHED";
BchBlockEntry candidate; BchBlockEntry candidate;
try { candidate=new BchBlockEntry(stored.getBlockBytes()); candidate.body.check(); } catch(Exception e){ return "KEY_ROTATION_BAD_STORED_BLOCK"; } try { candidate=BchBlockEntry.fromCoreContent(stored.getBlockBytes()); candidate.body.check(); } catch(Exception e){ return "KEY_ROTATION_BAD_STORED_BLOCK"; }
if(candidate.blockNumber!=expectedNumber) return "KEY_ROTATION_BLOCK_NUMBER_MISMATCH"; if(candidate.blockNumber!=expectedNumber) return "KEY_ROTATION_BLOCK_NUMBER_MISMATCH";
if(!Arrays.equals(candidate.getHash32(),stored.getBlockHash())) return "KEY_ROTATION_STORED_HASH_MISMATCH"; if(!Arrays.equals(candidate.getHash32(),stored.getBlockHash())) return "KEY_ROTATION_STORED_HASH_MISMATCH";
if(!Arrays.equals(candidate.getDataItemId32(),stored.getDataItemId())) return "KEY_ROTATION_STORED_DATAITEM_MISMATCH"; if(!Arrays.equals(candidate.getDataItemId32(),stored.getDataItemId())) return "KEY_ROTATION_STORED_DATAITEM_MISMATCH";
if(!candidate.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME,ShineProtocolTags.APP_TAG_VALUE)) return "KEY_ROTATION_BAD_APP_TAG";
String expectedTypeTag=expectedTypeTag(candidate), actualTypeTag=candidate.getDataItem().tagValue(ShineProtocolTags.TYPE_TAG_NAME);
if(expectedTypeTag!=null?!expectedTypeTag.equals(actualTypeTag):actualTypeTag!=null) return "KEY_ROTATION_BAD_TYPE_TAG";
byte[] newKey=Base64.getDecoder().decode(session.getNewBlockchainKey()); byte[] newKey=Base64.getDecoder().decode(session.getNewBlockchainKey());
if(newKey.length!=32 || !BchCryptoVerifier.verifyBlock(candidate,newKey)) return "KEY_ROTATION_BAD_SIGNATURE"; if(newKey.length!=32 || !BchCryptoVerifier.verifyBlock(candidate,newKey)) return "KEY_ROTATION_BAD_SIGNATURE";
if(!Arrays.equals(candidate.prevHash32,session.getForkFromHash())) return "KEY_ROTATION_CHAIN_HASH_MISMATCH"; if(!Arrays.equals(candidate.prevHash32,session.getForkFromHash())) return "KEY_ROTATION_CHAIN_HASH_MISMATCH";
byte[] expectedBack32=new byte[32];
if(candidate.blockNumber>=32){ expectedBack32=canonicalChain.getHash(c,session.getSourceBlockchainName(),candidate.blockNumber-32); if(expectedBack32==null)return "KEY_ROTATION_BACK32_SOURCE_MISSING"; }
if(!Arrays.equals(candidate.back32Hash32,expectedBack32)) return "KEY_ROTATION_BACK32_HASH_MISMATCH";
return validateAgainstRotation(c,session,candidate); return validateAgainstRotation(c,session,candidate);
} }
@@ -153,10 +146,14 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
if(candidate.blockNumber!=session.getForkFromBlock()+1) return "KEY_ROTATION_UNEXPECTED_BLOCK_NUMBER"; if(candidate.blockNumber!=session.getForkFromBlock()+1) return "KEY_ROTATION_UNEXPECTED_BLOCK_NUMBER";
if((candidate.type&0xFFFF)!=0 || (candidate.subType&0xFFFF)!=(MsgSubType.TECH_FORK&0xFFFF) || !(candidate.body instanceof ForkBody fork)) return "KEY_ROTATION_TECH_FORK_REQUIRED"; if((candidate.type&0xFFFF)!=0 || (candidate.subType&0xFFFF)!=(MsgSubType.TECH_FORK&0xFFFF) || !(candidate.body instanceof ForkBody fork)) return "KEY_ROTATION_TECH_FORK_REQUIRED";
if(!Arrays.equals(candidate.prevHash32,session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_PREV_HASH"; if(!Arrays.equals(candidate.prevHash32,session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_PREV_HASH";
BlockEntry techTail = canonicalChain.getLastLineBlock(c, session.getSourceBlockchainName(), 0, 0, candidate.blockNumber);
if (techTail == null) techTail = canonicalChain.getBlock(c, session.getSourceBlockchainName(), 0);
if (techTail == null || fork.prevLineNumber != techTail.getBlockNumber()
|| !Arrays.equals(fork.prevLineHash32, techTail.getBlockHash())) return "KEY_ROTATION_TECH_FORK_LINE";
BlockEntry forkSourceEntry=canonicalChain.getBlock(c,session.getSourceBlockchainName(),session.getForkFromBlock()); BlockEntry forkSourceEntry=canonicalChain.getBlock(c,session.getSourceBlockchainName(),session.getForkFromBlock());
BlockEntry tipSourceEntry=blocks.getByNumber(c,session.getSourceBlockchainName(),session.getSourceTipBlock()); BlockEntry tipSourceEntry=blocks.getByNumber(c,session.getSourceBlockchainName(),session.getSourceTipBlock());
if(forkSourceEntry==null||tipSourceEntry==null)return "KEY_ROTATION_SOURCE_BLOCK_MISSING"; if(forkSourceEntry==null||tipSourceEntry==null)return "KEY_ROTATION_SOURCE_BLOCK_MISSING";
BchBlockEntry forkSource=new BchBlockEntry(forkSourceEntry.getBlockBytes()), tipSource=new BchBlockEntry(tipSourceEntry.getBlockBytes()); BchBlockEntry forkSource=BchBlockEntry.fromCoreContent(forkSourceEntry.getBlockBytes()), tipSource=BchBlockEntry.fromCoreContent(tipSourceEntry.getBlockBytes());
byte[] oldBlockchain=Base64.getDecoder().decode(session.getOldBlockchainKey()); byte[] oldBlockchain=Base64.getDecoder().decode(session.getOldBlockchainKey());
if(!Arrays.equals(fork.parentBlockchainKey32,oldBlockchain))return "KEY_ROTATION_TECH_FORK_PARENT_KEY"; if(!Arrays.equals(fork.parentBlockchainKey32,oldBlockchain))return "KEY_ROTATION_TECH_FORK_PARENT_KEY";
if(fork.forkPointBlockNumber!=session.getForkFromBlock())return "KEY_ROTATION_TECH_FORK_POINT"; if(fork.forkPointBlockNumber!=session.getForkFromBlock())return "KEY_ROTATION_TECH_FORK_POINT";
@@ -181,14 +178,4 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
if (value == null) return ""; if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n'); return value.trim().replace("\r\n", "\n").replace('\r', '\n');
} }
private static String expectedTypeTag(BchBlockEntry block) {
int type = block.type & 0xffff;
return switch (type) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
} }
@@ -1,3 +1,3 @@
package server.logic.ws_protocol.JSON.handlers.profile; package server.logic.ws_protocol.JSON.handlers.profile;
import server.logic.ws_protocol.JSON.*;import server.logic.ws_protocol.JSON.entyties.*;import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;import server.logic.ws_protocol.JSON.handlers.profile.entyties.*;import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;import server.logic.ws_protocol.WireCodes;import shine.db.dao.UserProfileStateDAO;import java.sql.*;import java.util.*; import server.logic.ws_protocol.JSON.*;import server.logic.ws_protocol.JSON.entyties.*;import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;import server.logic.ws_protocol.JSON.handlers.profile.entyties.*;import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;import server.logic.ws_protocol.WireCodes;import shine.db.dao.UserProfileStateDAO;import java.sql.*;import java.util.*;
public class Net_ListUserProfileChannels_Handler implements JsonMessageHandler {public Net_Response handle(Net_Request base,ConnectionContext ctx)throws Exception{var req=(Net_ListUserProfileChannels_Request)base;if(req.getLogin()==null||req.getLogin().isBlank())return NetExceptionResponseFactory.error(req,400,"BAD_FIELDS","login required");try(Connection c=shine.db.DbController.getInstance().getConnection()){var rows=UserProfileStateDAO.getInstance().listPublicChannels(c,req.getLogin(),req.getMode(),Boolean.TRUE.equals(req.getIncludeDeleted()),req.getLimit()==null?100:req.getLimit(),req.getOffset()==null?0:req.getOffset());var resp=new Net_ListUserProfileChannels_Response();resp.setOp(req.getOp());resp.setRequestId(req.getRequestId());resp.setStatus(WireCodes.Status.OK);resp.setLogin(req.getLogin());resp.setMode(req.getMode());List<Net_ListUserProfileChannels_Response.ChannelItem> items=new ArrayList<>();for(var r:rows){var i=new Net_ListUserProfileChannels_Response.ChannelItem();i.setOwnerLogin(r.ownerLogin());i.setSlug(r.slug());i.setDisplayName(r.displayName());i.setAvatarAr(r.avatarAr());i.setAvatarPr(r.avatarPr());i.setOwnerBlockchainName(r.ownerBlockchainName());i.setRootBlockNumber(r.rootBlockNumber());i.setRootBlockHashHex(r.rootBlockHashHex());i.setDeleted(r.deleted());i.setDeletedAtMs(r.deletedAtMs());i.setDeletedBlockNumber(r.deletedBlockNumber());items.add(i);}resp.setChannels(items);return resp;}}} public class Net_ListUserProfileChannels_Handler implements JsonMessageHandler {public Net_Response handle(Net_Request base,ConnectionContext ctx)throws Exception{var req=(Net_ListUserProfileChannels_Request)base;if(req.getLogin()==null||req.getLogin().isBlank())return NetExceptionResponseFactory.error(req,400,"BAD_FIELDS","login required");try(Connection c=shine.db.DbController.getInstance().getConnection()){var rows=UserProfileStateDAO.getInstance().listPublicChannels(c,req.getLogin(),req.getMode(),Boolean.TRUE.equals(req.getIncludeDeleted()),req.getLimit()==null?100:req.getLimit(),req.getOffset()==null?0:req.getOffset());var resp=new Net_ListUserProfileChannels_Response();resp.setOp(req.getOp());resp.setRequestId(req.getRequestId());resp.setStatus(WireCodes.Status.OK);resp.setLogin(req.getLogin());resp.setMode(req.getMode());List<Net_ListUserProfileChannels_Response.ChannelItem> items=new ArrayList<>();for(var r:rows){var i=new Net_ListUserProfileChannels_Response.ChannelItem();i.setOwnerLogin(r.ownerLogin());i.setSlug(r.slug());i.setDisplayName(r.displayName());if(r.rootBlockNumber()==0){var avatar=AvatarValueParser.parse(r.avatarAr());i.setAvatarAr(avatar.ar());i.setAvatarPr(avatar.pr());}else{i.setAvatarAr(r.avatarAr());i.setAvatarPr(r.avatarPr());}i.setOwnerBlockchainName(r.ownerBlockchainName());i.setRootBlockNumber(r.rootBlockNumber());i.setRootBlockHashHex(r.rootBlockHashHex());i.setDeleted(r.deleted());i.setDeletedAtMs(r.deletedAtMs());i.setDeletedBlockNumber(r.deletedBlockNumber());items.add(i);}resp.setChannels(items);return resp;}}}
@@ -1,86 +0,0 @@
package server.logic.ws_protocol.JSON.handlers.system;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.system.entyties.Net_GetSyncUserProfile_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.CurrentUserEntry;
/**
* GetSyncUserProfile — server-to-server профиль пользователя для межсерверной синхронизации.
* Нужен, чтобы принимающий сервер мог создать локальную runtime-проекцию пользователя
* и blockchain_state без прямого запроса в Solana RPC.
*/
public final class Net_GetSyncUserProfile_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetSyncUserProfile_Handler.class);
private final CurrentUsersDAO usersDAO = CurrentUsersDAO.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetSyncUserProfile_Request req = (Net_GetSyncUserProfile_Request) baseRequest;
String login = req.getLogin() == null ? "" : req.getLogin().trim();
if (login.isEmpty()) {
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.BAD_REQUEST,
"BAD_FIELDS",
"Некорректные поля: login"
);
}
try {
CurrentUserEntry user = usersDAO.getByLogin(login);
Net_GetSyncUserProfile_Response resp = new Net_GetSyncUserProfile_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
if (user == null) {
resp.setExists(false);
return resp;
}
BlockchainStateEntry state = stateDAO.getByBlockchainName(user.getBlockchainName());
if (state == null) {
log.warn("GetSyncUserProfile: blockchain_state not found for login={} blockchainName={}",
user.getLogin(), user.getBlockchainName());
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.NOT_FOUND,
"BLOCKCHAIN_STATE_NOT_FOUND",
"Состояние блокчейна пользователя не найдено"
);
}
resp.setExists(true);
resp.setLogin(user.getLogin());
resp.setBlockchainName(user.getBlockchainName());
resp.setSolanaKey(user.getSolanaKey());
resp.setBlockchainKey(user.getBlockchainKey());
resp.setClientKey(user.getClientKey());
resp.setBlockchainSizeLimitBytes(state.getSizeLimit());
return resp;
} catch (Exception e) {
log.error("❌ Internal error GetSyncUserProfile login={}", login, e);
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.INTERNAL_ERROR,
"INTERNAL_ERROR",
NetExceptionResponseFactory.detailedMessage("Внутренняя ошибка сервера при GetSyncUserProfile", e)
);
}
}
}
@@ -1,14 +0,0 @@
package server.logic.ws_protocol.JSON.handlers.system.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/**
* Запрос межсерверного профиля пользователя для синхронизации.
*/
public class Net_GetSyncUserProfile_Request extends Net_Request {
private String login;
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
}
@@ -1,38 +0,0 @@
package server.logic.ws_protocol.JSON.handlers.system.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
/**
* Ответ межсерверного профиля пользователя для синхронизации.
*/
public class Net_GetSyncUserProfile_Response extends Net_Response {
private Boolean exists;
private String login;
private String blockchainName;
private String solanaKey;
private String blockchainKey;
private String clientKey;
private Long blockchainSizeLimitBytes;
public Boolean getExists() { return exists; }
public void setExists(Boolean exists) { this.exists = exists; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
public String getSolanaKey() { return solanaKey; }
public void setSolanaKey(String solanaKey) { this.solanaKey = solanaKey; }
public String getBlockchainKey() { return blockchainKey; }
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
public String getClientKey() { return clientKey; }
public void setClientKey(String clientKey) { this.clientKey = clientKey; }
public Long getBlockchainSizeLimitBytes() { return blockchainSizeLimitBytes; }
public void setBlockchainSizeLimitBytes(Long blockchainSizeLimitBytes) { this.blockchainSizeLimitBytes = blockchainSizeLimitBytes; }
}
@@ -139,7 +139,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
} }
private static void loadUserStats(Net_GetUser_Response resp, String login) { private static void loadUserStats(Net_GetUser_Response resp, String login) {
resp.setOwnedPublicChannelsCount(0); resp.setOwnedPublicChannelsCount(1);
resp.setFollowingUsersCount(0); resp.setFollowingUsersCount(0);
resp.setFollowingChannelsCount(0); resp.setFollowingChannelsCount(0);
resp.setCloseFriendsCount(0); resp.setCloseFriendsCount(0);
@@ -169,9 +169,9 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
if (!rs.next()) { if (!rs.next()) {
return; return;
} }
resp.setOwnedPublicChannelsCount(rs.getInt("owned_public_channels_count")); resp.setOwnedPublicChannelsCount(1 + rs.getInt("owned_public_channels_count"));
resp.setFollowingUsersCount(rs.getInt("following_users_count")); resp.setFollowingUsersCount(rs.getInt("following_users_count"));
resp.setFollowingChannelsCount(rs.getInt("following_channels_count")); resp.setFollowingChannelsCount(rs.getInt("following_channels_count") + rs.getInt("following_users_count"));
resp.setCloseFriendsCount(rs.getInt("close_friends_count")); resp.setCloseFriendsCount(rs.getInt("close_friends_count"));
resp.setFriendsCount(rs.getInt("friends_count")); resp.setFriendsCount(rs.getInt("friends_count"));
resp.setPrimaryConfirmationsReceivedCount(rs.getInt("primary_confirmations_received_count")); resp.setPrimaryConfirmationsReceivedCount(rs.getInt("primary_confirmations_received_count"));
@@ -54,8 +54,19 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
UserParamsDAO dao = UserParamsDAO.getInstance(); UserParamsDAO dao = UserParamsDAO.getInstance();
List<UserParamEntry> entries; List<UserParamEntry> entries;
Integer accountType = null;
List<String> previousAccounts = null;
try (Connection c = db.getConnection()) { try (Connection c = db.getConnection()) {
entries = dao.getByLogin(c, login); entries = dao.getByLogin(c, login);
try (var ps = c.prepareStatement("SELECT account_type,previous_accounts FROM account_identity_state WHERE login=LOWER(?)")) {
ps.setString(1, login);
try (var rs = ps.executeQuery()) {
if (rs.next()) {
accountType = rs.getInt(1);
previousAccounts = List.of((String[])rs.getArray(2).getArray());
}
}
}
} }
Net_ListUserParams_Response resp = new Net_ListUserParams_Response(); Net_ListUserParams_Response resp = new Net_ListUserParams_Response();
@@ -78,6 +89,8 @@ public class Net_ListUserParams_Handler implements JsonMessageHandler {
items.add(it); items.add(it);
} }
resp.setParams(items); resp.setParams(items);
resp.setAccountType(accountType);
resp.setPreviousAccounts(previousAccounts);
return resp; return resp;
@@ -63,6 +63,13 @@ public class Net_UpsertUserParam_Handler implements JsonMessageHandler {
final String login = req.getLogin().trim(); final String login = req.getLogin().trim();
final String param = req.getParam().trim(); final String param = req.getParam().trim();
if ("account_role".equalsIgnoreCase(param) || "official".equalsIgnoreCase(param)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
"account_type_immutable", "Тип аккаунта определяется только HEADER V3");
}
if ("gender".equalsIgnoreCase(param)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "gender_disabled", "Пол не используется");
}
final long timeMs = req.getTime_ms(); final long timeMs = req.getTime_ms();
final String value = req.getValue(); final String value = req.getValue();
final String clientKeyB64 = req.getClient_key().trim(); final String clientKeyB64 = req.getClient_key().trim();
@@ -31,6 +31,12 @@ import java.util.List;
public class Net_ListUserParams_Response extends Net_Response { public class Net_ListUserParams_Response extends Net_Response {
private String login; private String login;
private Integer accountType;
private List<String> previousAccounts;
public Integer getAccountType() { return accountType; }
public void setAccountType(Integer accountType) { this.accountType = accountType; }
public List<String> getPreviousAccounts() { return previousAccounts; }
public void setPreviousAccounts(List<String> previousAccounts) { this.previousAccounts = previousAccounts; }
private List<Item> params = new ArrayList<>(); private List<Item> params = new ArrayList<>();
public String getLogin() { return login; } public String getLogin() { return login; }
@@ -1,263 +0,0 @@
package server.sync;
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.Base64Ws;
import shine.db.dao.BlocksDAO;
import shine.db.dao.SyncServersDAO;
import shine.db.entities.BlockEntry;
import shine.db.entities.SyncServerEntry;
import utils.blockchain.BlockchainNameUtil;
import utils.config.AppConfig;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* @deprecated Legacy direct server-to-server blockchain sync. Not compatible with segmented forks; Arweave/Turbo is supported.
* Фоновая репликация AddBlock через общий постоянный WSS-пул на серверы
* из локальной таблицы sync_servers.
*/
@Deprecated
public final class AddBlockSyncService {
private static final Logger log = LoggerFactory.getLogger(AddBlockSyncService.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(
1,
Math.max(2, Runtime.getRuntime().availableProcessors()),
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<>(10_000),
new ThreadFactory() {
private final AtomicLong n = new AtomicLong(1);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "sync-addblock-" + n.getAndIncrement());
t.setDaemon(true);
return t;
}
},
new ThreadPoolExecutor.DiscardPolicy()
);
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final SyncServersDAO syncServersDAO = SyncServersDAO.getInstance();
public void replicateAsync(String blockchainName, int blockNumber) {
if (!isEnabled()) {
log.debug("AddBlock sync skipped: blockchain.sync.enabled=false blockchainName={} blockNumber={}",
blockchainName, blockNumber);
return;
}
EXECUTOR.execute(() -> {
try {
replicate(blockchainName, blockNumber);
} catch (Exception e) {
log.error("AddBlock sync failed unexpectedly (blockchainName={}, blockNumber={})",
blockchainName, blockNumber, e);
}
});
}
private static boolean isEnabled() {
// Legacy peer replication is disabled in PDA 1.2; Arweave is the synchronization source.
return false;
}
private void replicate(String blockchainName, int blockNumber) throws Exception {
String ownerLogin = normalize(BlockchainNameUtil.loginFromBlockchainName(blockchainName));
if (ownerLogin == null) {
log.warn("AddBlock sync skipped: cannot derive owner login from blockchainName={}", blockchainName);
return;
}
List<SyncServerEntry> partners = syncServersDAO.listAll();
if (partners.isEmpty()) {
return;
}
BlockEntry currentBlock = blocksDAO.getByNumber(blockchainName, blockNumber);
if (currentBlock == null || currentBlock.getBlockBytes() == null) {
log.warn("AddBlock sync skipped: block not found in DB (blockchainName={}, blockNumber={})",
blockchainName, blockNumber);
return;
}
for (SyncServerEntry partner : partners) {
if (partner == null) continue;
String partnerLogin = normalize(partner.getLogin());
if (partnerLogin == null) continue;
if (partnerLogin.equals(ownerLogin)) {
continue;
}
try {
replicateToPartner(partner, blockchainName, blockNumber, currentBlock);
} catch (Exception e) {
log.warn("AddBlock sync aborted for partner login={} blockchainName={} blockNumber={} reason={}",
partnerLogin, blockchainName, blockNumber, e.toString());
}
}
}
private void replicateToPartner(SyncServerEntry partner, String blockchainName, int blockNumber, BlockEntry currentBlock) throws Exception {
String wsUrl = ServerConnectionPool.buildWsUrl(partner.getServerAddress());
if (wsUrl == null) {
log.warn("AddBlock sync skipped: invalid server_address for partner login={} address={}",
partner.getLogin(), partner.getServerAddress());
return;
}
AddBlockPushResult firstTry = pushBlock(partner, blockchainName, currentBlock);
if (firstTry.ok()) {
log.info("AddBlock sync ok: partner={} blockchainName={} blockNumber={}",
partner.getLogin(), blockchainName, blockNumber);
return;
}
if (firstTry.serverAlreadyHasBlock(blockNumber)) {
log.info("AddBlock sync skipped: partner already has block. partner={} blockchainName={} blockNumber={} remoteLast={}",
partner.getLogin(), blockchainName, blockNumber, firstTry.serverLastGlobalNumber());
return;
}
if (!firstTry.needsBackfill()) {
log.warn("AddBlock sync failed without backfill: partner={} blockchainName={} blockNumber={} code={}",
partner.getLogin(), blockchainName, blockNumber, firstTry.code());
return;
}
int remoteLast = firstTry.serverLastGlobalNumber();
int fromBlockNumber = remoteLast + 1;
if (fromBlockNumber > blockNumber) {
log.info("AddBlock sync skipped: partner already caught up during backfill window. partner={} blockchainName={} remoteLast={} target={}",
partner.getLogin(), blockchainName, remoteLast, blockNumber);
return;
}
List<BlockEntry> missingBlocks = blocksDAO.listRangeByNumber(blockchainName, fromBlockNumber, blockNumber);
if (missingBlocks.isEmpty()) {
log.warn("AddBlock sync backfill failed: local range empty partner={} blockchainName={} from={} to={}",
partner.getLogin(), blockchainName, fromBlockNumber, blockNumber);
return;
}
for (BlockEntry blockEntry : missingBlocks) {
AddBlockPushResult backfillResult = pushBlock(partner, blockchainName, blockEntry);
if (!backfillResult.ok()) {
log.warn("AddBlock sync backfill failed: partner={} blockchainName={} blockNumber={} code={}",
partner.getLogin(), blockchainName, blockEntry.getBlockNumber(), backfillResult.code());
return;
}
}
log.info("AddBlock sync backfill ok: partner={} blockchainName={} from={} to={}",
partner.getLogin(), blockchainName, fromBlockNumber, blockNumber);
}
private AddBlockPushResult pushBlock(SyncServerEntry partner, String blockchainName, BlockEntry blockEntry) throws Exception {
JsonNode response = sendAddBlock(partner, blockchainName, blockEntry);
int status = response.path("status").asInt(500);
if (status >= 200 && status < 300) {
return AddBlockPushResult.success();
}
String code = textOrEmpty(response, "code");
if (code.isBlank()) {
code = textOrEmpty(response, "error");
}
JsonNode payload = response.path("payload");
int serverLastGlobalNumber = payload.path("serverLastGlobalNumber").asInt(Integer.MIN_VALUE);
String serverLastGlobalHash = payload.path("serverLastGlobalHash").asText("");
return new AddBlockPushResult(false, status, code, serverLastGlobalNumber, serverLastGlobalHash);
}
private JsonNode sendAddBlock(SyncServerEntry partner, String blockchainName, BlockEntry blockEntry) throws Exception {
String jsonTemplate = buildAddBlockJsonTemplate(blockchainName, blockEntry);
return ServerConnectionPool.getInstance().request(
partner.getLogin(),
partner.getServerAddress(),
jsonTemplate,
ServerConnectionPool.Priority.BULK);
}
private String buildAddBlockJsonTemplate(String blockchainName, BlockEntry blockEntry) throws Exception {
String prevHashHex = blockEntry.getBlockNumber() <= 0
? ""
: toHex(extractPrevHash32(blockEntry.getBlockBytes()));
String blockBytesB64 = Base64Ws.encode(blockEntry.getBlockBytes());
String safeBlockchainName = MAPPER.writeValueAsString(blockchainName);
String safePrevHashHex = MAPPER.writeValueAsString(prevHashHex);
String safeBlockBytes = MAPPER.writeValueAsString(blockBytesB64);
return """
{
"op":"AddBlock",
"requestId":%s,
"payload":{
"blockchainName":%s,
"blockNumber":%d,
"prevBlockHash":%s,
"blockBytesB64":%s
}
}
""".formatted("%s", safeBlockchainName, blockEntry.getBlockNumber(), safePrevHashHex, safeBlockBytes);
}
private static byte[] extractPrevHash32(byte[] blockBytes) {
if (blockBytes == null || blockBytes.length < 44) {
return new byte[32];
}
byte[] out = new byte[32];
System.arraycopy(blockBytes, 12, out, 0, 32);
return out;
}
private static String textOrEmpty(JsonNode node, String field) {
return node == null ? "" : node.path(field).asText("");
}
private static String normalize(String value) {
if (value == null) return null;
String s = value.trim().toLowerCase(Locale.ROOT);
return s.isEmpty() ? null : s;
}
private static String toHex(byte[] bytes) {
if (bytes == null) return "";
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
sb.append(Character.forDigit((b >>> 4) & 0xF, 16));
sb.append(Character.forDigit(b & 0xF, 16));
}
return sb.toString();
}
private record AddBlockPushResult(
boolean ok,
int status,
String code,
int serverLastGlobalNumber,
String serverLastGlobalHash
) {
static AddBlockPushResult success() {
return new AddBlockPushResult(true, 200, "", Integer.MIN_VALUE, "");
}
boolean needsBackfill() {
return !ok && ("bad_prev_hash".equalsIgnoreCase(code) || "bad_block_number".equalsIgnoreCase(code));
}
boolean serverAlreadyHasBlock(int targetBlockNumber) {
return !ok
&& serverLastGlobalNumber != Integer.MIN_VALUE
&& serverLastGlobalNumber >= targetBlockNumber;
}
}
}
@@ -1,167 +0,0 @@
package server.sync;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.List;
/**
* Минимальный клиент для межсерверных JSON-op запросов по WSS.
*/
public final class RemoteBlockchainSyncClient {
private static final ObjectMapper MAPPER = new ObjectMapper();
public List<RemoteBlockchainHead> listBlockchainHeads(String serverAddressRaw) throws Exception {
return listBlockchainHeads(null, serverAddressRaw);
}
public List<RemoteBlockchainHead> listBlockchainHeads(String serverLogin, String serverAddressRaw) throws Exception {
JsonNode response = send(serverLogin, serverAddressRaw, """
{
"op":"ListBlockchainHeads",
"requestId":%s,
"payload":{}
}
""");
int status = response.path("status").asInt(500);
if (status < 200 || status >= 300) {
throw new IllegalStateException("ListBlockchainHeads failed: status=" + status + " code=" + errorCode(response));
}
List<RemoteBlockchainHead> result = new ArrayList<>();
JsonNode items = response.path("payload").path("blockchains");
if (!items.isArray()) {
return result;
}
for (JsonNode item : items) {
result.add(new RemoteBlockchainHead(
item.path("blockchainName").asText(""),
item.path("lastBlockNumber").asInt(-1),
item.path("lastBlockHash").asText(""),
item.path("fileSizeBytes").asLong(0L)
));
}
return result;
}
public RemoteSyncUserProfile getSyncUserProfile(String serverAddressRaw, String login) throws Exception {
return getSyncUserProfile(null, serverAddressRaw, login);
}
public RemoteSyncUserProfile getSyncUserProfile(String serverLogin, String serverAddressRaw, String login) throws Exception {
String safeLogin = MAPPER.writeValueAsString(login);
JsonNode response = send(serverLogin, serverAddressRaw, """
{
"op":"GetSyncUserProfile",
"requestId":%s,
"payload":{
"login":%s
}
}
""".formatted("%s", safeLogin));
int status = response.path("status").asInt(500);
if (status == 404) {
return null;
}
if (status < 200 || status >= 300) {
throw new IllegalStateException("GetSyncUserProfile failed: status=" + status + " code=" + errorCode(response));
}
JsonNode payload = response.path("payload");
if (!payload.path("exists").asBoolean(false)) {
return null;
}
return new RemoteSyncUserProfile(
payload.path("login").asText(login),
payload.path("blockchainName").asText(""),
payload.path("solanaKey").asText(""),
payload.path("blockchainKey").asText(""),
payload.path("clientKey").asText(""),
payload.path("blockchainSizeLimitBytes").asLong(0L)
);
}
public RemoteBlockchainBlock getBlockchainBlock(
String serverAddressRaw, String blockchainName, int blockNumber
) throws Exception {
return getBlockchainBlock(null, serverAddressRaw, blockchainName, blockNumber);
}
public RemoteBlockchainBlock getBlockchainBlock(
String serverLogin, String serverAddressRaw, String blockchainName, int blockNumber
) throws Exception {
String safeBlockchainName = MAPPER.writeValueAsString(blockchainName);
JsonNode response = send(serverLogin, serverAddressRaw, """
{
"op":"GetBlockchainBlock",
"requestId":%s,
"payload":{
"blockchainName":%s,
"blockNumber":%d
}
}
""".formatted("%s", safeBlockchainName, blockNumber));
int status = response.path("status").asInt(500);
if (status == 404) {
return null;
}
if (status < 200 || status >= 300) {
throw new IllegalStateException("GetBlockchainBlock failed: status=" + status + " code=" + errorCode(response));
}
JsonNode payload = response.path("payload");
return new RemoteBlockchainBlock(
payload.path("blockchainName").asText(blockchainName),
payload.path("blockNumber").asInt(blockNumber),
payload.path("blockHash").asText(""),
payload.path("blockBytesB64").asText("")
);
}
private JsonNode send(String serverLogin, String serverAddressRaw, String jsonTemplate) throws Exception {
return ServerConnectionPool.getInstance().request(
serverLogin,
serverAddressRaw,
jsonTemplate,
ServerConnectionPool.Priority.BULK);
}
private static String errorCode(JsonNode response) {
String code = response.path("code").asText("");
if (!code.isBlank()) return code;
return response.path("error").asText("");
}
static String buildWsUrl(String serverAddressRaw) {
return ServerConnectionPool.buildWsUrl(serverAddressRaw);
}
public record RemoteBlockchainHead(
String blockchainName,
int lastBlockNumber,
String lastBlockHash,
long fileSizeBytes
) {}
public record RemoteBlockchainBlock(
String blockchainName,
int blockNumber,
String blockHash,
String blockBytesB64
) {}
public record RemoteSyncUserProfile(
String login,
String blockchainName,
String solanaKey,
String blockchainKey,
String clientKey,
long blockchainSizeLimitBytes
) {}
}
@@ -4,9 +4,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import shine.db.dao.SyncServersDAO;
import shine.db.dao.UserAccessServersCurrentDAO; import shine.db.dao.UserAccessServersCurrentDAO;
import shine.db.entities.SyncServerEntry;
import shine.db.entities.UserAccessServerRouteEntry; import shine.db.entities.UserAccessServerRouteEntry;
import utils.config.AppConfig; import utils.config.AppConfig;
@@ -136,10 +134,6 @@ public final class ServerConnectionPool implements AutoCloseable {
try { try {
String ownLogin = normalizeLogin(AppConfig.getInstance().getParam(SERVER_LOGIN_CONFIG)); String ownLogin = normalizeLogin(AppConfig.getInstance().getParam(SERVER_LOGIN_CONFIG));
Map<String, String> discovered = new LinkedHashMap<>(); Map<String, String> discovered = new LinkedHashMap<>();
for (SyncServerEntry entry : SyncServersDAO.getInstance().listAll()) {
if (entry == null) continue;
putDiscovered(discovered, ownLogin, entry.getLogin(), entry.getServerAddress());
}
for (UserAccessServerRouteEntry entry : UserAccessServersCurrentDAO.getInstance().listDistinctServers()) { for (UserAccessServerRouteEntry entry : UserAccessServersCurrentDAO.getInstance().listDistinctServers()) {
if (entry == null) continue; if (entry == null) continue;
putDiscovered(discovered, ownLogin, entry.getServerLogin(), entry.getServerUrl()); putDiscovered(discovered, ownLogin, entry.getServerLogin(), entry.getServerUrl());
@@ -0,0 +1,90 @@
package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain.*;
import blockchain.body.*;
import shine.db.entities.BlockEntry;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.LineContinuity;
import utils.crypto.Ed25519Util;
import java.util.Arrays;
import java.util.List;
import static blockchain.MsgSubType.*;
/** Автономный тест фактического парсера и вычисления старого индекса по каноническому хвосту. */
public final class M2LineContinuityCheck {
private static final byte[] SEED = new byte[32], OWNER = Ed25519Util.derivePublicKey(SEED);
private static int checks;
private static void ok(boolean b, String msg) { if (!b) throw new AssertionError(msg); checks++; }
private static BchBlockEntry pair(int n, byte[] prev, int type, int sub, BodyRecord body, CoreRecord.Line line) {
byte[] bytes = body.toBytes();
if (body instanceof BodyHasLine) bytes = Arrays.copyOfRange(bytes, type == 3 || type == 4 ? 40 : 44, bytes.length);
var c = new ContentRecord(type, sub, 1, bytes);
var content = CoreContentTransport.sign(c.toBytes(), List.of(), SEED);
var core = new CoreRecord(prev, n, 1700001000L, c.contentHash32(), content.id32(), line);
var item = CoreContentTransport.sign(core.toBytes(), CoreContentTransport.coreTags(core), SEED);
var packed = CoreContentContainer.pack(item, content);
var entry = BchBlockEntry.fromCoreContent(packed);
ok(Arrays.equals(packed, entry.toBytes()), "original bytes");
ok(Arrays.equals(item.id32(), entry.getDataItemId32()), "CORE DataItem ID");
ok(Arrays.equals(core.coreHash32(), entry.getHash32()), "CORE hash");
ok(BchCryptoVerifier.verifyBlock(entry, OWNER), "authorized owner");
byte[] wrong = OWNER.clone(); wrong[0] ^= 1;
ok(!BchCryptoVerifier.verifyBlock(entry, wrong), "wrong owner");
return entry;
}
private static BlockEntry row(BchBlockEntry b, Integer seq) {
var r = new BlockEntry(); r.setBlockNumber(b.blockNumber); r.setBlockBytes(b.toBytes());
r.setBlockHash(b.getHash32()); r.setDataItemId(b.getDataItemId32()); r.setThisLineNumber(seq);
return r;
}
private static CoreRecord.Line line(int code, BlockEntry prior) {
return new CoreRecord.Line(code, prior.getBlockNumber(), prior.getBlockHash());
}
private static TextLineBody text(int root, BlockEntry prev, short subtype, Integer target, byte[] targetHash) {
return new TextLineBody(root, prev.getBlockNumber(), prev.getBlockHash(), 0, subtype, null, null, target, targetHash, "test");
}
private static void seq(BchBlockEntry b, int rootNumber, int first, BlockEntry root, BlockEntry tail, int expected) {
var body = (BodyHasLine)b.body;
ok(body.lineSeq() == BodyHasLine.UNRESOLVED_SEQUENCE, "no signed ordinal");
var result = LineContinuity.resolve(body, rootNumber, first, root, tail);
ok(result.error() == null && result.sequence() == expected, "server ordinal " + result);
}
public static void main(String[] args) {
var h = pair(0,new byte[32],0,HEADER_COMPAT,HeaderBody.forCoreContent("Alice@shine",OWNER),null);
var root = row(h,null);
var post = pair(1,h.getHash32(),1,TEXT_POST,text(0,root,TEXT_POST,null,null),line(0,root));
seq(post,0,0,root,null,0);
var postRow = row(post,0);
var create = pair(2,post.getHash32(),0,TECH_CREATE_CHANNEL,
new CreateChannelBody(0,0,root.getBlockHash(),1,"News","",(short)1,(short)1),line(CoreRecord.TECH,root));
seq(create,0,1,root,null,1);
ok(((BodyHasLine)create.body).lineCode()==0, "TECH SQL index");
var channelRoot = row(create,1);
var channelPost = pair(3,create.getHash32(),1,TEXT_POST,text(2,channelRoot,TEXT_POST,null,null),line(2,channelRoot));
seq(channelPost,2,0,channelRoot,null,0);
var cp = row(channelPost,0);
var edit = pair(4,channelPost.getHash32(),1,TEXT_EDIT_POST,text(2,cp,TEXT_EDIT_POST,3,cp.getBlockHash()),line(2,cp));
seq(edit,2,0,channelRoot,cp,1);
var profile = pair(5,edit.getHash32(),4,USER_PARAM_TEXT_TEXT,new UserParamBody(0,root.getBlockHash(),1,"name","Alice"),line(CoreRecord.PROFILE,root));
seq(profile,0,1,root,null,1);
ok(((BodyHasLine)profile.body).lineCode()==0, "PROFILE SQL index");
var conn = pair(6,profile.getHash32(),3,CONNECTION_FOLLOW,new ConnectionBody(0,root.getBlockHash(),1,CONNECTION_FOLLOW,"Bob",1,0,root.getBlockHash()),line(CoreRecord.CONNECTION,root));
seq(conn,0,1,root,null,1);
ok(((BodyHasLine)conn.body).lineCode()==0, "CONNECTION SQL index");
var reply = pair(7,conn.getHash32(),1,TEXT_REPLY,new TextReplyBody(TEXT_REPLY,"Alice@shine",1,3,cp.getBlockHash(),"reply"),null);
ok(!(reply.body instanceof BodyHasLine),"reply has no line");
var like = pair(8,reply.getHash32(),2,REACTION_LIKE,new ReactionBody(REACTION_LIKE,"Alice@shine",1,3,cp.getBlockHash()),null);
ok(!(like.body instanceof BodyHasLine),"reaction has no line");
var defaultNext = pair(9,like.getHash32(),1,TEXT_POST,text(0,postRow,TEXT_POST,null,null),line(0,postRow));
seq(defaultNext,0,0,root,postRow,1);
var body = (BodyHasLine)defaultNext.body;
ok("bad_prev_line_number".equals(LineContinuity.resolve(body,0,0,root,null).error()), "wrong tail number");
var broken = row(post,0); broken.setBlockHash(new byte[32]);
ok("bad_prev_line_hash".equals(LineContinuity.resolve(body,0,0,root,broken).error()), "wrong tail hash");
broken.setThisLineNumber(-1);
ok("bad_line_state".equals(LineContinuity.resolve(body,0,0,root,broken).error()), "unresolved stored ordinal");
broken.setThisLineNumber(Integer.MAX_VALUE);
ok("bad_line_state".equals(LineContinuity.resolve(body,0,0,root,broken).error()), "ordinal overflow");
ok("line_root_not_found".equals(LineContinuity.resolve(body,0,0,null,null).error()), "missing root");
System.out.println("PASS M2 parser/line-index checks: " + checks + " assertions (no PostgreSQL)");
}
}
@@ -0,0 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.blockchain;
import org.junit.jupiter.api.Test;
final class M2LineContinuityTest {
@Test void signedPairsAndServerOrdinals() { M2LineContinuityCheck.main(new String[0]); }
}
@@ -52,8 +52,8 @@ public final class KeyRotationRebuildService {
try(PreparedStatement d=c.prepareStatement("DELETE FROM key_rotation_rebuild_staging WHERE rotation_session_id=?")){d.setLong(1,s.getId());d.executeUpdate();} try(PreparedStatement d=c.prepareStatement("DELETE FROM key_rotation_rebuild_staging WHERE rotation_session_id=?")){d.setLong(1,s.getId());d.executeUpdate();}
String ins="INSERT INTO key_rotation_rebuild_staging(rotation_session_id,logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash) VALUES(?,?,?,?,?,?)"; String ins="INSERT INTO key_rotation_rebuild_staging(rotation_session_id,logical_block_number,physical_fork_number,blockchain_key,block_bytes,block_hash) VALUES(?,?,?,?,?,?)";
try(PreparedStatement ps=c.prepareStatement(ins)){ try(PreparedStatement ps=c.prepareStatement(ins)){
for(int n=0;n<=s.getForkFromBlock();n++){BlockEntry e=canonical.getBlock(c,s.getSourceBlockchainName(),n);if(e==null)throw new IllegalStateException("canonical block missing #"+n);BchBlockEntry b=new BchBlockEntry(e.getBlockBytes());ps.setLong(1,s.getId());ps.setInt(2,n);ps.setInt(3,e.getForkNumber());ps.setString(4,Base64.getEncoder().encodeToString(b.getOwner32()));ps.setBytes(5,e.getBlockBytes());ps.setBytes(6,e.getBlockHash());ps.addBatch();} for(int n=0;n<=s.getForkFromBlock();n++){BlockEntry e=canonical.getBlock(c,s.getSourceBlockchainName(),n);if(e==null)throw new IllegalStateException("canonical block missing #"+n);BchBlockEntry b=BchBlockEntry.fromCoreContent(e.getBlockBytes());ps.setLong(1,s.getId());ps.setInt(2,n);ps.setInt(3,e.getForkNumber());ps.setString(4,Base64.getEncoder().encodeToString(b.getOwner32()));ps.setBytes(5,e.getBlockBytes());ps.setBytes(6,e.getBlockHash());ps.addBatch();}
BchBlockEntry b=new BchBlockEntry(tech.getBlockBytes());ps.setLong(1,s.getId());ps.setInt(2,b.blockNumber);ps.setInt(3,forkOf(s.getCandidateBlockchainName()));ps.setString(4,s.getNewBlockchainKey());ps.setBytes(5,tech.getBlockBytes());ps.setBytes(6,tech.getBlockHash());ps.addBatch();ps.executeBatch(); BchBlockEntry b=BchBlockEntry.fromCoreContent(tech.getBlockBytes());ps.setLong(1,s.getId());ps.setInt(2,b.blockNumber);ps.setInt(3,forkOf(s.getCandidateBlockchainName()));ps.setString(4,s.getNewBlockchainKey());ps.setBytes(5,tech.getBlockBytes());ps.setBytes(6,tech.getBlockHash());ps.addBatch();ps.executeBatch();
}c.commit();}catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(ac);}} }c.commit();}catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(ac);}}
} }
private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}} private void registerCandidateSegment(KeyRotationSessionEntry s)throws Exception{try(Connection c=DbController.getInstance().getConnection()){segments.upsert(c,new BlockchainForkSegmentsDAO.Segment(s.getLogin(),forkOf(s.getCandidateBlockchainName()),forkOf(s.getSourceBlockchainName()),s.getForkFromBlock(),s.getForkFromHash(),s.getForkFromBlock()+1,System.currentTimeMillis()));}}
@@ -70,18 +70,18 @@ public final class KeyRotationRebuildService {
private void validateStaging(KeyRotationSessionEntry s)throws Exception{ private void validateStaging(KeyRotationSessionEntry s)throws Exception{
int expected=0,last=-1;byte[] previousHash=null; int expected=0,last=-1;byte[] previousHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){ try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM key_rotation_rebuild_staging WHERE rotation_session_id=? ORDER BY logical_block_number ASC")){
ps.setLong(1,s.getId());try(ResultSet rs=ps.executeQuery()){while(rs.next()){int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("rebuild staging gap: expected #"+expected+" got #"+n);BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("rebuild staging block number mismatch #"+n);if(n==0 && !(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical history must start with HEADER #0");if(n>0 && (previousHash==null||!Arrays.equals(b.prevHash32,previousHash)))throw new IllegalStateException("rebuild staging prevHash mismatch #"+n);if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("rebuild staging hash mismatch #"+n);previousHash=hash;last=n;expected++;}} ps.setLong(1,s.getId());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("rebuild staging gap: expected #"+expected+" got #"+n);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("rebuild staging block number mismatch #"+n);if(n==0 && !(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical history must start with HEADER #0");if(n>0 && (previousHash==null||!Arrays.equals(b.prevHash32,previousHash)))throw new IllegalStateException("rebuild staging prevHash mismatch #"+n);if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("rebuild staging hash mismatch #"+n);previousHash=hash;last=n;expected++;}}
} }
int expectedTip=s.getForkFromBlock()+1;if(last!=expectedTip)throw new IllegalStateException("rebuild staging tip mismatch: expected #"+expectedTip+" got #"+last); int expectedTip=s.getForkFromBlock()+1;if(last!=expectedTip)throw new IllegalStateException("rebuild staging tip mismatch: expected #"+expectedTip+" got #"+last);
} }
private void verifyReplayResult(KeyRotationSessionEntry s,KeyRotationCandidateBlockEntry tech)throws Exception{ private void verifyReplayResult(KeyRotationSessionEntry s,KeyRotationCandidateBlockEntry tech)throws Exception{
BlockchainStateEntry st=states.getByBlockchainName(s.getCandidateBlockchainName());if(st==null)throw new IllegalStateException("candidate blockchain state missing after replay"); BlockchainStateEntry st=states.getByBlockchainName(s.getCandidateBlockchainName());if(st==null)throw new IllegalStateException("candidate blockchain state missing after replay");
BchBlockEntry b=new BchBlockEntry(tech.getBlockBytes()); BchBlockEntry b=BchBlockEntry.fromCoreContent(tech.getBlockBytes());
if(st.getLastBlockNumber()!=b.blockNumber)throw new IllegalStateException("replay tip number mismatch"); if(st.getLastBlockNumber()!=b.blockNumber)throw new IllegalStateException("replay tip number mismatch");
if(st.getLastBlockHash()==null||!Arrays.equals(st.getLastBlockHash(),b.getHash32()))throw new IllegalStateException("replay tip hash mismatch"); if(st.getLastBlockHash()==null||!Arrays.equals(st.getLastBlockHash(),b.getHash32()))throw new IllegalStateException("replay tip hash mismatch");
BlockEntry zero=canonical.getBlock(s.getCandidateBlockchainName(),0);if(zero==null){throw new IllegalStateException("canonical HEADER #0 missing after replay");} BlockEntry zero=canonical.getBlock(s.getCandidateBlockchainName(),0);if(zero==null){throw new IllegalStateException("canonical HEADER #0 missing after replay");}
BchBlockEntry header=new BchBlockEntry(zero.getBlockBytes());if(!(header.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical block #0 is not HEADER"); BchBlockEntry header=BchBlockEntry.fromCoreContent(zero.getBlockBytes());if(!(header.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical block #0 is not HEADER");
} }
private void clearStaging(long id)throws SQLException{try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("DELETE FROM key_rotation_rebuild_staging WHERE rotation_session_id=?")){ps.setLong(1,id);ps.executeUpdate();}} private void clearStaging(long id)throws SQLException{try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("DELETE FROM key_rotation_rebuild_staging WHERE rotation_session_id=?")){ps.setLong(1,id);ps.executeUpdate();}}
@@ -1,427 +0,0 @@
package server.sync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.entyties.Net_Exception_Response;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.SyncServersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.entities.SyncServerEntry;
import server.sync.BlockchainResyncGuard;
import utils.blockchain.BlockchainNameUtil;
import utils.config.AppConfig;
import java.util.concurrent.locks.ReentrantLock;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* @deprecated Legacy direct server-to-server blockchain sync. Not compatible with segmented forks; Arweave/Turbo is supported.
* Плановый межсерверный sync блокчейнов.
* Сейчас реализует:
* - догоняющую синхронизацию отсутствующего хвоста;
* - базовый full-resync при divergence, если удалённая цепочка сильнее.
*/
@Deprecated
public final class PeriodicBlockchainSyncService {
private static final Logger log = LoggerFactory.getLogger(PeriodicBlockchainSyncService.class);
private static final long PERIOD_HOURS = 12L;
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
private static final ScheduledExecutorService EXECUTOR = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "periodic-blockchain-sync");
t.setDaemon(true);
return t;
}
});
private static final RemoteBlockchainSyncClient REMOTE = new RemoteBlockchainSyncClient();
private static final Net_AddBlock_Handler ADD_BLOCK_HANDLER = new Net_AddBlock_Handler();
private static final BlockchainStateDAO STATE_DAO = BlockchainStateDAO.getInstance();
private static final SyncServersDAO SYNC_SERVERS_DAO = SyncServersDAO.getInstance();
private static final BlockchainResyncCleanupDAO RESYNC_CLEANUP_DAO = BlockchainResyncCleanupDAO.getInstance();
private static final SolanaUserPdaCurrentDAO SOLANA_USER_PDA_CURRENT_DAO = SolanaUserPdaCurrentDAO.getInstance();
private PeriodicBlockchainSyncService() {}
public static void startOrLog() {
if (!isEnabled()) {
log.info("Periodic blockchain sync disabled by blockchain.sync.enabled=false");
return;
}
if (!STARTED.compareAndSet(false, true)) {
return;
}
EXECUTOR.scheduleWithFixedDelay(
PeriodicBlockchainSyncService::runCycleSafe,
0L,
PERIOD_HOURS,
TimeUnit.HOURS
);
log.info("Periodic blockchain sync scheduled: startup + every {} hours", PERIOD_HOURS);
}
private static boolean isEnabled() {
// PDA 1.2 удаляет sync_servers: пользовательские блокчейны синхронизируются через Arweave.
return false;
}
private static void runCycleSafe() {
try {
runCycle();
} catch (Exception e) {
log.error("Periodic blockchain sync failed unexpectedly", e);
}
}
private static void runCycle() throws Exception {
SyncServersBootstrapService.refreshFromSolanaOrLog();
List<SyncServerEntry> partners = SYNC_SERVERS_DAO.listAll();
if (partners.isEmpty()) {
log.info("Periodic blockchain sync skipped: sync_servers is empty");
return;
}
for (SyncServerEntry partner : partners) {
if (partner == null) continue;
try {
syncPartner(partner);
} catch (Exception e) {
log.warn("Periodic blockchain sync partner failed: login={} reason={}",
partner.getLogin(), String.valueOf(e));
}
}
}
private static void syncPartner(SyncServerEntry partner) throws Exception {
String partnerLogin = normalize(partner.getLogin());
if (partnerLogin == null) return;
List<RemoteBlockchainSyncClient.RemoteBlockchainHead> remoteHeads =
REMOTE.listBlockchainHeads(partner.getLogin(), partner.getServerAddress());
for (RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead : remoteHeads) {
if (remoteHead == null || remoteHead.blockchainName() == null || remoteHead.blockchainName().isBlank()) {
continue;
}
BlockchainStateEntry localState = STATE_DAO.getByBlockchainName(remoteHead.blockchainName());
if (localState == null) {
syncMissingTail(partner, remoteHead, -1, "");
continue;
}
int localLast = localState.getLastBlockNumber();
String localHash = toHex32(localState.getLastBlockHash());
if (localLast < remoteHead.lastBlockNumber()) {
syncMissingTail(partner, remoteHead, localLast, localHash);
continue;
}
if (localLast == remoteHead.lastBlockNumber()) {
if (localHash.equalsIgnoreCase(remoteHead.lastBlockHash())) {
continue;
}
if (isRemoteStronger(localState, remoteHead)) {
log.warn("Periodic blockchain sync: divergence detected, remote chain is stronger, starting full resync. partner={} blockchainName={} localLast={} localHash={} remoteHash={} localSize={} remoteSize={}",
partnerLogin,
remoteHead.blockchainName(),
localLast,
localHash,
remoteHead.lastBlockHash(),
localState.getFileSizeBytes(),
remoteHead.fileSizeBytes());
resyncFromScratch(partner, remoteHead);
} else {
log.info("Periodic blockchain sync skipped: local chain is stronger or equal. partner={} blockchainName={} localLast={} remoteLast={} localSize={} remoteSize={}",
partnerLogin,
remoteHead.blockchainName(),
localLast,
remoteHead.lastBlockNumber(),
localState.getFileSizeBytes(),
remoteHead.fileSizeBytes());
}
continue;
}
log.info("Periodic blockchain sync skipped: local chain is not weaker. partner={} blockchainName={} localLast={} remoteLast={}",
partnerLogin, remoteHead.blockchainName(), localLast, remoteHead.lastBlockNumber());
}
}
private static void syncMissingTail(
SyncServerEntry partner,
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead,
int localLast,
String localHash
) throws Exception {
String partnerLogin = normalize(partner.getLogin());
if (!ensureLocalChainExists(partner, remoteHead.blockchainName())) {
log.warn("Periodic blockchain sync: cannot prepare local chain. partner={} blockchainName={}",
partnerLogin, remoteHead.blockchainName());
return;
}
int fromBlockNumber = Math.max(localLast + 1, 0);
for (int blockNumber = fromBlockNumber; blockNumber <= remoteHead.lastBlockNumber(); blockNumber++) {
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock =
REMOTE.getBlockchainBlock(
partner.getLogin(), partner.getServerAddress(), remoteHead.blockchainName(), blockNumber);
if (remoteBlock == null) {
log.warn("Periodic blockchain sync: remote block not found. partner={} blockchainName={} blockNumber={}",
partnerLogin, remoteHead.blockchainName(), blockNumber);
return;
}
LocalAddBlockApplyResult result = applyBlockLocally(remoteBlock, blockNumber == 0 ? "" : localHash);
if (!result.ok()) {
if ("bad_prev_hash".equalsIgnoreCase(result.code()) || "bad_block_number".equalsIgnoreCase(result.code())) {
log.warn("Periodic blockchain sync: divergence detected during replay, starting full resync. partner={} blockchainName={} blockNumber={} code={}",
partnerLogin, remoteHead.blockchainName(), blockNumber, result.code());
resyncFromScratch(partner, remoteHead);
} else {
log.warn("Periodic blockchain sync: local AddBlock rejected remote block. partner={} blockchainName={} blockNumber={} code={} message={}",
partnerLogin, remoteHead.blockchainName(), blockNumber, result.code(), result.message());
}
return;
}
localHash = result.serverLastHash();
}
log.info("Periodic blockchain sync ok: partner={} blockchainName={} from={} to={}",
partnerLogin, remoteHead.blockchainName(), fromBlockNumber, remoteHead.lastBlockNumber());
}
static void resyncFromScratch(
SyncServerEntry partner,
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead
) throws Exception {
if (partner == null || remoteHead == null || remoteHead.blockchainName() == null || remoteHead.blockchainName().isBlank()) {
return;
}
String blockchainName = remoteHead.blockchainName();
String partnerLogin = normalize(partner.getLogin());
if (!BlockchainResyncGuard.tryBegin(blockchainName)) {
log.warn("Blockchain resync skipped: already in progress for blockchainName={}", blockchainName);
return;
}
ReentrantLock chainLock = BlockchainLocks.lockFor(blockchainName);
chainLock.lock();
boolean success = false;
try {
BlockchainResyncCleanupDAO.CleanupResult cleanup =
RESYNC_CLEANUP_DAO.cleanupBlockchainForFullResync(blockchainName);
log.info("Blockchain resync cleanup finished: blockchainName={} login={} deletedReactionsState={} deletedConnectionsState={} deletedBlocks={} deletedState={}",
blockchainName,
cleanup.login(),
cleanup.deletedReactionsStateRows(),
cleanup.deletedConnectionsStateRows(),
cleanup.deletedBlocksRows(),
cleanup.deletedBlockchainStateRows());
if (!ensureLocalChainExists(partner, blockchainName)) {
throw new IllegalStateException("failed to recreate local chain state for " + blockchainName);
}
boolean replayOk = replayRemoteChainFromStart(partner, remoteHead);
if (!replayOk) {
throw new IllegalStateException("failed to replay remote chain for " + blockchainName);
}
success = true;
log.info("Blockchain resync completed: partner={} blockchainName={} blocks=0..{}",
partnerLogin, blockchainName, remoteHead.lastBlockNumber());
} finally {
chainLock.unlock();
BlockchainResyncGuard.end(blockchainName);
}
if (!success) {
throw new IllegalStateException("Blockchain resync did not complete for " + blockchainName);
}
}
private static boolean replayRemoteChainFromStart(
SyncServerEntry partner,
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead
) throws Exception {
String blockchainName = remoteHead.blockchainName();
String partnerLogin = normalize(partner.getLogin());
return BlockchainResyncGuard.withBypass(blockchainName, () -> {
String localPrevHash = "";
for (int blockNumber = 0; blockNumber <= remoteHead.lastBlockNumber(); blockNumber++) {
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock =
REMOTE.getBlockchainBlock(
partner.getLogin(), partner.getServerAddress(), blockchainName, blockNumber);
if (remoteBlock == null) {
log.warn("Blockchain resync: remote block not found. partner={} blockchainName={} blockNumber={}",
partnerLogin, blockchainName, blockNumber);
return false;
}
LocalAddBlockApplyResult result = applyBlockLocally(remoteBlock, localPrevHash);
if (!result.ok()) {
log.warn("Blockchain resync: AddBlock rejected replay block. partner={} blockchainName={} blockNumber={} code={} message={}",
partnerLogin, blockchainName, blockNumber, result.code(), result.message());
return false;
}
localPrevHash = result.serverLastHash();
}
return true;
});
}
private static boolean isRemoteStronger(BlockchainStateEntry localState,
RemoteBlockchainSyncClient.RemoteBlockchainHead remoteHead) {
if (localState == null || remoteHead == null) return false;
int localLast = localState.getLastBlockNumber();
int remoteLast = remoteHead.lastBlockNumber();
if (remoteLast != localLast) {
return remoteLast > localLast;
}
long localSize = localState.getFileSizeBytes();
long remoteSize = remoteHead.fileSizeBytes();
if (remoteSize != localSize) {
return remoteSize > localSize;
}
String localHash = toHex32(localState.getLastBlockHash()).toLowerCase(Locale.ROOT);
String remoteHash = normalizeHex64(remoteHead.lastBlockHash());
return remoteHash.compareTo(localHash) > 0;
}
private static LocalAddBlockApplyResult applyBlockLocally(
RemoteBlockchainSyncClient.RemoteBlockchainBlock remoteBlock,
String prevHash
) {
Net_AddBlock_Request req = new Net_AddBlock_Request();
req.setOp("AddBlock");
req.setRequestId("periodic-sync-local");
req.setBlockchainName(remoteBlock.blockchainName());
req.setBlockNumber(remoteBlock.blockNumber());
req.setPrevBlockHash(prevHash == null ? "" : prevHash);
req.setBlockBytesB64(remoteBlock.blockBytesB64());
Net_Response response = ADD_BLOCK_HANDLER.handle(req, null);
if (response.getStatus() >= 200 && response.getStatus() < 300) {
server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response ok =
(server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Response) response;
return new LocalAddBlockApplyResult(true, "", "", ok.getServerLastGlobalHash());
}
Net_Exception_Response error = (Net_Exception_Response) response;
return new LocalAddBlockApplyResult(false, error.getCode(), error.getMessage(), "");
}
private static boolean ensureLocalChainExists(SyncServerEntry partner, String blockchainName) {
try {
BlockchainStateEntry existingState = STATE_DAO.getByBlockchainName(blockchainName);
if (hasValidBlockchainKey(existingState)) {
return true;
}
if (ensureLocalChainStateFromCurrentPostgresSnapshot(blockchainName, existingState)) {
return true;
}
String login = BlockchainNameUtil.loginFromBlockchainName(blockchainName);
if (login == null || login.isBlank()) {
return false;
}
return false;
} catch (Exception e) {
log.warn("Periodic blockchain sync: failed to ensure local chain exists for blockchainName={} reason={}",
blockchainName, String.valueOf(e));
return false;
}
}
private static boolean ensureLocalChainStateFromCurrentPostgresSnapshot(String blockchainName,
BlockchainStateEntry existingState) throws Exception {
SolanaUserPdaCurrentEntry currentUser = SOLANA_USER_PDA_CURRENT_DAO.getByBlockchainName(blockchainName);
if (currentUser == null) {
return false;
}
BlockchainStateEntry state = new BlockchainStateEntry();
state.setBlockchainName(currentUser.getBlockchainName());
state.setLogin(currentUser.getLogin());
state.setBlockchainKey(currentUser.getBlockchainKey());
state.setSizeLimit(currentUser.getPaidLimitBytes());
state.setFileSizeBytes(existingState == null ? 0L : existingState.getFileSizeBytes());
state.setLastBlockNumber(existingState == null ? -1 : existingState.getLastBlockNumber());
state.setLastBlockHash(existingState == null ? null : existingState.getLastBlockHash());
state.setUpdatedAtMs(System.currentTimeMillis());
if (existingState == null) {
STATE_DAO.insertIfMissing(state);
} else {
STATE_DAO.upsert(state);
}
return hasValidBlockchainKey(STATE_DAO.getByBlockchainName(blockchainName));
}
private static boolean hasValidBlockchainKey(BlockchainStateEntry state) {
if (state == null) {
return false;
}
byte[] keyBytes = state.getBlockchainKeyBytes();
return keyBytes != null && keyBytes.length == 32;
}
private static String normalize(String value) {
if (value == null) return null;
String s = value.trim().toLowerCase(Locale.ROOT);
return s.isEmpty() ? null : s;
}
private static String toHex32(byte[] bytes32) {
byte[] bytes = bytes32;
if (bytes == null || bytes.length != 32) {
bytes = new byte[32];
}
StringBuilder sb = new StringBuilder(64);
for (byte b : bytes) {
sb.append(Character.forDigit((b >>> 4) & 0xF, 16));
sb.append(Character.forDigit(b & 0xF, 16));
}
return sb.toString();
}
private static String normalizeHex64(String value) {
if (value == null) return "";
String s = value.trim().toLowerCase(Locale.ROOT);
return s.length() == 64 ? s : "";
}
private record LocalAddBlockApplyResult(
boolean ok,
String code,
String message,
String serverLastHash
) {}
}
@@ -1,42 +0,0 @@
package server.sync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.auth.SolanaUserPdaImportService;
import shine.db.dao.SyncServersDAO;
import shine.db.entities.SyncServerEntry;
import utils.config.AppConfig;
import java.util.ArrayList;
import java.util.List;
/**
* При старте сервера читает server PDA текущего сервера, затем PDA партнёров из
* sync_servers и сохраняет их логины/адреса в локальную таблицу sync_servers.
*/
public final class SyncServersBootstrapService {
private static final Logger log = LoggerFactory.getLogger(SyncServersBootstrapService.class);
private static final String CONFIG_KEY = "server.SHiNE.login";
private SyncServersBootstrapService() {}
public static void refreshFromSolanaOrLog() {
try {
SyncServersDAO.getInstance().replaceAll(List.of());
log.info("Legacy sync_servers disabled: blockchain synchronization uses Arweave");
} catch (Exception e) {
log.warn("Failed to clear legacy sync_servers table", e);
}
}
private static String normalize(String value) {
if (value == null) return null;
String s = value.trim().toLowerCase();
return s.isEmpty() ? null : s;
}
private static String safe(String value) {
return value == null ? "" : value.trim();
}
}
@@ -14,10 +14,8 @@ import server.archive.ArweaveBlockSyncScheduler;
import server.debug.DebugApiConfigurator; import server.debug.DebugApiConfigurator;
import server.files.DmFileApiConfigurator; import server.files.DmFileApiConfigurator;
import server.files.PublicFileApiConfigurator; import server.files.PublicFileApiConfigurator;
import server.sync.PeriodicBlockchainSyncService;
import server.sync.PeriodicDmDeliveryService; import server.sync.PeriodicDmDeliveryService;
import server.sync.SolanaUsersSyncStartupService; import server.sync.SolanaUsersSyncStartupService;
import server.sync.SyncServersBootstrapService;
import server.sync.ServerConnectionPool; import server.sync.ServerConnectionPool;
import shine.db.DbController; import shine.db.DbController;
import utils.config.AppConfig; import utils.config.AppConfig;
@@ -61,18 +59,6 @@ public final class WsServer {
log.info("Не удалось прочитать параметр server.port, используем порт по умолчанию {}", port); log.info("Не удалось прочитать параметр server.port, используем порт по умолчанию {}", port);
} }
// ============================================================
// 1.1) Загрузка списка серверов синхронизации из Solana PDA
// ============================================================
// Legacy direct server-to-server sync is retired. Do not bootstrap sync_servers.
// Arweave/Turbo is the supported blockchain recovery/synchronization source.
// ============================================================
// 1.2) Плановый межсерверный sync блокчейнов
// ============================================================
// Legacy direct server-to-server blockchain sync is intentionally disabled.
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers. // ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
FreeRegistrationApiBootstrap.startOrThrow(); FreeRegistrationApiBootstrap.startOrThrow();
ArweaveBlockPublisherScheduler.startOrLog(); ArweaveBlockPublisherScheduler.startOrLog();
@@ -2,7 +2,10 @@ package test.it.blockchain;
import blockchain.Ans104DataItem; import blockchain.Ans104DataItem;
import blockchain.BchBlockEntry; import blockchain.BchBlockEntry;
import blockchain.ShineProtocolTags; import blockchain.CoreRecord;
import blockchain.ContentRecord;
import blockchain.CoreContentTransport;
import blockchain.CoreContentContainer;
import blockchain.body.*; import blockchain.body.*;
import test.it.utils.TestConfig; import test.it.utils.TestConfig;
import test.it.utils.TestIds; import test.it.utils.TestIds;
@@ -11,19 +14,16 @@ import test.it.utils.log.TestLog;
import test.it.utils.ws.WsSession; import test.it.utils.ws.WsSession;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList; import java.util.Arrays;
import java.util.Base64; import java.util.Base64;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
/** /**
* AddBlockSender для Frame v1: blockBytesB64 содержит готовый ANS-104 DataItem. * AddBlockSender для CORE/CONTENT: сохраняет прежние сценарии тестов,
* SHiNE hash цепочки остаётся SHA-256(Frame v1 bytes), а пользователь подписывает * но подписывает пару и передаёт один контейнер.
* ANS-104 deep-hash одним Ed25519 ключом.
*/ */
public final class AddBlockSender { public final class AddBlockSender {
@@ -35,7 +35,6 @@ public final class AddBlockSender {
private final String login; private final String login;
private final String blockchainName; private final String blockchainName;
private final byte[] loginPrivKey; private final byte[] loginPrivKey;
private final Map<Integer, String> channelSlugByRoot = new HashMap<>();
public AddBlockSender(WsSession ws, ChainState state, String login, String blockchainName, byte[] loginPrivKey) { public AddBlockSender(WsSession ws, ChainState state, String login, String blockchainName, byte[] loginPrivKey) {
this.ws = ws; this.ws = ws;
@@ -69,29 +68,32 @@ public final class AddBlockSender {
int blockNumber = state.nextBlockNumber(); int blockNumber = state.nextBlockNumber();
byte[] prevHash32 = state.prevHash32ForNext(); byte[] prevHash32 = state.prevHash32ForNext();
byte[] back32Hash32 = state.back32Hash32ForNext();
long tsSec = System.currentTimeMillis() / 1000L; long tsSec = System.currentTimeMillis() / 1000L;
short type = typeOf(body); short type = typeOf(body);
short subType = subTypeOf(body); short subType = subTypeOf(body);
short version = versionOf(body); short version = versionOf(body);
// Старые test fixtures задают sequence для локального ChainState.
// В подписанный CONTENT старый структурный префикс не попадает.
byte[] bodyBytes = body.toBytes(); byte[] bodyBytes = body.toBytes();
CoreRecord.Line line = null;
byte[] frame = buildFrame(prevHash32, back32Hash32, blockNumber, tsSec, type, subType, version, bodyBytes); if (body instanceof BodyHasLine l) {
byte[] owner32 = utils.crypto.Ed25519Util.derivePublicKey(loginPrivKey); int code = switch (type) {
case 0 -> CoreRecord.TECH;
List<Ans104DataItem.Tag> tags = new ArrayList<>(); case 3 -> CoreRecord.CONNECTION;
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)); case 4 -> CoreRecord.PROFILE;
String typeTag = typeTagFor(type); default -> l.lineCode();
if (typeTag != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.TYPE_TAG_NAME, typeTag)); };
String channelSlug = channelSlugFor(body); line = new CoreRecord.Line(code, l.prevLineBlockGlobalNumber(), l.prevLineBlockHash32());
if (channelSlug != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CHANNEL_TAG_NAME, channelSlug)); int prefix = (type == 3 || type == 4) ? 40 : 44;
bodyBytes = Arrays.copyOfRange(bodyBytes, prefix, bodyBytes.length);
byte[] signingMessage = Ans104DataItem.buildSigningMessage(owner32, tags, frame); }
byte[] signature64 = utils.crypto.Ed25519Util.sign(signingMessage, loginPrivKey); ContentRecord content = new ContentRecord(type & 0xffff, subType & 0xffff, version & 0xffff, bodyBytes);
byte[] rawDataItem = Ans104DataItem.serializeEd25519(signature64, owner32, tags, frame); Ans104DataItem contentItem = CoreContentTransport.sign(content.toBytes(), List.of(), loginPrivKey);
BchBlockEntry entry = new BchBlockEntry(rawDataItem); CoreRecord core = new CoreRecord(prevHash32, blockNumber, tsSec, content.contentHash32(), contentItem.id32(), line);
Ans104DataItem coreItem = CoreContentTransport.sign(core.toBytes(), CoreContentTransport.coreTags(core), loginPrivKey);
BchBlockEntry entry = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(coreItem, contentItem));
String prevHashHexForReq = (blockNumber == 0) ? ZERO64 : state.lastBlockHashHex(); String prevHashHexForReq = (blockNumber == 0) ? ZERO64 : state.lastBlockHashHex();
@@ -120,10 +122,6 @@ public final class AddBlockSender {
assertEquals(localHashHex, serverLastHash, op + ": serverLastBlockHash must match local hash"); assertEquals(localHashHex, serverLastHash, op + ": serverLastBlockHash must match local hash");
state.applyAppendedBlock(blockNumber, entry.getHash32(), isHeader, type, body); state.applyAppendedBlock(blockNumber, entry.getHash32(), isHeader, type, body);
if (body instanceof CreateChannelBody ccb) {
channelSlugByRoot.put(blockNumber, shine.db.channels.ChannelNameRules.toCanonicalSlug(ccb.channelName));
}
if (TestConfig.DEBUG()) TestLog.info(op + ": state updated"); if (TestConfig.DEBUG()) TestLog.info(op + ": state updated");
} }
@@ -208,61 +206,4 @@ public final class AddBlockSender {
throw new IllegalArgumentException("Unknown body class: " + body.getClass()); throw new IllegalArgumentException("Unknown body class: " + body.getClass());
} }
// ---------- Frame v1 + signed channel tag helpers ----------
private static String typeTagFor(short type) {
return switch (type & 0xFFFF) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
private String channelSlugFor(BodyRecord body) {
if (body instanceof CreateChannelBody ccb) {
return shine.db.channels.ChannelNameRules.toCanonicalSlug(ccb.channelName);
}
if (body instanceof TextLineBody tb && tb.lineCode > 0) {
String slug = channelSlugByRoot.get(tb.lineCode);
if (slug == null) {
throw new IllegalStateException("Unknown channel slug for lineCode=" + tb.lineCode);
}
return slug;
}
return null;
}
private static byte[] buildFrame(byte[] prevHash32,
byte[] back32Hash32,
int blockNumber,
long tsSec,
short type,
short subType,
short version,
byte[] bodyBytes) {
if (prevHash32 == null || prevHash32.length != 32) {
throw new IllegalArgumentException("prevHash32 must be 32 bytes");
}
if (back32Hash32 == null || back32Hash32.length != 32) {
throw new IllegalArgumentException("back32Hash32 must be 32 bytes");
}
int bodyLen = bodyBytes == null ? 0 : bodyBytes.length;
int blockSize = BchBlockEntry.FRAME_HEADER_SIZE + bodyLen;
java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(blockSize).order(java.nio.ByteOrder.BIG_ENDIAN);
bb.putShort((short) BchBlockEntry.FRAME_CODE_V1);
bb.put(prevHash32);
bb.put(back32Hash32);
bb.putInt(blockSize);
bb.putInt(blockNumber);
bb.putLong(tsSec);
bb.putShort(type);
bb.putShort(subType);
bb.putShort(version);
if (bodyBytes != null) bb.put(bodyBytes);
return bb.array();
}
} }
@@ -77,7 +77,7 @@ public class IT_03_AddBlock_NoAuth {
ChainState st1 = new ChainState(); ChainState st1 = new ChainState();
AddBlockSender sender1 = new AddBlockSender(ws, st1, u1, bch1, TestConfig.getBlockchainPrivatKey(u1)); AddBlockSender sender1 = new AddBlockSender(ws, st1, u1, bch1, TestConfig.getBlockchainPrivatKey(u1));
sender1.send(new HeaderBody(u1, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u1))), t); sender1.send(HeaderBody.identity(u1, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u1)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
assertTrue(st1.hasHeader()); assertTrue(st1.hasHeader());
int u1HeaderBlock = 0; int u1HeaderBlock = 0;
@@ -195,7 +195,7 @@ public class IT_03_AddBlock_NoAuth {
ChainState st2 = new ChainState(); ChainState st2 = new ChainState();
AddBlockSender sender2 = new AddBlockSender(ws, st2, u2, bch2, TestConfig.getBlockchainPrivatKey(u2)); AddBlockSender sender2 = new AddBlockSender(ws, st2, u2, bch2, TestConfig.getBlockchainPrivatKey(u2));
sender2.send(new HeaderBody(u2, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u2))), t); sender2.send(HeaderBody.identity(u2, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u2)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
assertTrue(st2.hasHeader()); assertTrue(st2.hasHeader());
int u2HeaderBlock = 0; int u2HeaderBlock = 0;
@@ -267,7 +267,7 @@ public class IT_03_AddBlock_NoAuth {
ChainState st3 = new ChainState(); ChainState st3 = new ChainState();
AddBlockSender sender3 = new AddBlockSender(ws, st3, u3, bch3, TestConfig.getBlockchainPrivatKey(u3)); AddBlockSender sender3 = new AddBlockSender(ws, st3, u3, bch3, TestConfig.getBlockchainPrivatKey(u3));
sender3.send(new HeaderBody(u3, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u3))), t); sender3.send(HeaderBody.identity(u3, Ed25519Util.derivePublicKey(TestConfig.getBlockchainPrivatKey(u3)), "", HeaderBody.ALTERNATIVE, java.util.List.of()), t);
assertTrue(st3.hasHeader()); assertTrue(st3.hasHeader());
int u3HeaderBlock = 0; int u3HeaderBlock = 0;
@@ -97,6 +97,9 @@ public class IT_04_UserParams_NoAuth {
assertNotNull(lp2.signatureB64); assertNotNull(lp2.signatureB64);
r.ok("ListUserParams OK"); r.ok("ListUserParams OK");
for (String reserved : new String[]{"account_role", "official", "ACCOUNT_ROLE"}) {
upsertUserParam(r, login, reserved, t1b + 10, "primary", clientKeyB64, clientPrivKey, timeout, 400);
}
} catch (Throwable e) { } catch (Throwable e) {
r.fail("IT_04 упал: " + e.getMessage()); r.fail("IT_04 упал: " + e.getMessage());
@@ -110,6 +113,10 @@ public class IT_04_UserParams_NoAuth {
// ================================================================================= // =================================================================================
private static void upsertUserParam_OK(TestResult r, String login, String param, long timeMs, String value, String clientKeyB64, byte[] clientPrivKey, Duration timeout) { private static void upsertUserParam_OK(TestResult r, String login, String param, long timeMs, String value, String clientKeyB64, byte[] clientPrivKey, Duration timeout) {
upsertUserParam(r, login, param, timeMs, value, clientKeyB64, clientPrivKey, timeout, 200);
}
private static void upsertUserParam(TestResult r, String login, String param, long timeMs, String value, String clientKeyB64, byte[] clientPrivKey, Duration timeout, int expectedStatus) {
String signatureB64 = signUserParam(clientPrivKey, login, param, timeMs, value); String signatureB64 = signUserParam(clientPrivKey, login, param, timeMs, value);
String reqJson = """ String reqJson = """
@@ -129,7 +136,8 @@ public class IT_04_UserParams_NoAuth {
try (WsSession ws = WsSession.open()) { try (WsSession ws = WsSession.open()) {
String resp = ws.call("UpsertUserParam(" + param + ")", reqJson, timeout); String resp = ws.call("UpsertUserParam(" + param + ")", reqJson, timeout);
assertEquals(200, JsonParsers.status(resp), "UpsertUserParam expected 200, resp=" + resp); assertEquals(expectedStatus, JsonParsers.status(resp), "UpsertUserParam expected " + expectedStatus + ", resp=" + resp);
if (expectedStatus == 400) assertTrue(resp.contains("account_type_immutable"), resp);
r.ok("UpsertUserParam(" + param + "): OK"); r.ok("UpsertUserParam(" + param + "): OK");
} }
} }
@@ -51,7 +51,7 @@ public final class SeedDataPopulationHelper {
} }
public void createUsersAndHeaders(List<UserSpec> users) { public void createUsersAndHeaders(List<UserSpec> users) {
for (UserSpec user : users) initHeader(user.login); for (UserSpec user : users) initHeader(user.login, Boolean.TRUE.equals(user.official));
} }
public void applyProfiles(List<UserSpec> users) { public void applyProfiles(List<UserSpec> users) {
@@ -62,8 +62,7 @@ public final class SeedDataPopulationHelper {
if (notBlank(user.address)) upsertProfileParam(user.login, "address", user.address); if (notBlank(user.address)) upsertProfileParam(user.login, "address", user.address);
if (notBlank(user.web)) upsertProfileParam(user.login, "web", user.web); if (notBlank(user.web)) upsertProfileParam(user.login, "web", user.web);
if (notBlank(user.phone)) upsertProfileParam(user.login, "phone", user.phone); if (notBlank(user.phone)) upsertProfileParam(user.login, "phone", user.phone);
if (user.official != null) upsertProfileParam(user.login, "official", user.official ? "yes" : "no"); if (user.shine != null) upsertProfileParam(user.login, "shine", user.shine ? "shining" : "unknown");
if (user.shine != null) upsertProfileParam(user.login, "shine", user.shine ? "yes" : "no");
} }
} }
@@ -158,10 +157,10 @@ public final class SeedDataPopulationHelper {
), timeout); ), timeout);
} }
private void initHeader(String login) { private void initHeader(String login, boolean primary) {
ChainState state = new ChainState(); ChainState state = new ChainState();
AddBlockSender sender = new AddBlockSender(ws, state, login, bch(login), keys.blockchainPrivate32); AddBlockSender sender = new AddBlockSender(ws, state, login, bch(login), keys.blockchainPrivate32);
sender.send(new HeaderBody(login, Ed25519Util.derivePublicKey(keys.blockchainPrivate32)), timeout); sender.send(HeaderBody.identity(login, Ed25519Util.derivePublicKey(keys.blockchainPrivate32), "", primary ? HeaderBody.PRIMARY : HeaderBody.ALTERNATIVE, java.util.List.of()), timeout);
byte[] headerHash = state.getHash32(0); byte[] headerHash = state.getHash32(0);
if (headerHash == null || headerHash.length != 32) { if (headerHash == null || headerHash.length != 32) {
@@ -14,7 +14,7 @@ import static org.junit.jupiter.api.Assertions.fail;
* Заполняет тестовую соц-сеть через API: * Заполняет тестовую соц-сеть через API:
* - пользователи должны уже существовать в актуальном PDA snapshot; * - пользователи должны уже существовать в актуальном PDA snapshot;
* - HEADER и остальные блоки пишутся через AddBlock; * - HEADER и остальные блоки пишутся через AddBlock;
* - параметры профиля (имя, фамилия, пол, адрес, web, phone, official, shine) через AddBlock USER_PARAM; * - параметры профиля (имя, фамилия, пол, адрес, web, phone, shine; official задаётся в HEADER) через AddBlock USER_PARAM;
* - связи (close friend/contact/follow/parent/child/sibling) через AddBlock CONNECTION; * - связи (close friend/contact/follow/parent/child/sibling) через AddBlock CONNECTION;
* - посты через AddBlock TEXT_POST. * - посты через AddBlock TEXT_POST.
*/ */
@@ -0,0 +1,379 @@
# SHiNE — смена ключей и методы восстановления доступа
**Статус:** ToDo / задание на реализацию. **Дата:** 28.11.2026.
**Базовая версия для сверки:** `SHiNE-bundle-2026.11.27-15.53.44(1).zip`. Настоящий документ заменяет предыдущую спецификацию восстановления доступа. Код не изменён.
# Часть I. Краткое описание для человека
В SHiNE аккаунт принадлежит пользователю, а не администрации сервиса. Если пользователь потерял пароль или его аккаунт захватили, вернуть контроль над своей цифровой личностью можно двумя независимыми способами: с помощью заранее сохранённого резервного ключа или с помощью доверенных людей.
**Первый этап — резервный ключ.** В настройках пользователь создаёт специальный случайный резервный пароль, сохраняет его отдельно и подтверждает установку. Через 20 суток он становится действительным. Если основной пароль потерян, на экране входа пользователь выбирает восстановление, вводит логин, резервный ключ и новый пароль. После подтверждения операции он снова получает доступ к аккаунту. Использованный резервный ключ автоматически аннулируется. Новый можно установить сразу, но он начнёт действовать через 20 суток.
Резервный ключ можно заменить даже без знания прежнего резервного пароля, если доступен основной пароль. Замена происходит через 20 суток: до этой даты действует старый ключ, после неё — новый. Удаление также происходит через 20 суток. Не нужно ждать два последовательных срока или возвращаться в настройки для завершения операции.
**Второй этап — доверенные пользователи.** В настройках можно выбрать до 12 других аккаунтов SHiNE. Добавление и удаление вступают в силу через 14 суток. Если пользователь потерял доступ, он создаёт заявку, задаёт новый пароль и отправляет доверенным людям специальную ссылку. Они подтверждают восстановление в своих аккаунтах. Когда набирается не менее двух третей действующих доверенных, заявка может быть исполнена, и пользователь входит с новым паролем. Заявка действует ровно 30 суток с момента создания, после чего восстановление по ней невозможно.
Оба аварийных способа работают без временных ограничений на смену ключей. При любом успешном восстановлении резервный ключ (в том числе ожидающий активации) аннулируется, а ещё не вступившие в силу изменения состава доверенных отменяются. Действующий состав доверенных сохраняется. Старые заявки восстановления становятся недействительными.
**Что сохраняется:** логин, профиль, цифровая личность, публичные публикации, каналы, подписчики, друзья и публичные социальные связи — в пределах сохранившейся истории данных. **Что не восстанавливается:** доступ к прежней зашифрованной личной переписке, если старые приватные ключи расшифрования потеряны. Резервный ключ не является резервной копией этих ключей или стороннего кошелька.
Функции добровольные. Можно пользоваться одним способом, обоими или ни одним. Доверенные люди не получают пароль, переписку или право повседневного управления аккаунтом. Однако достаточное их количество способно коллективно заменить ключи аккаунта — выбирать их следует осознанно.
На экране входа появляется ссылка «Восстановить доступ», а в настройках — одноимённый раздел. На первом этапе в нём только резервный ключ; на втором добавляются доверенные пользователи и подтверждение чужих заявок.
# Часть II. Техническое задание
## 1. Объём и этапы реализации
1. Этап 1: отдельный Recovery PDA, установка/замена/удаление резервного ключа, восстановление, правило обычных форков 3/10/20, интеграция UI, сервера и проверки истории. Этап должен работать самостоятельно.
2. Этап 2: список доверенных в том же Recovery PDA, Recovery Request PDA, создание заявок, голосование, исполнение, закрытие и возврат лампортов DAO. Сохранить совместимость с PDA первого этапа.
Не вводить централизованное восстановление, параллельную идентичность или обязательную регистрацию настроек восстановления. Сервер, плательщик транзакции и DAO не имеют права самостоятельно сменить ключи пользователя. DAO получает лампорты закрываемых заявок, но не полномочия восстановления.
## 2. Константы и время
| Параметр | Значение |
| --- | ---: |
| Установка/замена/удаление Recovery Key через Root Key | 20 суток |
| Добавление/удаление доверенного | 14 суток |
| Максимум доверенных записей после очистки | 12 |
| Максимальная длина полного логина в текущем формате | 30 ASCII-байт |
| Порог голосования | ceil(2 × N / 3), N > 0 |
| Срок жизни заявки | 30 суток от создания |
| Обычные форки/смена ключей | 3/10/20 суток |
| Аварийное восстановление обоими способами | Без cooldown |
| Повторное использование Recovery Key после восстановления | Запрещено |
Сутки — 86 400 секунд. Для совместимости с текущей программой использовать миллисекунды (`u64`), проверяемое арифметическое сложение и доверенное время `Clock::get().unix_timestamp`. Не использовать часы клиента для определения полномочий, дедлайнов или доступности форков. В момент `now == validFrom` полномочия уже действуют; в момент `now == validUntil` или `now == expiresAt` они уже не действуют. Никаких фоновых транзакций для наступления сроков не требуется.
## 3. Обычная смена ключей и форки
Через действующий Root Key создание форка (смена Blockchain Key) и полная ротация Root + Client + Blockchain допускаются только при выполнении всех существующих проверок и правила:
```text
nextAllowedAt = max(
lastFork.createdAt + 3 суток, если lastFork существует,
previousFork.createdAt + 10 суток, если previousFork существует,
thirdLastFork.createdAt + 20 суток если thirdLastFork существует
)
allowed = now >= nextAllowedAt
```
При отсутствии соответствующих записей проверки пропускаются. Регистрационный форк учитывается, если он входит в историю форков. Форки аварийного восстановления также учитываются в последующих обычных операциях. Не использовать отдельный прогрессивный счётчик: это три скользящие проверки по существующим датам. Например, при первом форке в день 0 допустимые следующие даты: 3, 10, 20, 23, 30, 40. Интервалы 3/7/10 повторяются, что является ожидаемым результатом выбранной формулы, а не прогрессивным cooldown.
Смена настроек восстановления, которая не создаёт форк, не подпадает под это ограничение: у неё собственные задержки. Оба аварийных способа пропускают только cooldown, но не проверки авторизации, формата, уникальности новых ключей и финансирования операции.
### Привязка к исходному коду
В архиве в `shine-solana/shine/programs/shine_users/src/lib.rs` подтверждены `ForkRecordV12.created_at_ms`, `UserRecordV12`, `UpdateUserPdaArgs`, `FORK_COOLDOWN_MS`, `enforce_fork_cooldown`, `current_time_ms`, `validate_client_time_ms` и ветка `full_key_rotation`. Сейчас cooldown составляет три дня и не применяется при полной ротации (`if !full_key_rotation`). Это исключение необходимо убрать для обычной ротации. Привести проверку к трём последним форкам, а аварийную авторизацию выделить в отдельный строго ограниченный путь. Для новых временных отметок форков использовать согласованное с контрактом время: при сохранении формата клиентской подписанной записи не допускать обхода ограничений с помощью backdating/future dating; при необходимости отдельно зафиксировать контрактное время или адаптировать формирование подписываемой записи. Не менять существующую семантику временных меток незаметно.
## 4. Постоянный Recovery PDA
Создаётся только по необходимости, связан с неизменным User PDA/каноническим логином, принадлежит программе `shine_users`. Должен быть однозначно выводимым и не пересекаться с другими типами PDA. Пример seed: `[b"recovery", user_pda_pubkey]`; конкретные seed, discriminator и версии согласовать с существующим бинарным протоколом. Поддержать существующие legacy-логины по текущему разрешению User PDA, не вводить новые правила их канонизации.
Логическая схема (не фиксированный wire format):
```text
RecoveryRecord {
formatVersion
userPda // или другая проверяемая привязка
recoveryEpoch: u64 // поколение аварийного восстановления
configRevision: u64 // защита от повторного исполнения изменений
currentRecoveryKey?: Pubkey // действующий в нормализованном состоянии
pendingKeyChange?: {
effectiveAtMs: u64
nextKey?: Pubkey // None = запланированное удаление
}
guardians: Vec<Guardian> // этап 2; 0..12, на этапе 1 пусто
}
Guardian {
login: String // канонический полный логин, без дубликатов
validFromMs: u64
validUntilMs?: u64 // None = без назначенной даты удаления
}
```
Два счётчика — предлагаемое минимальное решение для защиты от повторов и инвалидирования заявок; допускается эквивалентная проверяемая схема. `configRevision` меняется при каждой записанной операции изменения/отмены конфигурации; обычная смена пароля не увеличивает `recoveryEpoch`.
Использовать компактную версионированную сериализацию (явные длины и optional-флаги, строгие проверки границ). Не выделять заранее место под 12 максимальных логинов или два ключа, если их ещё нет. Размер увеличивать по фактической необходимости, пополняя rent-exempt баланс. При перезаписи нормализовать состояние и удалять устаревшие поля/записи; допустимо уменьшение выделенной длины, если это безопасно и соответствует принятой политике rent. Не возвращать освободившийся баланс постоянного Recovery PDA произвольному вызывающему. Правило возврата DAO для заявок не означает автоматически закрытие самого Recovery PDA. После восстановления сохранить PDA и `recoveryEpoch`, даже если ключей и доверенных больше нет, чтобы старые заявки не ожили при повторном создании. Специально не закрывать постоянный Recovery PDA в рамках этой задачи.
Поля ключей содержат только 32-байтные публичные ключи Ed25519; приватные ключи и пароли никогда не хранятся в PDA. Доверенные представлены логинами, не копиями их публичных ключей. Список публично наблюдаем в Solana; UI должен сообщить об этом.
## 5. Этап 1. Резервный ключ
### 5.1. Установка, замена, удаление
Любое из этих действий через обычный Root Key вступает в силу через 20 суток. Старая конфигурация сохраняет полномочия до даты изменения. Прямую замену поддержать обязательно, знание старого резервного пароля для неё не требуется.
| Операция | До effectiveAt | Начиная с effectiveAt |
| --- | --- | --- |
| Установка при отсутствии активного ключа | Нет активного ключа | Новый ключ |
| Замена A на B | A | B |
| Удаление A | A | Нет ключа |
При замене одновременно хранится максимум два публичных ключа (A и B). При удалении `nextKey = None`. При установке `currentRecoveryKey = None`. В каждый момент действителен максимум один ключ.
```text
resolveActiveKey(record, now):
if pendingKeyChange exists and now >= pendingKeyChange.effectiveAtMs:
return pendingKeyChange.nextKey
return currentRecoveryKey
```
При чтении применять эту функцию без записи. Перед любой записью нормализовать: если срок наступил, перенести `nextKey` в `currentRecoveryKey` и убрать `pendingKeyChange`. При повторном планировании взять именно актуальный ключ и создать новое изменение с `effectiveAt = now + 20 суток`; новый кандидат не наследует чужой срок. Отмена допустима только до наступления срока, авторизуется действующим Root Key и сохраняет текущий активный ключ. После наступления срока обратное изменение — новая операция с новой задержкой. Повторный запрос с тем же желаемым состоянием предпочтительно считать no-op/ошибкой, не сдвигать срок неявно. Не разрешать параллельные ожидающие изменения или немедленную замену через Recovery Key как отдельную операцию: этот ключ предназначен для аварийного восстановления и при нём уничтожается.
Обычная ротация основных ключей не меняет Recovery Key и не отменяет ожидающие настройки. Иначе злоумышленник смог бы сбросить защиту простым знанием основного пароля.
### 5.2. Генерация секрета
Резервный пароль независим от основного пароля и остальных секретов. Рекомендуется 32 случайных байта из системного CSPRNG, представленных в удобном копируемом формате с версией/контрольной суммой, и детерминированное получение Ed25519 keypair по документированному алгоритму. Не изобретать собственную криптографию; согласовать используемую библиотеку, формат, нормализацию и тестовые векторы между клиентами. Секрет должен быть воспроизводим только из сохранённого резервного пароля; не использовать основной пароль как обязательный вход. При установке проверять владение новым резервным ключом его подписью над контекстом установки/замены, чтобы избежать сохранения недоступного ключа.
Показать резервный пароль при генерации, дать скопировать и сохранить, потребовать подтверждение сохранения. Не сохранять открытый секрет в IndexedDB/localStorage, телеметрии, URL, логах или серверной БД. Не передавать основной или резервный пароль на сервер/в Solana; клиент формирует подписи локально. Очищать поля и чувствительные данные после операции настолько, насколько это позволяет платформа.
### 5.3. Аварийная ротация через резервный ключ
Контракт получает целевой User PDA, Recovery PDA, новые Root/Client/Blockchain публичные ключи, подпись актуального Recovery Key над конкретной операцией и подпись нового Root Key (доказательство владения новым основным секретом). Применять существующие правила формирования и проверки подписанного UserRecord. Подпись аварийного ключа должна быть привязана к программе/сети, типу операции, User PDA, текущему состоянию/поколению и точному набору новых ключей/подписываемой записи. Проверить owner, seeds, формат и полномочия на момент исполнения. Никакая старая или ожидающая подпись не должна подменять актуальный ключ. Не требовать старого Root Key, Client Key или Blockchain Key — они могут быть потеряны.
Переиспользовать общую процедуру ротации из раздела 8. Без cooldown. В одной атомарной транзакции обновить User PDA и уничтожить оба резервных ключа (действующий и ожидающий активации), включая ожидающее удаление. Если транзакция не завершилась успешно, резервный ключ не считается использованным. После успеха повтор той же подписи или использование того же ключа для другой ротации не проходит.
Новый резервный ключ устанавливается новым Root Key отдельным обычным запросом с задержкой 20 суток. До его активации резервной защиты этим способом нет; UI показывает это явно.
### 5.4. Интерфейс первого этапа
**Настройки → Восстановление доступа → Резервный ключ.** Показать состояния:
| Состояние | Что видит пользователь |
| --- | --- |
| Нет активного и ожидающего ключа | «Не установлен», кнопка «Создать резервный ключ» |
| Ожидается первичная установка | «Начнёт действовать [дата]», отсчёт, отмена |
| Активен | «Резервный ключ активен», «Заменить», «Удалить» |
| Ожидается замена | «Старый ключ действует до [дата], затем будет действовать новый», отмена/перепланирование |
| Ожидается удаление | «Действует до [дата]», отмена |
| Использован при восстановлении | «Резервный ключ аннулирован», предложение создать новый |
При установке/замене: показать сгенерированный секрет, кнопку копирования, подтверждение сохранения, дату активации, предупреждение о том, что любой знающий ключ может восстановить аккаунт. Авторизовать операцию основным паролем через существующий механизм Root Key. При удалении не требовать резервный пароль. Не показывать секрет повторно в настройках.
**Экран входа по логину и паролю:** ссылка «Восстановить доступ» с пояснением «Воспользуйтесь заранее установленным резервным ключом». При первом этапе допустим прямой переход на форму; предусмотреть возможность меню выбора способов на втором. Восстановление также доступно из настроек при действующей сессии, но не должно требовать старого пароля.
Поток восстановления:
1. Ввод полного логина (подставить имеющийся, разрешить исправить) и резервного пароля. Получить актуальный User PDA и Recovery PDA; проверить наличие активного ключа и соответствие введённого секрета локально. Если ключ неактивен/неверен — понятное сообщение, дата активации при наличии.
2. Ввести и повторить новый основной пароль по существующим правилам SHiNE. Локально получить новый Root/Client/Blockchain Key и необходимые параметры нового счёта/кошелька.
3. Показать предупреждение: «Вы получите доступ к своему аккаунту и публичным публикациям. Старая зашифрованная личная переписка не восстановится без прежних ключей. Резервный ключ будет аннулирован».
4. Если для выполнения операции необходимо пополнение, показать сумму, адрес нового счёта, статус пополнения и назначение платежа (комиссия, увеличение rent, иные действующие сборы). Переиспользовать существующий платёжный UX; не требовать пополнения, если средства уже имеются или предусмотрен иной плательщик. Не требовать доступа к старому кошельку.
5. Кнопка «Восстановить аккаунт». Сформировать и отправить транзакцию. До подтверждения не считать операцию завершённой; при неопределённом результате перечитать актуальное состояние перед повтором.
6. «Доступ восстановлен. Войдите с новым паролем. Резервный ключ аннулирован». Переход на вход, предложение установить новый резервный ключ, действующий через 20 суток.
## 6. Этап 2. Доверенные пользователи
### 6.1. Состав и временные полномочия
Из настроек владелец, подтверждая изменение Root Key, добавляет других пользователей по полному логину. Проверить существование их User PDA, канонизацию, отсутствие дубликатов и самого владельца. Максимум 12 записей после нормализации, включая ожидающие вступления и ожидающие удаления, чтобы рост PDA был ограничен. Если список заполнен и одно удаление ещё ожидается, новый пользователь добавляется после истечения срока удаления. Это простое предложенное правило лимита; не увеличивать лимит незаметно.
```text
active(guardian, now) =
guardian.validFromMs <= now
AND (guardian.validUntilMs is None OR now < guardian.validUntilMs)
```
Добавление: `validFromMs = now + 14 суток`, `validUntilMs = None`. Удаление активного: `validUntilMs = now + 14 суток`, полномочия до этого срока сохраняются. Отмена добавления до вступления — удаление ожидающей записи. Отмена ожидающего удаления активного — сброс `validUntilMs`, без прерывания действующих полномочий. После окончательного удаления новое добавление всегда начинает новый 14-дневный срок. Повторное добавление уже действующего/ожидающего пользователя не создаёт второй записи и не сокращает срок. Окончательно истекшие записи очищать при перезаписи.
**Согласие доверенного:** в предыдущем обсуждении предусматривалось подтверждение согласия. Для минимальной реализации не делать его дополнительным обязательным on-chain состоянием: владелец сам назначает доверенного, а тот свободен не голосовать. UI может уведомить и предложить подтвердить готовность помочь. Если решено сделать согласие обязательным, срок 14 суток должен отсчитываться не раньше подтверждения; это отдельное продуктовое уточнение, не смешивать оба варианта. Сроки основного сценария здесь отсчитываются от назначения владельцем.
### 6.2. Порог
Требуется не менее двух третей действующих доверенных, с округлением вверх. Не строго больше 2/3 и не простое большинство.
| Действующих N | Голосов |
| ---: | ---: |
| 0 | Недоступно |
| 1 | 1 |
| 2 | 2 |
| 3 | 2 |
| 4 | 3 |
| 5 | 4 |
| 6 | 4 |
| 7 | 5 |
| 8 | 6 |
| 9 | 6 |
| 10 | 7 |
| 11 | 8 |
| 12 | 8 |
```text
allowed = N > 0 AND 3 * validVotes >= 2 * N
required = (2 * N + 2) / 3 // целочисленное деление
```
При единственном доверенном явно предупреждать владельца о единоличном праве восстановления. Состав и порог на момент создания заявки НЕ замораживать. Всегда определять актуальное состояние при исполнении, включая наступившие отложенные изменения.
## 7. Recovery Request PDA — заявка и голосование
### 7.1. Создание
Отдельный PDA на каждую заявку. Создание доступно без старого пароля; пользователь задаёт новый пароль, локально генерирует новые основные ключи и доказывает владение новым Root Key. Создание заявки само по себе не блокирует аккаунт и не меняет ключи, не отменяет настройки, не предоставляет доступ. Несколько заявок могут сосуществовать. Создатель оплачивает создание и необходимые транзакции или использует предусмотренную схему спонсирования; не списывать средства с восстанавливаемого аккаунта без его полномочий.
```text
RecoveryRequest {
formatVersion
targetUserPda
requestId // уникальный криптографически случайный nonce
recoveryEpoch // значение при создании
createdAtMs // только время контракта
newRootKey
newClientKey
newBlockchainKey
votes: Vec<Vote> // компактное ограниченное хранение
}
Vote {
guardianLogin // либо однозначный идентификатор его User PDA
signedByRootKey // публичный ключ, проверенный при голосовании
guardianValidFromMs // начало конкретного назначения
// подпись можно хранить для аудита; достаточно проверенного контрактом факта
// голосования, однозначно привязанного к неизменяемой заявке
}
```
Предлагаемый seed `[b"recovery-request", target_user_pda, request_id]` с nonce длиной не более 32 байт. Адрес заявки используется в ссылке. Подписываемое сообщение включает домен программы/сети, тип действия, target, request PDA/nonce, поколение и все три новые публичные ключи. Для голоса — также идентификатор голосующего, начало его конкретного назначения и подтверждённое время создания заявки. При создании заявки подпись нового Root Key не обязана содержать ещё неизвестное контрактное время, но должна содержать уникальный nonce; финальная подпись привязывается к уже созданной заявке и итоговой записи. Не хранить пароли, приватные ключи или ссылки с секретами. Ключи и дата создания неизменяемы; исправление нового пароля требует новой заявки. Голоса привязаны к конкретной заявке; перенос на другую невозможен.
Пример ссылки (путь согласовать с роутером): `https://shineup.me/recovery?request=<PDA_ADDRESS>`. Можно добавить логин как удобную подсказку, но доверять только данным проверенного PDA. Ссылка не является авторизацией. Открытие без входа показывает экран входа с сохранением контекста заявки.
### 7.2. Голосование
Каждый доверенный открывает ссылку, видит полный логин владельца, время окончания, прогресс и предупреждение подтвердить личность заявителя независимым способом. Подтверждает своим действующим Root Key. Контракт проверяет актуальный User PDA голосующего, право голоса и подпись над неизменяемыми данными заявки. Сохраняет голос, а не секрет. Сервер или плательщик транзакции не голосуют от его имени.
Один действительный голос на доверенный аккаунт. Повторный голос не увеличивает результат. Если Root Key доверенного изменился, старый голос не учитывается; он может проголосовать новым ключом, заменив запись. Если человек перестал быть действующим доверенным, его голос не учитывается; при добавлении новых доверенных они получают право голосовать только с даты вступления. При записи можно очищать голоса окончательно неактуальных доверенных и поддерживать не более 12 записей, чтобы накопление смен состава не раздувало заявку. При повторном назначении ранее удалённого доверенного не оживлять старый голос автоматически: привязать голос также к конкретному интервалу назначения (`validFromMs`) или потребовать новое подтверждение.
Обычная смена пароля восстанавливаемого аккаунта не отменяет заявку или голоса. Старый Root Key владельца не может единолично отменить коллективное восстановление. Не замораживать аккаунт при создании заявки или отдельном голосе.
### 7.3. Исполнение
После достижения порога пользователь с новым паролем или другой отправитель, имеющий подготовленную корректную подпись нового Root Key над итоговой записью, отправляет транзакцию исполнения. Для простого UI — кнопка «Завершить восстановление» у заявителя, без повторного сбора голосов. Последний голос не обязан автоматически выполнять ротацию, если для неё требуется отдельная транзакция.
При исполнении заново проверить:
- программа владеет всеми нужными PDA, адреса/привязки корректны;
- `now < createdAtMs + 30 суток`, поколение совпадает с текущим `recoveryEpoch`;
- актуальный состав доверенных и уникальность их логинов/идентификаторов, число N;
- каждый учитываемый голос ранее подтверждён контрактом над этой заявкой; соответствующий User PDA голосующего проверен, голосующий сейчас активен, его текущий Root Key совпадает с `signedByRootKey`, интервал назначения не изменился;
- `N > 0` и `3 * validVotes >= 2 * N`;
- новые ключи совпадают с заявкой, новый Root Key подписал итоговую запись, сохраняются все неизменяемые поля, выполняются обычные проверки структуры и уникальности ключей.
Исполнить общую аварийную ротацию без cooldown и закрыть именно эту заявку в той же атомарной операции. При изменении целевого User PDA между подписанием и отправкой пересобрать итоговую запись и получить новую подпись нового Root Key, голоса за фиксированный набор ключей сохраняются. Не разрешать подменить набор новых ключей или менять посторонние настройки в обход их собственных правил. Для передачи доступа и серверных параметров, если она нужна, использовать проверенные текущие значения либо отдельно утверждённые операции.
### 7.4. Ровно 30 суток и возврат лампортов DAO
`expiresAtMs = createdAtMs + 30 суток`. Срок фиксируется при создании. Ни голос, ни повторный голос, ни попытка исполнения его не продлевают. При `now >= expiresAtMs` заявка никогда не исполняется и не принимает новые голоса. Она остаётся в Solana до закрытия, автоматически по времени не исчезает.
Два допустимых пути закрытия:
1. Успешное исполнение — закрыть заявку атомарно с восстановлением и перечислить весь её остаток лампортов на предусмотренный протоколом счёт DAO.
2. По истечении 30 суток — любой желающий может вызвать `close_expired_recovery_request`. Не требовать подписи владельца/заявителя/доверенных. Все лампорты заявки перечисляются исключительно DAO. Инициатор платит обычную комиссию своей транзакции, но не получает лампорты заявки.
Заявка, инвалидированная другим успешным восстановлением до своего дедлайна, не может исполняться, но остаётся до наступления 30 суток; затем также закрывается любым желающим с перечислением DAO. Это консервативное уточнение согласованного правила: не вводить дополнительное досрочное закрытие.
Адрес получателя DAO определяется из действующей доверенной конфигурации программы/протокола и проверяется контрактом; нельзя принимать произвольный адрес от вызывающего. Проверить, что закрывается именно Recovery Request PDA, не User PDA или Recovery PDA. Не путать остаток rent с комиссиями уже проведённых транзакций: комиссии не возвращаются. Не создавать выплату закрывающему или возврат заявителю. После закрытия удалить данные и исключить повторное исполнение; nonce новых заявок должен быть уникальным. Повторное создание с тем же адресом не должно позволять воспроизвести старые подписи/голоса: подписываемый контекст привязать также к уникальной инкарнации заявки (например, проверяемому времени создания) и к поколению.
### 7.5. Интерфейс второго этапа
В настройках «Восстановление доступа» добавить:
- «Доверенные пользователи» — поиск по логину, добавление, удаление, отмена ожидающих действий; состояния «ожидает активации», «действует», «действует до [дата]». Показать действующее число, требуемые голоса и предупреждение о коллективном праве смены ключей.
- «Восстановить доступ» — выбор резервного ключа или голосования.
- «Подтвердить восстановление другого пользователя» — открытие/вставка ссылки (не требовать глобального поиска заявок). При наличии уведомлений показывать входящие запросы/изменения как дополнительное удобство, не как условие безопасности.
В форме восстановления голосованием: логин → новый пароль и подтверждение → предупреждение о старой переписке → при необходимости пополнение нового счёта/плательщика → создание заявки → копирование/системная отправка ссылки → прогресс `X из Y` → завершение при достаточных актуальных голосах → вход с новым паролем. Показывать дату окончания и статус «просрочена», «недействительна», «исполнена» (последний по подтверждённому результату операции/событию, поскольку PDA закрыт). Если пользователь потерял новый пароль до исполнения, предложить создать другую заявку; не менять ключи существующей заявки. Если приложение закрыто, пользователь может вернуться по ссылке и повторно ввести новый пароль для завершения без хранения секрета в ссылке.
Экран доверенного: «Пользователь [полный логин] просит восстановить доступ к своему аккаунту. Подтверждая, вы разрешаете заменить его ключи. Убедитесь, что запрос действительно от него». Кнопка «Подтвердить восстановление», статус голоса, срок заявки. Рекомендуется показывать краткий проверочный код, вычисленный из полного идентификатора заявки и ключей, чтобы стороны могли сверить конкретный запрос; он не является секретом или заменой подписи.
## 8. Общая атомарная процедура аварийного восстановления
Один внутренний путь ротации с двумя альтернативными способами авторизации. Не использовать обычный Root Key как дополнительное обязательное подтверждение аварийного восстановления.
1. Получить актуальный User PDA и Recovery PDA; проверить формат, принадлежность, адреса и выбранный способ авторизации.
2. Нормализовать настройки по текущему времени. Определить фактически действующие полномочия; не откатывать изменения, срок которых уже наступил.
3. Проверить подпись действующего Recovery Key или действительные голоса заявки, а также подпись нового Root Key над итоговой записью.
4. Заменить Root Key, Client Key и Blockchain Key, создать новый форк с текущим временем и прежней семантикой начального лимита. Сохранить логин, идентичность User PDA, историю старых форков, статистику, системные лимиты и другие поля, которые восстановление не должно менять. Сохранить механизм связи версий записи (`record_number`, `prev_record_hash`) и каноническую подпись нового состояния. Не требовать старых приватных ключей.
5. Удалить действующий Recovery Key и любое ожидающее изменение ключа, даже если восстановление проведено голосованием.
6. Оставить только доверенных, действующих в момент восстановления; убрать ещё не вступивших и уже окончательно удалённых. Для каждого оставшегося убрать ожидающее прекращение полномочий (`validUntil = None`).
7. Увеличить `recoveryEpoch` и `configRevision` с проверкой переполнения. Это аннулирует остальные ранее созданные заявки без перебора всех PDA. Обычная смена основных ключей не меняет `recoveryEpoch`.
8. При коллективном восстановлении закрыть исполненную заявку и перечислить весь её остаток лампортов DAO. При ошибке любой части операции откатить все изменения, включая аннулирование ключа и закрытие заявки.
После подтверждения транзакции серверы и клиенты должны проверять именно новые ключи как действующие. Сессии, зарегистрированные по старым полномочиям, прекратить; старые действующие подключения отозвать/переавторизовать. Если сервер ещё не знает о ротации, предусмотреть проверку подтверждённого актуального состояния перед чувствительными операциями. Сохранить доступность проверки исторических подписей старых форков, но не принимать новые операции старых ключей в качестве текущего управления аккаунтом. Отдельно проверить существующие правила выбора активного форка, подтверждения/обрезки истории и обработки поздно поступивших блоков; не обещать криптографическое восстановление утраченных данных. Не изменять историю произвольно ради восстановления.
## 9. Инструкции контракта, форматы и интеграция
Предлагаемые логические инструкции (названия не являются обязательными ABI):
| Инструкция | Этап | Авторизация |
| --- | ---: | --- |
| `schedule_recovery_key_change` | 1 | текущий Root Key, при установке/замене также владение новым Recovery Key |
| `cancel_recovery_key_change` | 1 | текущий Root Key до даты вступления |
| `recover_with_key` | 1 | актуальный Recovery Key + новый Root Key |
| `add_guardian` / `remove_guardian` / `cancel_guardian_change` | 2 | текущий Root Key владельца |
| `create_recovery_request` | 2 | новый Root Key; плательщик транзакции |
| `vote_recovery_request` | 2 | текущий Root Key доверенного |
| `execute_recovery_request` | 2 | достаточное число актуальных голосов + новый Root Key |
| `close_expired_recovery_request` | 2 | любой плательщик, без полномочий владельца |
Инициализация Recovery PDA может быть частью первой операции настройки. Не давать универсальной инструкции, произвольно записывающей новые данные Recovery PDA без проверки каждого изменения. Все сообщения подписи должны иметь каноническую бинарную форму, разделение доменов инструкций, программы и сети, адрес целевого аккаунта, конкретные значения операции, релевантную версию/поколение, а также защиту от повторов. Проверять Ed25519 через существующий безопасный механизм instructions sysvar, не доверять произвольным полям с якобы проверенной подписью. Не принимать чужие PDA, заменённые аккаунты, дублирующиеся аккаунты голосующих, недостоверные часы, произвольные адреса DAO или непроверенные экономические параметры.
В текущем архиве обнаружены следующие точки интеграции:
| Компонент | Путь / ориентир |
| --- | --- |
| Смарт-контракт и ротация | `shine-solana/shine/programs/shine_users/src/lib.rs` |
| Конфигурация программы | `shine-solana/shine/programs/shine_users/src/settings.rs` |
| JS-кодек и операции User PDA | `shine-UI/js/services/shine-user-pda-service.js` |
| Сервис и экран смены ключей | `shine-UI/js/services/key-rotation-service.js`, `shine-UI/js/pages/key-rotation-view.js` |
| Вход | `shine-UI/js/pages/login-view.js`, `shine-UI/js/pages/login-password-view.js` |
| Настройки | `shine-UI/js/pages/settings-view.js`, соответствующие entry/advanced settings и роутер |
| Регистрация и платежи | `shine-UI/js/services/solana-register-service.js`, `shine-UI/js/services/solana-wallet-service.js`, существующий UI пополнения |
| Синхронизация Solana | `SHiNE-server/shine-server-solana-users-sync/` (в т.ч. `ShineUsersCodec.java`, `SolanaUsersSyncService.java`, `PostgresStorageRepository.java`) |
| Импорт PDA на сервере | `SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/auth/SolanaUserPdaImportService.java` |
Это ориентиры по наличию файлов и проверенной Rust-ветке ротации, а не утверждение, что все перечисленные компоненты уже поддерживают восстановление. Перед изменениями прочитать их актуальное содержимое, разобраться с моделью доступа, сертификатами, текущими правилами импорта, проверкой подписей, идентификацией форматов и отзыва сессий.
Сохранить совместимость текущих User PDA и старых пользователей, не требовать миграции аккаунтов, которые не включают восстановление. Новые типы PDA должны распознаваться отдельно в RPC/индексаторе и не попадать в декодер обычных User PDA как ошибочные записи. Синхронизация, интерфейс и кэш должны учитывать переходы по времени, даже если содержимое PDA не изменилось. Ввести тестовые векторы для бинарного формата, адресов PDA и подписываемых сообщений; обновить соответствующую документацию протокола.
**Реализуемость Solana:** заранее проверить лимиты размера транзакции, числа аккаунтов и compute budget для максимальных 12 доверенных. Не собирать 8–12 сырых Ed25519-подписей в одной финальной транзакции без проверки ограничений. Предпочтительно проверять подпись при каждом голосе, а при исполнении сверять сохранённый результат голосования и актуальные User PDA голосующих; проверить практическую необходимость versioned transaction/ALT. Финальная ротация, аннулирование ключа и закрытие исполненной заявки должны оставаться атомарными. Отдельно проверить расширение rent и верхнюю границу длины существующей записи User PDA (в архиве используется поле длины `u16`): не вводить жёсткий предел, который позволит обычными форками заблокировать аварийное восстановление. Если приближение к предельному размеру требует миграции или другого формата истории, это самостоятельная инженерная задача и ограничение перед выпуском, а не повод молча терять старые форки.
## 10. Уведомления и безопасность
По возможности показывать владельцу и затронутым доверенным уведомления об установке/замене/удалении резервного ключа, изменении доверенных, создании заявки и факте восстановления. Уведомления не являются доверенным источником времени, условием активации или обязательной зависимостью протокола.
Задержки защищают от немедленного изменения настроек при краже основного пароля, но не защищают бесконечно: после 14/20 суток ранее запланированные изменения вступят в силу. Если злоумышленник получил Recovery Key, он может однократно захватить аккаунт; коллективное восстановление после этого возможно при сохранившихся доверенных. Если скомпрометировано достаточное число доверенных, они могут коллективно восстановить чужой аккаунт без cooldown. Это осознанная модель полномочий, а не абсолютная защита. Не обещать пользователю обратное. Не вводить скрытое право вето старого Root Key или DAO. При необходимости дополнительных мер безопасности обсуждать их отдельно.
## 11. Критерии приёмки и тесты
### Этап 1 — обязательно до выпуска
- Установка первого резервного ключа: до T+20 дней не действует; ровно в T+20 действует без дополнительной транзакции.
- Замена A на B без знания A: непосредственно до T+20 действует только A, ровно с T+20 — только B. Не требуется 40 дней. Удаление работает с теми же границами.
- Повторная замена B на C до срока запускает новый срок для C, не изменяя действующий A. Отмена до срока сохраняет A. Отмена после срока не оживляет старый ключ.
- Нормализация просроченного ожидающего изменения при любой новой записи не изменяет фактически действующие полномочия; неактуальные данные удаляются. Динамический размер и rent корректны.
- Ошибочные/неактивные ключи, подписи с другим target, сетью, типом операции, набором новых ключей или старой версией отклоняются. Новый Root Key обязан доказать владение.
- Проверить правило 3/10/20 для истории из 0, 1, 2, 3 и более форков, включая точные границы и попытки манипулировать клиентским временем. Обычная полная ротация не обходит cooldown.
- Аварийное восстановление успешно даже сразу после обычного форка; оба резервных ключа и все ожидающие настройки резервного ключа аннулируются. Старый секрет не может восстановить ещё раз. При неуспешной транзакции ничего не аннулируется.
- Обычная смена пароля не уничтожает резервный ключ. Новый ключ после аварийного восстановления активируется только через 20 суток.
- Новый пароль работает; прежние ключи не дают текущих полномочий, старые сессии прекращаются; логин, публичная идентичность, старая история форков и системные данные сохраняются. Историческая переписка не обещается как восстановленная.
- UI содержит вход, настройки, создание/сохранение/замену/удаление, даты, понятные ошибки, пополнение при необходимости и предупреждение о переписке. Секреты не попадают в логи, URL или серверную БД.
### Этап 2 — обязательно до выпуска
- Доверенный до T+14 не может голосовать; с T+14 может. При удалении голосует до даты прекращения, после — нет. Повторные изменения не обходят задержку. Проверить очистку, длины логинов, дубликаты, максимум 12 и отсутствие самоназначения.
- Все N=0..12 дают указанный порог, особенно 3→2, 6→4, 9→6, 12→8. Ноль не даёт разрешения. Состав пересчитывается при исполнении, включая изменения за время голосования.
- Посторонний, неактивный доверенный, устаревший Root Key, дубликат и голос за другую заявку не дают действительного голоса. После смены Root Key доверенный может проголосовать заново; переименование/повторное назначение не оживляет старый голос.
- Создание заявки и единичный голос не блокируют владельца. Обычная смена пароля владельца не отменяет заявки. Нельзя изменить новые ключи заявки или выполнить её без доказательства владения новым Root Key.
- При успешном восстановлении без cooldown сохраняется действующий состав, отменяются ожидающие добавления и удаления, уничтожаются оба резервных ключа, увеличивается поколение. Одновременно созданные старые заявки не могут быть исполнены, в том числе при гонке транзакций.
- Заявка действует до, но не включая, T+30 суток; голоса не изменяют дедлайн. Исполненную закрыть атомарно; просроченную закрывает любой плательщик, все лампорты в обоих случаях DAO. Чужой получатель, повторное закрытие и попытка закрытия до срока без исполнения отклоняются.
- Проверить реальную транзакцию с 12 доверенными и 8+ действительными голосами, максимальные длины, оплату/расширение PDA, индексатор, открытие внешней ссылки после входа и повторное открытие после перезапуска приложения.
## 12. Зафиксированные решения и вопросы реализации
Окончательные продуктовые правила: 20 суток для любой установки/замены/удаления резервного ключа; прямая замена за один срок; 14 суток для доверенных; максимум 12; не менее 2/3; ровно 30 суток от создания заявки, без продления; лампорты закрытой заявки исключительно DAO; обычные форки 3/10/20; оба аварийных способа без cooldown; резервный ключ одноразовый и уничтожается при любом аварийном восстановлении.
Дополнения для реализации, предложенные в этом документе: логическая модель `currentRecoveryKey + pendingKeyChange`, два счётчика, проверка владения новым ключом, правила отмены/повторной записи, привязка голоса к интервалу назначения, лимит 12 физических записей, сохранение постоянного PDA после очистки, отсутствие досрочного закрытия инвалидированной заявки, минимальный вариант без обязательного on-chain согласия доверенного. Это не готовый ABI. Конкретный формат, KDF/кодирование, точное использование времени в подписанном UserRecord, адрес DAO, платежи, совместимость сервера и возможности Solana проверить перед изменением кода. При необходимости отклонения от продуктовых правил согласовать его отдельно.
Начать с этапа 1, сделать полноценные тесты и рабочий пользовательский сценарий. Этап 2 выполнять отдельно, сохраняя уже утверждённые форматы и совместимость. Не считать данный документ результатом аудита безопасности или готовой реализацией.
@@ -1,5 +0,0 @@
Баланс в салане
баланс в Арвив / и турбо
Балан лимит МБ / оно же сияния токены SHN

Some files were not shown because too many files have changed in this diff Show More