Compare commits

...
Author SHA256 Message Date
AidarKC f9e7c4ef94 Новый формат блоков CORE/CONTENT test5595 2026-11-27 10:04:22 +03:00
AidarKC d3a84dd451 Слить доработки регистрации и UI 2026-11-21 17:14:49 +03:00
AidarKC 653015b2e7 Улучшить ввод пароля при входе и регистрации 2026-11-21 17:14:46 +03:00
AidarKC 8ac8f04128 Сохранить окружение t2 при deploy 2026-11-21 01:10:13 +03:00
AidarKC 80c70ebcdc Ограничить бесплатную регистрацию namespace сервера 2026-11-21 01:09:37 +03:00
AidarKC 792f368175 Проверить вложения и блоки в каналах 2026-11-21 00:24:25 +03:00
AidarKC 859dbee1f1 Добавить Canvas v4 для исследования связей 2026-11-19 21:13:24 +03:00
AidarKC 8f3b81c368 Исправить регистр ключей и ответные связи 2026-11-19 18:45:57 +03:00
AidarKC 0274183730 Исправить отображение веток комментариев 2026-11-19 16:11:23 +03:00
AidarKC c9f54224bb Обновить тестовый деплой и текст регистрации 2026-11-18 16:23:28 +03:00
AidarKC 02c705d41e Улучшить ссылки и прокрутку личных чатов 2026-11-18 15:50:14 +03:00
AidarKC 76bbc9d023 Обновить shine-users и синхронизацию пользователей 2026-11-18 15:28:07 +03:00
AidarKC 780ca53931 Сделаны переводы другим пользователям 2026-11-18 12:07:13 +03:00
AidarKC fc86c6190e Зафиксировать план будущего формата DM-вложений 2026-11-17 23:08:26 +03:00
AidarKC 2dd0ed6d59 Улучшить вложения и запись голосовых в личной переписке 2026-11-17 15:34:36 +03:00
AidarKC 1f06629838 Увеличить размер частей DM до 64 МиБ 2026-11-17 01:09:16 +03:00
AidarKC c477560632 Добавить лицензию CC0 1.0 2026-11-16 23:50:28 +03:00
AidarKC 548160f7f8 Обновить уведомление безопасности личных чатов 2026-11-16 21:18:03 +03:00
AidarKC a86a380dc7 Обновить окно ошибки запуска UI 2026-11-16 21:14:05 +03:00
AidarKC d9fdaf1930 Включить диагностику ошибок браузера 2026-11-16 12:13:42 +03:00
AidarKC 102feccb2e Очистить устаревший черновик регистрации 2026-11-16 10:59:27 +03:00
AidarKC 1b86bca19a Обновить хранение вложений R2 2026-11-16 10:47:43 +03:00
AidarKC fed28527ae Убрать ложное предупреждение о ротации ключей 2026-11-16 10:03:17 +03:00
AidarKC 2aa770a07b Добавить fallback хранения ключей при сбое IndexedDB 2026-11-16 09:57:41 +03:00
AidarKC 4362c0a015 Исправить завершение регистрации и кнопку повтора 2026-11-16 09:51:57 +03:00
AidarKC 2983ac89e6 Исправить восстановление входа при занятом WebSocket 2026-11-16 09:42:26 +03:00
AidarKC 4a6e072946 Обновить публичные идентификаторы файлов 2026-11-15 15:45:33 +03:00
AidarKC ac6a2e5b3f Исправить восстановление сессии после переподключения 2026-11-15 15:34:10 +03:00
AidarKC e01da7ae87 Исправить восстановление сессии после переподключения WS 2026-11-15 14:35:28 +03:00
AidarKC 70540ff041 Перевести вложения DM на R2 и обновить файловый API 2026-11-15 14:33:52 +03:00
382 changed files with 23110 additions and 3283 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. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
+65
View File
@@ -0,0 +1,65 @@
# SHiNE — патч DM R2 v3 (15.11.2026)
## Основа патча
Накладывать **поверх версии проекта с применённым патчем** `SHiNE-R2-public-MVP-patch-2026.11.14.zip` на архив `SHiNE-bundle-2026.11.14-13.22.24.zip` (либо поверх более новой версии, совместимой с этими серверными API).
Патч **не заменяет** изменённый после предыдущей работы `attachment-format.js` и не трогает новую публичную загрузку, Arweave и аватары.
## Что изменилось
- **Новые DM**: формат `S:file;v=3`, root manifest и AES-256-GCM-шифрование отдельных кусков до 8 МиБ, id = Base58(SHA-256(ciphertext)); **никаких новых BitTorrent/Merkle-хешей**.
- Клиент отправляет JSON `fileId, size` на `POST /api/dm-files/prepare` со старым session key Ed25519 и отдельным доменом подписи `DM_R2_PREPARE_V1`.
- Java подписывает PUT только в корзину `shine-dm`. Ciphertext загружается браузером **напрямую** в S3 endpoint R2. PUT использует `If-None-Match: *`; `Content-Type: application/octet-stream`.
- Скачивание напрямую `https://dm-files.shineup.me/<fileId>` по публичной ссылке; получатель перед расшифровкой проверяет SHA-256/Base58 каждого объекта.
- Никакой ключ AES и исходный MIME в R2 не передаются, они находятся только в E2EE DM.
- **Чтение старых вложений v1 и v2** сохранено. В старых v2 BitTorrent ещё проверяется — исключительно ради совместимости. UI не показывает подпись BitTorrent для v3.
- Передача голосовых вложений использует тот же v3.
- Лимит одного исходного файла в MVP 500 МиБ, один ciphertext-объект ≤8 МиБ+16; нет S3 Multipart и нет строгой гарантии отсутствия повреждённого R2-объекта при первом недобросовестном PUT.
## Настройка Cloudflare
1. Проверьте, что корзина R2 **`shine-dm`** существует и пользовательский домен **`dm-files.shineup.me`** имеет статус **Active**.
2. К `shine-dm` применено **Object Lifecycle → Delete after 14 days → All objects**. По согласованной политике это очистка R2, не гарантия исчезновения CDN-копий.
3. У `shine-dm` установлен CORS для `https://shineup.me` (и реально используемых клиентских доменов). Methods `GET`, `HEAD`, `PUT`; Headers `*`; Expose `Content-Length`, `ETag`.
4. R2 API credential server имеет права **Object Read & Write** для **`shine-files` и `shine-dm`**. Никакие ключи не передаются в UI.
## Настройка Java-сервера
В приватной конфигурации приложения:
```properties
r2.dmBucket=shine-dm
```
В переменных окружения сервиса Java (используются и публичным R2-модулем):
```text
R2_ENDPOINT=https://<account-id>.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=<серверный S3 Access Key ID>
R2_SECRET_ACCESS_KEY=<серверный S3 Secret Access Key>
```
В случае jurisdiction-specific endpoint использовать именно значение из Cloudflare. Не включать переменные в Git или клиентский JS. После применения патча обновить JAR и выполнить restart службы.
**Caddy / Nginx:** добавить точный маршрут `POST /api/dm-files/prepare` (и CORS OPTIONS на тот же URL) к той же Java/Jetty, которая обрабатывает `/ws` и публичный `/api/files/prepare`. Маршрут должен быть выше SPA fallback; `/dm-files/*` оставить для старых файлов v1/v2.
## Проверки
```bash
node scripts/tests/test-dm-r2-v3.mjs
node scripts/tests/test-r2-file-preparation.mjs
python3 scripts/check_docs.py
```
Нужно дополнительно сделать полноценную **Java-сборку и live R2 интеграционный тест на тестовом сервере**, поскольку в среде сборки этого патча Gradle не может скачать дистрибутив.
Рекомендуемый живой сценарий: отправить файл ~9 МиБ из личного чата; убедиться, что появились 2 ciphertext-части и 1 зашифрованный manifest в `shine-dm`, что ключи не попали в R2, а получатель скачал и открыл исходный файл. Затем проверить отправку голосового сообщения, файл 0 байт, файл около 500 МиБ, отсутствующую CORS-настройку и старую переписку v2.
### Ограничения перед production
- Нужны rate limits на выдачу подписанных URL и мониторинг расходов R2; сервер не проверяет байты против объявленного SHA-256 (это проверяет скачивающий клиент).
- `If-None-Match: *` запрещает перезапись уже существующего ID, но не предотвращает первоначальную загрузку неправильных байтов под этим ID.
- Старые клиенты **не умеют читать v3** — потребуется обновить клиентов обоих участников DM.
- Пропуск зашифрованного файла через Java не происходит, но Java подписывает каждую новую часть; возможны десятки prepare-запросов на одно крупное вложение.
- **Production deployment не выполнялся**.
@@ -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||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 <mbedtls/gcm.h>
#include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
#include "shine_core_content.h"
#include <mbedtls/base64.h>
#include <Ed25519.h>
#include <sodium.h>
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
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 blockchainPub[32] = {};
uint8_t blockchainSec[64] = {};
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
continue;
}
uint8_t hash32[32] = {};
sha256calc(preimage.data(), preimage.size(), hash32);
uint8_t signature[64] = {};
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\":\"")
std::vector<uint8_t> fullBlock;
const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
return mbedtls_sha256(data, len, out, 0) == 0;
};
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) + "\"}";
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
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)
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
String addBlockResp;
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;
jsonInt64Field(addBlockResp, "status", statusCode);
String serverLastHash;
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
jsonStringField(addBlockResp, "message", errorMessage);
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 (errorCode.isEmpty()) {
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
@@ -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 server.sync.ArweavePublishSignal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
@@ -20,12 +19,11 @@ public final class ArweaveBlockPublisherService {
private final ArweaveBlocksConfig cfg;
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
private final ArweaveL1Uploader arweaveUploader;
private final TurboDataItemUploader turboUploader;
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
cfg.validatePublisher();
this.cfg = cfg;
this.arweaveUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.ARWEAVE ? new ArweaveL1Uploader(cfg) : null;
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
}
@@ -42,7 +40,7 @@ public final class ArweaveBlockPublisherService {
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
@@ -53,7 +51,7 @@ public final class ArweaveBlockPublisherService {
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
@@ -83,7 +81,7 @@ public final class ArweaveBlockPublisherService {
attempted += rotationCandidates.size();
published += switch (cfg.publishMode()) {
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates);
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0;
};
}
@@ -96,7 +94,7 @@ public final class ArweaveBlockPublisherService {
if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> publishDirectArweave(candidates);
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0;
};
return published;
@@ -110,7 +108,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id);
published++;
@@ -135,7 +133,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id);
published++;
@@ -151,71 +149,4 @@ public final class ArweaveBlockPublisherService {
return published;
}
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
long estimated = 32;
for (KeyRotationCandidateBlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
long next = estimated + 64L + raw.length;
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
if (next > cfg.publishMaxBundleBytes()) {
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
continue;
}
items.add(raw);
ids.add(id);
estimated = next;
}
if (items.isEmpty()) return 0;
byte[] bundle = Ans104Bundle.write(items);
List<ArweaveL1Uploader.Tag> rootTags = List.of(
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
);
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
items.size(), result.txId(), bundle.length);
return items.size();
}
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
long estimated = 32;
for (BlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
long next = estimated + 64L + raw.length;
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
if (next > cfg.publishMaxBundleBytes()) {
log.error("One DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
e.getBchName(), e.getBlockNumber(), raw.length);
continue;
}
items.add(raw);
ids.add(id);
estimated = next;
}
if (items.isEmpty()) return 0;
byte[] bundle = Ans104Bundle.write(items);
List<ArweaveL1Uploader.Tag> rootTags = List.of(
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
);
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
blocksDAO.markArweavePublished(ids, System.currentTimeMillis());
log.info("Published {} SHiNE test DataItems in direct Arweave root tx {} (bundle={} bytes)",
items.size(), result.txId(), bundle.length);
return items.size();
}
}
@@ -10,6 +10,7 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard;
import shine.db.DbController;
import shine.db.KeyEncodingUtil;
import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
@@ -19,6 +20,7 @@ import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO;
import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.RegistrationIdentityDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
@@ -38,9 +40,8 @@ import java.time.Duration;
import java.util.*;
/**
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
* or inside a direct server-created ANS-104 bundle.
* Discovers signed CORE items and registration certificates in the active App namespace.
* Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
*/
public final class ArweaveBlockSyncService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
@@ -120,8 +121,8 @@ public final class ArweaveBlockSyncService {
}
try {
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
if (isRegistrationItem(downloaded.rawDataItem())) {
DownloadedEvent downloaded = downloadEvent(dataItemId);
if (downloaded.registration()) {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(dataItemId);
@@ -167,9 +168,9 @@ public final class ArweaveBlockSyncService {
continue;
}
DownloadedDataItem downloaded;
DownloadedEvent downloaded;
try {
downloaded = downloadSignedDataItem(pending.dataItemId());
downloaded = downloadEvent(pending.dataItemId());
} catch (RetryableDataItemDownloadException e) {
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
unresolvedDownloads.remove(pending.dataItemId());
@@ -183,7 +184,7 @@ public final class ArweaveBlockSyncService {
continue;
}
if (isRegistrationItem(downloaded.rawDataItem())) {
if (downloaded.registration()) {
try {
registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
@@ -225,7 +226,7 @@ public final class ArweaveBlockSyncService {
if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) {
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue;
@@ -249,15 +250,16 @@ public final class ArweaveBlockSyncService {
Ans104DataItem item;
BchBlockEntry parsedBlock;
try {
item = new Ans104DataItem(q.rawDataItem());
parsedBlock = new BchBlockEntry(q.rawDataItem());
parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
item = parsedBlock.getCoreDataItem();
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
} catch (Exception e) {
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
progress = true;
continue;
}
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
@@ -328,14 +330,11 @@ public final class ArweaveBlockSyncService {
}
try {
// Metadata is trusted only after complete ANS-104 validation.
Ans104DataItem item = new Ans104DataItem(raw);
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
Ans104DataItem item = b.getCoreDataItem();
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
throw new IllegalArgumentException("bad App tag");
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
BchBlockEntry b = new BchBlockEntry(raw);
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue;
@@ -352,7 +351,7 @@ public final class ArweaveBlockSyncService {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
@@ -388,9 +387,64 @@ public final class ArweaveBlockSyncService {
}
}
/**
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
*/
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
if (solana != null) return solana;
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
return null;
}
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
if (solana != null) return solana;
if (owner32 == null || owner32.length != 32) return null;
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT login, blockchain_key
FROM user_identity_current
WHERE registration_status='FREE_CERT' AND blockchain_key=?
LIMIT 1
""")) {
ps.setString(1, blockchainKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
}
}
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
if (solana != null) return solana;
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
String login = blockchainName.substring(0, blockchainName.length() - 4);
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
}
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
owner.setLogin(login);
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
owner.setPaidLimitBytes(0L);
return owner;
}
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
@@ -414,7 +468,7 @@ public final class ArweaveBlockSyncService {
while(rs.next())logins.add(rs.getString(1));
}
for(String login:logins){
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
}
@@ -467,7 +521,7 @@ public final class ArweaveBlockSyncService {
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
@@ -477,17 +531,17 @@ public final class ArweaveBlockSyncService {
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
}
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{
validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login);
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,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")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}
@@ -565,6 +619,17 @@ public final class ArweaveBlockSyncService {
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
}
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
if (isRegistrationItem(first.rawDataItem())) {
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
}
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
return new DownloadedEvent(first.rootTxId(), container, false);
}
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
return graphQlPage(minHeight, cursor, false);
}
@@ -763,6 +828,7 @@ public final class ArweaveBlockSyncService {
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
private static final class RetryableDataItemDownloadException extends IOException {
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
}
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE;
public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
public static ArweaveBlocksConfig load() {
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
public void validatePublisher() {
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) {
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave");
if (publishMode == PublishMode.ARWEAVE) {
throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
}
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
@@ -33,7 +33,9 @@ public final class FreeRegistrationApiBootstrap {
FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null;
AllowedEmailDomains allowedEmailDomains=null;
if (cfg.getBoolean("freeRegistration.enabled",false)) {
String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
if (freeRegistrationEnabled) {
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
// Относительный путь — от WorkingDirectory процесса Java.
@@ -44,6 +46,8 @@ public final class FreeRegistrationApiBootstrap {
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport");
newSigner=LocalRegistrarSigner.fromConfig(cfg);
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
cfg.getStringOrEmpty("server.SHiNE.login"));
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
new VerifiedFreeRegistrationImporter(allowEmailReuse));
@@ -58,7 +62,8 @@ public final class FreeRegistrationApiBootstrap {
}
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
freeRegistrationEnabled ? freeNamespace : "");
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow;
}
@@ -16,10 +16,7 @@ import java.util.Locale;
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
public final class FreeRegistrationCertificateV1 {
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
private static final List<Ans104DataItem.Tag> TAGS = List.of(
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
byte[] clientKey, byte[] innerSignature,
@@ -24,6 +24,30 @@ public final class FreeRegistrationIssuer {
this.allowEmailReuse = allowEmailReuse;
}
/** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */
static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace,
String localServerLogin) throws Exception {
if (localServerLogin == null || localServerLogin.isBlank())
throw new IllegalStateException("server.SHiNE.login is required for free registration");
try (Connection conn = db.getConnection();
PreparedStatement statement = conn.prepareStatement("""
SELECT namespace_type, registrar_pubkey, default_server_login
FROM shine_namespace_current WHERE namespace = ?
""")) {
statement.setString(1, namespace);
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next() || rs.getInt("namespace_type") != 2)
throw new IllegalStateException("Configured free registration namespace is unavailable");
byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey"));
if (!Arrays.equals(namespaceKey, signer.publicKey32()))
throw new IllegalStateException("Registrar public key does not match configured namespace");
String namespaceServer = rs.getString("default_server_login");
if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim()))
throw new IllegalStateException("Configured free namespace belongs to another access server");
}
}
}
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
byte[] client32, String email) throws Exception {
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
private final boolean allowTestCode;
private final boolean allowEmailReuse;
private final AllowedEmailDomains allowedEmailDomains;
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
private final String freeRegistrationNamespace;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
if (emailSender != null && allowedEmailDomains == null)
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
this.emailSender = emailSender;
this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse;
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
}
private static String normalizeConfiguredNamespace(String value) {
String namespace = value == null ? "" : value.trim();
if (namespace.isEmpty()) return "";
if (!namespace.matches("[a-z0-9_]+"))
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
return namespace;
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
emailSender == null ? null : loadDefaultEmailDomains());
emailSender == null ? null : loadDefaultEmailDomains(), "");
}
private static AllowedEmailDomains loadDefaultEmailDomains() {
try {
@@ -94,11 +109,16 @@ public final class FreeRegistrationWorkflow {
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
FROM shine_namespace_current ORDER BY namespace
"""); ResultSet rs = ps.executeQuery()) {
FROM shine_namespace_current
WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?)
ORDER BY namespace
""")) {
ps.setString(1, freeRegistrationNamespace);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
rs.getString(4),rs.getInt(5),rs.getString(6)));
}
}
return List.copyOf(result);
}
public LoginCheck checkLogin(String login) throws Exception {
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
try (ResultSet rs=p.executeQuery()) {
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
}
@@ -122,9 +122,12 @@ public final class VerifiedFreeRegistrationImporter {
INSERT INTO blockchain_state_store (
login, fork_number, blockchain_key, size_limit, file_size_bytes,
last_block_number, last_block_hash, updated_at_ms)
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
""")) {
insert.setString(1, login);
// blockchain_state — техническая проекция chain: её ключ
// совпадает с normalized_login и blockchain_name, а не с
// отображаемым написанием login в сертификате.
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
// как и у пользователей, импортированных из Solana PDA.
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
@@ -19,7 +19,7 @@ public final class FreeRegistrationCertificateV1Check {
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
" Alice.Example+Tag@Example.COM ", signer);
var item = new Ans104DataItem(cert);
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE))
throw new AssertionError("Current App tag missing");
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
@@ -37,7 +37,7 @@ public final class FreeRegistrationCertificateV1Check {
throw new AssertionError("Inner signature tampering accepted"); }
catch (IllegalArgumentException expected) {}
}
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
}
}
@@ -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)");
}
}
@@ -0,0 +1,20 @@
package server.archive.registration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FreeRegistrationNamespaceConfigurationTest {
@Test
void acceptsLowercaseNamespaceForLocalFreeRegistration() {
assertDoesNotThrow(() -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "testfree"));
}
@Test
void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() {
assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "TestFree"));
}
}
@@ -56,7 +56,7 @@ public final class Ans104DataItem {
public Ans104DataItem(byte[] bytes) {
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);
}
if (bytes.length > MAX_DATA_ITEM_BYTES) {
@@ -126,7 +126,8 @@ public final class Ans104DataItem {
}
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[] 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(
utf8("dataitem"),
utf8("1"),
@@ -270,15 +275,20 @@ public final class Ans104DataItem {
}
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
if (raw.length == 0 && declaredCount == 0) return List.of();
AvroCursor c = new AvroCursor(raw);
List<Tag> out = new ArrayList<>();
boolean terminated = false;
while (!c.eof()) {
long count = c.readLong();
if (count == 0) break;
if (count == 0) { terminated = true; break; }
int blockEnd = -1;
if (count < 0) {
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
count = -count;
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) {
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");
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()) {
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
}
@@ -312,6 +324,7 @@ public final class Ans104DataItem {
while (true) {
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
int b = data[p++] & 0xff;
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
raw |= (long) (b & 0x7f) << shift;
if ((b & 0x80) == 0) break;
shift += 7;
@@ -324,7 +337,9 @@ public final class Ans104DataItem {
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
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;
return s;
}
@@ -49,6 +49,9 @@ public final class BchBlockEntry {
public final BodyRecord body;
private final Ans104DataItem dataItem;
private final Ans104DataItem contentItem;
private final CoreRecord coreRecord;
private final ContentRecord contentRecord;
private final byte[] frameBytes;
private final byte[] hash32;
@@ -56,6 +59,9 @@ public final class BchBlockEntry {
public BchBlockEntry(byte[] fullDataItemBytes) {
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
this.dataItem = new Ans104DataItem(fullDataItemBytes);
this.contentItem = null;
this.coreRecord = null;
this.contentRecord = null;
this.frameBytes = dataItem.data();
if (frameBytes.length < FRAME_HEADER_SIZE) {
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
@@ -90,7 +96,57 @@ public final class BchBlockEntry {
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); }
/** Kept as an alias for code/docs that called the old field preimage. */
public byte[] getPreimageBytes() { return getFrameBytes(); }
@@ -98,8 +154,8 @@ public final class BchBlockEntry {
public byte[] getOwner32() { return dataItem.owner32(); }
public byte[] getDataItemId32() { return dataItem.id32(); }
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
/** Full serialized ANS-104 DataItem. */
public byte[] toBytes() { return dataItem.rawBytes(); }
/** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
@Override
public String toString() {
@@ -22,6 +22,13 @@ public final class BchCryptoVerifier {
Objects.requireNonNull(block, "block == null");
Objects.requireNonNull(publicKey32, "publicKey32 == null");
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();
}
}
@@ -18,7 +18,8 @@ public final class BodyRecordParser {
// TECH supports Header v1 and CreateChannel current format (ver=1).
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) && v == (HeaderBody.VER & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
&& (v == (HeaderBody.VER & 0xFFFF) || v == (HeaderBody.VER_CC0 & 0xFFFF))) {
return new HeaderBody(subType, version, bodyBytes).check();
}
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -0,0 +1,65 @@
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");
if (content.version() != 1) throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
boolean header = content.type() == 0 && content.subType() == MsgSubType.HEADER_COMPAT;
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;
//
///**
// * LineIndex — канонические номера линий блокчейна.
// *
// * Линия = независимая последовательность блоков внутри одного блокчейна.
// */
//public final class LineIndex {
//
// private LineIndex() {}
//
// 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; // профиль пользователя да надо
//}
package blockchain;
/** Канонические линии CORE v2; Frame v1 использует старую модель. */
public final class LineIndex {
private LineIndex() {}
public static final int DEFAULT_CHANNEL = 0;
public static final int USER_PROFILE = CoreRecord.PROFILE;
public static final int CONNECTION = CoreRecord.CONNECTION;
public static final int TECH = CoreRecord.TECH;
public static final int MAX_CHANNEL = CoreRecord.MAX_BLOCK_NUMBER;
public static boolean isChannel(int code) { return code >= 0 && code <= MAX_CHANNEL; }
}
@@ -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 {
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 APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE;
@@ -21,6 +21,9 @@ package blockchain.body;
*/
public interface BodyHasLine {
/** CORE не подписывает ordinal; до проверки канонического хвоста значение отсутствует. */
int UNRESOLVED_SEQUENCE = -1;
int lineCode();
int prevLineBlockGlobalNumber();
@@ -1,6 +1,7 @@
package blockchain.body;
import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer;
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 int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType;
public final short version;
public final int prevConnectionBlockNumber;
@@ -27,16 +29,28 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public final byte[] toBlockHash32;
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");
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, 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.prevConnectionBlockHash32 = new byte[32];
bb.get(this.prevConnectionBlockHash32);
this.connectionSequence = bb.getInt();
}
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login();
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,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
this.contentOnly = false;
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
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 (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
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");
return this;
}
@Override public byte[] toBytes() {
check();
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 40) + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array();
}
@@ -1,6 +1,7 @@
package blockchain.body;
import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -42,6 +43,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
private final boolean contentOnly;
public final short subType;
public final short version;
@@ -56,6 +58,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
public final short channelTypeVersion;
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");
this.subType = subType;
this.version = version;
@@ -67,16 +75,23 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
if ((this.subType & 0xFFFF) != (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");
}
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.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
}
int nameLen = Byte.toUnsignedInt(bb.get());
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];
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());
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
@@ -100,7 +115,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
} else {
byte[] descriptionBytes = new byte[descriptionLen];
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.channelTypeVersion = bb.getShort();
@@ -117,6 +132,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String channelDescription,
short channelTypeCode,
short channelTypeVersion) {
this.contentOnly = false;
Objects.requireNonNull(channelName, "channelName == null");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
@@ -142,6 +158,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String normalizedName = normalizeDisplayName(channelName);
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
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");
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 (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;
}
@@ -199,12 +216,14 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
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);
if (!contentOnly) {
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
}
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
@@ -1,6 +1,7 @@
package blockchain.body;
import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer;
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_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
private final boolean contentOnly;
public final short subType;
public final short version;
@@ -69,6 +71,12 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public final String comment;
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");
this.subType = subType;
this.version = version;
@@ -79,16 +87,23 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
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");
}
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.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
}
this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32);
@@ -111,7 +126,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
}
byte[] commentBytes = new byte[commentLen];
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,
@@ -128,6 +143,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
int discardedBlocksCount,
int reasonCode,
String comment) {
this.contentOnly = false;
this.subType = SUBTYPE;
this.version = VER;
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 (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
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(forkPointBlockHash32, "forkPointBlockHash32");
@@ -186,11 +202,13 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public byte[] toBytes() {
check();
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(prevLineNumber);
bb.put(prevLineHash32);
bb.putInt(thisLineNumber);
}
bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32);
@@ -9,12 +9,13 @@ import java.util.Arrays;
import java.util.Objects;
/**
* HeaderBody — type=0, subType=0, version=1.
* HeaderBody — TECH type=0, subType=0; version=1 legacy / version=2 CC0.
*
* bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII
* [1] loginLength (uint8)
* [N] login UTF-8
* [15] ASCII "license:CC0-1.0" (version=2 only)
* [32] initialBlockchainKey32
*
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
@@ -23,7 +24,11 @@ import java.util.Objects;
*/
public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
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 String LICENSE_CC0 = "CC0-1.0";
public static final String LICENSE_FIELD_CC0 = "license:" + LICENSE_CC0;
private static final byte[] LICENSE_BYTES = LICENSE_FIELD_CC0.getBytes(StandardCharsets.US_ASCII);
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final short SUBTYPE_COMPAT = 0;
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
@@ -36,14 +41,16 @@ public final class HeaderBody implements BodyRecord {
public final String tag;
public final String login;
public final byte[] initialBlockchainKey32;
public final String license; // null for legacy HEADER v1
public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("HeaderBody version must be 1 or 2");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0))
throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
byte[] tagBytes = new byte[TAG_LEN];
@@ -53,30 +60,57 @@ public final class HeaderBody implements BodyRecord {
this.tag = parsedTag;
int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0 || bb.remaining() != loginLen + 32) throw new IllegalArgumentException("Bad HeaderBody login/key length");
if (loginLen <= 0 || bb.remaining() != loginLen + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0))
throw new IllegalArgumentException("Bad HeaderBody login/key/license length");
byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
if (version == VER_CC0) {
byte[] actual = new byte[LICENSE_BYTES.length];
bb.get(actual);
if (!Arrays.equals(actual, LICENSE_BYTES)) throw new IllegalArgumentException("Unsupported HEADER license");
this.license = LICENSE_CC0;
} else {
this.license = null;
}
this.initialBlockchainKey32 = new byte[32];
bb.get(this.initialBlockchainKey32);
requireNonZeroKey(this.initialBlockchainKey32);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
}
// Legacy constructor is kept for historical fixtures and importing v1 blocks.
public HeaderBody(String login, byte[] initialBlockchainKey32) {
this(login, initialBlockchainKey32, VER);
}
/** HEADER для CORE v2 / CONTENT v1: сохраняет login и начальный ключ, без поля лицензии. */
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER);
}
public static HeaderBody licensedCc0(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32, VER_CC0);
}
private HeaderBody(String login, byte[] initialBlockchainKey32, short version) {
Objects.requireNonNull(login, "login == null");
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
this.subType = SUBTYPE_COMPAT;
this.version = VER;
this.version = version;
this.tag = TAG;
this.login = login;
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
this.license = version == VER_CC0 ? LICENSE_CC0 : null;
check();
}
@Override
public HeaderBody check() {
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_CC0 && !LICENSE_CC0.equals(license)) throw new IllegalArgumentException("Bad HEADER CC0 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");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
@@ -95,10 +129,11 @@ public final class HeaderBody implements BodyRecord {
public byte[] toBytes() {
check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32 + (version == VER_CC0 ? LICENSE_BYTES.length : 0)).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII);
bb.put((byte) loginUtf8.length);
bb.put(loginUtf8);
if (version == VER_CC0) bb.put(LICENSE_BYTES);
bb.put(initialBlockchainKey32);
return bb.array();
}
@@ -112,6 +147,6 @@ public final class HeaderBody implements BodyRecord {
@Override
public String toString() {
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}";
return "HeaderBody{version=" + version + ", login='" + login + "', license=" + license + ", initialBlockchainKey32=<32 bytes>}";
}
}
@@ -1,6 +1,7 @@
package blockchain.body;
import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer;
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 int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType;
public final short version;
public final int lineCode;
@@ -40,17 +42,30 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
public final String message;
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");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
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.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
}
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
@@ -88,6 +103,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
Integer toBlockGlobalNumber,
byte[] toBlockHash32,
String message) {
this.contentOnly = false;
Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
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;
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);
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 44) + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
@@ -1,6 +1,7 @@
package blockchain.body;
import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer;
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);
private final boolean contentOnly;
public final short subType;
public final short version;
@@ -46,6 +48,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public final String paramValue;
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");
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)
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");
}
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.prevProfileBlockHash32 = new byte[32];
bb.get(this.prevProfileBlockHash32);
this.profileSequence = bb.getInt();
}
int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
@@ -98,6 +112,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
int profileSequence,
String paramKey,
String paramValue) {
this.contentOnly = false;
Objects.requireNonNull(paramKey, "paramKey == 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 (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 (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 (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 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(prevProfileBlockNumber);
bb.put(prevProfileBlockHash32);
bb.putInt(profileSequence);
}
bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8);
bb.putShort((short) valUtf8.length);
@@ -0,0 +1,287 @@
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");
bad(() -> parseSemantic(new ContentRecord(0,0,2,HeaderBody.licensedCc0("Alice",OWNER).toBytes())),"CC0 HEADER");
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);
}
}
@@ -108,6 +108,41 @@ final class TargetLoginFormatTest {
}
}
@Test
void licensedHeaderV2IncludesExactCc0ConstantAndParsesAlongsideV1() {
HeaderBody v2 = HeaderBody.licensedCc0("Alice@shine", INITIAL_KEY);
assertEquals(HeaderBody.VER_CC0, v2.version);
assertEquals("CC0-1.0", v2.license);
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, v2.toBytes()).check();
assertEquals("Alice@shine", parsed.login);
assertEquals("CC0-1.0", parsed.license);
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
assertArrayEquals(v2.toBytes(), parsed.toBytes());
HeaderBody legacy = new HeaderBody("Alice@shine", INITIAL_KEY);
assertNull(new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, legacy.toBytes()).license);
assertEquals(legacy.toBytes().length + 15, v2.toBytes().length);
byte[] expectedLicenseMarker = "license:CC0-1.0".getBytes(java.nio.charset.StandardCharsets.US_ASCII);
int markerOffset = 5 + 1 + "Alice@shine".getBytes(java.nio.charset.StandardCharsets.UTF_8).length;
assertArrayEquals(expectedLicenseMarker, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset, markerOffset + 15));
assertArrayEquals(INITIAL_KEY, java.util.Arrays.copyOfRange(v2.toBytes(), markerOffset + 15, v2.toBytes().length));
byte[] invalid = v2.toBytes();
invalid[markerOffset + 8] = (byte)'X';
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, invalid));
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, v2.toBytes()));
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, legacy.toBytes()));
byte[] swapped = v2.toBytes();
System.arraycopy(INITIAL_KEY, 0, swapped, markerOffset, 32);
System.arraycopy(expectedLicenseMarker, 0, swapped, markerOffset + 32, 15);
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER_CC0, swapped));
}
@Test
void namespacedHeaderRejectsMalformedOrOversizedLogin() {
for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) {
@@ -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);
}
}
}
@@ -31,6 +31,11 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_38 = 38;
public static final int SCHEMA_VERSION_39 = 39;
public static final int SCHEMA_VERSION_40 = 40;
public static final int SCHEMA_VERSION_41 = 41;
public static final int SCHEMA_VERSION_42 = 42;
public static final int SCHEMA_VERSION_43 = 43;
public static final int SCHEMA_VERSION_44 = 44;
public static final int SCHEMA_VERSION_45 = 45;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -42,6 +47,11 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.sql";
public static final String POSTGRES_MIGRATION_V39_RESOURCE = "postgres/migration_v39.sql";
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
public static final String POSTGRES_MIGRATION_V41_RESOURCE = "postgres/migration_v41.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_V44_RESOURCE = "postgres/migration_v44.sql";
public static final String POSTGRES_MIGRATION_V45_RESOURCE = "postgres/migration_v45.sql";
private DatabaseInitializer() {}
@@ -173,9 +183,29 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V40_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_40) {
if (currentVersion == SCHEMA_VERSION_40) {
runSqlScript(conn, POSTGRES_MIGRATION_V41_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_41) {
runSqlScript(conn, POSTGRES_MIGRATION_V42_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_42) {
runSqlScript(conn, POSTGRES_MIGRATION_V43_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_43) {
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_44) {
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_45) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 40, found " + currentVersion);
"Unsupported SHiNE DB v2 schema version: expected 45, found " + currentVersion);
}
normalizeBlockchainStateKeysToBase64(conn);
}
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
}
}
/** Change ONLY the quota projection; 0 means unbounded. */
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
ChainRef r = chainRef(blockchainName);
ps.setLong(1, limit);
ps.setLong(2, System.currentTimeMillis());
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.executeUpdate();
}
}
/**
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
*/
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
String sql = """
UPDATE blockchain_state_store
SET
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
updated_at_ms = ?
WHERE
LOWER(login) = LOWER(?) AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit
AND file_size_bytes <= 9223372036854775807 - ?
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.setLong(5, deltaBytes);
ps.setLong(6, deltaBytes);
return ps.executeUpdate() > 0;
}
}
@@ -9,7 +9,7 @@ import java.sql.*;
import java.util.ArrayList;
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 {
private static volatile BlocksDAO instance;
private final DbController db = DbController.getInstance();
@@ -67,12 +67,53 @@ public final class ChannelNameStateDAO {
channel_root_block_hash,
created_at_ms,
ava_ar,
ava_sha256,
ava_pr,
ava_size,
meta_updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""";
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(2, entry.getDisplayName());
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
@@ -84,11 +125,9 @@ public final class ChannelNameStateDAO {
ps.setBytes(9, entry.getChannelRootBlockHash());
ps.setLong(10, entry.getCreatedAtMs());
ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr());
ps.setString(12, entry.getAvaSha256() == null ? "" : entry.getAvaSha256());
ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
ps.setLong(13, Math.max(0L, entry.getAvaSize()));
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.executeUpdate();
}
}
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
@@ -97,7 +136,7 @@ public final class ChannelNameStateDAO {
SET display_name = ?,
channel_description = ?,
ava_ar = ?,
ava_sha256 = ?,
ava_pr = ?,
ava_size = ?,
meta_updated_at_ms = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
@@ -106,7 +145,7 @@ public final class ChannelNameStateDAO {
ps.setString(1, entry.getDisplayName() == null ? "" : entry.getDisplayName());
ps.setString(2, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
ps.setString(3, entry.getAvaAr() == null ? "" : entry.getAvaAr());
ps.setString(4, entry.getAvaSha256() == null ? "" : entry.getAvaSha256());
ps.setString(4, entry.getAvaPr() == null ? "" : entry.getAvaPr());
ps.setLong(5, Math.max(0L, entry.getAvaSize()));
ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.setString(7, entry.getOwnerLogin());
@@ -299,7 +299,8 @@ public final class ChannelReadStateDAO {
}
/**
* 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 {
String sql = """
@@ -317,6 +318,8 @@ public final class ChannelReadStateDAO {
)
UPDATE channel_read_state crs
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=?
FROM counts
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
@@ -13,7 +13,7 @@ public final class ChannelSearchDAO {
private ChannelSearchDAO() {}
public record Match(String ownerLogin, String slug, String displayName, String description,
String avatarAr, String avatarSha256, String ownerBlockchainName,
String avatarAr, String avatarPr, String ownerBlockchainName,
int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {}
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
@@ -45,7 +45,7 @@ public final class ChannelSearchDAO {
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
String sql = """
SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description,
cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash,
COALESCE(cs.subscribers_count, 0) AS subscribers_count
FROM channel_names_state cn
@@ -109,7 +109,7 @@ public final class ChannelSearchDAO {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) matches.add(new Match(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"),
rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_sha256"),
rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_pr"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"),
rs.getString("root_hash"), rs.getInt("subscribers_count")
));
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
return null;
if (rs.next()) return mapRow(rs);
}
return mapRow(rs);
}
// Old forks remain valid separate blockchains even after root rotation.
String forkSql = """
SELECT u.login,
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
f.value ->> 'blockchainKey' AS blockchain_key,
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
FROM solana_user_pda_current u
CROSS JOIN LATERAL jsonb_array_elements(
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
) AS f(value)
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
@@ -10,6 +10,7 @@ import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public final class UserNotificationsStateDAO {
private static volatile UserNotificationsStateDAO instance;
@@ -45,7 +46,7 @@ public final class UserNotificationsStateDAO {
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, e.getOwnerLogin());
ps.setString(i++, normalizedLogin(e.getOwnerLogin()));
ps.setString(i++, e.getNotificationKind());
ps.setLong(i++, e.getCreatedAtMs());
ps.setString(i++, e.getSourceLogin());
@@ -74,7 +75,7 @@ public final class UserNotificationsStateDAO {
""";
List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin);
ps.setString(1, normalizedLogin(ownerLogin));
ps.setString(2, kind);
ps.setInt(3, Math.max(1, limit));
try (ResultSet rs = ps.executeQuery()) {
@@ -96,7 +97,7 @@ public final class UserNotificationsStateDAO {
""";
List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setLong(4, Math.max(0, cutoffMs));
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
}
@@ -106,7 +107,7 @@ public final class UserNotificationsStateDAO {
public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException {
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
}
}
@@ -129,4 +130,12 @@ public final class UserNotificationsStateDAO {
e.setSourceText(rs.getString("source_text"));
return e;
}
/**
* owner_login — технический FK на normalized_login. Исходный регистр остаётся
* в полях подписанного блока и в отображаемых source/target login.
*/
private static String normalizedLogin(String login) {
return login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
}
@@ -116,7 +116,7 @@ public final class UserProfileStateDAO {
String sql;
if ("owned".equals(mode)) {
sql="""
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, 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.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM channel_names_state cn
@@ -125,7 +125,7 @@ public final class UserProfileStateDAO {
""";
} else if ("following".equals(mode)) {
sql="""
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
SELECT DISTINCT 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.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM connections_state cs
@@ -142,7 +142,7 @@ public final class UserProfileStateDAO {
ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset);
try(ResultSet rs=ps.executeQuery()){
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_sha256"),
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.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number")
));
@@ -154,5 +154,5 @@ public final class UserProfileStateDAO {
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 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 ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String avatarSha256,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String avatarPr,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){}
}
@@ -6,9 +6,9 @@ package shine.db.entities;
* Храним:
* - login + fork_number (physical fork identity; bch_name is derived only for display/API)
* - block_number (глобальный номер в этой цепочке)
* - block_bytes (полный блок: preimage + signature)
* - block_hash (32 байта вычисленный SHA-256(preimage))
* - block_signature (64 байта)
* - block_bytes (контейнер двух оригинальных подписанных ANS-104)
* - block_hash (32 байта вычисленный SHA-256(CORE payload))
* - block_signature (64 байта, подпись CORE)
*
* Опционально:
* - line_code / prev_line_number / prev_line_hash / this_line_number
@@ -1,6 +1,7 @@
package shine.db.entities;
import java.util.Base64;
import java.util.Locale;
/**
* Агрегатная сущность текущего состояния блокчейна.
@@ -42,14 +43,18 @@ public final class BlockchainStateEntry {
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
this.login=blockchainName.substring(0,dash);
// Runtime-ключ цепочки всегда нормализован. Исходное написание
// зарегистрированного login хранится отдельно в user_identity_current.
this.login=blockchainName.substring(0,dash).trim().toLowerCase(Locale.ROOT);
this.forkNumber=parsedFork;
}
public int getForkNumber() { return forkNumber; }
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public void setLogin(String login) {
this.login = login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
public String getBlockchainKey() { return blockchainKey; }
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
@@ -14,7 +14,7 @@ public class ChannelNameStateEntry {
private byte[] channelRootBlockHash;
private long createdAtMs;
private String avaAr;
private String avaSha256;
private String avaPr;
private long avaSize;
private long metaUpdatedAtMs;
@@ -106,12 +106,12 @@ public class ChannelNameStateEntry {
this.avaAr = avaAr;
}
public String getAvaSha256() {
return avaSha256;
public String getAvaPr() {
return avaPr;
}
public void setAvaSha256(String avaSha256) {
this.avaSha256 = avaSha256;
public void setAvaPr(String avaPr) {
this.avaPr = avaPr;
}
public long getAvaSize() {
@@ -0,0 +1,7 @@
-- SHiNE v41: public channel avatars now use BitTorrent v2 PR (Base58), no SHA256 legacy.
BEGIN;
ALTER TABLE channel_names_state RENAME COLUMN ava_sha256 TO ava_pr;
-- Old sha256 hex values cannot be used as Pieces Root; no automatic conversion exists.
UPDATE channel_names_state SET ava_pr = '', ava_ar = '', ava_size = 0 WHERE ava_pr <> '';
UPDATE db_schema_version SET schema_version = 41 WHERE id = 1;
COMMIT;
@@ -0,0 +1,27 @@
-- SHiNE v42: журнал выдачи разрешений R2 (не подтверждение успешного PUT).
-- В DM записываются только зашифрованные объекты (включая манифест), без имени и MIME.
BEGIN;
CREATE TABLE IF NOT EXISTS public_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS public_file_uploads_user_time_idx ON public_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS public_file_uploads_hash_idx ON public_file_uploads (file_hash);
CREATE TABLE IF NOT EXISTS dm_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS dm_file_uploads_user_time_idx ON dm_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS dm_file_uploads_hash_idx ON dm_file_uploads (file_hash);
UPDATE db_schema_version SET schema_version = 42, updated_at_ms = (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT WHERE id = 1;
COMMIT;
@@ -0,0 +1,43 @@
-- v43: runtime-идентичность blockchain_state совпадает с normalized_login.
-- Исходный регистр зарегистрированного имени остаётся в user_identity_current.login
-- и никогда не переписывает подписанные сертификаты или блоки.
BEGIN;
-- blocks_store уже использует normalized_login. Временно снимаем составной FK,
-- чтобы привести родительские строки blockchain_state к тому же ключу.
ALTER TABLE blocks_store DROP CONSTRAINT IF EXISTS fk_blocks_physical_fork;
ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_login_fkey;
-- v36-совместимость подставляла display login, что несовместимо с blocks_store.
DROP TRIGGER IF EXISTS trg_canonical_identity_blockchain_state_store_login
ON blockchain_state_store;
UPDATE blockchain_state_store
SET login = LOWER(BTRIM(login))
WHERE login IS DISTINCT FROM LOWER(BTRIM(login));
ALTER TABLE blockchain_state_store
ADD CONSTRAINT blockchain_state_login_fkey
FOREIGN KEY (login) REFERENCES user_identity_current(normalized_login);
ALTER TABLE blocks_store
ADD CONSTRAINT fk_blocks_physical_fork
FOREIGN KEY (login, fork_number)
REFERENCES blockchain_state_store(login, fork_number);
CREATE OR REPLACE FUNCTION shine_normalize_blockchain_state_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.login := LOWER(BTRIM(NEW.login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_blockchain_state_login
BEFORE INSERT OR UPDATE OF login ON blockchain_state_store
FOR EACH ROW EXECUTE FUNCTION shine_normalize_blockchain_state_login();
UPDATE db_schema_version
SET schema_version = 43,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,29 @@
-- v44: owner_login уведомлений — технический ключ normalized_login.
-- Исходный регистр остаётся в содержимом подписанных блоков и полях source/target.
BEGIN;
UPDATE user_notifications_state
SET owner_login = LOWER(BTRIM(owner_login))
WHERE owner_login IS DISTINCT FROM LOWER(BTRIM(owner_login));
DROP TRIGGER IF EXISTS trg_canonical_identity_user_notifications_state_owner_login
ON user_notifications_state;
DROP TRIGGER IF EXISTS trg_normalize_user_notifications_state_owner_login
ON user_notifications_state;
CREATE OR REPLACE FUNCTION shine_normalize_user_notification_owner_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.owner_login := LOWER(BTRIM(NEW.owner_login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_user_notifications_state_owner_login
BEFORE INSERT OR UPDATE OF owner_login ON user_notifications_state
FOR EACH ROW EXECUTE FUNCTION shine_normalize_user_notification_owner_login();
UPDATE db_schema_version
SET schema_version = 44,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -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;
@@ -34,9 +34,14 @@ dependencies {
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
}
test {
useJUnitPlatform()
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseUserPdaV12(raw);
}
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5);
int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null;
if (major != 1 || (minor != 2 && minor != 3)) return null;
return parseServerProfileV12(raw);
}
@@ -0,0 +1,24 @@
package server.logic.ws_protocol.JSON.handlers.avatars;
import java.math.BigInteger;
import java.util.regex.Pattern;
/** Canonical 32-byte BitTorrent v2 pieces root encoded as Bitcoin Base58. */
public final class PiecesRootValidator {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static final Pattern B58 = Pattern.compile("^[1-9A-HJ-NP-Za-km-z]{32,44}$");
private PiecesRootValidator() {}
public static boolean valid(String root) {
if (root == null || !B58.matcher(root).matches()) return false;
int leadingZeros = 0;
while (leadingZeros < root.length() && root.charAt(leadingZeros) == '1') leadingZeros++;
BigInteger value = BigInteger.ZERO;
for (int i = leadingZeros; i < root.length(); i++) {
int digit = ALPHABET.indexOf(root.charAt(i));
if (digit < 0) return false;
value = value.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(digit));
}
int dataBytes = value.signum() == 0 ? 0 : (value.bitLength() + 7) / 8;
return leadingZeros + dataBytes == 32;
}
}
@@ -3,7 +3,7 @@ package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.CoreContentContainer;
import blockchain.body.BodyHasLine;
import blockchain.body.BodyHasTarget;
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.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.LineContinuity;
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.channels.ChannelMetaTextParser;
@@ -38,6 +39,8 @@ import shine.db.dao.BlocksDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.dao.UserNotificationsStateDAO;
import shine.db.dao.UserParamsDAO;
import shine.db.entities.BlockchainStateEntry;
@@ -53,6 +56,7 @@ import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;
/**
@@ -67,6 +71,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
@@ -201,9 +210,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "limit_exceeded" -> "Превышен лимит размера блокчейна";
case "limit_check_failed" -> "Ошибка проверки лимита размера";
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 "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
@@ -211,8 +217,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "bad_block_number" -> "Некорректный номер блока";
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
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 "signature_verify_failed" -> "Ошибка проверки подписи блока";
case "bad_signature" -> "Некорректная подпись блока";
@@ -222,7 +226,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "bad_line_state" -> "Повреждено состояние логической линии";
case "bad_prev_line_number" -> "Блок не продолжает текущий хвост логической линии";
case "bad_prev_line_hash" -> "Некорректный prevLineHash";
case "bad_line_sequence" -> "Некорректный порядковый номер логической линии";
case "unsupported_line_body" -> "Этот body не поддерживает логическую линию";
case "db_error_prev_line_check", "db_error_line_check" -> "Ошибка БД при проверке логической линии";
case "channel_name_already_exists" -> "Такое название канала уже занято";
@@ -281,7 +284,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
recovered.setBlockchainName(user.getBlockchainName());
recovered.setLogin(user.getLogin());
recovered.setBlockchainKey(user.getBlockchainKey());
recovered.setSizeLimit(100_000L);
recovered.setSizeLimit(Math.max(0L, resolveChainLimit(user.getBlockchainName())));
recovered.setFileSizeBytes(0L);
recovered.setLastBlockNumber(-1);
recovered.setLastBlockHash(new byte[32]);
@@ -335,7 +338,12 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// 3) лимит (оставляем как было)
try {
long oldSize = st.getFileSizeBytes();
long limit = st.getSizeLimit();
// Current synced Solana PDA is authoritative; free users have no PDA.
long limit = resolveChainLimit(blockchainName);
if (limit != st.getSizeLimit()) {
stateDAO.updateSizeLimit(blockchainName, limit);
st.setSizeLimit(limit);
}
long newSize = safeAdd(oldSize, blockBytes.length);
if (limit > 0 && newSize > limit) {
@@ -351,27 +359,14 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
// 4) parse block
final BchBlockEntry block;
try {
block = new BchBlockEntry(blockBytes);
block = BchBlockEntry.fromCoreContent(blockBytes);
} catch (Exception e) {
log.warn("AddBlock: не удалось распарсить BchBlockEntry (login={}, blockchainName={}, bytesLen={})",
login, blockchainName, blockBytes.length, e);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_format", serverLastNum, serverLastHashHex);
}
if (!block.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) {
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);
}
// Подписанные App/n/l и обе подписи уже проверены парсером пары.
// body.check()
try {
@@ -440,7 +435,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
try {
if (channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
if (!replayMode && channelNameStateDAO.existsByOwnerTypeAndSlug(blockchainName, channelTypeCode, slug)) {
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
@@ -454,7 +449,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
? ""
: ChannelNameRules.normalizeDisplayName(createChannelBody.channelDescription);
String avaAr = "";
String avaSha256 = "";
String avaPr = "";
long avaSize = 0L;
long metaUpdatedAtMs = 0L;
if (channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_PUBLIC & 0xFFFF)) {
@@ -463,7 +458,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
displayName = createMeta.title();
channelDescription = createMeta.description();
avaAr = createMeta.avaAr();
avaSha256 = createMeta.avaSha256();
avaPr = createMeta.avaPr();
avaSize = createMeta.avaSize();
metaUpdatedAtMs = block.timestamp * 1000L;
} catch (IllegalArgumentException e) {
@@ -476,7 +471,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
channelNameStateEntry.setDisplayName(displayName);
channelNameStateEntry.setChannelDescription(channelDescription);
channelNameStateEntry.setAvaAr(avaAr);
channelNameStateEntry.setAvaSha256(avaSha256);
channelNameStateEntry.setAvaPr(avaPr);
channelNameStateEntry.setAvaSize(avaSize);
channelNameStateEntry.setMetaUpdatedAtMs(metaUpdatedAtMs);
channelNameStateEntry.setOwnerLogin(login);
@@ -519,27 +514,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
channelMetaUpdateEntry.setDisplayName(parsedMeta.title());
channelMetaUpdateEntry.setChannelDescription(parsedMeta.description());
channelMetaUpdateEntry.setAvaAr(parsedMeta.avaAr());
channelMetaUpdateEntry.setAvaSha256(parsedMeta.avaSha256());
channelMetaUpdateEntry.setAvaPr(parsedMeta.avaPr());
channelMetaUpdateEntry.setAvaSize(parsedMeta.avaSize());
channelMetaUpdateEntry.setMetaUpdatedAtMs(block.timestamp * 1000L);
}
// Channel DataItems are indexed by a signed canonical channel slug tag: c=<slug>.
try {
String expectedChannelSlug = expectedChannelSlug(blockchainName, block, channelNameStateEntry);
String actualChannelSlug = block.getDataItem().tagValue(ShineProtocolTags.CHANNEL_TAG_NAME);
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
&& (block.subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
try {
@@ -603,29 +582,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
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
final byte[] pubKey32 = st.getBlockchainKeyBytes();
if (pubKey32 == null || pubKey32.length != 32) {
@@ -665,15 +621,16 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
lineCode = bl.lineCode();
prevLineNumber = bl.prevLineBlockGlobalNumber();
prevLineHash32 = bl.prevLineBlockHash32();
thisLineNumber = bl.lineSeq();
try {
String lineError = validateLineContinuity(blockchainName, block, bl);
LineContinuity.Result lineResult = validateLineContinuity(blockchainName, block, bl);
String lineError = lineResult.error();
if (lineError != null) {
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);
}
thisLineNumber = lineResult.sequence();
} catch (Exception e) {
log.error("AddBlock: db_error_line_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
@@ -808,29 +765,34 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
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)) {
return new ArweaveImportResult(false, "chain_resync_in_progress", -1, "");
}
if (rawBlockBytes == null || rawBlockBytes.length == 0) {
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;
try {
parsed = new BchBlockEntry(rawBlockBytes);
parsed = BchBlockEntry.fromCoreContent(rawBlockBytes);
} catch (Exception e) {
return new ArweaveImportResult(false, "bad_block_format", -1, "");
}
ReentrantLock lock = BlockchainLocks.lockFor(blockchainName);
lock.lock();
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(
blockchainName,
parsed.blockNumber,
@@ -852,56 +814,46 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
/* ====================== 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-блока, а именно продолжение текущего хвоста линии.
* Это запрещает боковые ветки линии и гарантирует монотонный 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 lineCode = line.lineCode();
int rootBlockNumber;
int firstSequence;
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;
firstSequence = 1;
} 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;
firstSequence = 1;
} 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;
// Channel sequence is zero-based after its root anchor.
firstSequence = 0;
} else {
return "unsupported_line_body";
return LineContinuity.Result.rejected("unsupported_line_body");
}
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) {
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) {
return "bad_line_root";
return LineContinuity.Result.rejected("bad_line_root");
}
} else {
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) {
return "bad_line_root";
return LineContinuity.Result.rejected("bad_line_root");
}
}
@@ -909,45 +861,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
try (Connection resolverConnection = shine.db.DbController.getInstance().getConnection()) {
tail = canonicalChain.getLastLineBlock(resolverConnection, blockchainName, type, lineCode, block.blockNumber);
}
int expectedPrevNumber;
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());
return LineContinuity.resolve(line, rootBlockNumber, firstSequence, root, tail);
}
private String validateConnectionVotingRights(String actorLogin, int subType, String targetLogin) {
@@ -977,7 +891,13 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static byte[] decodeBase64(String b64) {
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) {
@@ -21,7 +21,7 @@ import java.util.LinkedHashSet;
import java.util.List;
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.
*/
public final class BlockchainWriter {
@@ -47,7 +47,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.
*/
public List<String> appendBlockAndState(String blockchainName,
@@ -61,7 +61,7 @@ public final class BlockchainWriter {
boolean replayMode) throws SQLException {
long nowMs = System.currentTimeMillis();
byte[] rawDataItem = block.toBytes();
byte[] rawBlock = block.toBytes();
Set<String> counterChangedLogins = new LinkedHashSet<>();
try (Connection c = shine.db.DbController.getInstance().getConnection()) {
c.setAutoCommit(false);
@@ -72,14 +72,17 @@ public final class BlockchainWriter {
// самый первый HEADER ранее импортированной цепочки.
st.setLastBlockNumber(block.blockNumber);
st.setLastBlockHash(block.getHash32());
st.setFileSizeBytes(st.getFileSizeBytes() + rawDataItem.length);
st.setFileSizeBytes(st.getFileSizeBytes() + rawBlock.length);
st.setUpdatedAtMs(nowMs);
stateDAO.upsert(c, st);
blocksDAO.insert(c, be);
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 (notificationEntry != null) userNotificationsStateDAO.upsert(c, notificationEntry);
@@ -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());
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();
item.setBlockNumber(row.getBlockNumber());
item.setBlockHash(hex(row.getBlockHash()));
@@ -71,6 +71,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
item.setMsgType(Short.toUnsignedInt(parsed.type));
item.setMsgSubType(Short.toUnsignedInt(parsed.subType));
item.setMsgVersion(Short.toUnsignedInt(parsed.version));
item.setThisLineNumber(row.getThisLineNumber());
if (parsed.body instanceof BodyHasTarget target) {
item.setToLogin(target.toLogin());
item.setToForkNumber(target.toForkNumber());
@@ -7,7 +7,7 @@ public final class Net_AddBlock_Request extends Net_Request {
private String blockchainName; // обязателен
private int blockNumber; // обязателен
private String prevBlockHash; // HEX(64) или "" для нулевого
private String blockBytesB64; // байты FULL-блока (raw+sig+hash) в Base64
private String blockBytesB64; // контейнер двух подписанных DataItem в Base64
public String getBlockchainName() { return 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 String toBlockHash;
private String blockBytesB64;
private Integer thisLineNumber;
public int getBlockNumber() { return 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 String getToBlockHash() { return 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 void setBlockBytesB64(String blockBytesB64) { this.blockBytesB64 = blockBytesB64; }
}
@@ -0,0 +1,92 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
/** Только проверка небезопасных входящих маркеров v=2. Исходный TEXT не переписывается. */
final class AttachmentMarkerValidator {
private static final Pattern ROOT = Pattern.compile("[1-9A-HJ-NP-Za-km-z]{32,44}");
private static final Pattern SHA = Pattern.compile("[0-9a-f]{64}");
private static final Pattern TX_ID = Pattern.compile("[A-Za-z0-9_-]{43}");
private static final Pattern MIME = Pattern.compile("(?i)[a-z0-9!#$&^_.+-]+/[a-z0-9!#$&^_.+-]+");
private static final Set<String> ALLOWED = Set.of("v", "nm", "sz", "pr", "sha256", "mm", "ar");
private AttachmentMarkerValidator() { }
static boolean validateLeadingV2Markers(String raw) {
String text = raw == null ? "" : raw;
int offset = 0;
for (int i = 0; i < 10; i++) {
String prefix;
if (text.startsWith("<S:att;", offset)) prefix = "<S:att;";
else if (text.startsWith("<S:attach;", offset)) prefix = "<S:attach;";
else if (text.startsWith("<SHiNE:attach;", offset)) prefix = "<SHiNE:attach;";
else return true;
int start = offset + prefix.length();
int end = text.indexOf('>', start);
if (end < 0 || end - start > 2048 || text.substring(start, end).contains("\n")) return false;
String fields = text.substring(start, end);
if (java.util.Arrays.stream(fields.split(";", -1)).anyMatch(field -> field.matches("v\\s*=\\s*0*2"))) {
if (!validateV2(fields)) return false;
}
offset = end + 1;
if (offset >= text.length()) return true;
if (text.charAt(offset) != '\n') return false;
offset++;
}
// Больше десяти технических тегов трактуем как недопустимые метаданные.
return !text.startsWith("<S:att;", offset) && !text.startsWith("<S:attach;", offset)
&& !text.startsWith("<SHiNE:attach;", offset);
}
private static boolean validateV2(String rawFields) {
String[] fields = rawFields.split(";", -1);
if (fields.length < 4 || !fields[0].equals("v=2")) return false;
Set<String> seen = new HashSet<>();
String name = null, size = null, root = null, sha = null, mime = null, ar = null;
for (String part : fields) {
int index = part.indexOf('=');
if (index <= 0 || part.indexOf('=', index + 1) >= 0) return false;
String key = part.substring(0, index);
String value = part.substring(index + 1);
if (!ALLOWED.contains(key) || !seen.add(key) || value.isEmpty()) return false;
switch (key) {
case "v": if (!value.equals("2")) return false; break;
case "nm": name = value; break;
case "sz": size = value; break;
case "pr": root = value; break;
case "sha256": sha = value; break;
case "mm": mime = value; break;
case "ar": ar = value; break;
default: return false;
}
}
if (name == null || size == null || !seen.contains("v") || (root == null) == (sha == null)) return false;
if (!size.matches("[1-9][0-9]{0,18}")) return false;
try { if (Long.parseLong(size) < 1) return false; } catch (NumberFormatException e) { return false; }
if (root != null && !ROOT.matcher(root).matches()) return false;
if (sha != null && !SHA.matcher(sha).matches()) return false;
if (mime != null && (mime.length() > 127 || !MIME.matcher(mime).matches())) return false;
if (ar != null && !TX_ID.matcher(ar).matches()) return false;
StringBuilder decoded = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
char ch = name.charAt(i);
if (ch == '%') {
if (i + 2 >= name.length()) return false;
String code = name.substring(i + 1, i + 3).toUpperCase(java.util.Locale.ROOT);
ch = switch (code) {
case "25" -> '%'; case "3B" -> ';'; case "3D" -> '=';
case "3C" -> '<'; case "3E" -> '>'; default -> 0;
};
if (ch == 0) return false;
i += 2;
} else if (ch == '<' || ch == '>' || ch == '=' || ch == ';') return false;
if (ch < 32 || ch == 127) return false;
decoded.append(ch);
}
return decoded.toString().getBytes(StandardCharsets.UTF_8).length <= 255;
}
}
@@ -1,5 +1,6 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import server.logic.ws_protocol.JSON.handlers.avatars.PiecesRootValidator;
import java.util.HashMap;
import java.util.Map;
@@ -15,7 +16,7 @@ public final class ChannelMetaTextParser {
String text = String.valueOf(rawText == null ? "" : rawText);
String title = "";
String avaAr = "";
String avaSha256 = "";
String avaPr = "";
long avaSize = 0L;
boolean seenTitle = false;
boolean seenAvatar = false;
@@ -33,10 +34,14 @@ public final class ChannelMetaTextParser {
} else if (body.startsWith("avatar;") || body.startsWith("ava;")) {
if (seenAvatar) throw new IllegalArgumentException("duplicate_channel_meta_avatar");
seenAvatar = true;
// Old SHA/hex avatars are not supported. Ignore just the avatar, not the whole channel.
// Otherwise rebuilding the index from an old channel block would remove that channel.
if (!body.matches("(?:ava|avatar);v=1;.*")) {
Avatar avatar = parseAvatarTag(body);
avaAr = avatar.ar;
avaSha256 = avatar.sha256;
avaPr = avatar.pr;
avaSize = avatar.size;
}
} else {
throw new IllegalArgumentException("unknown_channel_meta_tag");
}
@@ -52,7 +57,7 @@ public final class ChannelMetaTextParser {
String cleanTitle = title.isBlank() ? String.valueOf(fallbackTitle == null ? "" : fallbackTitle).trim() : title.trim();
validateTitle(cleanTitle);
return new Parsed(cleanTitle, description, avaAr, avaSha256, avaSize);
return new Parsed(cleanTitle, description, avaAr, avaPr, avaSize);
}
private static String parseTitleTag(String body) {
@@ -68,12 +73,12 @@ public final class ChannelMetaTextParser {
? body.substring("ava;".length())
: body.substring("avatar;".length());
Map<String, String> fields = parseFields(rawFields);
if (!"1".equals(fields.get("v"))) throw new IllegalArgumentException("bad_channel_meta_avatar_version");
if (!"2".equals(fields.get("v"))) throw new IllegalArgumentException("bad_channel_meta_avatar_version");
String ar = String.valueOf(fields.getOrDefault("ar", "")).trim();
String sha256 = String.valueOf(fields.getOrDefault("sha256", "")).trim().toLowerCase();
String pr = String.valueOf(fields.getOrDefault("pr", "")).trim();
String sizeRaw = String.valueOf(fields.containsKey("sz") ? fields.get("sz") : fields.getOrDefault("size", "")).trim();
if (!ar.isEmpty() && !ar.matches("^[A-Za-z0-9_-]{43}$")) throw new IllegalArgumentException("bad_channel_meta_avatar_ar");
if (!sha256.matches("^[0-9a-f]{64}$")) throw new IllegalArgumentException("bad_channel_meta_avatar_sha256");
if (!PiecesRootValidator.valid(pr)) throw new IllegalArgumentException("bad_channel_meta_avatar_pr");
long size;
try {
size = Long.parseLong(sizeRaw);
@@ -81,7 +86,7 @@ public final class ChannelMetaTextParser {
throw new IllegalArgumentException("bad_channel_meta_avatar_size");
}
if (size <= 0L) throw new IllegalArgumentException("bad_channel_meta_avatar_size");
return new Avatar(ar, sha256, size);
return new Avatar(ar, pr, size);
}
private static boolean startsWithTagPrefix(String text, int offset) {
@@ -122,7 +127,7 @@ public final class ChannelMetaTextParser {
return String.valueOf(value == null ? "" : value).codePointCount(0, String.valueOf(value == null ? "" : value).length());
}
private record Avatar(String ar, String sha256, long size) {}
private record Avatar(String ar, String pr, long size) {}
public record Parsed(String title, String description, String avaAr, String avaSha256, long avaSize) {}
public record Parsed(String title, String description, String avaAr, String avaPr, long avaSize) {}
}
@@ -41,7 +41,8 @@ public final class ChannelNamesStateBootstrapper {
private static void rebuildFromBlocksOrThrow() {
ChannelNameStateDAO dao = ChannelNameStateDAO.getInstance();
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> skipped = new ArrayList<>();
@@ -49,14 +50,7 @@ public final class ChannelNamesStateBootstrapper {
SELECT login, bch_name, block_number, block_hash, block_bytes
FROM blocks
WHERE msg_type = ? AND msg_sub_type = ?
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)
ORDER BY LOWER(login), block_number
""";
@@ -78,7 +72,7 @@ public final class ChannelNamesStateBootstrapper {
final BchBlockEntry parsed;
final CreateChannelBody createChannelBody;
try {
parsed = new BchBlockEntry(blockBytes);
parsed = BchBlockEntry.fromCoreContent(blockBytes);
if (!(parsed.body instanceof CreateChannelBody ccb)) continue;
createChannelBody = ccb;
} catch (Exception parseError) {
@@ -92,7 +86,7 @@ public final class ChannelNamesStateBootstrapper {
final int channelTypeCode;
final int channelTypeVersion;
String avaAr = "";
String avaSha256 = "";
String avaPr = "";
long avaSize = 0L;
long metaUpdatedAtMs = 0L;
try {
@@ -106,7 +100,7 @@ public final class ChannelNamesStateBootstrapper {
displayName = createMeta.title();
channelDescription = createMeta.description();
avaAr = createMeta.avaAr();
avaSha256 = createMeta.avaSha256();
avaPr = createMeta.avaPr();
avaSize = createMeta.avaSize();
metaUpdatedAtMs = parsed.timestamp * 1000L;
}
@@ -115,20 +109,12 @@ public final class ChannelNamesStateBootstrapper {
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();
entry.setSlug(slug);
entry.setDisplayName(displayName);
entry.setChannelDescription(channelDescription == null ? "" : channelDescription);
entry.setAvaAr(avaAr);
entry.setAvaSha256(avaSha256);
entry.setAvaPr(avaPr);
entry.setAvaSize(avaSize);
entry.setMetaUpdatedAtMs(metaUpdatedAtMs);
entry.setOwnerLogin(ownerLogin);
@@ -138,18 +124,28 @@ public final class ChannelNamesStateBootstrapper {
entry.setChannelRootBlockNumber(blockNumber);
entry.setChannelRootBlockHash(blockHash);
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.insertAll(c, entries);
redirectFollowedChannelRoots(c, replacedRoots);
applyMetaUpdates(c, dao, entries, skipped);
applyDeletionStates(c, dao, skipped);
// 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();
}
try (PreparedStatement ps = c.prepareStatement("""
@@ -162,7 +158,7 @@ public final class ChannelNamesStateBootstrapper {
c.commit();
log.info("channel_names_state bootstrapped: {}", entries.size());
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);
for (int i = 0; i < preview; 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 {
String sql = """
SELECT bch_name, block_number, block_bytes, msg_sub_type
FROM blocks
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
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)
ORDER BY LOWER(login), block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -221,7 +235,7 @@ public final class ChannelNamesStateBootstrapper {
String ownerBch = rs.getString("bch_name");
int blockNumber = rs.getInt("block_number");
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;
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);
@@ -233,6 +247,8 @@ public final class ChannelNamesStateBootstrapper {
}
}
private record ChannelRoot(String ownerBlockchainName, int blockNumber, byte[] blockHash) {}
private static void applyMetaUpdates(Connection c,
ChannelNameStateDAO dao,
List<ChannelNameStateEntry> entries,
@@ -246,14 +262,7 @@ public final class ChannelNamesStateBootstrapper {
SELECT login, bch_name, block_number, block_bytes
FROM blocks
WHERE msg_type = ? AND msg_sub_type = ?
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)
ORDER BY LOWER(login), block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -266,7 +275,7 @@ public final class ChannelNamesStateBootstrapper {
int blockNumber = rs.getInt("block_number");
byte[] blockBytes = rs.getBytes("block_bytes");
try {
BchBlockEntry parsed = new BchBlockEntry(blockBytes);
BchBlockEntry parsed = BchBlockEntry.fromCoreContent(blockBytes);
if (!(parsed.body instanceof TextLineBody metaBody)) continue;
int lineCode = metaBody.lineCode();
String fallbackTitle = fallbackTitles.get(ownerLogin.toLowerCase() + "#" + lineCode);
@@ -280,7 +289,7 @@ public final class ChannelNamesStateBootstrapper {
update.setDisplayName(parsedMeta.title());
update.setChannelDescription(parsedMeta.description());
update.setAvaAr(parsedMeta.avaAr());
update.setAvaSha256(parsedMeta.avaSha256());
update.setAvaPr(parsedMeta.avaPr());
update.setAvaSize(parsedMeta.avaSize());
update.setMetaUpdatedAtMs(parsed.timestamp * 1000L);
dao.updateMeta(c, update);
@@ -5,6 +5,7 @@ import blockchain.body.BodyRecord;
import blockchain.body.CreateChannelBody;
import blockchain.body.TextLineBody;
import blockchain.body.TextReplyBody;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMessages_Response;
import shine.db.channels.ChannelNameRules;
import shine.db.MsgSubType;
import shine.db.sql.CurrentUsersSql;
@@ -68,7 +69,7 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT slug, display_name, channel_description, channel_type_code, channel_type_version,
created_at_ms, ava_ar, ava_sha256, ava_size, meta_updated_at_ms, is_deleted, deleted_at_ms, deleted_block_number
created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms, is_deleted, deleted_at_ms, deleted_block_number
FROM channel_names_state
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
@@ -85,7 +86,7 @@ final class ChannelsReadSupport {
meta.channelTypeVersion = rs.getInt("channel_type_version");
meta.createdAtMs = rs.getLong("created_at_ms");
meta.avaAr = String.valueOf(rs.getString("ava_ar") == null ? "" : rs.getString("ava_ar"));
meta.avaSha256 = String.valueOf(rs.getString("ava_sha256") == null ? "" : rs.getString("ava_sha256"));
meta.avaPr = String.valueOf(rs.getString("ava_pr") == null ? "" : rs.getString("ava_pr"));
meta.avaSize = rs.getLong("ava_size");
meta.metaUpdatedAtMs = rs.getLong("meta_updated_at_ms");
meta.deleted = rs.getBoolean("is_deleted");
@@ -117,7 +118,7 @@ final class ChannelsReadSupport {
return meta;
}
byte[] bytes = rs.getBytes("block_bytes");
BchBlockEntry e = new BchBlockEntry(bytes);
BchBlockEntry e = BchBlockEntry.fromCoreContent(bytes);
BodyRecord body = e.body;
if (body instanceof CreateChannelBody ccb) {
meta.channelName = ccb.channelName;
@@ -130,7 +131,7 @@ final class ChannelsReadSupport {
meta.displayName = parsedMeta.title();
meta.channelDescription = parsedMeta.description();
meta.avaAr = parsedMeta.avaAr();
meta.avaSha256 = parsedMeta.avaSha256();
meta.avaPr = parsedMeta.avaPr();
meta.avaSize = parsedMeta.avaSize();
meta.createdAtMs = e.timestamp * 1000L;
meta.metaUpdatedAtMs = e.timestamp * 1000L;
@@ -214,7 +215,7 @@ final class ChannelsReadSupport {
static TextInfo parseTextAndTime(byte[] blockBytes) {
try {
BchBlockEntry e = new BchBlockEntry(blockBytes);
BchBlockEntry e = BchBlockEntry.fromCoreContent(blockBytes);
TextInfo ti = new TextInfo();
ti.createdAtMs = e.timestamp * 1000L;
if (e.body instanceof TextLineBody tlb) {
@@ -226,6 +227,7 @@ final class ChannelsReadSupport {
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
ti.text = sab.message;
}
ti.attachmentMetadataValid = AttachmentMarkerValidator.validateLeadingV2Markers(ti.text);
return ti;
} catch (Exception ex) {
return new TextInfo();
@@ -236,7 +238,7 @@ final class ChannelsReadSupport {
String order = asc ? "ASC" : "DESC";
boolean bounded = limit > 0;
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,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_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
@@ -263,6 +265,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
pb.blockBytes = rs.getBytes("block_bytes");
pb.dataItemId = rs.getBytes("data_item_id");
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
pb.toBchName = rs.getString("to_bch_name");
pb.toBlockNumber = (Integer) rs.getObject("to_block_number");
pb.toBlockHash = rs.getBytes("to_block_hash");
@@ -286,7 +291,7 @@ final class ChannelsReadSupport {
static List<PostBlock> versionsForPost(Connection c, String ownerBch, int originalBlock, byte[] originalHash) throws SQLException {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes
SELECT login,bch_name,block_number,block_hash,block_bytes,data_item_id,arweave_publish_pending,arweave_published_at_ms
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
@@ -309,6 +314,9 @@ final class ChannelsReadSupport {
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
pb.blockBytes = rs.getBytes("block_bytes");
pb.dataItemId = rs.getBytes("data_item_id");
pb.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
pb.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
out.add(pb);
}
return out;
@@ -401,7 +409,7 @@ final class ChannelsReadSupport {
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return "";
byte[] bytes = rs.getBytes("block_bytes");
BchBlockEntry e = new BchBlockEntry(bytes);
BchBlockEntry e = BchBlockEntry.fromCoreContent(bytes);
BodyRecord body = e.body;
if (body instanceof CreateChannelBody ccb) {
return ccb.channelDescription == null ? "" : ccb.channelDescription;
@@ -487,7 +495,7 @@ final class ChannelsReadSupport {
event.blockHash = rs.getBytes("block_hash");
event.lineStep = null;
try {
BchBlockEntry entry = new BchBlockEntry(rs.getBytes("block_bytes"));
BchBlockEntry entry = BchBlockEntry.fromCoreContent(rs.getBytes("block_bytes"));
event.createdAtMs = entry.timestamp * 1000L;
if (entry.body instanceof CreateChannelBody ccb) {
event.title = ccb.channelName;
@@ -497,7 +505,7 @@ final class ChannelsReadSupport {
event.title = parsedMeta.title();
event.description = parsedMeta.description();
event.avaAr = parsedMeta.avaAr();
event.avaSha256 = parsedMeta.avaSha256();
event.avaPr = parsedMeta.avaPr();
event.avaSize = parsedMeta.avaSize();
}
}
@@ -509,7 +517,7 @@ final class ChannelsReadSupport {
}
if (event.description == null) event.description = "";
if (event.avaAr == null) event.avaAr = "";
if (event.avaSha256 == null) event.avaSha256 = "";
if (event.avaPr == null) event.avaPr = "";
out.add(event);
}
}
@@ -545,7 +553,7 @@ final class ChannelsReadSupport {
event.title = parsed.title();
event.description = parsed.description();
event.avaAr = parsed.avaAr();
event.avaSha256 = parsed.avaSha256();
event.avaPr = parsed.avaPr();
event.avaSize = parsed.avaSize();
out.add(event);
} catch (Exception ignored) {
@@ -577,7 +585,7 @@ final class ChannelsReadSupport {
event.blockNumber = rs.getInt("block_number");
event.blockHash = rs.getBytes("block_hash");
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; }
out.add(event);
}
@@ -703,12 +711,27 @@ final class ChannelsReadSupport {
|| subType == MsgSubType.TEXT_COURSE;
}
static String dataItemIdBase64Url(byte[] bytes) {
return bytes != null && bytes.length == 32
? java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(bytes) : null;
}
static void setStorageInfo(Net_GetChannelMessages_Response.VersionItem out, byte[] id, boolean pending, Long publishedAt, byte[] raw) {
out.setArweaveDataItemId(dataItemIdBase64Url(id));
out.setArweavePublishPending(pending);
out.setArweavePublishedAtMs(publishedAt);
out.setSignedDataItemBytes(raw == null ? null : raw.length);
}
static final class PostBlock {
String login;
String bchName;
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toBchName;
Integer toBlockNumber;
byte[] toBlockHash;
@@ -717,6 +740,7 @@ final class ChannelsReadSupport {
}
static final class TextInfo {
boolean attachmentMetadataValid = true;
String text = "";
long createdAtMs = 0L;
}
@@ -728,7 +752,7 @@ final class ChannelsReadSupport {
int channelTypeCode;
int channelTypeVersion;
String avaAr = "";
String avaSha256 = "";
String avaPr = "";
long avaSize = 0L;
long createdAtMs = 0L;
long metaUpdatedAtMs = 0L;
@@ -748,7 +772,7 @@ final class ChannelsReadSupport {
String title;
String description;
String avaAr;
String avaSha256;
String avaPr;
long avaSize;
}
@@ -67,7 +67,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
channel.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
channel.setChannelDescription(meta.channelDescription);
channel.setAvaAr(meta.avaAr);
channel.setAvaSha256(meta.avaSha256);
channel.setAvaPr(meta.avaPr);
channel.setAvaSize(meta.avaSize);
channel.setMetaUpdatedAtMs(meta.metaUpdatedAtMs);
channel.setCreatedAtMs(meta.createdAtMs);
@@ -98,7 +98,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
outEvent.setTitle(event.title);
outEvent.setDescription(event.description);
outEvent.setAvaAr(event.avaAr);
outEvent.setAvaSha256(event.avaSha256);
outEvent.setAvaPr(event.avaPr);
outEvent.setAvaSize(event.avaSize);
metaEvents.add(outEvent);
}
@@ -152,7 +152,9 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
v1.setBlockNumber(post.blockNumber);
v1.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
v1.setText(postText.text);
v1.setAttachmentMetadataValid(postText.attachmentMetadataValid);
v1.setCreatedAtMs(postText.createdAtMs);
ChannelsReadSupport.setStorageInfo(v1, post.dataItemId, post.arweavePublishPending, post.arweavePublishedAtMs, post.blockBytes);
versionsOut.add(v1);
if (ChannelsReadSupport.supportsEditPostVersions(post.msgSubType)) {
@@ -164,13 +166,20 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
ve.setBlockNumber(edit.blockNumber);
ve.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
ve.setText(editText.text);
ve.setAttachmentMetadataValid(editText.attachmentMetadataValid);
ve.setCreatedAtMs(editText.createdAtMs);
ChannelsReadSupport.setStorageInfo(ve, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versionsOut.add(ve);
}
}
item.setVersions(versionsOut);
item.setVersionsTotal(versionsOut.size());
item.setAttachmentMetadataValid(v1.isAttachmentMetadataValid());
item.setArweaveDataItemId(v1.getArweaveDataItemId());
item.setArweavePublishPending(v1.getArweavePublishPending());
item.setArweavePublishedAtMs(v1.getArweavePublishedAtMs());
item.setSignedDataItemBytes(v1.getSignedDataItemBytes());
Net_GetChannelMessages_Response.VersionItem lastV = versionsOut.get(versionsOut.size() - 1);
item.setText(lastV.getText());
@@ -158,14 +158,13 @@ public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
String sql = """
SELECT login, bch_name, block_number, block_hash, block_bytes
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
""";
List<MsgRow> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
ps.setInt(2, line);
ps.setString(3, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
MsgRow row = new MsgRow();
@@ -1,4 +1,5 @@
package server.logic.ws_protocol.JSON.handlers.channels;
import server.logic.ws_protocol.JSON.handlers.profile.AvatarValueParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -72,7 +73,9 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
user.setLogin(rs.getString("from_login"));
user.setFirstName(rs.getString("first_name"));
user.setLastName(rs.getString("last_name"));
user.setAvatarAr(rs.getString("avatar_ar"));
var avatar = AvatarValueParser.parse(rs.getString("avatar_ar"));
user.setAvatarAr(avatar.ar());
user.setAvatarPr(avatar.pr());
boolean isOfficial = "primary".equalsIgnoreCase(rs.getString("account_role"));
boolean isShining = "shining".equalsIgnoreCase(rs.getString("shine_status"));
@@ -19,7 +19,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
@@ -116,7 +115,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,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
WHERE msg_type=1
AND to_block_number=? AND to_block_hash=?
@@ -124,7 +123,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
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)) {
ps.setInt(1, toBlockNumber);
@@ -153,17 +152,16 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,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
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
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
@@ -172,17 +170,16 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,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
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
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
String login=ChannelsReadSupport.loginFromChainName(bchName);
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setString(3, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
@@ -191,10 +188,10 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,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
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
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -202,7 +199,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
@@ -226,6 +222,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
row.blockNumber = rs.getInt("block_number");
row.blockHash = rs.getBytes("block_hash");
row.blockBytes = rs.getBytes("block_bytes");
row.dataItemId = rs.getBytes("data_item_id");
row.arweavePublishPending = rs.getBoolean("arweave_publish_pending");
row.arweavePublishedAtMs = (Long) rs.getObject("arweave_published_at_ms");
row.toLogin = rs.getString("to_login");
row.toBchName = rs.getString("to_bch_name");
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
@@ -259,7 +258,13 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
first.setBlockNumber(row.blockNumber);
first.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
first.setText(base.text);
first.setAttachmentMetadataValid(base.attachmentMetadataValid);
first.setCreatedAtMs(base.createdAtMs);
ChannelsReadSupport.setStorageInfo(first, row.dataItemId, row.arweavePublishPending, row.arweavePublishedAtMs, row.blockBytes);
node.setArweaveDataItemId(first.getArweaveDataItemId());
node.setArweavePublishPending(first.getArweavePublishPending());
node.setArweavePublishedAtMs(first.getArweavePublishedAtMs());
node.setSignedDataItemBytes(first.getSignedDataItemBytes());
versions.add(first);
if (row.msgSubType == MsgSubType.TEXT_REPLY
@@ -275,19 +280,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
v.setBlockNumber(edit.blockNumber);
v.setBlockHash(ChannelsReadSupport.toHex(edit.blockHash));
v.setText(et.text);
v.setAttachmentMetadataValid(et.attachmentMetadataValid);
v.setCreatedAtMs(et.createdAtMs);
ChannelsReadSupport.setStorageInfo(v, edit.dataItemId, edit.arweavePublishPending, edit.arweavePublishedAtMs, edit.blockBytes);
versions.add(v);
}
}
node.setVersions(versions);
node.setVersionsTotal(versions.size());
node.setAttachmentMetadataValid(first.isAttachmentMetadataValid());
node.setText(versions.get(versions.size() - 1).getText());
if (row.blockBytes != null) {
node.setRawBlockB64(Base64.getEncoder().encodeToString(row.blockBytes));
}
int[] stats = ChannelsReadSupport.loadStats(c, row.bchName, row.blockNumber, row.blockHash);
node.setLikesCount(stats[0]);
node.setPrimaryLikesCount(stats[3]);
@@ -310,11 +314,11 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,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
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
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
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -323,7 +327,6 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
ps.setInt(2, subType);
ps.setInt(3, targetBlock);
ps.setBytes(4, targetHash);
ps.setString(5, login);
try (ResultSet rs = ps.executeQuery()) {
List<PostRow> out = new ArrayList<>();
while (rs.next()) out.add(mapRow(rs));
@@ -338,6 +341,9 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
byte[] dataItemId;
boolean arweavePublishPending;
Long arweavePublishedAtMs;
String toLogin;
String toBchName;
Integer toBlockNumber;
@@ -89,7 +89,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
try (PreparedStatement ps = c.prepareStatement("""
SELECT blockchain_name
FROM solana_user_pda_current
FROM user_identity_current
WHERE LOWER(login)=LOWER(?)
LIMIT 1
""")) {
@@ -116,7 +116,7 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
byte[] blockBytes = rs.getBytes("block_bytes");
BchBlockEntry entry = new BchBlockEntry(blockBytes);
BchBlockEntry entry = BchBlockEntry.fromCoreContent(blockBytes);
if (!(entry.body instanceof StatusActionBody statusBody)) continue;
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 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
""")) {
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(4, originalBlockNumber);
ps.setBytes(5, originalBlockHash);
ps.setString(6, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
@@ -72,7 +72,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
channelRef.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
channelRef.setChannelDescription(meta.channelDescription);
channelRef.setAvaAr(meta.avaAr);
channelRef.setAvaSha256(meta.avaSha256);
channelRef.setAvaPr(meta.avaPr);
channelRef.setAvaSize(meta.avaSize);
channelRef.setMetaUpdatedAtMs(meta.metaUpdatedAtMs);
channelRef.setChannelTypeCode(meta.channelTypeCode);
@@ -34,7 +34,7 @@ public class Net_SearchChannels_Handler implements JsonMessageHandler {
var item = new Net_SearchChannels_Response.ChannelItem();
item.setOwnerLogin(match.ownerLogin()); item.setSlug(match.slug());
item.setDisplayName(match.displayName()); item.setDescription(match.description());
item.setAvatarAr(match.avatarAr()); item.setAvatarSha256(match.avatarSha256());
item.setAvatarAr(match.avatarAr()); item.setAvatarPr(match.avatarPr());
item.setOwnerBlockchainName(match.ownerBlockchainName());
item.setRootBlockNumber(match.rootBlockNumber()); item.setRootBlockHashHex(match.rootBlockHashHex());
item.setSubscribersCount(match.subscribersCount());
@@ -27,7 +27,7 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String displayName;
private String channelDescription;
private String avaAr;
private String avaSha256;
private String avaPr;
private Long avaSize;
private Long metaUpdatedAtMs;
private Long createdAtMs;
@@ -57,8 +57,8 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public String getAvaAr() { return avaAr; }
public void setAvaAr(String avaAr) { this.avaAr = avaAr; }
public String getAvaSha256() { return avaSha256; }
public void setAvaSha256(String avaSha256) { this.avaSha256 = avaSha256; }
public String getAvaPr() { return avaPr; }
public void setAvaPr(String avaPr) { this.avaPr = avaPr; }
public Long getAvaSize() { return avaSize; }
public void setAvaSize(Long avaSize) { this.avaSize = avaSize; }
@@ -99,7 +99,7 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String title;
private String description;
private String avaAr;
private String avaSha256;
private String avaPr;
private Long avaSize;
public String getKind() { return kind; }
@@ -129,8 +129,8 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public String getAvaAr() { return avaAr; }
public void setAvaAr(String avaAr) { this.avaAr = avaAr; }
public String getAvaSha256() { return avaSha256; }
public void setAvaSha256(String avaSha256) { this.avaSha256 = avaSha256; }
public String getAvaPr() { return avaPr; }
public void setAvaPr(String avaPr) { this.avaPr = avaPr; }
public Long getAvaSize() { return avaSize; }
public void setAvaSize(Long avaSize) { this.avaSize = avaSize; }
@@ -159,6 +159,11 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private int repliesCount;
private int ratingsCount;
private int versionsTotal;
private boolean attachmentMetadataValid = true;
private String arweaveDataItemId;
private Boolean arweavePublishPending;
private Long arweavePublishedAtMs;
private Integer signedDataItemBytes;
private List<VersionItem> versions = new ArrayList<>();
public BlockRef getMessageRef() { return messageRef; }
@@ -221,6 +226,17 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public int getRatingsCount() { return ratingsCount; }
public void setRatingsCount(int ratingsCount) { this.ratingsCount = ratingsCount; }
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
public String getArweaveDataItemId() { return arweaveDataItemId; }
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
public Boolean getArweavePublishPending() { return arweavePublishPending; }
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
public int getVersionsTotal() { return versionsTotal; }
public void setVersionsTotal(int versionsTotal) { this.versionsTotal = versionsTotal; }
@@ -234,6 +250,22 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String blockHash;
private String text;
private long createdAtMs;
private boolean attachmentMetadataValid = true;
private String arweaveDataItemId;
private Boolean arweavePublishPending;
private Long arweavePublishedAtMs;
private Integer signedDataItemBytes;
public boolean isAttachmentMetadataValid() { return attachmentMetadataValid; }
public void setAttachmentMetadataValid(boolean value) { this.attachmentMetadataValid = value; }
public String getArweaveDataItemId() { return arweaveDataItemId; }
public void setArweaveDataItemId(String value) { this.arweaveDataItemId = value; }
public Boolean getArweavePublishPending() { return arweavePublishPending; }
public void setArweavePublishPending(Boolean value) { this.arweavePublishPending = value; }
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
public void setArweavePublishedAtMs(Long value) { this.arweavePublishedAtMs = value; }
public Integer getSignedDataItemBytes() { return signedDataItemBytes; }
public void setSignedDataItemBytes(Integer value) { this.signedDataItemBytes = value; }
public int getVersionIndex() { return versionIndex; }
public void setVersionIndex(int versionIndex) { this.versionIndex = versionIndex; }
@@ -27,6 +27,7 @@ public class Net_GetMessageLikes_Response extends Net_Response {
private String firstName;
private String lastName;
private String avatarAr;
private String avatarPr;
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
@@ -36,5 +37,7 @@ public class Net_GetMessageLikes_Response extends Net_Response {
public void setLastName(String lastName) { this.lastName = lastName; }
public String getAvatarAr() { return avatarAr; }
public void setAvatarAr(String avatarAr) { this.avatarAr = avatarAr; }
public String getAvatarPr() { return avatarPr; }
public void setAvatarPr(String avatarPr) { this.avatarPr = avatarPr; }
}
}
@@ -21,13 +21,10 @@ public class Net_GetMessageThread_Response extends Net_Response {
public static class MessageNode extends Net_GetChannelMessages_Response.MessageItem {
private ChannelInfo channelInfo;
private String rawBlockB64;
public ChannelInfo getChannelInfo() { return channelInfo; }
public void setChannelInfo(ChannelInfo channelInfo) { this.channelInfo = channelInfo; }
public String getRawBlockB64() { return rawBlockB64; }
public void setRawBlockB64(String rawBlockB64) { this.rawBlockB64 = rawBlockB64; }
}
public static class ChannelInfo {
@@ -57,7 +57,7 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
private String displayName;
private String channelDescription;
private String avaAr;
private String avaSha256;
private String avaPr;
private Long avaSize;
private Long metaUpdatedAtMs;
private Integer channelTypeCode;
@@ -86,8 +86,8 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
public String getAvaAr() { return avaAr; }
public void setAvaAr(String avaAr) { this.avaAr = avaAr; }
public String getAvaSha256() { return avaSha256; }
public void setAvaSha256(String avaSha256) { this.avaSha256 = avaSha256; }
public String getAvaPr() { return avaPr; }
public void setAvaPr(String avaPr) { this.avaPr = avaPr; }
public Long getAvaSize() { return avaSize; }
public void setAvaSize(Long avaSize) { this.avaSize = avaSize; }
@@ -10,7 +10,7 @@ public class Net_SearchChannels_Response extends Net_Response {
public void setChannels(List<ChannelItem> channels) { this.channels = channels; }
public static class ChannelItem {
private String ownerLogin, slug, displayName, description, avatarAr, avatarSha256,
private String ownerLogin, slug, displayName, description, avatarAr, avatarPr,
ownerBlockchainName, rootBlockHashHex;
private int rootBlockNumber, subscribersCount;
public String getOwnerLogin() { return ownerLogin; }
@@ -23,8 +23,8 @@ public class Net_SearchChannels_Response extends Net_Response {
public void setDescription(String v) { description = v; }
public String getAvatarAr() { return avatarAr; }
public void setAvatarAr(String v) { avatarAr = v; }
public String getAvatarSha256() { return avatarSha256; }
public void setAvatarSha256(String v) { avatarSha256 = v; }
public String getAvatarPr() { return avatarPr; }
public void setAvatarPr(String v) { avatarPr = v; }
public String getOwnerBlockchainName() { return ownerBlockchainName; }
public void setOwnerBlockchainName(String v) { ownerBlockchainName = v; }
public int getRootBlockNumber() { return rootBlockNumber; }
@@ -297,7 +297,7 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
if (!parsed.ok()) return null;
Net_GetUserConnectionsGraph_Response.AvatarItem avatar = new Net_GetUserConnectionsGraph_Response.AvatarItem();
avatar.setAr(parsed.ar());
avatar.setSha256Hex(parsed.sha256Hex());
avatar.setPr(parsed.pr());
return avatar;
}
@@ -63,7 +63,7 @@ public class Net_ListContacts_Handler implements JsonMessageHandler {
AvatarValueParser.Parsed parsed = AvatarValueParser.parse(value);
if (!parsed.ok()) return out;
out.setAr(parsed.ar());
out.setSha256Hex(parsed.sha256Hex());
out.setPr(parsed.pr());
return out;
}
@@ -39,12 +39,12 @@ public class Net_GetUserConnectionsGraph_Response extends Net_Response {
public static class AvatarItem {
private String ar;
private String sha256Hex;
private String pr;
public String getAr() { return ar; }
public void setAr(String ar) { this.ar = ar; }
public String getSha256Hex() { return sha256Hex; }
public void setSha256Hex(String sha256Hex) { this.sha256Hex = sha256Hex; }
public String getPr() { return pr; }
public void setPr(String pr) { this.pr = pr; }
}
public static class RelativeItem {
@@ -56,10 +56,10 @@ public class Net_ListContacts_Response extends Net_Response {
public static class Avatar {
private String ar;
private String sha256Hex;
private String pr;
public String getAr() { return ar; }
public void setAr(String ar) { this.ar = ar; }
public String getSha256Hex() { return sha256Hex; }
public void setSha256Hex(String sha256Hex) { this.sha256Hex = sha256Hex; }
public String getPr() { return pr; }
public void setPr(String pr) { this.pr = pr; }
}
}
@@ -3,7 +3,6 @@ package server.logic.ws_protocol.JSON.handlers.keyRotation;
import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.ForkBody;
import server.logic.ws_protocol.Base64Ws;
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());
if (existing != null) {
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"); }
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 KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), session);
@@ -92,7 +91,7 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
final BchBlockEntry block;
try {
raw = Base64Ws.decode(req.getBlockBytesB64());
block = new BchBlockEntry(raw);
block = BchBlockEntry.fromCoreContent(raw);
block.body.check();
} catch (Exception e) {
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()) {
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)) {
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;
try {
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";
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 tipSourceEntry = blocks.getByNumber(c, session.getSourceBlockchainName(), session.getSourceTipBlock());
if (forkSourceEntry == null || tipSourceEntry == null) return "KEY_ROTATION_SOURCE_BLOCK_MISSING";
BchBlockEntry forkSource = new BchBlockEntry(forkSourceEntry.getBlockBytes());
BchBlockEntry tipSource = new BchBlockEntry(tipSourceEntry.getBlockBytes());
BchBlockEntry forkSource = BchBlockEntry.fromCoreContent(forkSourceEntry.getBlockBytes());
BchBlockEntry tipSource = BchBlockEntry.fromCoreContent(tipSourceEntry.getBlockBytes());
byte[] oldBlockchain = Base64.getDecoder().decode(session.getOldBlockchainKey());
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 "";
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.BchCryptoVerifier;
import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.ForkBody;
import server.logic.ws_protocol.JSON.ConnectionContext;
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.isArweavePublishPending() || stored.getArweavePublishedAtMs()==null) return "KEY_ROTATION_CHAIN_NOT_PUBLISHED";
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(!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(!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());
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";
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);
}
@@ -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.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";
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 tipSourceEntry=blocks.getByNumber(c,session.getSourceBlockchainName(),session.getSourceTipBlock());
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());
if(!Arrays.equals(fork.parentBlockchainKey32,oldBlockchain))return "KEY_ROTATION_TECH_FORK_PARENT_KEY";
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 "";
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,57 +1,38 @@
package server.logic.ws_protocol.JSON.handlers.profile;
import server.logic.ws_protocol.JSON.handlers.avatars.PiecesRootValidator;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Avatar v2 only. No SHA256/hex or legacy avatar tag support. */
public final class AvatarValueParser {
private static final Pattern NEW_TAG = Pattern.compile("^<(?:SHiNE|S):(?:ava|avatar);([^>]*)>$");
private static final Pattern LEGACY_AR = Pattern.compile("AR:([A-Za-z0-9_-]{43})");
private static final Pattern LEGACY_SHA = Pattern.compile("SHA256:([A-Fa-f0-9]{64})");
private static final Pattern TAG = Pattern.compile("^<S:ava;([^>]*)>$");
private static final Pattern AR = Pattern.compile("^[A-Za-z0-9_-]{43}$");
private static final Pattern SHA = Pattern.compile("^[A-Fa-f0-9]{64}$");
private AvatarValueParser() {}
public static Parsed parse(String rawValue) {
String raw = String.valueOf(rawValue == null ? "" : rawValue).trim();
if (raw.isEmpty()) return new Parsed("", "", 0L, false);
Matcher tag = NEW_TAG.matcher(raw);
if (tag.matches()) {
Matcher tag = TAG.matcher(raw);
if (!tag.matches()) return new Parsed("", "", 0L, false);
Map<String, String> fields = fields(tag.group(1));
if (!"1".equals(fields.get("v"))) return new Parsed("", "", 0L, false);
String ar = String.valueOf(fields.getOrDefault("ar", "")).trim();
String sha = String.valueOf(fields.getOrDefault("sha256", "")).trim().toLowerCase();
String sizeRaw = String.valueOf(fields.containsKey("sz") ? fields.get("sz") : fields.getOrDefault("size", "")).trim();
if (!ar.isEmpty() && !AR.matcher(ar).matches()) return new Parsed("", "", 0L, false);
if (!SHA.matcher(sha).matches()) return new Parsed("", "", 0L, false);
if (!"2".equals(fields.get("v"))) return new Parsed("", "", 0L, false);
String ar = fields.getOrDefault("ar", "").trim();
String pr = fields.getOrDefault("pr", "").trim();
if ((!ar.isEmpty() && !AR.matcher(ar).matches()) || !PiecesRootValidator.valid(pr))
return new Parsed("", "", 0L, false);
long size;
try { size = Long.parseLong(sizeRaw); } catch (Exception e) { return new Parsed("", "", 0L, false); }
if (size <= 0L) return new Parsed("", "", 0L, false);
return new Parsed(ar, sha, size, true);
try { size = Long.parseLong(fields.getOrDefault("sz", "")); }
catch (Exception e) { return new Parsed("", "", 0L, false); }
return size > 0 ? new Parsed(ar, pr, size, true) : new Parsed("", "", 0L, false);
}
Matcher arMatcher = LEGACY_AR.matcher(raw);
Matcher shaMatcher = LEGACY_SHA.matcher(raw);
String ar = arMatcher.find() ? arMatcher.group(1) : "";
String sha = shaMatcher.find() ? shaMatcher.group(1).toLowerCase() : "";
if (!AR.matcher(ar).matches()) return new Parsed("", "", 0L, false);
return new Parsed(ar, SHA.matcher(sha).matches() ? sha : "", 0L, true);
}
private static Map<String, String> fields(String raw) {
Map<String, String> out = new HashMap<>();
for (String part : String.valueOf(raw == null ? "" : raw).split(";")) {
for (String part : raw.split(";")) {
int eq = part.indexOf('=');
if (eq <= 0) continue;
String key = part.substring(0, eq).trim();
String value = part.substring(eq + 1).trim();
if (!key.isEmpty()) out.put(key, value);
if (eq > 0) out.put(part.substring(0, eq).trim(), part.substring(eq + 1).trim());
}
return out;
}
public record Parsed(String ar, String sha256Hex, long size, boolean ok) {}
public record Parsed(String ar, String pr, long size, boolean ok) {}
}
@@ -1,3 +1,3 @@
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.*;
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.setAvatarSha256(r.avatarSha256());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());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;}}}
@@ -8,7 +8,7 @@ public class Net_ListUserProfileRelations_Handler implements JsonMessageHandler
try(Connection c=shine.db.DbController.getInstance().getConnection()){
var rows=UserProfileStateDAO.getInstance().listRelations(c,req.getLogin(),req.getListType(),req.getLimit()==null?100:req.getLimit(),req.getOffset()==null?0:req.getOffset());
var resp=new Net_ListUserProfileRelations_Response(); resp.setOp(req.getOp());resp.setRequestId(req.getRequestId());resp.setStatus(WireCodes.Status.OK);resp.setLogin(req.getLogin());resp.setListType(req.getListType());
List<Net_ListUserProfileRelations_Response.UserItem> items=new ArrayList<>(); for(var r:rows){var i=new Net_ListUserProfileRelations_Response.UserItem();i.setLogin(r.login());i.setFirstName(r.firstName());i.setLastName(r.lastName());i.setAvatarAr(r.avatarAr());i.setAccountRole(r.accountRole());i.setShineStatus(r.shineStatus());i.setRelationType(r.relationType());i.setPrimaryConfirmed(r.primaryConfirmed());i.setShineConfirmed(r.shineConfirmed());i.setPrimaryConfirmationsCount(r.primaryConfirmationsCount());i.setShineConfirmationsCount(r.shineConfirmationsCount());items.add(i);} resp.setUsers(items);return resp;
List<Net_ListUserProfileRelations_Response.UserItem> items=new ArrayList<>(); for(var r:rows){var i=new Net_ListUserProfileRelations_Response.UserItem();i.setLogin(r.login());i.setFirstName(r.firstName());i.setLastName(r.lastName());var avatar = AvatarValueParser.parse(r.avatarAr());i.setAvatarAr(avatar.ar());i.setAvatarPr(avatar.pr());i.setAccountRole(r.accountRole());i.setShineStatus(r.shineStatus());i.setRelationType(r.relationType());i.setPrimaryConfirmed(r.primaryConfirmed());i.setShineConfirmed(r.shineConfirmed());i.setPrimaryConfirmationsCount(r.primaryConfirmationsCount());i.setShineConfirmationsCount(r.shineConfirmationsCount());items.add(i);} resp.setUsers(items);return resp;
}
}
}
@@ -1,3 +1,3 @@
package server.logic.ws_protocol.JSON.handlers.profile.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;import java.util.*;
public class Net_ListUserProfileChannels_Response extends Net_Response {private String login,mode;private List<ChannelItem> channels=new ArrayList<>();public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public List<ChannelItem> getChannels(){return channels;}public void setChannels(List<ChannelItem> v){channels=v;}public static class ChannelItem{private String ownerLogin,slug,displayName,avatarAr,avatarSha256,ownerBlockchainName,rootBlockHashHex;private int rootBlockNumber;private boolean deleted;private long deletedAtMs;private Integer deletedBlockNumber;public String getOwnerLogin(){return ownerLogin;}public void setOwnerLogin(String v){ownerLogin=v;}public String getSlug(){return slug;}public void setSlug(String v){slug=v;}public String getDisplayName(){return displayName;}public void setDisplayName(String v){displayName=v;}public String getAvatarAr(){return avatarAr;}public void setAvatarAr(String v){avatarAr=v;}public String getAvatarSha256(){return avatarSha256;}public void setAvatarSha256(String v){avatarSha256=v;}public String getOwnerBlockchainName(){return ownerBlockchainName;}public void setOwnerBlockchainName(String v){ownerBlockchainName=v;}public int getRootBlockNumber(){return rootBlockNumber;}public void setRootBlockNumber(int v){rootBlockNumber=v;}public String getRootBlockHashHex(){return rootBlockHashHex;}public void setRootBlockHashHex(String v){rootBlockHashHex=v;}public boolean isDeleted(){return deleted;}public void setDeleted(boolean v){deleted=v;}public long getDeletedAtMs(){return deletedAtMs;}public void setDeletedAtMs(long v){deletedAtMs=v;}public Integer getDeletedBlockNumber(){return deletedBlockNumber;}public void setDeletedBlockNumber(Integer v){deletedBlockNumber=v;}}}
public class Net_ListUserProfileChannels_Response extends Net_Response {private String login,mode;private List<ChannelItem> channels=new ArrayList<>();public String getLogin(){return login;}public void setLogin(String v){login=v;}public String getMode(){return mode;}public void setMode(String v){mode=v;}public List<ChannelItem> getChannels(){return channels;}public void setChannels(List<ChannelItem> v){channels=v;}public static class ChannelItem{private String ownerLogin,slug,displayName,avatarAr,avatarPr,ownerBlockchainName,rootBlockHashHex;private int rootBlockNumber;private boolean deleted;private long deletedAtMs;private Integer deletedBlockNumber;public String getOwnerLogin(){return ownerLogin;}public void setOwnerLogin(String v){ownerLogin=v;}public String getSlug(){return slug;}public void setSlug(String v){slug=v;}public String getDisplayName(){return displayName;}public void setDisplayName(String v){displayName=v;}public String getAvatarAr(){return avatarAr;}public void setAvatarAr(String v){avatarAr=v;}public String getAvatarPr(){return avatarPr;}public void setAvatarPr(String v){avatarPr=v;}public String getOwnerBlockchainName(){return ownerBlockchainName;}public void setOwnerBlockchainName(String v){ownerBlockchainName=v;}public int getRootBlockNumber(){return rootBlockNumber;}public void setRootBlockNumber(int v){rootBlockNumber=v;}public String getRootBlockHashHex(){return rootBlockHashHex;}public void setRootBlockHashHex(String v){rootBlockHashHex=v;}public boolean isDeleted(){return deleted;}public void setDeleted(boolean v){deleted=v;}public long getDeletedAtMs(){return deletedAtMs;}public void setDeletedAtMs(long v){deletedAtMs=v;}public Integer getDeletedBlockNumber(){return deletedBlockNumber;}public void setDeletedBlockNumber(Integer v){deletedBlockNumber=v;}}}
@@ -7,12 +7,13 @@ public class Net_ListUserProfileRelations_Response extends Net_Response {
public String getListType(){return listType;} public void setListType(String v){listType=v;}
public List<UserItem> getUsers(){return users;} public void setUsers(List<UserItem> v){users=v;}
public static class UserItem {
private String login,firstName,lastName,avatarAr,accountRole,shineStatus,relationType;
private String login,firstName,lastName,avatarAr,avatarPr,accountRole,shineStatus,relationType;
private boolean primaryConfirmed,shineConfirmed; private int primaryConfirmationsCount,shineConfirmationsCount;
public String getLogin(){return login;} public void setLogin(String v){login=v;}
public String getFirstName(){return firstName;} public void setFirstName(String v){firstName=v;}
public String getLastName(){return lastName;} public void setLastName(String v){lastName=v;}
public String getAvatarAr(){return avatarAr;} public void setAvatarAr(String v){avatarAr=v;}
public String getAvatarPr(){return avatarPr;} public void setAvatarPr(String v){avatarPr=v;}
public String getAccountRole(){return accountRole;} public void setAccountRole(String v){accountRole=v;}
public String getShineStatus(){return shineStatus;} public void setShineStatus(String v){shineStatus=v;}
public String getRelationType(){return relationType;} public void setRelationType(String v){relationType=v;}
@@ -13,88 +13,113 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import java.net.SocketAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* ClientErrorLog — технический endpoint для фронтенд-ошибок.
* Не требует авторизации: клиент должен иметь возможность отправить ошибку
* даже если логин/сессия ещё не установлены.
*/
/** Единая точка диагностики ошибок браузера (доступна до авторизации). */
public class Net_ClientErrorLog_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger("client.frontend");
private static final long WINDOW_MS = 60_000L;
private static final int MAX_PER_SOURCE = 60;
private static final int MAX_ALL = 1200;
private static final int MAX_SOURCES = 4096;
private static final Map<String, Bucket> rateLimits = new HashMap<>();
private static long globalWindow = 0;
private static int globalCount = 0;
private static int cleanCounter = 0;
private static final Logger log = LoggerFactory.getLogger(Net_ClientErrorLog_Handler.class);
private static final class Bucket {
long start;
int count;
Bucket(long now) { start = now; }
}
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_ClientErrorLog_Request req = (Net_ClientErrorLog_Request) baseRequest;
if (req.getMessage() == null || req.getMessage().isBlank()) {
return NetExceptionResponseFactory.error(
req,
WireCodes.Status.BAD_REQUEST,
"BAD_FIELDS",
"Поле message обязательно для ClientErrorLog"
);
if (req.getMessage() == null || req.getMessage().isBlank() || invalidSize(req)) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
"BAD_FIELDS", "Недопустимый размер или отсутствие message в ClientErrorLog");
}
long serverTs = System.currentTimeMillis();
String login = safe(ctx != null ? ctx.getLogin() : null);
String sessionId = safe(ctx != null ? ctx.getSessionId() : null);
String remote = safe(remoteAddress(ctx));
log.error(
"CLIENT_FRONTEND_ERROR kind={} clientTs={} serverTs={} login={} sessionId={} remote={} route={} href={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} userAgent={} context={}",
clip(req.getKind(), 64),
req.getClientTs(),
serverTs,
clip(login, 64),
clip(sessionId, 128),
clip(remote, 128),
clip(req.getRoute(), 200),
clip(req.getHref(), 240),
clip(req.getSourceUrl(), 240),
req.getLineNumber(),
req.getColumnNumber(),
clip(req.getRequestOp(), 64),
clip(req.getRequestIdRef(), 128),
clip(req.getMessage(), 500),
clip(req.getUserAgent(), 240),
clip(req.getContextJson(), 2000)
);
if (req.getStack() != null && !req.getStack().isBlank()) {
log.error("CLIENT_FRONTEND_ERROR_STACK requestId={} stack={}",
clip(req.getRequestId(), 128),
clip(req.getStack(), 8000));
boolean accepted = allow(remoteAddress(ctx), serverTs);
if (accepted) {
log.error("CLIENT_FRONTEND_ERROR id={} clientVersion={} kind={} clientTs={} serverTs={} login={} "
+ "route={} sourceUrl={} line={} column={} requestOp={} requestIdRef={} message={} "
+ "userAgent={} context={} stack={}",
clip(req.getErrorId(), 48), clip(req.getClientVersion(), 80),
clip(req.getKind(), 64), req.getClientTs(), serverTs,
clip(ctx != null ? ctx.getLogin() : null, 64), clip(req.getRoute(), 150),
clip(req.getSourceUrl(), 240), req.getLineNumber(), req.getColumnNumber(),
clip(req.getRequestOp(), 64), clip(req.getRequestIdRef(), 128),
clip(req.getMessage(), 500), clip(req.getUserAgent(), 240),
clip(req.getContextJson(), 800), clip(req.getStack(), 6000));
}
Net_ClientErrorLog_Response resp = new Net_ClientErrorLog_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setAccepted(true);
resp.setAccepted(accepted); // false = ограничение частоты, отчёт не записан
resp.setServerTs(serverTs);
return resp;
}
private static String remoteAddress(ConnectionContext ctx) {
if (ctx == null) return "";
Session ws = ctx.getWsSession();
if (ws == null) return "";
SocketAddress remote = ws.getRemoteAddress();
return remote != null ? remote.toString() : "";
private static boolean invalidSize(Net_ClientErrorLog_Request req) {
return length(req.getMessage()) > 500 || length(req.getStack()) > 6000
|| length(req.getContextJson()) > 800 || length(req.getKind()) > 64
|| length(req.getSourceUrl()) > 240 || length(req.getUserAgent()) > 240
|| length(req.getErrorId()) > 48 || length(req.getClientVersion()) > 80
|| length(req.getRoute()) > 150 || length(req.getHref()) > 240
|| length(req.getRequestOp()) > 64 || length(req.getRequestIdRef()) > 128;
}
private static String safe(String value) {
return value == null ? "" : value.trim();
private static int length(String value) { return value == null ? 0 : value.length(); }
// Ограничение по IP WebSocket (не по полю JSON, которое клиент может подделать).
private static synchronized boolean allow(String source, long now) {
if (now - globalWindow >= WINDOW_MS) { globalWindow = now; globalCount = 0; }
if (globalCount >= MAX_ALL) return false;
if (rateLimits.size() >= MAX_SOURCES || ++cleanCounter % 128 == 0) {
Iterator<Map.Entry<String, Bucket>> it = rateLimits.entrySet().iterator();
while (it.hasNext()) {
if (now - it.next().getValue().start >= WINDOW_MS) it.remove();
}
}
Bucket bucket = rateLimits.get(source);
if (bucket == null) {
if (rateLimits.size() >= MAX_SOURCES) return false;
bucket = new Bucket(now);
rateLimits.put(source, bucket);
}
if (now - bucket.start >= WINDOW_MS) { bucket.start = now; bucket.count = 0; }
if (bucket.count >= MAX_PER_SOURCE) return false;
bucket.count++;
globalCount++;
return true;
}
private static String remoteAddress(ConnectionContext ctx) {
if (ctx == null) return "unknown";
Session session = ctx.getWsSession();
if (session == null) return "unknown";
SocketAddress remote = session.getRemoteAddress();
// Адрес не записывается в журнал и хранится только как ключ лимита на 1 минуту.
if (remote instanceof InetSocketAddress inet) {
return inet.getAddress() != null ? inet.getAddress().getHostAddress() : inet.getHostString();
}
return remote != null ? remote.toString() : "unknown";
}
private static String clip(String value, int maxLen) {
String cleaned = safe(value)
.replace('\n', ' ')
.replace('\r', ' ');
if (cleaned.length() <= maxLen) {
return cleaned;
}
return cleaned.substring(0, Math.max(0, maxLen - 3)) + "...";
if (value == null) return "";
String clean = value.replaceAll("[\\p{Cntrl}]", " ")
.replaceAll("(?i)\\bBearer\\s+[^\\s,;]+", "Bearer [REDACTED]")
.replaceAll("(?i)\\b(password|passwd|token|secret|privateKey|sessionId|authorization|apiKey|storagePwd)\\s*[:=]\\s*[^\\s,;}&]+", "$1=[REDACTED]")
.replaceAll("[A-Za-z0-9_+/=-]{96,}", "[REDACTED_LONG_VALUE]")
.replaceAll("(?i)[?&](token|key|password|secret|session|auth|code|signature)=[^&#\\s]+", "[REDACTED_PARAM]");
return clean.length() <= maxLen ? clean : clean.substring(0, Math.max(0, maxLen - 3)) + "...";
}
}
@@ -26,6 +26,8 @@ import server.logic.ws_protocol.JSON.entyties.Net_Request;
*/
public class Net_ClientErrorLog_Request extends Net_Request {
private String errorId;
private String clientVersion;
private String kind;
private String message;
private String stack;
@@ -40,6 +42,12 @@ public class Net_ClientErrorLog_Request extends Net_Request {
private String requestIdRef;
private String contextJson;
public String getErrorId() { return errorId; }
public void setErrorId(String errorId) { this.errorId = errorId; }
public String getClientVersion() { return clientVersion; }
public void setClientVersion(String clientVersion) { this.clientVersion = clientVersion; }
public String getKind() { return kind; }
public void setKind(String kind) { this.kind = kind; }
@@ -13,6 +13,8 @@ import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.DbController;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.CurrentUserEntry;
@@ -26,6 +28,11 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetUser_Handler.class);
private static long resolveChainLimit(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry current = SolanaUserPdaCurrentDAO.getInstance().getByBlockchainName(blockchainName);
return current == null ? 0L : current.getPaidLimitBytes();
}
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
Net_GetUser_Request req = (Net_GetUser_Request) baseRequest;
@@ -80,7 +87,7 @@ public class Net_GetUser_Handler implements JsonMessageHandler {
st.setLastBlockNumber(-1);
st.setLastBlockHash(new byte[32]);
st.setFileSizeBytes(0);
st.setSizeLimit(1_000_000L);
st.setSizeLimit(Math.max(0L, resolveChainLimit(u.getBlockchainName())));
st.setUpdatedAtMs(System.currentTimeMillis());
stateDAO.upsert(st);
log.warn("GetUser: восстановлена запись blockchain_state для login={}, blockchainName={}",
@@ -6,6 +6,7 @@ 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.profile.AvatarValueParser;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_SearchUsers_Request;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_SearchUsers_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
@@ -50,7 +51,9 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
var item = new Net_SearchUsers_Response.UserItem();
item.setLogin(card.login());
item.setDisplayName(card.displayName());
item.setAvatarAr(card.avatarAr());
AvatarValueParser.Parsed avatar = AvatarValueParser.parse(card.avatarAr());
item.setAvatarAr(avatar.ar());
item.setAvatarPr(avatar.pr());
users.add(item);
}

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