SHA256
Compare commits
84
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
f9e7c4ef94 | ||
|
|
d3a84dd451 | ||
|
|
653015b2e7 | ||
|
|
8ac8f04128 | ||
|
|
80c70ebcdc | ||
|
|
792f368175 | ||
|
|
859dbee1f1 | ||
|
|
8f3b81c368 | ||
|
|
0274183730 | ||
|
|
c9f54224bb | ||
|
|
02c705d41e | ||
|
|
76bbc9d023 | ||
|
|
780ca53931 | ||
|
|
fc86c6190e | ||
|
|
2dd0ed6d59 | ||
|
|
1f06629838 | ||
|
|
c477560632 | ||
|
|
548160f7f8 | ||
|
|
a86a380dc7 | ||
|
|
d9fdaf1930 | ||
|
|
102feccb2e | ||
|
|
1b86bca19a | ||
|
|
fed28527ae | ||
|
|
2aa770a07b | ||
|
|
4362c0a015 | ||
|
|
2983ac89e6 | ||
|
|
4a6e072946 | ||
|
|
ac6a2e5b3f | ||
|
|
e01da7ae87 | ||
|
|
70540ff041 | ||
|
|
3ecec25fce | ||
|
|
2f5736e67d | ||
|
|
97db033eb8 | ||
|
|
c972a975fd | ||
|
|
42a05a7a67 | ||
|
|
2a72842a7a | ||
|
|
c97df82538 | ||
|
|
6b120731a3 | ||
|
|
d39d2777d1 | ||
|
|
afece72444 | ||
|
|
6031d95fe8 | ||
|
|
84f2400bef | ||
|
|
e7f6e0580c | ||
|
|
689321da1a | ||
|
|
b220f2ac8b | ||
|
|
6489fb56ab | ||
|
|
003cc942d8 | ||
|
|
9c30b33b39 | ||
|
|
405b9a91a7 | ||
|
|
526941eb33 | ||
|
|
34f7faf0a8 | ||
|
|
4068465ee6 | ||
|
|
9405f28525 | ||
|
|
571f4cbc7d | ||
|
|
e8f68f8fc4 | ||
|
|
4591d171d6 | ||
|
|
3185ce8b5e | ||
|
|
e575512ebb | ||
|
|
4f8c2a72e9 | ||
|
|
3c6021a290 | ||
|
|
dafa377cbe | ||
|
|
7ed47f7b7e | ||
|
|
bd52a23bec | ||
|
|
e84ab41fe6 | ||
|
|
41d5e79f83 | ||
|
|
c13734cbc9 | ||
|
|
e78402c860 | ||
|
|
2ce80eeaef | ||
|
|
551bdc2d65 | ||
|
|
f507bdb343 | ||
|
|
395aa62bda | ||
|
|
d2b2876a79 | ||
|
|
8bb7d39c76 | ||
|
|
e296217f21 | ||
|
|
c0257f4be2 | ||
|
|
7b88b61b22 | ||
|
|
ab61787ee7 | ||
|
|
219a65ae27 | ||
|
|
94d4665185 | ||
|
|
ce97171d5a | ||
|
|
a22f590395 | ||
|
|
a520c5c5e1 | ||
|
|
cab26bbf41 | ||
|
|
6c8159c5f7 |
+20
@@ -116,3 +116,23 @@ SHiNE-bundle-*.zip
|
|||||||
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
||||||
*.bak.png
|
*.bak.png
|
||||||
shine-UI/assets/navbar_preview.png
|
shine-UI/assets/navbar_preview.png
|
||||||
|
|
||||||
|
# Private local configuration: keep on disk, never push to GitHub
|
||||||
|
/SHiNE-server/src/main/resources/application.properties
|
||||||
|
/application.properties
|
||||||
|
/deploy/backup/scheme/
|
||||||
|
/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env
|
||||||
|
**/.env
|
||||||
|
**/.env.*
|
||||||
|
!**/.env.example
|
||||||
|
!**/.env.sample
|
||||||
|
|
||||||
|
# Private key files and local credential stores (never commit)
|
||||||
|
*.key
|
||||||
|
*.pem
|
||||||
|
*.p12
|
||||||
|
*.pfx
|
||||||
|
*.jwk
|
||||||
|
*.jks
|
||||||
|
*.keystore
|
||||||
|
*keypair*.json
|
||||||
|
|||||||
@@ -1,145 +1,33 @@
|
|||||||
# AGENTS
|
# Актуальная ветка 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.
|
||||||
- По умолчанию использовать русский язык во всех пользовательских текстах и технических пояснениях.
|
|
||||||
- Пояснения к коммитам, PR и merge-запросам писать на русском языке.
|
|
||||||
- Комментарии в коде, встроенные справки, документацию и инструкции писать по возможности на русском языке.
|
|
||||||
|
|
||||||
## Примечание
|
---
|
||||||
- Если внешний инструмент/интеграция требует английский формат, допускается английский, но рядом желательно дать краткое пояснение на русском.
|
|
||||||
|
|
||||||
## Структура проекта (кратко)
|
# Инструкции для агентов SHiNE
|
||||||
- Серверный код SHiNE находится в папке `SHiNE-server/`.
|
|
||||||
- Код клиентского UI SHiNE находится в папке `shine-UI/`.
|
|
||||||
- Веб-панель администратора сервера (управление Solana PDA сервера) находится в `shine-UI/`:
|
|
||||||
- точка входа `shine-UI/server-ui.html`;
|
|
||||||
- остальные файлы серверного UI — в `shine-UI/server-ui/`.
|
|
||||||
- Локальный Telegram-бот агента-кодера живёт рядом с репозиторием продукта, обычно в `../SHiNE-agent-bot-coder/`, и не входит в публичный код основного приложения.
|
|
||||||
- Solana/Anchor-модуль находится в папке `shine-solana/shine/` и ведётся отдельно от основного server/UI деплоя.
|
|
||||||
|
|
||||||
## Сервис агента-кодера
|
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
|
||||||
- Локальный Telegram-бот-сервис агента-кодера находится вне этого git-репозитория, обычно в `../SHiNE-agent-bot-coder/`.
|
|
||||||
- Сервис принимает сообщения из Telegram, ведёт историю диалога, ставит задачи в очередь и вызывает Codex CLI для обработки запросов по проекту.
|
|
||||||
- Рабочая папка Codex для сервиса должна указывать на этот продуктовый репозиторий: `CODEX_WORKDIR=/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-product`.
|
|
||||||
- Автоматически читаемые инструкции для Codex внутри сервиса держать в `../SHiNE-agent-bot-coder/AGENTS.md`.
|
|
||||||
- Подробные служебные правила Telegram-обработчика, его очередь, история, systemd-запуск и особенности ответов описывать в `../SHiNE-agent-bot-coder/AGENT.md`.
|
|
||||||
- Если в сообщениях пользователя встречается «агент MD» или похожая формулировка про файл инструкций Codex, считать, что имеется в виду автоматически читаемый `AGENTS.md`.
|
|
||||||
|
|
||||||
## ESP32 UI homeserver
|
## Сначала определить область работы
|
||||||
- Для UI-скетча устройства `ESP32-S3-Touch-AMOLED-2.16` документ-спецификация и Arduino-скетч должны всегда оставаться синхронными.
|
|
||||||
- Актуальный документ по экранной логике, состояниям, кнопкам, полям, статусам и ограничениям UI считать источником истины для скетча.
|
|
||||||
- При изменении документа обязательно в том же наборе изменений приводить в соответствие скетч.
|
|
||||||
- При изменении скетча обязательно в том же наборе изменений обновлять документ, если поменялись экраны, тексты, переходы, статусы, кнопки, поля или поведение.
|
|
||||||
- Для нового ESP32 UI-прототипа homeserver использовать русский язык как основной и отдельно следить, чтобы текст реально отображался на устройстве, а не только логически присутствовал в коде.
|
|
||||||
|
|
||||||
## Solana-модуль
|
| Область | Код | Правила и документация |
|
||||||
- В проекте есть отдельный Solana/Anchor-модуль в папке `shine-solana/shine/`.
|
| --- | --- | --- |
|
||||||
- Модуль логически связан с SHiNE, но не должен автоматически подключаться к сборке или деплою основного сервера без отдельного решения.
|
| Сервер, WebSocket/API, PostgreSQL | `SHiNE-server/` | `SHiNE-server/AGENTS.md`, `docs/API/` |
|
||||||
- В Solana-модуле действуют локальные инструкции `shine-solana/shine/AGENTS.md`; при изменениях внутри модуля сначала читать их.
|
| Блокчейн, Arweave | `SHiNE-server/shine-server-blockchain/` | `docs/Blockchain/README.md` |
|
||||||
- В git добавлять исходники, lock-файлы, настройки проекта и документацию Solana-модуля, но не добавлять локальные ключи, `.git`, `.idea`, `.gradle`, `target`, `node_modules`, `test-ledger`, логи, временные run-отчёты и `.env`-конфиги.
|
| Личные сообщения | сервер и `shine-UI/` | `docs/Personal_Messages/README.md`, локальный `AGENTS.md` |
|
||||||
- Для Solana deploy/push использовать правила из локального `shine-solana/shine/AGENTS.md`; не смешивать deploy Solana-модуля со скриптами основного server/UI deploy из `deploy/scripts/`.
|
| Браузерный UI | `shine-UI/` | `shine-UI/AGENTS.md`, `docs/UI-Design/README.md` |
|
||||||
- Для регистрации пользователей в Solana (программа `shine_users`) единая актуальная инструкция по деплою/инициализации, адресам программ, и куда их прописывать в UI/сервере находится в:
|
| Solana/Anchor | `shine-solana/shine/` | локальный `AGENTS.md`, `docs/Solana_Architecture/README.md` |
|
||||||
- `docs/Инициализация_Solana_регистрации/README.md`
|
| ESP32 | `ESP32/` | `ESP32/AGENTS.md`, инструкции конкретного устройства |
|
||||||
- Этот файл считать основной справкой (single source of truth) по деплою и первичной инициализации Solana-регистрации в текущем проекте.
|
| Деплой и резервные копии | `deploy/` | `deploy/AGENTS.md`, `deploy/backup/AGENTS.md` |
|
||||||
- Актуальная архитектурная справка по устройству Solana-программ, PDA-счетам, ролям DAO и движению средств находится в:
|
| Тестовый издатель | `tools/test-publisher/` | локальный `AGENTS.md` |
|
||||||
- `docs/Solana_Architecture/README.md`
|
|
||||||
- Документы формата пользовательской PDA-записи `shine_users`:
|
|
||||||
- текущий: `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.2.md`;
|
|
||||||
- legacy: `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`.
|
|
||||||
- Актуальная документация по серверному модулю синхронизации Solana users находится в:
|
|
||||||
- `docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md`
|
|
||||||
- При любом изменении логики серверной синхронизации `shine_users`, её таблиц PostgreSQL, checkpoint-механизма, startup/lifecycle или deploy-настроек обязательно обновлять:
|
|
||||||
- `docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md`
|
|
||||||
- `deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md`
|
|
||||||
|
|
||||||
## Документация блокчейна
|
Общий каталог — `docs/README.md`; карта компонентов и потоков данных — `docs/ARCHITECTURE.md`. Правила сопровождения документов — `docs/CONTRIBUTING_DOCS.md`; после правки документации запускать `python3 scripts/check_docs.py`. Планы в `TODO/` не считать описанием действующего поведения или разрешением на реализацию.
|
||||||
- Актуальная документация по форматам блокчейна находится в `docs/Blockchain/README.md`.
|
|
||||||
- Это точка входа (оглавление), рядом расположены детальные файлы по форматам, типам каналов и командным сообщениям.
|
|
||||||
- При любом изменении кода, связанного с блокчейном (формат блока, типы каналов, правила чтения/записи, команды), обязательно обновлять соответствующие документы в `docs/Blockchain/`.
|
|
||||||
- Дополнительно обязательно вести `docs/Blockchain/CHANGELOG.md`: дописывать изменения построчно с указанием даты/времени и хэша коммита, после которого внесено изменение.
|
|
||||||
- Перед любым изменением формата блокчейна обязательно заранее предупреждать пользователя, что формат будет изменён.
|
|
||||||
- Изменять формат блокчейна можно только после явного подтверждения пользователя (без подтверждения формат не менять).
|
|
||||||
- Добавление любых данных в блокчейн выполнять только через операцию `AddBlock`.
|
|
||||||
- Перед каждым `AddBlock` обязательно проверять/актуализировать текущее состояние вершины блокчейна (`last global number/hash`) и использовать его при формировании блока.
|
|
||||||
|
|
||||||
## Документация личных сообщений (DM)
|
## Постоянные правила
|
||||||
- Актуальная документация по логике личных сообщений находится в `docs/Personal_Messages/Протокол_DM_v1.md`.
|
|
||||||
- Точный байтовый формат DM находится в `docs/Personal_Messages/Формат_DM_v1.md`.
|
|
||||||
- При любом изменении кода, связанного с личными сообщениями (формат подписанного DM-блока, типы DM-сообщений, правила доставки/ACK/read-receipt, роутинг по сессиям, UI-логика чатов), обязательно обновлять оба документа:
|
|
||||||
- `docs/Personal_Messages/Протокол_DM_v1.md`
|
|
||||||
- `docs/Personal_Messages/Формат_DM_v1.md`
|
|
||||||
- Логика личных сообщений в коде должна всегда соответствовать этим документам.
|
|
||||||
- Документ по личным сообщениям обязан поддерживаться в актуальном состоянии.
|
|
||||||
|
|
||||||
## Документация API сервера
|
- Прежде чем править подсистему, прочитать её локальный `AGENTS.md` и действующую документацию через `docs/README.md`. Архивные отчёты и старые планы не использовать как текущий контракт. При расхождении документа с кодом проверить реализацию и исправить документ либо явно отметить неопределённость.
|
||||||
- Актуальная документация по публичному JSON/WebSocket API сервера находится в `docs/API/`.
|
- Изменение поведения, формата, API, конфигурации или пользовательского сценария сопровождать обновлением соответствующего документа в том же наборе изменений. Не выдавать план, черновик или тестовое состояние за действующую функцию.
|
||||||
- При любом изменении серверного API/эндпоинтов/операций `op` обязательно обновлять соответствующие документы в `docs/API/`.
|
- Формат блокчейна и контракт серверного API изменять только после отдельного явного согласия пользователя; документировать изменения в `docs/Blockchain/` и `docs/API/`. Для добавления блока использовать `AddBlock` с актуальной вершиной цепочки.
|
||||||
- Перед изменением самого серверного API обязательно явно предупредить пользователя, какие операции, поля запросов/ответов или коды ошибок будут изменены, и запросить отдельное подтверждение.
|
- Любые изменения и деплой production (`shineup.me`, `server2.shineup.me`) — только после отдельного явного согласия пользователя. Перед деплоем прочитать `deploy/AGENTS.md` и проверить резервную копию. Для деплоя использовать скрипты `deploy/scripts/`.
|
||||||
- Без явного подтверждения пользователя формат серверного API не менять; допускается только приведение документации в соответствие уже существующему коду.
|
- Секреты, приватные ключи, локальные конфиги, сборочные артефакты и логи не добавлять в git.
|
||||||
- Если добавляется новая операция `op`, нужно обновить общий список операций в `docs/API/09_Operations_Index.md` или создать его, если файла ещё нет.
|
- Коммиты, версии и merge выполнять по `COMMIT_AND_VERSION_RULES.md`. Не делать коммит или push без необходимости для задачи.
|
||||||
|
|
||||||
## Документация Figma
|
|
||||||
- Актуальная документация по переносу экранов SHiNE в Figma и обратному переносу из Figma в код находится в `docs/Figma/`.
|
|
||||||
- Точка входа: `docs/Figma/README.md`.
|
|
||||||
- Подробный рабочий регламент: `docs/Figma/TRANSFER_UI_SCREENS.md`.
|
|
||||||
- Для экранов регистрации, входа и других чувствительных UI-flow по умолчанию переносить экраны в Figma по одному, а не пачкой, если пользователь отдельно не подтвердил иной способ.
|
|
||||||
|
|
||||||
## Версионирование
|
|
||||||
- Все правила по коммитам, merge в `main`, `git push` и обновлению `VERSION.properties` находятся в `COMMIT_AND_VERSION_RULES.md`.
|
|
||||||
- Этот файл считать единым источником истины по правилам версионирования и коммитов для данного репозитория.
|
|
||||||
|
|
||||||
## Deploy
|
|
||||||
- Все документы, инструкции, backup-правила и скрипты деплоя хранить в папке `deploy/`.
|
|
||||||
- Подробные правила для агента по деплою находятся в `deploy/AGENTS.md`; перед любым deploy читать этот файл.
|
|
||||||
- Production-серверы SHiNE: `shineup.me` и `server2.shineup.me`.
|
|
||||||
- Тестовые/devnet серверы SHiNE: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
|
|
||||||
- В deploy-документах и скриптах использовать домены, а не IP.
|
|
||||||
- По возможности все справки, комментарии и примечания в конфигах/документах писать на русском языке.
|
|
||||||
- Любые изменения и любой деплой на production (`shineup.me` и `server2.shineup.me`) выполнять только после отдельного явного подтверждения пользователя.
|
|
||||||
- Перед production deploy обязательно проверить/обновить бэкап в `deploy/backup/archive/`.
|
|
||||||
- Если пользователь пишет просто `задеплой` без уточнения production/test, уточнить целевой контур; не выбирать production автоматически.
|
|
||||||
- Deploy выполнять shell-скриптами из `deploy/scripts/`; Gradle deploy-задачи не использовать.
|
|
||||||
- Для локального запуска использовать `./gradlew startLocal` (или `startLocalWithBuild`).
|
|
||||||
- Сначала предлагать локальную проверку, а деплой на сервер выполнять по запросу пользователя.
|
|
||||||
- Для временной бесплатной загрузки аватаров в Arweave секретный JWK нельзя хранить в git и нельзя прописывать в репозиторный `application.properties`.
|
|
||||||
- Для продовой настройки тестового Arweave-кошелька JWK-файл нужно хранить только на сервере, например: `/home/player/SHiNE/secrets/test-free-avatar-wallet.json`.
|
|
||||||
- Для этой временной фичи на проде должны быть заданы параметры `test.freeAvatar.walletJwkPath` и `test.freeAvatar.walletAddress` через серверный override-конфиг/секреты на хосте.
|
|
||||||
- После изменения продовых значений `test.freeAvatar.*` нужно заново выполнить серверный деплой или перезапуск сервера, чтобы настройки были перечитаны приложением.
|
|
||||||
- При таких изменениях в git допускается коммитить только документацию и код чтения настроек, но не сам JWK, не содержимое секрета и не реальные приватные ключи.
|
|
||||||
|
|
||||||
## Логи звонков (установка соединения)
|
|
||||||
- Специальный поток диагностики установки звонков идёт через `CallDeliveryReport` (клиент → сервер).
|
|
||||||
- На проде специальный файл для звонков:
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/call-delivery-events.log`
|
|
||||||
- Общий серверный лог (и ротации) на проде:
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/app.log`
|
|
||||||
- `/home/player/SHiNE/shine-server/logs/app.YYYY-MM-DD.log`
|
|
||||||
- Для анализа причин недозвона в первую очередь фильтровать записи по ключам:
|
|
||||||
- `CallDeliveryReport`
|
|
||||||
- `call_connected`
|
|
||||||
- `outgoing_failed`
|
|
||||||
- `incoming_failed`
|
|
||||||
- `call_busy`
|
|
||||||
- `call_declined`
|
|
||||||
- `unknown_error`
|
|
||||||
- В этих записях искать поля `reason`, `failureStage`, `pcConnectionState`, `pcIceConnectionState`, `routeLabel`, `configuredTurnHosts*`, `reachableTurnHosts*`.
|
|
||||||
|
|
||||||
## Будущие фичи / TODO
|
|
||||||
- Папка для задач, сознательно отложенных на будущее: `TODO/`.
|
|
||||||
- Точка входа по планам: `TODO/README.md`.
|
|
||||||
- Внутри планы разделены по горизонтам: `near/`, `medium/`, `far/` и тематическим подпапкам.
|
|
||||||
- Если пользователь спрашивает, какие есть планы или что можно продолжить, сначала читать `TODO/README.md`, затем при необходимости конкретные файлы из подпапок.
|
|
||||||
- Файлы из этой папки не считать активными задачами и не начинать реализацию без явной просьбы пользователя.
|
|
||||||
- Старую папку `docs/Future_Features/` считать выведенной из использования и больше не использовать для новых записей.
|
|
||||||
- Если часть кода временно отключена или закомментирована, либо удалена как временная заглушка, в TODO-файле подробно описывать:
|
|
||||||
- какие файлы и участки отключены;
|
|
||||||
- что осталось в коде как заготовка;
|
|
||||||
- какие документы нужно обновить при возврате;
|
|
||||||
- с какого сценария продолжать разработку;
|
|
||||||
- из какого коммита брать последнюю полную реализацию.
|
|
||||||
|
|
||||||
## Коммуникация по новым задачам
|
|
||||||
- При получении нового задания кратко подтвердить понимание задачи, если это помогает синхронизироваться.
|
|
||||||
- До начала реализации задавать уточняющие вопросы только когда без ответа есть риск сделать не то или затронуть опасную область.
|
|
||||||
- Если задача понятна и не требует отдельного подтверждения по другим правилам проекта, переходить к реализации сразу.
|
|
||||||
- Если есть уместные идеи/улучшения — кратко предложить их; если полезных идей нет, ничего дополнительно не предлагать.
|
|
||||||
|
|||||||
@@ -32,15 +32,6 @@
|
|||||||
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
|
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
|
||||||
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
|
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
|
||||||
|
|
||||||
## Версионирование при merge или прямом коммите в `main`
|
|
||||||
|
|
||||||
- Для попадания изменений в `main` действует отдельная схема инкремента.
|
|
||||||
- Нужно увеличивать вторую цифру версии и обнулять третью.
|
|
||||||
- Пример: `1.2.346` → `1.3.0`.
|
|
||||||
- Если в наборе изменений менялся только UI, обновлять только `client.version`.
|
|
||||||
- Если в наборе изменений менялся только сервер, обновлять только `server.version`.
|
|
||||||
- Если соответствующая часть не менялась, её версию не трогать.
|
|
||||||
|
|
||||||
## Правила для git commit и git push
|
## Правила для git commit и git push
|
||||||
|
|
||||||
- Обычные коммиты делать стандартным `git commit`; токен для локального коммита не нужен и не используется.
|
- Обычные коммиты делать стандартным `git commit`; токен для локального коммита не нужен и не используется.
|
||||||
|
|||||||
@@ -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 не выполнялся**.
|
||||||
+83
@@ -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
|
||||||
+48
-23
@@ -9,6 +9,8 @@
|
|||||||
#include <TouchDrvCSTXXX.hpp>
|
#include <TouchDrvCSTXXX.hpp>
|
||||||
#include <mbedtls/gcm.h>
|
#include <mbedtls/gcm.h>
|
||||||
#include <mbedtls/sha256.h>
|
#include <mbedtls/sha256.h>
|
||||||
|
#include <mbedtls/sha512.h>
|
||||||
|
#include "shine_core_content.h"
|
||||||
#include <mbedtls/base64.h>
|
#include <mbedtls/base64.h>
|
||||||
#include <Ed25519.h>
|
#include <Ed25519.h>
|
||||||
#include <sodium.h>
|
#include <sodium.h>
|
||||||
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> preimage;
|
|
||||||
preimage.reserve(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
|
||||||
appendUint16BE(preimage, 0);
|
|
||||||
preimage.insert(preimage.end(), prevHash32, prevHash32 + 32);
|
|
||||||
int32_t blockSize = (int32_t)(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
|
||||||
appendInt32BE(preimage, blockSize);
|
|
||||||
appendInt32BE(preimage, nextBlockNumber);
|
|
||||||
appendInt64BE(preimage, (int64_t)(shineNowMs() / 1000ULL));
|
|
||||||
appendUint16BE(preimage, msgType);
|
|
||||||
appendUint16BE(preimage, msgSubType);
|
|
||||||
appendUint16BE(preimage, msgVersion);
|
|
||||||
preimage.insert(preimage.end(), bodyBytes.begin(), bodyBytes.end());
|
|
||||||
|
|
||||||
uint8_t blockchainSeed[32] = {};
|
uint8_t blockchainSeed[32] = {};
|
||||||
uint8_t blockchainPub[32] = {};
|
uint8_t blockchainPub[32] = {};
|
||||||
uint8_t blockchainSec[64] = {};
|
uint8_t blockchainSec[64] = {};
|
||||||
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t hash32[32] = {};
|
std::vector<uint8_t> fullBlock;
|
||||||
sha256calc(preimage.data(), preimage.size(), hash32);
|
const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||||
uint8_t signature[64] = {};
|
return mbedtls_sha256(data, len, out, 0) == 0;
|
||||||
if (!signMessageEd25519(std::vector<uint8_t>(hash32, hash32 + 32), blockchainSec, signature)) {
|
};
|
||||||
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign AddBlock hash\",\"requestId\":\"")
|
const auto hash384 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||||
|
uint8_t buffer[64] = {};
|
||||||
|
if (mbedtls_sha512(data, len, buffer, 1) != 0) return false;
|
||||||
|
memcpy(out, buffer, 48);
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
const auto sign = +[](const std::vector<uint8_t>& data, const uint8_t* key, uint8_t* sig) -> bool {
|
||||||
|
return signMessageEd25519(data, key, sig);
|
||||||
|
};
|
||||||
|
// Same semantic remote body and signal contract; only the signed wire bytes change.
|
||||||
|
if (resolvedBlockchainName != blockchainName || nextBlockNumber < 0 ||
|
||||||
|
!shine_core::buildPair(msgType, msgSubType, msgVersion, bodyBytes, (uint32_t)nextBlockNumber,
|
||||||
|
shineNowMs()/1000ULL, prevHash32, blockchainPub, blockchainSec,
|
||||||
|
"test5595", hash256, hash384, sign, fullBlock)) {
|
||||||
|
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign CORE/CONTENT pair\",\"requestId\":\"")
|
||||||
+ jsonEscape(item.signalRequestId) + "\"}";
|
+ jsonEscape(item.signalRequestId) + "\"}";
|
||||||
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
|
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
std::vector<uint8_t> fullBlock = preimage;
|
|
||||||
fullBlock.push_back(0x01);
|
|
||||||
fullBlock.push_back(0x00);
|
|
||||||
fullBlock.insert(fullBlock.end(), signature, signature + 64);
|
|
||||||
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||||
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
|
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
|
||||||
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
|
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
|
||||||
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
|
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
|
||||||
String addBlockResp;
|
String addBlockResp;
|
||||||
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||||
|
const bool uncertain = !addBlockOk;
|
||||||
|
if (uncertain) {
|
||||||
|
// Retry the identical container, not the semantic request or a new timestamp.
|
||||||
|
addBlockResp = "";
|
||||||
|
addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||||
|
}
|
||||||
uint64_t statusCode = 0;
|
uint64_t statusCode = 0;
|
||||||
jsonInt64Field(addBlockResp, "status", statusCode);
|
jsonInt64Field(addBlockResp, "status", statusCode);
|
||||||
String serverLastHash;
|
String serverLastHash;
|
||||||
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
|
|||||||
jsonStringField(addBlockResp, "message", errorMessage);
|
jsonStringField(addBlockResp, "message", errorMessage);
|
||||||
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
|
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
|
||||||
|
|
||||||
|
if (uncertain && (!addBlockOk || statusCode != 200)) {
|
||||||
|
const String readReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||||
|
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "}";
|
||||||
|
String readResp, readBytes;
|
||||||
|
uint64_t readStatus = 0;
|
||||||
|
if (shineWsRequest(gShineWs, "GetBlockchainBlock", readReq, readResp, SHINE_RPC_TIMEOUT_MS)) {
|
||||||
|
jsonInt64Field(readResp, "status", readStatus);
|
||||||
|
jsonStringField(readResp, "blockBytesB64", readBytes);
|
||||||
|
if (readStatus == 200 && readBytes == bytesToBase64String(fullBlock.data(), fullBlock.size())) {
|
||||||
|
jsonStringField(readResp, "blockHash", serverLastHash);
|
||||||
|
serverLastNumber = (uint64_t)nextBlockNumber;
|
||||||
|
addBlockOk = true;
|
||||||
|
statusCode = 200;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!addBlockOk || statusCode != 200) {
|
||||||
|
errorCode = "addblock_outcome_unknown";
|
||||||
|
errorMessage = "AddBlock outcome unknown; refresh history before retrying";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (!addBlockOk || statusCode != 200) {
|
if (!addBlockOk || statusCode != 200) {
|
||||||
if (errorCode.isEmpty()) {
|
if (errorCode.isEmpty()) {
|
||||||
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
|
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
# Инструкция по commit и push в Git
|
||||||
|
|
||||||
|
## Репозиторий
|
||||||
|
|
||||||
|
Работать с Git нужно из корня репозитория `SHiNE-product/`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-product
|
||||||
|
```
|
||||||
|
|
||||||
|
## Канонический Gitea
|
||||||
|
|
||||||
|
Всегда использовать этот Git-сервер и этот remote:
|
||||||
|
|
||||||
|
```text
|
||||||
|
https://git.shineup.me/Aidar/SHiNE-server.git
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверка и исправление `origin`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git remote set-url origin https://git.shineup.me/Aidar/SHiNE-server.git
|
||||||
|
git remote -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Старый адрес `git2.shineup.me` не использовать.
|
||||||
|
|
||||||
|
Секреты, токены, приватные ключи, `.env`, логи и сборочные артефакты в Git не добавлять.
|
||||||
|
|
||||||
|
## Перед коммитом
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status --short --branch
|
||||||
|
git diff --check
|
||||||
|
git diff
|
||||||
|
```
|
||||||
|
|
||||||
|
Перед обычным коммитом обновить `VERSION.properties`:
|
||||||
|
|
||||||
|
- только UI — увеличить `client.version`;
|
||||||
|
- только сервер — увеличить `server.version`;
|
||||||
|
- UI и сервер — увеличить обе версии;
|
||||||
|
- в рабочей ветке использовать patch-инкремент: `1.2.346` → `1.2.347`.
|
||||||
|
|
||||||
|
Сообщения коммитов писать на русском языке.
|
||||||
|
|
||||||
|
## Commit
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git add <нужные-файлы>
|
||||||
|
git commit -m "Краткое описание изменения"
|
||||||
|
```
|
||||||
|
|
||||||
|
Для локального `git commit` токен не нужен. Не использовать `git add .`, если в рабочем дереве есть непроверенные локальные файлы.
|
||||||
|
|
||||||
|
## Push
|
||||||
|
|
||||||
|
Сначала проверить ветку и remote:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git branch --show-current
|
||||||
|
git remote -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Для push использовать токен из переменной окружения `GITEA_TOKEN`; сам токен в команду, файл или историю shell не записывать. При HTTPS Git обычно запросит имя пользователя и пароль токена:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
export GITEA_TOKEN='токен задаётся локально и не коммитится'
|
||||||
|
git push origin HEAD
|
||||||
|
unset GITEA_TOKEN
|
||||||
|
```
|
||||||
|
|
||||||
|
Если credential helper не умеет автоматически подставлять `GITEA_TOKEN`, использовать настроенный локально способ авторизации Gitea; не вставлять токен в URL remote.
|
||||||
|
|
||||||
|
После push проверить результат:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status --short --branch
|
||||||
|
git log -1 --oneline
|
||||||
|
```
|
||||||
|
|
||||||
|
## Ветка `main`
|
||||||
|
|
||||||
|
`main` предназначена для стабильных версий. По умолчанию изменения сначала коммитить в рабочей ветке, затем вливать в `main`. Для merge в `main` увеличивать вторую цифру версии и обнулять третью: `1.2.346` → `1.3.0`.
|
||||||
|
|
||||||
|
Перед push в `main` отдельно проверить diff, версию и отсутствие секретов.
|
||||||
@@ -1,29 +0,0 @@
|
|||||||
# SHiNE ANS-104 `test5590` patch
|
|
||||||
|
|
||||||
Этот архив содержит **только новые/изменённые файлы** плюс `DELETE_FILES.txt`.
|
|
||||||
|
|
||||||
## Что меняется
|
|
||||||
|
|
||||||
- Frame v1 без поддержки старого формата.
|
|
||||||
- Один пользовательский block = готовый Ed25519 ANS-104 DataItem.
|
|
||||||
- Test tag: `App=test5590`; channel tag: `c=<canonical slug>`.
|
|
||||||
- SHiNE `prevHash` остаётся `SHA-256(FrameV1Bytes)` и не зависит от Arweave ID.
|
|
||||||
- PostgreSQL — единственное локальное хранилище пользовательских blocks.
|
|
||||||
- Старый custom SHINE-ARCHIVE и filesystem blockchain storage удаляются.
|
|
||||||
- Каждые ~15 минут локальные pending DataItems собираются в standard ANS-104 bundle и идут через существующий native Arweave L1 transport.
|
|
||||||
- Другие серверы находят `App=test5590`, импортируют и не публикуют повторно.
|
|
||||||
- `ESP32/**` **не изменён**.
|
|
||||||
|
|
||||||
## Состав
|
|
||||||
|
|
||||||
- изменено/добавлено файлов: 46
|
|
||||||
- удалить файлов: 41
|
|
||||||
|
|
||||||
Применение и проверки: `docs/Blockchain/CODEX_APPLY_ANS104_TEST5590_PATCH.md`.
|
|
||||||
|
|
||||||
## Проверки при сборке patch
|
|
||||||
|
|
||||||
- `node --check` для изменённых production JS: OK.
|
|
||||||
- `diff -qr` каталога `ESP32` относительно исходного архива: без изменений.
|
|
||||||
- Active Java refs на удалённые SHINE-ARCHIVE/file-recovery classes: отсутствуют.
|
|
||||||
- `./gradlew testClasses --offline --no-daemon`: не запущен до компиляции, потому что wrapper требует скачать Gradle 8.14 с `services.gradle.org`, а рабочая среда не имеет внешнего сетевого доступа. Полный Gradle test обязателен после применения patch в dev-среде.
|
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
# SHiNE — патч R2 для публичных вложений (14.11.2026)
|
||||||
|
|
||||||
|
**База:** `SHiNE-bundle-2026.11.14-13.22.24.zip`. Это overlay-патч: распаковать **поверх точно этой версии** репозитория, сохраняя пути. Не раскатывать без проверки на тестовом сервере.
|
||||||
|
|
||||||
|
## Что изменено
|
||||||
|
|
||||||
|
- `S:att;v=1` поддерживает `pr` (BitTorrent v2 pieces root, base64url) и необязательное `mm` (MIME); `ar` сохраняется. Старый `sha256` остаётся читаемым.
|
||||||
|
- SHA-256 у аватаров и существующий `/files/<sha256>` не меняются.
|
||||||
|
- Новый `file-preparation-service.js` вычисляет `pr` через существующий аккумулятор порциями 1 МиБ; по окончательному файлу.
|
||||||
|
- Новый `POST /api/files/prepare` принимает `{pr,size,mm}`, проверяет Ed25519 подпись существующей сессии, возвращает `uploadUrl` / `requiredHeaders` или `exists=true`.
|
||||||
|
- Клиент напрямую делает один PUT в Cloudflare R2 (без проксирования байтов Java), максимальный размер 500 МиБ, без Multipart.
|
||||||
|
- Для публичных вложений нет встроенного медиа-превью — только файловые карточки и прямые URL; в DM просмотрщик не меняется.
|
||||||
|
- Для новых Arweave-вложений считаем `pr` и сохраняем `mm`, но аватары и транзакции прошлых версий остаются на SHA-256.
|
||||||
|
|
||||||
|
## Конфигурация Java-сервера
|
||||||
|
|
||||||
|
В защищённом окружении процесса Java задать:
|
||||||
|
|
||||||
|
```
|
||||||
|
R2_ENDPOINT=https://<account_id>.r2.cloudflarestorage.com
|
||||||
|
R2_ACCESS_KEY_ID=<secret>
|
||||||
|
R2_SECRET_ACCESS_KEY=<secret>
|
||||||
|
```
|
||||||
|
|
||||||
|
И `r2.publicBucket=shine-files` в обычной конфигурации. Убедиться, что используется endpoint юрисдикции, соответствующей bucket. Значения в Git НЕ добавлять.
|
||||||
|
|
||||||
|
Cloudflare CORS bucket `shine-files` должен позволять `PUT`, `GET`, `HEAD` с origins SHiNE и с заголовками **Content-Type, If-None-Match** (можно `AllowedHeaders: ["*"]`). Для тестового UI-домена добавить соответствующий origin в Cloudflare CORS; Java API в патче разрешает `https://test.shineup.me` наряду с основным доменом. Custom Domain: `https://files.shineup.me`.
|
||||||
|
|
||||||
|
## Запрос подписанного разрешения
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /api/files/prepare
|
||||||
|
Content-Type: application/json
|
||||||
|
X-Shine-Session-Id: <sessionId>
|
||||||
|
X-Shine-Time-Ms: <epoch-ms>
|
||||||
|
X-Shine-Signature: <Ed25519 signature>
|
||||||
|
|
||||||
|
{"pr":"<43-char-base64url>","size":12345,"mm":"video/mp4"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Подпись по UTF-8 строке:
|
||||||
|
|
||||||
|
```
|
||||||
|
PUBLIC_R2_PREPARE_V1:<sessionId>:<pr>:<size>:<mm>:<epoch-ms>
|
||||||
|
```
|
||||||
|
|
||||||
|
От сервера клиент получает `requiredHeaders`: передать **ровно эти заголовки** при PUT в `uploadUrl`. `If-None-Match: *` запрещает перезапись. Ключи API никогда не отправляются клиенту.
|
||||||
|
|
||||||
|
## Тесты
|
||||||
|
|
||||||
|
```
|
||||||
|
node scripts/tests/test-r2-file-preparation.mjs
|
||||||
|
python3 scripts/check_docs.py
|
||||||
|
./gradlew compileJava test
|
||||||
|
```
|
||||||
|
|
||||||
|
В среде подготовки патча проверки JavaScript и документации прошли. **Java-сборку нельзя было завершить**: Gradle Wrapper хотел скачать Gradle 8.14 с `services.gradle.org`, но сеть контейнера недоступна. Выполнить Gradle-сборку и сквозной тест реального R2 **до production deploy**. Реальный R2 не тестировался.
|
||||||
|
|
||||||
|
## Риски, которые остаются в MVP
|
||||||
|
|
||||||
|
- Клиент задаёт `pr`; сервер не пересчитывает хеш содержимого. Возможна первоначальная подмена объекта под заявленным ключом; проверка размера и `If-None-Match` не решают эту проблему полностью. Для доверенной дедупликации нужна независимая проверка или механизм карантина.
|
||||||
|
- Сервер проверяет **заявленный** размер до подписи, но простой Presigned PUT сам по себе не обеспечивает строгий лимит фактически переданных байтов. Обязательно ограничить расходы/злоупотребления в окружении R2; для публичного production это отдельный вопрос безопасности.
|
||||||
|
- Один PUT при обрыве загружается заново. Multipart пока исключён по согласованию.
|
||||||
|
- Для тестового домена нужны правильные CORS origins; кэширование Cloudflare необязательно.
|
||||||
@@ -1,7 +1,29 @@
|
|||||||
# SHiNE
|
# SHiNE
|
||||||
|
|
||||||
## План запуска DAO
|
SHiNE — проект децентрализованного общения: браузерный клиент, сервер, пользовательские блокчейны, личные сообщения и интеграция с Solana и Arweave. Репозиторий содержит также экспериментальные компоненты для ESP32 и браузерное расширение кошелька.
|
||||||
|
|
||||||
План запуска DAO зафиксирован в [DAO_запуск/README.md](DAO_запуск/README.md).
|
> **Статус:** активная разработка и подготовка к публичному запуску. Исходный код доступен для изучения; самостоятельный запуск возможен, но инструкции по установке ещё дорабатываются. Не все описанные в планах возможности реализованы.
|
||||||
|
|
||||||
Это рабочий список задач по `этап1` и `этап2`. Дальше ведём его как основной чек-лист запуска DAO и отмечаем в нём выполненные пункты по мере готовности.
|
## Как устроен проект
|
||||||
|
|
||||||
|
| Компонент | Назначение |
|
||||||
|
| --- | --- |
|
||||||
|
| [`shine-UI/`](shine-UI/) | Браузерный клиент и панель администратора сервера |
|
||||||
|
| [`SHiNE-server/`](SHiNE-server/) | WebSocket/HTTP сервер, PostgreSQL, блокчейн, доставка сообщений |
|
||||||
|
| [`shine-solana/shine/`](shine-solana/shine/) | Anchor-программы и инструменты Solana |
|
||||||
|
| [`SHiNE-browser-plugin-wallet/`](SHiNE-browser-plugin-wallet/) | Браузерное расширение кошелька |
|
||||||
|
| [`ESP32/`](ESP32/) | Прошивки и прототипы устройств |
|
||||||
|
| [`deploy/`](deploy/) | Скрипты и инструкции по развёртыванию |
|
||||||
|
|
||||||
|
Архитектура и границы компонентов описаны в [общей схеме](docs/ARCHITECTURE.md). Пользовательские блоки проектируются для публикации в Arweave; подробности и текущие ограничения тестового контура приведены в [документации блокчейна](docs/Blockchain/README.md).
|
||||||
|
|
||||||
|
## Самостоятельный запуск
|
||||||
|
|
||||||
|
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
|
||||||
|
|
||||||
|
## Документация
|
||||||
|
|
||||||
|
- [Каталог документации](docs/README.md) — действующие спецификации, инструкции и планы.
|
||||||
|
- [Общая архитектура](docs/ARCHITECTURE.md) — компоненты и потоки данных.
|
||||||
|
- [API](docs/API/09_Operations_Index.md), [формат блокчейна](docs/Blockchain/README.md), [личные сообщения](docs/Personal_Messages/README.md), [Solana](docs/Solana_Architecture/README.md).
|
||||||
|
- [Правила обновления документации](docs/CONTRIBUTING_DOCS.md).
|
||||||
|
|||||||
+1
-1
@@ -7,7 +7,7 @@
|
|||||||
"": {
|
"": {
|
||||||
"name": "shine-browser-plugin-wallet",
|
"name": "shine-browser-plugin-wallet",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"license": "ISC",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/curves": "^1.5.0",
|
"@noble/curves": "^1.5.0",
|
||||||
"@solana/web3.js": "^1.98.4"
|
"@solana/web3.js": "^1.98.4"
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "shine-browser-plugin-wallet",
|
"name": "shine-browser-plugin-wallet",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
"description": "Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.",
|
"description": "Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.",
|
||||||
"main": "popup.js",
|
"main": "popup.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -8,7 +9,7 @@
|
|||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
"license": "ISC",
|
"license": "UNLICENSED",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/curves": "^1.5.0",
|
"@noble/curves": "^1.5.0",
|
||||||
"@solana/web3.js": "^1.98.4"
|
"@solana/web3.js": "^1.98.4"
|
||||||
|
|||||||
@@ -15,6 +15,17 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
|
|||||||
- `shine-server-config/` — конфигурация сервера
|
- `shine-server-config/` — конфигурация сервера
|
||||||
- `shine-server-log/` — логирование
|
- `shine-server-log/` — логирование
|
||||||
- `shine-server-geo/` — геолокация IP
|
- `shine-server-geo/` — геолокация IP
|
||||||
|
- `shine-server-solana-users-sync/` — синхронизация PDA Solana в серверные данные
|
||||||
|
- `shine-server-archive/` — публикация/импорт Arweave и workflow бесплатной регистрации
|
||||||
|
|
||||||
|
## Документация при изменении кода
|
||||||
|
|
||||||
|
- Новая или изменённая WS-операция: обновить профильный документ `../docs/API/` и `../docs/API/09_Operations_Index.md`; список зарегистрированных операций сверять с `JsonHandlerRegistry.java`.
|
||||||
|
- Формат блока, правила проверки или публикации: обновить `../docs/Blockchain/` и журнал изменений этого раздела.
|
||||||
|
- Доставка или формат DM: обновить затронутые документы из `../docs/Personal_Messages/README.md`.
|
||||||
|
- Синхронизация Solana users: обновить `../docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md` и `../deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md`.
|
||||||
|
- Регистрация с email, namespace или Arweave-сертификатами: обновить действующие документы в `../docs/registration-v2/`, а исторические планы явно оставлять помеченными как история.
|
||||||
|
- Изменение локального запуска или конфигурации: обновить корневой `../README.md`, `../docs/ARCHITECTURE.md` либо `../deploy/README.md` по затронутой теме.
|
||||||
|
|
||||||
## Настройка сервера в Solana (Solana PDA)
|
## Настройка сервера в Solana (Solana PDA)
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
import blockchain.BchBlockEntry;
|
||||||
|
import blockchain.CoreContentContainer;
|
||||||
|
import blockchain.CoreContentTransport;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/** Thin adapter for the existing archive queues. No signing, state or independent retry. */
|
||||||
|
final class ArchiveBlockPair {
|
||||||
|
private ArchiveBlockPair() {}
|
||||||
|
|
||||||
|
@FunctionalInterface interface Upload<R> {
|
||||||
|
R upload(byte[] raw, byte[] id) throws Exception;
|
||||||
|
}
|
||||||
|
@FunctionalInterface interface Download {
|
||||||
|
byte[] download(byte[] id) throws Exception;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns CORE acknowledgement only after both uploads succeed. */
|
||||||
|
static <R> R publish(byte[] container, byte[] expectedCoreId, Upload<R> uploader) throws Exception {
|
||||||
|
BchBlockEntry block = BchBlockEntry.fromCoreContent(container);
|
||||||
|
Ans104DataItem core = block.getCoreDataItem(), content = block.getContentDataItem();
|
||||||
|
if (!Arrays.equals(core.id32(), expectedCoreId)) throw new IllegalArgumentException("CORE id mismatch");
|
||||||
|
uploader.upload(content.rawBytes(), content.id32());
|
||||||
|
return uploader.upload(core.rawBytes(), core.id32());
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Download by signed reference, not by search tag or the CORE bundle location. */
|
||||||
|
static byte[] download(byte[] coreRaw, byte[] expectedCoreId, Download downloader) throws Exception {
|
||||||
|
Ans104DataItem core = new Ans104DataItem(coreRaw);
|
||||||
|
var record = CoreContentTransport.verifyCore(core, core.owner32(), expectedCoreId, Instant.now().getEpochSecond());
|
||||||
|
Ans104DataItem content = new Ans104DataItem(downloader.download(record.contentDataItemId32()));
|
||||||
|
CoreContentTransport.verifyContent(record, content, core.owner32());
|
||||||
|
return CoreContentContainer.pack(core, content);
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
-76
@@ -8,7 +8,6 @@ import shine.db.entities.BlockEntry;
|
|||||||
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
||||||
import server.sync.ArweavePublishSignal;
|
import server.sync.ArweavePublishSignal;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.function.Consumer;
|
import java.util.function.Consumer;
|
||||||
import java.util.function.Predicate;
|
import java.util.function.Predicate;
|
||||||
@@ -20,12 +19,11 @@ public final class ArweaveBlockPublisherService {
|
|||||||
private final ArweaveBlocksConfig cfg;
|
private final ArweaveBlocksConfig cfg;
|
||||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||||
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
|
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
|
||||||
private final ArweaveL1Uploader arweaveUploader;
|
|
||||||
private final TurboDataItemUploader turboUploader;
|
private final TurboDataItemUploader turboUploader;
|
||||||
|
|
||||||
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
|
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
|
||||||
|
cfg.validatePublisher();
|
||||||
this.cfg = cfg;
|
this.cfg = cfg;
|
||||||
this.arweaveUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.ARWEAVE ? new ArweaveL1Uploader(cfg) : null;
|
|
||||||
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
|
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -42,7 +40,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
if (entry == null) return true;
|
if (entry == null) return true;
|
||||||
byte[] raw = entry.getBlockBytes();
|
byte[] raw = entry.getBlockBytes();
|
||||||
if (raw == null || raw.length == 0) return false;
|
if (raw == null || raw.length == 0) return false;
|
||||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||||
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
|
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
|
||||||
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
|
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
|
||||||
@@ -53,7 +51,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
if (entry == null) return true;
|
if (entry == null) return true;
|
||||||
byte[] raw = entry.getBlockBytes();
|
byte[] raw = entry.getBlockBytes();
|
||||||
if (raw == null || raw.length == 0) return false;
|
if (raw == null || raw.length == 0) return false;
|
||||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||||
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
|
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
|
||||||
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
|
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
|
||||||
@@ -83,7 +81,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
attempted += rotationCandidates.size();
|
attempted += rotationCandidates.size();
|
||||||
published += switch (cfg.publishMode()) {
|
published += switch (cfg.publishMode()) {
|
||||||
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
|
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
|
||||||
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates);
|
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||||
case NONE -> 0;
|
case NONE -> 0;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -96,7 +94,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
if (candidates.isEmpty()) return published;
|
if (candidates.isEmpty()) return published;
|
||||||
published += switch (cfg.publishMode()) {
|
published += switch (cfg.publishMode()) {
|
||||||
case TURBO -> publishTurbo(candidates, onPublished);
|
case TURBO -> publishTurbo(candidates, onPublished);
|
||||||
case ARWEAVE -> publishDirectArweave(candidates);
|
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||||
case NONE -> 0;
|
case NONE -> 0;
|
||||||
};
|
};
|
||||||
return published;
|
return published;
|
||||||
@@ -110,7 +108,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
byte[] id = e.getDataItemId();
|
byte[] id = e.getDataItemId();
|
||||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||||
try {
|
try {
|
||||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||||
onPublished.accept(id);
|
onPublished.accept(id);
|
||||||
published++;
|
published++;
|
||||||
@@ -135,7 +133,7 @@ public final class ArweaveBlockPublisherService {
|
|||||||
byte[] id = e.getDataItemId();
|
byte[] id = e.getDataItemId();
|
||||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||||
try {
|
try {
|
||||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||||
onPublished.accept(id);
|
onPublished.accept(id);
|
||||||
published++;
|
published++;
|
||||||
@@ -151,71 +149,4 @@ public final class ArweaveBlockPublisherService {
|
|||||||
return published;
|
return published;
|
||||||
}
|
}
|
||||||
|
|
||||||
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
|
|
||||||
List<byte[]> items = new ArrayList<>();
|
|
||||||
List<byte[]> ids = new ArrayList<>();
|
|
||||||
long estimated = 32;
|
|
||||||
for (KeyRotationCandidateBlockEntry e : candidates) {
|
|
||||||
byte[] raw = e.getBlockBytes();
|
|
||||||
byte[] id = e.getDataItemId();
|
|
||||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
|
||||||
long next = estimated + 64L + raw.length;
|
|
||||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
|
||||||
if (next > cfg.publishMaxBundleBytes()) {
|
|
||||||
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
|
||||||
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
items.add(raw);
|
|
||||||
ids.add(id);
|
|
||||||
estimated = next;
|
|
||||||
}
|
|
||||||
if (items.isEmpty()) return 0;
|
|
||||||
|
|
||||||
byte[] bundle = Ans104Bundle.write(items);
|
|
||||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
|
||||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
|
||||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
|
||||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
|
||||||
);
|
|
||||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
|
||||||
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
|
||||||
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
|
||||||
items.size(), result.txId(), bundle.length);
|
|
||||||
return items.size();
|
|
||||||
}
|
|
||||||
|
|
||||||
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
|
|
||||||
List<byte[]> items = new ArrayList<>();
|
|
||||||
List<byte[]> ids = new ArrayList<>();
|
|
||||||
long estimated = 32;
|
|
||||||
for (BlockEntry e : candidates) {
|
|
||||||
byte[] raw = e.getBlockBytes();
|
|
||||||
byte[] id = e.getDataItemId();
|
|
||||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
|
||||||
long next = estimated + 64L + raw.length;
|
|
||||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
|
||||||
if (next > cfg.publishMaxBundleBytes()) {
|
|
||||||
log.error("One DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
|
||||||
e.getBchName(), e.getBlockNumber(), raw.length);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
items.add(raw);
|
|
||||||
ids.add(id);
|
|
||||||
estimated = next;
|
|
||||||
}
|
|
||||||
if (items.isEmpty()) return 0;
|
|
||||||
|
|
||||||
byte[] bundle = Ans104Bundle.write(items);
|
|
||||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
|
||||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
|
||||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
|
||||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
|
||||||
);
|
|
||||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
|
||||||
blocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
|
||||||
log.info("Published {} SHiNE test DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
|
||||||
items.size(), result.txId(), bundle.length);
|
|
||||||
return items.size();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
+189
-26
@@ -2,6 +2,7 @@ package server.archive;
|
|||||||
|
|
||||||
import blockchain.Ans104DataItem;
|
import blockchain.Ans104DataItem;
|
||||||
import blockchain.BchBlockEntry;
|
import blockchain.BchBlockEntry;
|
||||||
|
import server.archive.registration.VerifiedFreeRegistrationImporter;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -9,6 +10,8 @@ import org.slf4j.LoggerFactory;
|
|||||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||||
import server.sync.BlockchainResyncGuard;
|
import server.sync.BlockchainResyncGuard;
|
||||||
import shine.db.DbController;
|
import shine.db.DbController;
|
||||||
|
import shine.db.KeyEncodingUtil;
|
||||||
|
import utils.config.AppConfig;
|
||||||
import shine.db.dao.ArweaveBlockImportDAO;
|
import shine.db.dao.ArweaveBlockImportDAO;
|
||||||
import shine.db.dao.BlockchainStateDAO;
|
import shine.db.dao.BlockchainStateDAO;
|
||||||
import shine.db.dao.BlocksDAO;
|
import shine.db.dao.BlocksDAO;
|
||||||
@@ -17,6 +20,7 @@ import shine.db.dao.CanonicalChainResolver;
|
|||||||
import shine.db.dao.ChannelReadStateDAO;
|
import shine.db.dao.ChannelReadStateDAO;
|
||||||
import shine.db.dao.BlockchainResyncCleanupDAO;
|
import shine.db.dao.BlockchainResyncCleanupDAO;
|
||||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||||
|
import shine.db.dao.RegistrationIdentityDAO;
|
||||||
import shine.db.entities.BlockchainStateEntry;
|
import shine.db.entities.BlockchainStateEntry;
|
||||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||||
|
|
||||||
@@ -36,9 +40,8 @@ import java.time.Duration;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
|
* Discovers signed CORE items and registration certificates in the active App namespace.
|
||||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
* Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
|
||||||
* or inside a direct server-created ANS-104 bundle.
|
|
||||||
*/
|
*/
|
||||||
public final class ArweaveBlockSyncService {
|
public final class ArweaveBlockSyncService {
|
||||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
|
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
|
||||||
@@ -50,6 +53,8 @@ public final class ArweaveBlockSyncService {
|
|||||||
.connectTimeout(Duration.ofSeconds(20))
|
.connectTimeout(Duration.ofSeconds(20))
|
||||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||||
.build();
|
.build();
|
||||||
|
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
|
||||||
|
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
|
||||||
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
||||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||||
@@ -68,6 +73,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
public void runCycle() throws Exception {
|
public void runCycle() throws Exception {
|
||||||
recoverInterruptedCanonicalRebuilds();
|
recoverInterruptedCanonicalRebuilds();
|
||||||
discover();
|
discover();
|
||||||
|
discoverFreeRegistrations();
|
||||||
drainQueue();
|
drainQueue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -115,7 +121,13 @@ public final class ArweaveBlockSyncService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
DownloadedEvent downloaded = downloadEvent(dataItemId);
|
||||||
|
if (downloaded.registration()) {
|
||||||
|
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
unresolvedDownloads.remove(dataItemId);
|
||||||
|
continue; // Не парсить регистрацию как BchBlockEntry.
|
||||||
|
}
|
||||||
unresolvedDownloads.remove(dataItemId);
|
unresolvedDownloads.remove(dataItemId);
|
||||||
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
||||||
} catch (RetryableDataItemDownloadException e) {
|
} catch (RetryableDataItemDownloadException e) {
|
||||||
@@ -156,9 +168,9 @@ public final class ArweaveBlockSyncService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
DownloadedDataItem downloaded;
|
DownloadedEvent downloaded;
|
||||||
try {
|
try {
|
||||||
downloaded = downloadSignedDataItem(pending.dataItemId());
|
downloaded = downloadEvent(pending.dataItemId());
|
||||||
} catch (RetryableDataItemDownloadException e) {
|
} catch (RetryableDataItemDownloadException e) {
|
||||||
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
|
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
|
||||||
unresolvedDownloads.remove(pending.dataItemId());
|
unresolvedDownloads.remove(pending.dataItemId());
|
||||||
@@ -172,6 +184,18 @@ public final class ArweaveBlockSyncService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (downloaded.registration()) {
|
||||||
|
try {
|
||||||
|
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
unresolvedDownloads.remove(pending.dataItemId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
unresolvedDownloads.remove(pending.dataItemId());
|
||||||
|
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||||
|
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
||||||
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
||||||
queued++;
|
queued++;
|
||||||
@@ -202,7 +226,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
if (pending.isEmpty()) break;
|
if (pending.isEmpty()) break;
|
||||||
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
||||||
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
||||||
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
|
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
|
||||||
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
||||||
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
||||||
continue;
|
continue;
|
||||||
@@ -226,15 +250,16 @@ public final class ArweaveBlockSyncService {
|
|||||||
Ans104DataItem item;
|
Ans104DataItem item;
|
||||||
BchBlockEntry parsedBlock;
|
BchBlockEntry parsedBlock;
|
||||||
try {
|
try {
|
||||||
item = new Ans104DataItem(q.rawDataItem());
|
parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
|
||||||
parsedBlock = new BchBlockEntry(q.rawDataItem());
|
item = parsedBlock.getCoreDataItem();
|
||||||
|
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
|
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
|
||||||
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
|
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
|
||||||
progress = true;
|
progress = true;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
|
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||||
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
||||||
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
||||||
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
||||||
@@ -305,14 +330,11 @@ public final class ArweaveBlockSyncService {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
// Metadata is trusted only after complete ANS-104 validation.
|
// Metadata is trusted only after complete ANS-104 validation.
|
||||||
Ans104DataItem item = new Ans104DataItem(raw);
|
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
|
||||||
|
Ans104DataItem item = b.getCoreDataItem();
|
||||||
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
|
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
|
||||||
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
|
|
||||||
throw new IllegalArgumentException("bad App tag");
|
|
||||||
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
|
|
||||||
BchBlockEntry b = new BchBlockEntry(raw);
|
|
||||||
|
|
||||||
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
|
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||||
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
||||||
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
||||||
continue;
|
continue;
|
||||||
@@ -329,7 +351,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
|
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
|
||||||
if (b.blockNumber != fb.forkPointBlockNumber + 1)
|
if (b.blockNumber != fb.forkPointBlockNumber + 1)
|
||||||
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
|
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
|
||||||
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
|
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
|
||||||
if (parent == null || parent.getBlockchainName() == null
|
if (parent == null || parent.getBlockchainName() == null
|
||||||
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
||||||
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
||||||
@@ -365,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 {
|
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
|
||||||
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
||||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>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);
|
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
|
||||||
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||||
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
||||||
@@ -391,7 +468,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
while(rs.next())logins.add(rs.getString(1));
|
while(rs.next())logins.add(rs.getString(1));
|
||||||
}
|
}
|
||||||
for(String login:logins){
|
for(String login:logins){
|
||||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
|
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
|
||||||
if(u==null||u.getBlockchainName()==null)continue;
|
if(u==null||u.getBlockchainName()==null)continue;
|
||||||
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
||||||
}
|
}
|
||||||
@@ -444,7 +521,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||||
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
|
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
|
||||||
BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
|
BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
|
||||||
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
|
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
|
||||||
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
|
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
|
||||||
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
|
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
|
||||||
@@ -454,17 +531,17 @@ public final class ArweaveBlockSyncService {
|
|||||||
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
||||||
}
|
}
|
||||||
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
||||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||||
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
|
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
|
||||||
try{
|
try{
|
||||||
validateGenericStaging(login);
|
validateGenericStaging(login);
|
||||||
cleanupDAO.cleanupLoginForCanonicalReplay(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")){
|
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
|
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
|
||||||
String bch=login+"-"+String.format("%03d",f);
|
String bch=login+"-"+String.format("%03d",f);
|
||||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||||
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
||||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||||
}}
|
}}
|
||||||
@@ -474,10 +551,95 @@ public final class ArweaveBlockSyncService {
|
|||||||
}finally{BlockchainResyncGuard.end(activeName);}
|
}finally{BlockchainResyncGuard.end(activeName);}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
|
||||||
|
private void discoverFreeRegistrations() throws Exception {
|
||||||
|
long stored;
|
||||||
|
try (Connection c = DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
|
||||||
|
ResultSet rs = ps.executeQuery()) {
|
||||||
|
stored = rs.next() ? rs.getLong(1) : 0;
|
||||||
|
}
|
||||||
|
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
|
||||||
|
long high = minHeight;
|
||||||
|
long retryFrom = Long.MAX_VALUE;
|
||||||
|
String cursor = null;
|
||||||
|
int count = 0;
|
||||||
|
do {
|
||||||
|
JsonNode response = graphQlPage(minHeight, cursor, true);
|
||||||
|
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
|
||||||
|
JsonNode txs = response.path("data").path("transactions");
|
||||||
|
JsonNode edges = txs.path("edges");
|
||||||
|
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
|
||||||
|
String next = null;
|
||||||
|
for (JsonNode edge : edges) {
|
||||||
|
next = edge.path("cursor").asText(null);
|
||||||
|
JsonNode node = edge.path("node");
|
||||||
|
String id = node.path("id").asText("").trim();
|
||||||
|
long height = node.path("block").path("height").asLong(-1);
|
||||||
|
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
|
||||||
|
high = Math.max(high, height);
|
||||||
|
try {
|
||||||
|
byte[] idBytes = B64URL.decode(id);
|
||||||
|
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
|
||||||
|
DownloadedDataItem item = downloadSignedDataItem(id);
|
||||||
|
if (!isRegistrationItem(item.rawDataItem()))
|
||||||
|
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
|
||||||
|
registrationImporter.importSigned(item.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
count++;
|
||||||
|
} catch (RetryableDataItemDownloadException e) {
|
||||||
|
retryFrom = Math.min(retryFrom, height);
|
||||||
|
log.debug("Registration DataItem {} is not downloadable yet", id);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
retryFrom = Math.min(retryFrom, height);
|
||||||
|
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
|
||||||
|
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
|
||||||
|
throw new IOException("Registration GraphQL cursor missing");
|
||||||
|
} while (cursor != null);
|
||||||
|
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement("""
|
||||||
|
UPDATE free_registration_arweave_sync_state
|
||||||
|
SET last_block_height=?, updated_at_ms=? WHERE id=1
|
||||||
|
""")) {
|
||||||
|
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
|
||||||
|
}
|
||||||
|
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isRegistrationItem(byte[] raw) {
|
||||||
|
Ans104DataItem item = new Ans104DataItem(raw);
|
||||||
|
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
|
||||||
|
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
|
||||||
|
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
|
||||||
|
if (isRegistrationItem(first.rawDataItem())) {
|
||||||
|
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
|
||||||
|
}
|
||||||
|
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
|
||||||
|
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
|
||||||
|
return new DownloadedEvent(first.rootTxId(), container, false);
|
||||||
|
}
|
||||||
|
|
||||||
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
||||||
|
return graphQlPage(minHeight, cursor, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
|
||||||
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
||||||
String query = "query { transactions(tags:[{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}], block:{min:" + minHeight + "}, first:"
|
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
|
||||||
|
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
|
||||||
|
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
|
||||||
+ cfg.syncPageSize() + ", after:" + after
|
+ cfg.syncPageSize() + ", after:" + after
|
||||||
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
||||||
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
||||||
@@ -666,6 +828,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
|
|
||||||
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
|
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
|
||||||
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
|
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
|
||||||
|
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
|
||||||
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
|
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
|
||||||
|
|
||||||
private static final class RetryableDataItemDownloadException extends IOException {
|
private static final class RetryableDataItemDownloadException extends IOException {
|
||||||
|
|||||||
+3
-3
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
|
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
|
||||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE;
|
public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
|
||||||
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
|
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
|
||||||
|
|
||||||
public static ArweaveBlocksConfig load() {
|
public static ArweaveBlocksConfig load() {
|
||||||
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
|
|||||||
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
|
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
|
||||||
|
|
||||||
public void validatePublisher() {
|
public void validatePublisher() {
|
||||||
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) {
|
if (publishMode == PublishMode.ARWEAVE) {
|
||||||
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave");
|
throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
|
||||||
}
|
}
|
||||||
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
|
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
|
||||||
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
|
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
|
||||||
|
|||||||
+50
@@ -0,0 +1,50 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.Locale;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/** Список разрешённых доменов для бесплатной регистрации; читается при старте Java-сервера. */
|
||||||
|
public final class AllowedEmailDomains {
|
||||||
|
// Обычные ASCII-домены (в том числе punycode), без масок, пробелов и URL.
|
||||||
|
private static final Pattern DOMAIN = Pattern.compile(
|
||||||
|
"(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+");
|
||||||
|
private final Set<String> domains;
|
||||||
|
|
||||||
|
private AllowedEmailDomains(Set<String> domains) {
|
||||||
|
this.domains = Set.copyOf(domains);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ошибки чтения, пустой или неверный список — ошибка запуска регистрации (fail-closed). */
|
||||||
|
public static AllowedEmailDomains load(Path file) throws IOException {
|
||||||
|
if (!Files.isRegularFile(file))
|
||||||
|
throw new IOException("Email domain allowlist is missing: " + file.toAbsolutePath());
|
||||||
|
Set<String> result = new HashSet<>();
|
||||||
|
int lineNumber = 0;
|
||||||
|
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
|
||||||
|
lineNumber++;
|
||||||
|
String domain = line.strip().toLowerCase(Locale.ROOT);
|
||||||
|
if (domain.isEmpty() || domain.startsWith("#")) continue;
|
||||||
|
if (!DOMAIN.matcher(domain).matches())
|
||||||
|
throw new IOException("Invalid allowed email domain at " + file + ":" + lineNumber);
|
||||||
|
result.add(domain);
|
||||||
|
}
|
||||||
|
if (result.isEmpty())
|
||||||
|
throw new IOException("Email domain allowlist is empty: " + file.toAbsolutePath());
|
||||||
|
return new AllowedEmailDomains(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Сопоставление строго по части после одного символа @, без wildcard и суффиксов. */
|
||||||
|
public boolean permits(String email) {
|
||||||
|
if (email == null) return false;
|
||||||
|
String value = email.strip().toLowerCase(Locale.ROOT);
|
||||||
|
int at = value.indexOf('@');
|
||||||
|
if (at <= 0 || at != value.lastIndexOf('@')) return false;
|
||||||
|
return domains.contains(value.substring(at + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
+145
@@ -0,0 +1,145 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import server.archive.ArweaveBlocksConfig;
|
||||||
|
import server.archive.TurboDataItemUploader;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationApiBridge;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||||
|
import shine.db.DbController;
|
||||||
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.SQLFeatureNotSupportedException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/** Единственная точка подключения API без циклической зависимости Gradle-модулей. */
|
||||||
|
public final class FreeRegistrationApiBootstrap {
|
||||||
|
private static volatile FreeRegistrationWorkflow workflow;
|
||||||
|
private static volatile LocalRegistrarSigner signer;
|
||||||
|
private FreeRegistrationApiBootstrap() {}
|
||||||
|
|
||||||
|
public static synchronized void startOrThrow() throws Exception {
|
||||||
|
if (workflow != null) return;
|
||||||
|
AppConfig cfg=AppConfig.getInstance();
|
||||||
|
LocalRegistrarSigner newSigner=null;
|
||||||
|
FreeRegistrationIssuer issuer=null;
|
||||||
|
FreeRegistrationPublisher publisher=null;
|
||||||
|
RegistrationEmailSender emailSender=null;
|
||||||
|
AllowedEmailDomains allowedEmailDomains=null;
|
||||||
|
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.
|
||||||
|
allowedEmailDomains = AllowedEmailDomains.load(Path.of(domainsFile));
|
||||||
|
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
|
||||||
|
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||||
|
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||||
|
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));
|
||||||
|
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
|
||||||
|
String resendKey=System.getenv("RESEND_API_KEY");
|
||||||
|
if(resendKey==null || resendKey.isBlank())
|
||||||
|
resendKey=cfg.getStringOrEmpty("freeRegistration.email.apiKey");
|
||||||
|
emailSender=new ResendRegistrationEmailSender(resendKey,
|
||||||
|
cfg.getStringOrEmpty("freeRegistration.email.from").isBlank()
|
||||||
|
? "SHiNE <noreply@shineup.me>"
|
||||||
|
: cfg.getStringOrEmpty("freeRegistration.email.from"));
|
||||||
|
}
|
||||||
|
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
|
||||||
|
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
|
||||||
|
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
|
||||||
|
freeRegistrationEnabled ? freeNamespace : "");
|
||||||
|
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||||
|
signer=newSigner; workflow=newWorkflow;
|
||||||
|
}
|
||||||
|
public static synchronized void close() {
|
||||||
|
RegistrationApiBridge.uninstall();
|
||||||
|
workflow=null;
|
||||||
|
if(signer!=null) signer.close();
|
||||||
|
signer=null;
|
||||||
|
}
|
||||||
|
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
|
||||||
|
Map<String,Object> out=new LinkedHashMap<>();
|
||||||
|
switch(op) {
|
||||||
|
case "GetNamespaces" -> {
|
||||||
|
out.put("namespaces",w.listNamespaces().stream().map(ns->Map.of(
|
||||||
|
"name",ns.namespace(), "type",ns.type(), "minLocalLength",ns.minLoginLength(),
|
||||||
|
"registrationFeeLamports",ns.priceLamports(), "currencyCode",ns.currencyCode(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
|
||||||
|
)).toList());
|
||||||
|
}
|
||||||
|
case "CheckRegistrationLogin" -> {
|
||||||
|
var info=w.checkLogin(req.getFullLogin());
|
||||||
|
out.put("loginAvailable",info.loginAvailable());
|
||||||
|
out.put("namespaceType",info.namespaceType());
|
||||||
|
out.put("minLocalLength",info.minLocalLength());
|
||||||
|
out.put("registrationFeeLamports",info.registrationFeeLamports());
|
||||||
|
out.put("currencyCode",info.currencyCode());
|
||||||
|
}
|
||||||
|
case "CheckRegistrationEmail" -> {
|
||||||
|
var check=w.checkEmail(req.getEmail());
|
||||||
|
out.put("emailAvailable",check.emailAvailable());
|
||||||
|
out.put("emailStatus",check.emailStatus());
|
||||||
|
}
|
||||||
|
case "StartFreeRegistration" -> {
|
||||||
|
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
|
||||||
|
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
|
||||||
|
out.put("challengeId",state.challengeId()); out.put("expiresAtMs",state.expiresAtMs());
|
||||||
|
}
|
||||||
|
case "ConfirmFreeRegistration" -> {
|
||||||
|
var value=w.confirm(req.getChallengeId(),req.getCode());
|
||||||
|
out.put("fullLogin",value.fullLogin());out.put("dataItemId",value.dataItemId());
|
||||||
|
out.put("publicationStatus",value.state());out.put("chainConfirmed",false);
|
||||||
|
}
|
||||||
|
case "GetRegistrationStatus" -> {
|
||||||
|
var value=w.getStatus(req.getFullLogin());
|
||||||
|
out.put("registrationStatus",value.status());
|
||||||
|
out.put("dataItemId",value.dataItemId()==null?"":value.dataItemId());
|
||||||
|
out.put("publicationStatus",value.publicationStatus()==null?"":value.publicationStatus());
|
||||||
|
// Публичная историческая часть сертификата для бесплатного → Solana upgrade.
|
||||||
|
if("FREE_CERT".equals(value.status())) {
|
||||||
|
out.put("innerSignature64B64",value.innerSignature64B64()==null?"":value.innerSignature64B64());
|
||||||
|
out.put("rootPublicKey",value.rootPublicKey()==null?"":value.rootPublicKey());
|
||||||
|
out.put("blockchainPublicKey",value.blockchainPublicKey()==null?"":value.blockchainPublicKey());
|
||||||
|
out.put("clientPublicKey",value.clientPublicKey()==null?"":value.clientPublicKey());
|
||||||
|
out.put("defaultServerLogin",value.defaultServerLogin()==null?"":value.defaultServerLogin());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> throw new IllegalArgumentException("Unknown registration operation");
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
private static byte[] decodeKey(String base64) {
|
||||||
|
if(base64==null || base64.length()>64)throw new IllegalArgumentException("Invalid public key");
|
||||||
|
byte[] decoded=Base64.getDecoder().decode(base64);
|
||||||
|
if(decoded.length!=32)throw new IllegalArgumentException("Invalid public key length");
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
private static DataSource dbSource() {
|
||||||
|
return new DataSource() {
|
||||||
|
@Override public Connection getConnection() throws SQLException {return DbController.getInstance().getConnection();}
|
||||||
|
@Override public Connection getConnection(String u,String p) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||||
|
@Override public PrintWriter getLogWriter(){return null;}
|
||||||
|
@Override public void setLogWriter(PrintWriter p){}
|
||||||
|
@Override public void setLoginTimeout(int t){}
|
||||||
|
@Override public int getLoginTimeout(){return 0;}
|
||||||
|
@Override public Logger getParentLogger(){return Logger.getGlobal();}
|
||||||
|
@Override public <T> T unwrap(Class<T> type) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||||
|
@Override public boolean isWrapperFor(Class<?> type){return false;}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+112
@@ -0,0 +1,112 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
import blockchain.ShineProtocolTags;
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.text.Normalizer;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
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 = ShineProtocolTags.CORE_REGISTRATION_TAGS;
|
||||||
|
|
||||||
|
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||||
|
byte[] clientKey, byte[] innerSignature,
|
||||||
|
byte[] emailSha256, byte[] owner32, String idBase64Url) {}
|
||||||
|
|
||||||
|
private FreeRegistrationCertificateV1() {}
|
||||||
|
|
||||||
|
public static String validateLogin(String login) {
|
||||||
|
if (login == null || !login.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
|
||||||
|
throw new IllegalArgumentException("Full login must use ASCII letters (any local-part case), lowercase namespace, <= 30 bytes");
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] identityFields(String login, byte[] root32, byte[] blockchain32, byte[] client32) {
|
||||||
|
byte[] name = validateLogin(login).getBytes(StandardCharsets.UTF_8);
|
||||||
|
require32(root32); require32(blockchain32); require32(client32);
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
out.write(1); out.write(0); out.write(name.length); out.writeBytes(name);
|
||||||
|
out.writeBytes(root32); out.writeBytes(blockchain32); out.writeBytes(client32);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] innerMessage(byte[] identity) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
out.writeBytes(DOMAIN); out.writeBytes(identity);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalizeEmail(String email) {
|
||||||
|
if (email == null) throw new IllegalArgumentException("Email is required");
|
||||||
|
String value = Normalizer.normalize(email.strip(), Normalizer.Form.NFC).toLowerCase(Locale.ROOT);
|
||||||
|
if (value.isBlank() || value.indexOf('@') < 1 || value.contains(" "))
|
||||||
|
throw new IllegalArgumentException("Invalid email");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] emailHash(String email) {
|
||||||
|
return sha256(normalizeEmail(email).getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
|
||||||
|
byte[] client32, String email, RegistrarSigner signer) {
|
||||||
|
byte[] fields = identityFields(login, root32, blockchain32, client32);
|
||||||
|
byte[] inner = signer.sign(innerMessage(fields));
|
||||||
|
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
|
||||||
|
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||||
|
payload.writeBytes(fields);
|
||||||
|
payload.writeBytes(inner);
|
||||||
|
payload.writeBytes(emailHash(email));
|
||||||
|
byte[] data = payload.toByteArray();
|
||||||
|
byte[] owner = signer.publicKey32();
|
||||||
|
require32(owner);
|
||||||
|
byte[] outer = signer.sign(Ans104DataItem.buildSigningMessage(owner, TAGS, data));
|
||||||
|
byte[] raw = Ans104DataItem.serializeEd25519(outer, owner, TAGS, data);
|
||||||
|
verify(raw, owner);
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Verified verify(byte[] signedDataItem, byte[] registrarPublicKey32) {
|
||||||
|
require32(registrarPublicKey32);
|
||||||
|
Ans104DataItem item = new Ans104DataItem(signedDataItem);
|
||||||
|
if (!item.ownerEquals(registrarPublicKey32) || !item.verifySignature())
|
||||||
|
throw new IllegalArgumentException("Invalid outer ANS-104 registrar signature");
|
||||||
|
if (!item.tags().equals(TAGS) || item.target().length != 0 || item.anchor().length != 0)
|
||||||
|
throw new IllegalArgumentException("Unexpected registration tags/target/anchor");
|
||||||
|
byte[] data = item.data();
|
||||||
|
if (data.length < 3 + 96 + 64 + 32 || data[0] != 1 || data[1] != 0)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate version/length");
|
||||||
|
int len = data[2] & 0xff;
|
||||||
|
if (data.length != 3 + len + 96 + 64 + 32)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate byte length");
|
||||||
|
String login = validateLogin(new String(data, 3, len, StandardCharsets.UTF_8));
|
||||||
|
int offset = 3 + len;
|
||||||
|
byte[] root = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] blockchain = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] client = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] innerSig = Arrays.copyOfRange(data, offset, offset+64); offset += 64;
|
||||||
|
byte[] emailSha = Arrays.copyOfRange(data, offset, offset+32);
|
||||||
|
byte[] fields = Arrays.copyOfRange(data, 0, 3 + len + 96);
|
||||||
|
if (!Ed25519Util.verify(innerMessage(fields), innerSig, registrarPublicKey32))
|
||||||
|
throw new IllegalArgumentException("Invalid inner certificate signature");
|
||||||
|
return new Verified(login, root, blockchain, client, innerSig, emailSha,
|
||||||
|
item.owner32(), Base64.getUrlEncoder().withoutPadding().encodeToString(item.id32()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void require32(byte[] key) {
|
||||||
|
if (key == null || key.length != 32) throw new IllegalArgumentException("Expected 32-byte public key");
|
||||||
|
}
|
||||||
|
private static byte[] sha256(byte[] data) {
|
||||||
|
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||||
|
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import sync.util.Base58Util;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||||
|
public final class FreeRegistrationIssuer {
|
||||||
|
private final DataSource db;
|
||||||
|
private final RegistrarSigner signer;
|
||||||
|
private final boolean allowEmailReuse;
|
||||||
|
|
||||||
|
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||||
|
this(db, signer, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
|
||||||
|
this.db = java.util.Objects.requireNonNull(db);
|
||||||
|
this.signer = java.util.Objects.requireNonNull(signer);
|
||||||
|
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 {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(fullLogin);
|
||||||
|
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
|
||||||
|
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
|
||||||
|
try (Connection conn = db.getConnection()) {
|
||||||
|
conn.setReadOnly(true);
|
||||||
|
String sql = """
|
||||||
|
SELECT namespace_type, min_localpart_len, registrar_pubkey, default_server_login
|
||||||
|
FROM shine_namespace_current WHERE namespace = ?
|
||||||
|
""";
|
||||||
|
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||||
|
statement.setString(1, namespace);
|
||||||
|
try (ResultSet rs = statement.executeQuery()) {
|
||||||
|
if (!rs.next() || rs.getInt("namespace_type") != 2 ||
|
||||||
|
fullLogin.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||||
|
throw new IllegalArgumentException("Free namespace is unavailable");
|
||||||
|
byte[] nsPub = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||||
|
if (!Arrays.equals(nsPub, signer.publicKey32()))
|
||||||
|
throw new IllegalStateException("Registrar public key does not match on-chain namespace");
|
||||||
|
String server = rs.getString("default_server_login");
|
||||||
|
if (server == null || server.isBlank())
|
||||||
|
throw new IllegalStateException("Free namespace server is not configured");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement ps = conn.prepareStatement(
|
||||||
|
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
|
||||||
|
ps.setString(1, fullLogin.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!allowEmailReuse) {
|
||||||
|
try (PreparedStatement ps = conn.prepareStatement(
|
||||||
|
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||||
|
ps.setBytes(1, expectedEmail);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||||
|
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||||
|
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import server.archive.TurboDataItemUploader;
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
|
||||||
|
/** Отдельный транспорт регистрации. Публикация не является пользовательским AddBlock. */
|
||||||
|
public final class FreeRegistrationPublisher {
|
||||||
|
private final FreeRegistrationIssuer issuer;
|
||||||
|
private final TurboDataItemUploader uploader;
|
||||||
|
private final VerifiedFreeRegistrationImporter importer;
|
||||||
|
|
||||||
|
public FreeRegistrationPublisher(FreeRegistrationIssuer issuer, TurboDataItemUploader uploader,
|
||||||
|
VerifiedFreeRegistrationImporter importer) {
|
||||||
|
this.issuer = java.util.Objects.requireNonNull(issuer);
|
||||||
|
this.uploader = java.util.Objects.requireNonNull(uploader);
|
||||||
|
this.importer = java.util.Objects.requireNonNull(importer);
|
||||||
|
}
|
||||||
|
/** Для повтора ПОСЛЕ потери ACK передавайте точно те же signedBytes. */
|
||||||
|
public VerifiedFreeRegistrationImporter.ImportResult publishSigned(byte[] signedBytes) throws Exception {
|
||||||
|
Ans104DataItem parsed = new Ans104DataItem(signedBytes);
|
||||||
|
importer.validateForUpload(signedBytes); // строго до HTTP/Turbo списания кредитов
|
||||||
|
// Импорт на этой точке вызовет полную проверку обеих подписей и namespace
|
||||||
|
// ПОСЛЕ успешного ACK Turbo, а не до окончательного подтверждения Arweave.
|
||||||
|
TurboDataItemUploader.UploadResult acknowledged = uploader.upload(signedBytes, parsed.id32());
|
||||||
|
String expectedId = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(parsed.id32());
|
||||||
|
if (!expectedId.equals(acknowledged.dataItemId()))
|
||||||
|
throw new IllegalStateException("Unexpected Turbo DataItem id");
|
||||||
|
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||||
|
}
|
||||||
|
}
|
||||||
+273
@@ -0,0 +1,273 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/** Внутренний state machine публичных операций регистрации v2. */
|
||||||
|
public final class FreeRegistrationWorkflow {
|
||||||
|
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, int currencyCode, String serverLogin) {}
|
||||||
|
public record Availability(boolean nameFree, boolean emailHashFree) {}
|
||||||
|
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports, int currencyCode) {}
|
||||||
|
public record EmailCheck(boolean emailAvailable, String emailStatus) {}
|
||||||
|
public record Started(String challengeId, long expiresAtMs) {}
|
||||||
|
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
|
||||||
|
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
|
||||||
|
String rootPublicKey, String blockchainPublicKey, String clientPublicKey,
|
||||||
|
String defaultServerLogin) {}
|
||||||
|
|
||||||
|
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
|
||||||
|
long expiresAtMs, byte[] codeHash, int attempts, boolean delivered,
|
||||||
|
boolean verified, byte[] signedBytes) {
|
||||||
|
Draft update(int attempts, boolean delivered, boolean verified, byte[] signedBytes) {
|
||||||
|
return new Draft(login, root, blockchain, client, email, expiresAtMs,
|
||||||
|
codeHash, attempts, delivered, verified, signedBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private final Map<String, Draft> pending = new ConcurrentHashMap<>();
|
||||||
|
// Не храним в БД почтовые адреса, пока регистрация не завершилась.
|
||||||
|
private final Map<String, Long> recentEmails = new HashMap<>();
|
||||||
|
private final Map<String, Long> recentLogins = new HashMap<>();
|
||||||
|
private final java.util.ArrayDeque<Long> globalSendTimes = new java.util.ArrayDeque<>();
|
||||||
|
private static final long TTL_MS = Duration.ofHours(1).toMillis();
|
||||||
|
private static final long EMAIL_COOLDOWN_MS = Duration.ofMinutes(1).toMillis();
|
||||||
|
private static final long GLOBAL_WINDOW_MS = Duration.ofHours(1).toMillis();
|
||||||
|
private static final int MAX_EMAILS_PER_HOUR = 60;
|
||||||
|
private static final int MAX_ATTEMPTS = 5;
|
||||||
|
private static final int MAX_PENDING = 512;
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
private final FreeRegistrationIssuer issuer;
|
||||||
|
private final FreeRegistrationPublisher publisher;
|
||||||
|
private final RegistrationEmailSender emailSender;
|
||||||
|
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, 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)
|
||||||
|
throw new IllegalArgumentException("Allowed email domain list is required");
|
||||||
|
this.allowedEmailDomains = allowedEmailDomains;
|
||||||
|
this.issuer = issuer;
|
||||||
|
this.publisher = publisher;
|
||||||
|
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(), "");
|
||||||
|
}
|
||||||
|
private static AllowedEmailDomains loadDefaultEmailDomains() {
|
||||||
|
try {
|
||||||
|
return AllowedEmailDomains.load(java.nio.file.Path.of("allowed-email-domains.txt"));
|
||||||
|
} catch (java.io.IOException e) {
|
||||||
|
throw new IllegalStateException("Cannot load allowed email domains", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||||
|
RegistrationEmailSender emailSender, boolean allowTestCode) {
|
||||||
|
this(issuer, publisher, emailSender, allowTestCode, false);
|
||||||
|
}
|
||||||
|
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||||
|
RegistrationEmailSender emailSender) {
|
||||||
|
this(issuer, publisher, emailSender, false);
|
||||||
|
}
|
||||||
|
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
|
||||||
|
this(issuer, publisher, null);
|
||||||
|
}
|
||||||
|
public List<NamespaceInfo> listNamespaces() throws Exception {
|
||||||
|
List<NamespaceInfo> result = new ArrayList<>();
|
||||||
|
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
|
||||||
|
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 {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(login);
|
||||||
|
String namespace=login.substring(login.indexOf('@')+1);
|
||||||
|
try (Connection c=DbController.getInstance().getConnection()) {
|
||||||
|
int type, minimum, currencyCode; String fee;
|
||||||
|
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports,currency_code FROM shine_namespace_current WHERE namespace=?")) {
|
||||||
|
p.setString(1,namespace);
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
|
||||||
|
p.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee,currencyCode); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public EmailCheck checkEmail(String email) throws Exception {
|
||||||
|
// До запроса к БД: отсутствие разрешения не должно раскрывать занятость email.
|
||||||
|
String normalizedEmail = FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||||
|
if (allowedEmailDomains == null || !allowedEmailDomains.permits(normalizedEmail))
|
||||||
|
return new EmailCheck(false, "DOMAIN_NOT_ALLOWED");
|
||||||
|
byte[] hash=FreeRegistrationCertificateV1.emailHash(normalizedEmail);
|
||||||
|
if (allowEmailReuse) return new EmailCheck(true, "AVAILABLE");
|
||||||
|
try (Connection c=DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||||
|
p.setBytes(1,hash);
|
||||||
|
try(ResultSet rs=p.executeQuery()) { return rs.next() ? new EmailCheck(false, "ALREADY_REGISTERED")
|
||||||
|
: new EmailCheck(true, "AVAILABLE"); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
|
||||||
|
public Availability availability(String login,String email) throws Exception {
|
||||||
|
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
|
||||||
|
}
|
||||||
|
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
|
||||||
|
if (issuer == null || publisher == null || emailSender == null)
|
||||||
|
throw new IllegalStateException("Free registration is disabled");
|
||||||
|
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
|
||||||
|
LoginCheck checked = checkLogin(login);
|
||||||
|
if (checked.namespaceType()!=2 || !checked.loginAvailable())
|
||||||
|
throw new IllegalStateException("Login is unavailable");
|
||||||
|
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
|
||||||
|
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||||
|
String normalizedLogin=login.toLowerCase(java.util.Locale.ROOT);
|
||||||
|
byte[] id=new byte[32]; RANDOM.nextBytes(id);
|
||||||
|
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
|
||||||
|
String code=RegistrationEmailCode.generate();
|
||||||
|
long now=System.currentTimeMillis();
|
||||||
|
long expires=now+TTL_MS;
|
||||||
|
Draft draft=new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,
|
||||||
|
expires,RegistrationEmailCode.hash(challenge,code),0,false,false,null);
|
||||||
|
synchronized (this) {
|
||||||
|
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < now);
|
||||||
|
recentEmails.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||||
|
recentLogins.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||||
|
while(!globalSendTimes.isEmpty() && globalSendTimes.peekFirst() < now-GLOBAL_WINDOW_MS)
|
||||||
|
globalSendTimes.removeFirst();
|
||||||
|
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||||
|
if (now-recentEmails.getOrDefault(cleanEmail,0L) < EMAIL_COOLDOWN_MS ||
|
||||||
|
now-recentLogins.getOrDefault(normalizedLogin,0L) < EMAIL_COOLDOWN_MS)
|
||||||
|
throw new IllegalStateException("Please wait before requesting another code");
|
||||||
|
if (globalSendTimes.size() >= MAX_EMAILS_PER_HOUR)
|
||||||
|
throw new IllegalStateException("Email verification temporarily limited");
|
||||||
|
recentEmails.put(cleanEmail,now);
|
||||||
|
recentLogins.put(normalizedLogin,now);
|
||||||
|
globalSendTimes.addLast(now);
|
||||||
|
pending.put(challenge,draft);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
// Не блокируем monitor workflow на время HTTP-запроса к Resend.
|
||||||
|
emailSender.sendVerificationCode(cleanEmail,code);
|
||||||
|
} catch (Exception e) {
|
||||||
|
synchronized (this) {
|
||||||
|
pending.remove(challenge);
|
||||||
|
recentEmails.remove(cleanEmail,now);
|
||||||
|
recentLogins.remove(normalizedLogin,now);
|
||||||
|
globalSendTimes.removeFirstOccurrence(now);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
synchronized (this) {
|
||||||
|
// Новый успешно отправленный код заменяет старые заявки на тот же login/email.
|
||||||
|
pending.entrySet().removeIf(e -> !e.getKey().equals(challenge) &&
|
||||||
|
(e.getValue().email.equals(cleanEmail) ||
|
||||||
|
e.getValue().login.equalsIgnoreCase(login)));
|
||||||
|
pending.computeIfPresent(challenge,(key,d)->d.update(d.attempts,true,d.verified,d.signedBytes));
|
||||||
|
}
|
||||||
|
return new Started(challenge,expires);
|
||||||
|
}
|
||||||
|
boolean isValidVerificationCode(byte[] expectedHash, String challenge, String code) {
|
||||||
|
return (allowTestCode && "777777".equals(code))
|
||||||
|
|| RegistrationEmailCode.matches(expectedHash, challenge, code);
|
||||||
|
}
|
||||||
|
|
||||||
|
public synchronized Completed confirm(String challenge, String code) throws Exception {
|
||||||
|
if (publisher == null) throw new IllegalStateException("Free registration disabled");
|
||||||
|
if (challenge == null || challenge.isBlank())
|
||||||
|
throw new IllegalArgumentException("Registration challenge missing");
|
||||||
|
Draft d=pending.get(challenge);
|
||||||
|
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
|
||||||
|
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
|
||||||
|
}
|
||||||
|
if (!d.delivered) throw new IllegalStateException("Verification email is not delivered yet");
|
||||||
|
if (!d.verified) {
|
||||||
|
if (!isValidVerificationCode(d.codeHash, challenge, code)) {
|
||||||
|
if (d.attempts+1 >= MAX_ATTEMPTS) pending.remove(challenge);
|
||||||
|
else pending.put(challenge,d.update(d.attempts+1,true,false,d.signedBytes));
|
||||||
|
throw new IllegalArgumentException("Invalid email code");
|
||||||
|
}
|
||||||
|
// Если Turbo не ответит, подтверждённая заявка может быть повторена до TTL.
|
||||||
|
d=d.update(d.attempts,true,true,d.signedBytes);
|
||||||
|
pending.put(challenge,d);
|
||||||
|
}
|
||||||
|
byte[] signed=d.signedBytes;
|
||||||
|
if(signed==null) {
|
||||||
|
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email);
|
||||||
|
d=d.update(d.attempts,true,true,signed);
|
||||||
|
pending.put(challenge,d);
|
||||||
|
}
|
||||||
|
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
|
||||||
|
// Повтор использует тот же подписанный DataItem, без смены ключей и адреса email.
|
||||||
|
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
|
||||||
|
}
|
||||||
|
public State getStatus(String login) throws Exception {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(login);
|
||||||
|
try (Connection c=DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement p=c.prepareStatement("""
|
||||||
|
SELECT i.registration_status,i.free_data_item_id,f.publication_status,f.inner_signature,
|
||||||
|
i.root_key,i.blockchain_key,i.client_key,n.default_server_login
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN free_registration_certificate f ON f.data_item_id=i.free_data_item_id
|
||||||
|
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||||
|
WHERE i.normalized_login=?
|
||||||
|
""")) {
|
||||||
|
p.setString(1,login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet r=p.executeQuery()) {
|
||||||
|
return r.next()?new State(r.getString(1),r.getString(2),r.getString(3),
|
||||||
|
r.getBytes(4)==null?null:Base64.getEncoder().encodeToString(r.getBytes(4)),
|
||||||
|
r.getString(5),r.getString(6),r.getString(7),r.getString(8))
|
||||||
|
:new State("NOT_FOUND",null,null,null,null,null,null,null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/** Временный signer. Файл вне Git: одно значение Base64 от 32-байтного Ed25519 seed. */
|
||||||
|
public final class LocalRegistrarSigner implements RegistrarSigner {
|
||||||
|
private final byte[] seed32;
|
||||||
|
private final byte[] publicKey32;
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
public LocalRegistrarSigner(byte[] seed) {
|
||||||
|
if (seed == null || seed.length != 32) throw new IllegalArgumentException("Registrar seed must be 32 bytes");
|
||||||
|
this.seed32 = seed.clone();
|
||||||
|
this.publicKey32 = Ed25519Util.derivePublicKey(seed32);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalRegistrarSigner fromConfig(AppConfig config) throws Exception {
|
||||||
|
if (!config.getBoolean("freeRegistration.enabled", false))
|
||||||
|
throw new IllegalStateException("Free registration is disabled");
|
||||||
|
String path = config.getStringOrEmpty("freeRegistration.registrarSeedFile");
|
||||||
|
if (path.isEmpty()) throw new IllegalStateException("Registrar key path is not configured");
|
||||||
|
byte[] seed = Base64.getDecoder().decode(Files.readString(Path.of(path), StandardCharsets.UTF_8).trim());
|
||||||
|
try { return new LocalRegistrarSigner(seed); }
|
||||||
|
finally { Arrays.fill(seed, (byte) 0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public synchronized byte[] publicKey32() { return publicKey32.clone(); }
|
||||||
|
@Override public synchronized byte[] sign(byte[] message) {
|
||||||
|
if (closed) throw new IllegalStateException("Signer closed");
|
||||||
|
return Ed25519Util.sign(message, seed32);
|
||||||
|
}
|
||||||
|
@Override public synchronized void close() {
|
||||||
|
Arrays.fill(seed32, (byte) 0);
|
||||||
|
closed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
/** Интерфейс приватного регистратора: private key не передаётся в бизнес-логику. */
|
||||||
|
public interface RegistrarSigner extends AutoCloseable {
|
||||||
|
byte[] publicKey32();
|
||||||
|
byte[] sign(byte[] message);
|
||||||
|
@Override default void close() {}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
/** Одноразовый код не сохраняется в открытом виде и не попадает в журнал. */
|
||||||
|
final class RegistrationEmailCode {
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
private RegistrationEmailCode() {}
|
||||||
|
|
||||||
|
static String generate() {
|
||||||
|
return String.format(java.util.Locale.ROOT, "%06d", RANDOM.nextInt(1_000_000));
|
||||||
|
}
|
||||||
|
|
||||||
|
static byte[] hash(String challengeId, String code) {
|
||||||
|
try {
|
||||||
|
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||||
|
return md.digest((challengeId + ":" + code).getBytes(StandardCharsets.UTF_8));
|
||||||
|
} catch (NoSuchAlgorithmException e) {
|
||||||
|
throw new IllegalStateException("SHA-256 unavailable", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static boolean matches(byte[] expectedHash, String challengeId, String submitted) {
|
||||||
|
return submitted != null && submitted.matches("[0-9]{6}") &&
|
||||||
|
MessageDigest.isEqual(expectedHash, hash(challengeId, submitted));
|
||||||
|
}
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
/** Отправка кода. Детали внешнего почтового провайдера не влияют на протокол регистрации. */
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface RegistrationEmailSender {
|
||||||
|
void sendVerificationCode(String recipient, String code) throws Exception;
|
||||||
|
}
|
||||||
+63
@@ -0,0 +1,63 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** Транзакционная отправка через Resend: HTTP API, без SMTP и внешней Java SDK. */
|
||||||
|
public final class ResendRegistrationEmailSender implements RegistrationEmailSender {
|
||||||
|
private static final URI ENDPOINT = URI.create("https://api.resend.com/emails");
|
||||||
|
private static final String SUBJECT = "SHiNE — код подтверждения email";
|
||||||
|
private final HttpClient client = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(5)).build();
|
||||||
|
private final ObjectMapper mapper = new ObjectMapper();
|
||||||
|
private final String apiKey;
|
||||||
|
private final String from;
|
||||||
|
|
||||||
|
public ResendRegistrationEmailSender(String apiKey, String from) {
|
||||||
|
if (apiKey == null || apiKey.isBlank())
|
||||||
|
throw new IllegalStateException("Resend API key is required for free registration");
|
||||||
|
if (from == null || from.isBlank())
|
||||||
|
throw new IllegalStateException("Sender email is missing");
|
||||||
|
this.apiKey = apiKey.trim();
|
||||||
|
this.from = from.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void sendVerificationCode(String recipient, String code) throws Exception {
|
||||||
|
if (recipient == null || recipient.isBlank() || !code.matches("[0-9]{6}"))
|
||||||
|
throw new IllegalArgumentException("Invalid email verification request");
|
||||||
|
String text = "Добро пожаловать в SHiNE!\n\n"
|
||||||
|
+ "Для завершения регистрации введите код подтверждения:\n\n"
|
||||||
|
+ code + "\n\n"
|
||||||
|
+ "Код действителен в течение 1 часа.\n\n"
|
||||||
|
+ "Если вы не регистрировались в SHiNE, просто проигнорируйте это письмо.\n\n"
|
||||||
|
+ "Команда SHiNE";
|
||||||
|
String html = "<div style=\"font-family:Arial,sans-serif;max-width:520px;margin:auto;"
|
||||||
|
+ "padding:24px;color:#1d2433;line-height:1.6\">"
|
||||||
|
+ "<h2 style=\"margin:0 0 20px\">Добро пожаловать в SHiNE!</h2>"
|
||||||
|
+ "<p>Для завершения регистрации введите код подтверждения:</p>"
|
||||||
|
+ "<p style=\"font-size:32px;font-weight:700;letter-spacing:6px\">" + code + "</p>"
|
||||||
|
+ "<p>Код действителен в течение 1 часа.</p>"
|
||||||
|
+ "<p style=\"color:#5d6470\">Если вы не регистрировались в SHiNE, "
|
||||||
|
+ "просто проигнорируйте это письмо.</p><p>Команда SHiNE</p></div>";
|
||||||
|
String json = mapper.writeValueAsString(Map.of(
|
||||||
|
"from", from, "to", new String[]{recipient}, "subject", SUBJECT,
|
||||||
|
"text", text, "html", html));
|
||||||
|
HttpRequest request = HttpRequest.newBuilder(ENDPOINT)
|
||||||
|
.header("Authorization", "Bearer " + apiKey)
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.timeout(Duration.ofSeconds(12))
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||||
|
.build();
|
||||||
|
// Тело ошибки не выводим: нельзя логировать email или токен провайдера.
|
||||||
|
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
|
||||||
|
if (response.statusCode() < 200 || response.statusCode() >= 300)
|
||||||
|
throw new IllegalStateException("Resend delivery rejected (HTTP " + response.statusCode() + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
+187
@@ -0,0 +1,187 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import sync.util.Base58Util;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/** Только верифицированный сертификат. Локальная БД — проекция Arweave/Solana. */
|
||||||
|
public final class VerifiedFreeRegistrationImporter {
|
||||||
|
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
|
||||||
|
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
|
||||||
|
private final boolean allowEmailReuse;
|
||||||
|
|
||||||
|
public VerifiedFreeRegistrationImporter() {
|
||||||
|
this(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
public VerifiedFreeRegistrationImporter(boolean allowEmailReuse) {
|
||||||
|
this.allowEmailReuse = allowEmailReuse;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
|
||||||
|
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
|
||||||
|
if (raw == null || raw.length < 200 || raw.length > 16_384)
|
||||||
|
throw new IllegalArgumentException("Invalid registration size");
|
||||||
|
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||||
|
String login = extractCanonicalLogin(item);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
String namespace = login.substring(login.indexOf('@') + 1);
|
||||||
|
var cert = FreeRegistrationCertificateV1.verify(raw, readRegistrar(c, namespace, login));
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT free_data_item_id FROM user_identity_current WHERE normalized_login=?")) {
|
||||||
|
ps.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||||
|
throw new IllegalArgumentException("Login is already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!allowEmailReuse) {
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||||
|
ps.setBytes(1, cert.emailSha256());
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||||
|
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cert;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Единая точка импорта: один и тот же raw ANS-104 из Turbo и Arweave. */
|
||||||
|
public ImportResult importSigned(byte[] raw, Provenance provenance) throws Exception {
|
||||||
|
if (raw == null || raw.length > 16_384 || raw.length < 200)
|
||||||
|
throw new IllegalArgumentException("Invalid registration data item size");
|
||||||
|
// Сначала разбираем/проверяем структурный контейнер, затем сверяем owner с on-chain namespace.
|
||||||
|
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||||
|
String login = extractCanonicalLogin(item);
|
||||||
|
String namespace = login.substring(login.indexOf('@') + 1);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
boolean oldAutoCommit = c.getAutoCommit();
|
||||||
|
c.setAutoCommit(false);
|
||||||
|
try {
|
||||||
|
byte[] registrar = readRegistrar(c, namespace, login);
|
||||||
|
FreeRegistrationCertificateV1.Verified cert = FreeRegistrationCertificateV1.verify(raw, registrar);
|
||||||
|
String id = cert.idBase64Url();
|
||||||
|
String publication = provenance == Provenance.ARWEAVE_CONFIRMED ? "ARWEAVE_CONFIRMED" : "TURBO_ACCEPTED";
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
// Защита от коллизий и двойного импорта: имя и email захвачены индексами UNIQUE.
|
||||||
|
try (PreparedStatement check = c.prepareStatement("""
|
||||||
|
SELECT f.raw_signed_data_item, f.publication_status, u.root_key, u.client_key,
|
||||||
|
u.blockchain_key FROM free_registration_certificate f
|
||||||
|
JOIN user_identity_current u ON u.login=f.login
|
||||||
|
WHERE f.data_item_id=? FOR UPDATE OF f
|
||||||
|
""")) {
|
||||||
|
check.setString(1, id);
|
||||||
|
try (ResultSet r = check.executeQuery()) {
|
||||||
|
if (r.next()) {
|
||||||
|
if (!Arrays.equals(raw, r.getBytes(1)))
|
||||||
|
throw new SQLException("DataItem id collision with different raw bytes");
|
||||||
|
if (!r.getString(3).equals(Base58Util.encode(cert.rootKey())) ||
|
||||||
|
!r.getString(4).equals(Base58Util.encode(cert.clientKey())) ||
|
||||||
|
!r.getString(5).equals(Base58Util.encode(cert.blockchainKey())))
|
||||||
|
throw new SQLException("Accepted identity keys conflict with certificate");
|
||||||
|
if (provenance == Provenance.ARWEAVE_CONFIRMED) {
|
||||||
|
try (PreparedStatement up = c.prepareStatement("""
|
||||||
|
UPDATE free_registration_certificate SET publication_status='ARWEAVE_CONFIRMED',last_seen_at_ms=?
|
||||||
|
WHERE data_item_id=?
|
||||||
|
""")) {
|
||||||
|
up.setLong(1, now); up.setString(2, id); up.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
return new ImportResult(login, id, true, provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (?, ?, ?, 'ARWEAVE', 'FREE_CERT', NULL, ?, ?, ?, ?, ?, false, ?, ?)
|
||||||
|
""")) {
|
||||||
|
insert.setString(1, login); insert.setString(2, login.toLowerCase(java.util.Locale.ROOT)); insert.setString(3, namespace);
|
||||||
|
insert.setString(4, id); insert.setString(5, Base58Util.encode(cert.rootKey()));
|
||||||
|
insert.setString(6, Base58Util.encode(cert.clientKey()));
|
||||||
|
insert.setString(7, Base58Util.encode(cert.blockchainKey()));
|
||||||
|
insert.setString(8, login.toLowerCase(java.util.Locale.ROOT) + "-001"); insert.setLong(9, now); insert.setLong(10, now);
|
||||||
|
insert.executeUpdate();
|
||||||
|
}
|
||||||
|
// blockchain_state — обязательная runtime-проекция новой цепочки.
|
||||||
|
// Без неё первый пользовательский AddBlock (например, «О себе») будет
|
||||||
|
// отклонён ещё до проверки подписи.
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
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, ?, 0, 0, -1, ?, ?)
|
||||||
|
""")) {
|
||||||
|
// 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()));
|
||||||
|
insert.setBytes(3, new byte[32]);
|
||||||
|
insert.setLong(4, now);
|
||||||
|
insert.executeUpdate();
|
||||||
|
}
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
INSERT INTO free_registration_certificate (
|
||||||
|
data_item_id, login, namespace, email_sha256, inner_signature,
|
||||||
|
raw_signed_data_item, publication_status, registered_at_ms, last_seen_at_ms)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?)
|
||||||
|
""")) {
|
||||||
|
insert.setString(1, id); insert.setString(2, login); insert.setString(3, namespace);
|
||||||
|
insert.setBytes(4, cert.emailSha256()); insert.setBytes(5, cert.innerSignature());
|
||||||
|
insert.setBytes(6, raw); insert.setString(7, publication);
|
||||||
|
insert.setLong(8, now); insert.setLong(9, now); insert.executeUpdate();
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
return new ImportResult(login, id, false, provenance);
|
||||||
|
} catch (Exception e) {
|
||||||
|
c.rollback(); throw e;
|
||||||
|
} finally { c.setAutoCommit(oldAutoCommit); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String extractCanonicalLogin(blockchain.Ans104DataItem item) {
|
||||||
|
boolean marker = item.tags().contains(new blockchain.Ans104DataItem.Tag("t", "reg"));
|
||||||
|
if (!marker) throw new IllegalArgumentException("Not a registration DataItem");
|
||||||
|
byte[] bytes = item.data();
|
||||||
|
if (bytes.length < 3 || bytes[0] != 1 || bytes[1] != 0) throw new IllegalArgumentException("Bad certificate header");
|
||||||
|
int len = bytes[2] & 0xff;
|
||||||
|
if (len < 3 || len > 30 || bytes.length < 3 + len + 96 + 64 + 32)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate login length");
|
||||||
|
return FreeRegistrationCertificateV1.validateLogin(
|
||||||
|
new String(bytes, 3, len, java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readRegistrar(Connection c, String namespace, String login) throws Exception {
|
||||||
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT registrar_pubkey, min_localpart_len, default_server_login
|
||||||
|
FROM shine_namespace_current WHERE namespace=? AND namespace_type=2
|
||||||
|
""")) {
|
||||||
|
ps.setString(1, namespace);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (!rs.next()) throw new IllegalStateException("Unknown/free namespace not yet synchronized");
|
||||||
|
if (login.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||||
|
throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||||
|
if (rs.getString("default_server_login") == null || rs.getString("default_server_login").isBlank())
|
||||||
|
throw new IllegalArgumentException("Namespace has no access server");
|
||||||
|
byte[] key = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||||
|
if (key.length != 32) throw new IllegalArgumentException("Invalid registrar pubkey");
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import server.archive.registration.*;
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
import blockchain.ShineProtocolTags;
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
/** Standalone test (no legacy signed fixture): certificate issue/verify for CURRENT App tag. */
|
||||||
|
public final class FreeRegistrationCertificateV1Check {
|
||||||
|
static final HexFormat HEX = HexFormat.of();
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
byte[] seed = Ed25519Util.generatePrivateKeyFromString("TEST-only-reg-v1-check");
|
||||||
|
byte[] root = HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8");
|
||||||
|
byte[] chain = HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7");
|
||||||
|
byte[] client = HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d");
|
||||||
|
try (var signer = new LocalRegistrarSigner(seed)) {
|
||||||
|
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.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)
|
||||||
|
|| !Arrays.equals(result.blockchainKey(), chain) || !Arrays.equals(result.clientKey(), client))
|
||||||
|
throw new AssertionError("Certificate identity corrupted");
|
||||||
|
if (!Arrays.equals(result.emailSha256(), HEX.parseHex(
|
||||||
|
"cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
|
||||||
|
throw new AssertionError("Email normalization differs");
|
||||||
|
byte[] bad = cert.clone(); bad[bad.length - 1] ^= 1;
|
||||||
|
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||||
|
throw new AssertionError("Email bit flip accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) {}
|
||||||
|
bad = cert.clone(); bad[bad.length - 40] ^= 1;
|
||||||
|
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||||
|
throw new AssertionError("Inner signature tampering accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) {}
|
||||||
|
}
|
||||||
|
System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
|
||||||
|
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import server.archive.registration.*;
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
/** Только проверки без БД/сети; полное E2E требует PostgreSQL и Turbo. */
|
||||||
|
public final class FreeRegistrationWorkflowLocalCheck {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
var signer = new RegistrarSigner() {
|
||||||
|
public byte[] publicKey32() { return new byte[32]; }
|
||||||
|
public byte[] sign(byte[] message) { return new byte[64]; }
|
||||||
|
};
|
||||||
|
DataSource noDb = new DataSource() {
|
||||||
|
public java.sql.Connection getConnection() throws java.sql.SQLException { throw new java.sql.SQLException("No database in local test"); }
|
||||||
|
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException { return getConnection(); }
|
||||||
|
public java.io.PrintWriter getLogWriter() {return null;}
|
||||||
|
public void setLogWriter(java.io.PrintWriter x) {}
|
||||||
|
public void setLoginTimeout(int x) {}
|
||||||
|
public int getLoginTimeout() {return 0;}
|
||||||
|
public java.util.logging.Logger getParentLogger() {return java.util.logging.Logger.getAnonymousLogger();}
|
||||||
|
public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {throw new java.sql.SQLException("unsupported");}
|
||||||
|
public boolean isWrapperFor(Class<?> iface) {return false;}
|
||||||
|
};
|
||||||
|
var issuer = new FreeRegistrationIssuer(noDb, signer);
|
||||||
|
var importer = new VerifiedFreeRegistrationImporter();
|
||||||
|
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||||
|
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
|
||||||
|
(email, code) -> { throw new AssertionError("No real email in an offline check"); },
|
||||||
|
false, false, AllowedEmailDomains.load(Files.isRegularFile(Path.of("allowed-email-domains.txt"))
|
||||||
|
? Path.of("allowed-email-domains.txt") : Path.of("../allowed-email-domains.txt")));
|
||||||
|
try { workflow.confirm("unknown", "123456"); throw new AssertionError("Missing challenge accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||||
|
throw new AssertionError("Invalid bytes accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
System.out.println("PASS: workflow missing challenge + reject invalid signed bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import blockchain.*;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Offline tests with real signed fixtures and fake upload/download callbacks (no network). */
|
||||||
|
public final class M4ArchiveBlockPairCheck {
|
||||||
|
private static int checks;
|
||||||
|
private static final HexFormat HEX = HexFormat.of();
|
||||||
|
@FunctionalInterface interface Action { void run() throws Exception; }
|
||||||
|
private static void ok(boolean value) { checks++; if (!value) throw new AssertionError("check " + checks); }
|
||||||
|
private static void reject(Class<? extends Exception> type, Action action) throws Exception {
|
||||||
|
try { action.run(); } catch (Exception e) { ok(type.isInstance(e)); return; }
|
||||||
|
throw new AssertionError("Expected " + type);
|
||||||
|
}
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
var lines = Files.readAllLines(Path.of(args[0]));
|
||||||
|
for (String line : lines.subList(1, lines.size())) {
|
||||||
|
String[] v = line.split("\t");
|
||||||
|
byte[] core = HEX.parseHex(v[6]), content = HEX.parseHex(v[8]);
|
||||||
|
byte[] coreId = new Ans104DataItem(core).id32(), contentId = new Ans104DataItem(content).id32();
|
||||||
|
byte[] pair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(content));
|
||||||
|
List<byte[]> sent = new ArrayList<>();
|
||||||
|
var ack = ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||||
|
ok(Arrays.equals(new Ans104DataItem(raw).id32(), id)); sent.add(raw); return HEX.formatHex(id);
|
||||||
|
});
|
||||||
|
ok(sent.size() == 2); ok(Arrays.equals(sent.get(0), content)); ok(Arrays.equals(sent.get(1), core));
|
||||||
|
ok(ack.equals(HEX.formatHex(coreId)));
|
||||||
|
sent.clear();
|
||||||
|
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||||
|
sent.add(raw); throw new IOException("CONTENT not accepted");
|
||||||
|
}));
|
||||||
|
ok(sent.size() == 1); ok(Arrays.equals(sent.get(0), content));
|
||||||
|
sent.clear();
|
||||||
|
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||||
|
sent.add(raw); if (Arrays.equals(id, coreId)) throw new IOException("CORE not accepted"); return null;
|
||||||
|
}));
|
||||||
|
ok(sent.size() == 2);
|
||||||
|
ArchiveBlockPair.publish(pair, coreId, (raw, id) -> { sent.add(raw); return null; });
|
||||||
|
ok(sent.size() == 4); ok(Arrays.equals(sent.get(0), sent.get(2))); ok(Arrays.equals(sent.get(1), sent.get(3)));
|
||||||
|
byte[] restored = ArchiveBlockPair.download(core, coreId, id -> { ok(Arrays.equals(id, contentId)); return content; });
|
||||||
|
ok(Arrays.equals(restored, pair));
|
||||||
|
reject(IOException.class, () -> ArchiveBlockPair.download(core, coreId, id -> { throw new IOException("CONTENT not visible yet"); }));
|
||||||
|
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> core));
|
||||||
|
byte[] damaged = content.clone(); damaged[damaged.length - 1] ^= 1;
|
||||||
|
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> damaged));
|
||||||
|
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, contentId, id -> { throw new AssertionError("Unverified CORE requested CONTENT"); }));
|
||||||
|
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(pair, contentId, (raw,id) -> { throw new AssertionError("Wrong CORE published"); }));
|
||||||
|
byte[] badPair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(damaged));
|
||||||
|
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(badPair, coreId, (raw,id) -> { throw new AssertionError("Invalid CONTENT published"); }));
|
||||||
|
}
|
||||||
|
System.out.println("PASS: " + checks + " archive pair checks (order, exact retry, missing CONTENT, wrong ID, signature/hash)");
|
||||||
|
}
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
/** Самостоятельный офлайн-тест: javac AllowedEmailDomains.java AllowedEmailDomainsCheck.java + java. */
|
||||||
|
public final class AllowedEmailDomainsCheck {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Path dir = Files.createTempDirectory("shine-email-domains-test-");
|
||||||
|
try {
|
||||||
|
Path file = dir.resolve("allowed-email-domains.txt");
|
||||||
|
Files.writeString(file, "# Test\n Gmail.com \nproton.me\n\n", StandardCharsets.UTF_8);
|
||||||
|
AllowedEmailDomains allowed = AllowedEmailDomains.load(file);
|
||||||
|
expect(allowed.permits("User@GMAIL.COM"), "case insensitive match");
|
||||||
|
expect(allowed.permits(" user@proton.me "), "trimmed match");
|
||||||
|
expect(!allowed.permits("user@gmail.com.evil.org"), "suffix bypass");
|
||||||
|
expect(!allowed.permits("user@sub.gmail.com"), "subdomain bypass");
|
||||||
|
expect(!allowed.permits("user@other.com"), "unknown domain");
|
||||||
|
expect(!allowed.permits("user@@gmail.com"), "invalid multiple @");
|
||||||
|
expect(!allowed.permits("@gmail.com"), "missing local part");
|
||||||
|
expect(!allowed.permits(null), "null address");
|
||||||
|
Files.writeString(file, "# no domains\n \n", StandardCharsets.UTF_8);
|
||||||
|
expectLoadFailure(file, "empty file");
|
||||||
|
Files.writeString(file, "*.gmail.com\n", StandardCharsets.UTF_8);
|
||||||
|
expectLoadFailure(file, "wildcard not allowed");
|
||||||
|
Files.writeString(file, "gmail.com\ninvalid_domain\n", StandardCharsets.UTF_8);
|
||||||
|
expectLoadFailure(file, "invalid line not ignored");
|
||||||
|
Files.delete(file);
|
||||||
|
expectLoadFailure(file, "missing file");
|
||||||
|
System.out.println("PASS: allowed email domains, strict matching, fail-closed");
|
||||||
|
} finally {
|
||||||
|
try (var files = Files.list(dir)) { files.forEach(path -> {try {Files.deleteIfExists(path);}catch(Exception ex){throw new RuntimeException(ex);}}); }
|
||||||
|
Files.deleteIfExists(dir);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void expect(boolean condition, String scenario) {
|
||||||
|
if (!condition) throw new AssertionError(scenario);
|
||||||
|
}
|
||||||
|
private static void expectLoadFailure(Path file, String scenario) throws Exception {
|
||||||
|
try {
|
||||||
|
AllowedEmailDomains.load(file);
|
||||||
|
throw new AssertionError("Invalid allowlist accepted: " + scenario);
|
||||||
|
} catch (java.io.IOException expected) { }
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
/** Локальная проверка генератора и сверки кода без БД/HTTP. */
|
||||||
|
public final class RegistrationEmailCodeCheck {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
for (int i=0; i<1000; ++i) {
|
||||||
|
String code = RegistrationEmailCode.generate();
|
||||||
|
if (!code.matches("[0-9]{6}")) throw new AssertionError("Wrong length");
|
||||||
|
byte[] hash = RegistrationEmailCode.hash("challenge-id", code);
|
||||||
|
if (!RegistrationEmailCode.matches(hash, "challenge-id", code)) throw new AssertionError("Cannot verify");
|
||||||
|
if (RegistrationEmailCode.matches(hash, "another-challenge", code)) throw new AssertionError("Challenge replay");
|
||||||
|
if (RegistrationEmailCode.matches(hash, "challenge-id", "1111")) throw new AssertionError("Old demo code accepted");
|
||||||
|
if (RegistrationEmailCode.matches(hash, "challenge-id", "bad")) throw new AssertionError("Bad code accepted");
|
||||||
|
}
|
||||||
|
System.out.println("PASS: email code generation and challenge binding");
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
/** Offline проверка часового TTL на уровне UX отдельно; bypass должен быть строго opt-in. */
|
||||||
|
public final class RegistrationEmailSettingsCheck {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
byte[] digest = RegistrationEmailCode.hash("challenge", "123456");
|
||||||
|
var safe = new FreeRegistrationWorkflow(null, null, null, false);
|
||||||
|
var test = new FreeRegistrationWorkflow(null, null, null, true);
|
||||||
|
if (safe.isValidVerificationCode(digest, "challenge", "777777"))
|
||||||
|
throw new AssertionError("Cheat unexpectedly enabled by default");
|
||||||
|
if (!test.isValidVerificationCode(digest, "challenge", "777777"))
|
||||||
|
throw new AssertionError("Explicit test code not accepted");
|
||||||
|
if (!safe.isValidVerificationCode(digest, "challenge", "123456"))
|
||||||
|
throw new AssertionError("Real code rejected");
|
||||||
|
if (test.isValidVerificationCode(digest, "challenge", "1111"))
|
||||||
|
throw new AssertionError("Old demo code unexpectedly accepted");
|
||||||
|
if (test.isValidVerificationCode(digest, "challenge", "777778"))
|
||||||
|
throw new AssertionError("Invalid code unexpectedly accepted");
|
||||||
|
System.out.println("PASS: real code and opt-in test code");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -56,7 +56,7 @@ public final class Ans104DataItem {
|
|||||||
|
|
||||||
public Ans104DataItem(byte[] bytes) {
|
public Ans104DataItem(byte[] bytes) {
|
||||||
Objects.requireNonNull(bytes, "bytes == null");
|
Objects.requireNonNull(bytes, "bytes == null");
|
||||||
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + 1) {
|
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8) {
|
||||||
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
|
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
|
||||||
}
|
}
|
||||||
if (bytes.length > MAX_DATA_ITEM_BYTES) {
|
if (bytes.length > MAX_DATA_ITEM_BYTES) {
|
||||||
@@ -126,7 +126,8 @@ public final class Ans104DataItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public byte[] signingMessage() {
|
public byte[] signingMessage() {
|
||||||
return buildSigningMessage(owner, target, anchor, tags, data);
|
// Проверяем именно подписанные исходные байты, не повторную Avro-сериализацию.
|
||||||
|
return signingMessageRaw(owner, target, anchor, rawTags, data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -151,6 +152,10 @@ public final class Ans104DataItem {
|
|||||||
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
|
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
|
||||||
|
|
||||||
byte[] rawTags = serializeAvroTags(safeTags);
|
byte[] rawTags = serializeAvroTags(safeTags);
|
||||||
|
return signingMessageRaw(owner32, safeTarget, safeAnchor, rawTags, safeData);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] signingMessageRaw(byte[] owner32, byte[] safeTarget, byte[] safeAnchor, byte[] rawTags, byte[] safeData) {
|
||||||
return deepHash(List.of(
|
return deepHash(List.of(
|
||||||
utf8("dataitem"),
|
utf8("dataitem"),
|
||||||
utf8("1"),
|
utf8("1"),
|
||||||
@@ -270,15 +275,20 @@ public final class Ans104DataItem {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
|
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
|
||||||
|
if (raw.length == 0 && declaredCount == 0) return List.of();
|
||||||
AvroCursor c = new AvroCursor(raw);
|
AvroCursor c = new AvroCursor(raw);
|
||||||
List<Tag> out = new ArrayList<>();
|
List<Tag> out = new ArrayList<>();
|
||||||
|
boolean terminated = false;
|
||||||
while (!c.eof()) {
|
while (!c.eof()) {
|
||||||
long count = c.readLong();
|
long count = c.readLong();
|
||||||
if (count == 0) break;
|
if (count == 0) { terminated = true; break; }
|
||||||
|
int blockEnd = -1;
|
||||||
if (count < 0) {
|
if (count < 0) {
|
||||||
|
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
|
||||||
count = -count;
|
count = -count;
|
||||||
long blockBytes = c.readLong();
|
long blockBytes = c.readLong();
|
||||||
if (blockBytes < 0) throw new IllegalArgumentException("Negative Avro tag block size");
|
if (blockBytes < 0 || blockBytes > raw.length - c.p) throw new IllegalArgumentException("Invalid Avro tag block size");
|
||||||
|
blockEnd = c.p + (int) blockBytes;
|
||||||
}
|
}
|
||||||
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
|
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
|
||||||
throw new IllegalArgumentException("Too many Avro tags");
|
throw new IllegalArgumentException("Too many Avro tags");
|
||||||
@@ -291,7 +301,9 @@ public final class Ans104DataItem {
|
|||||||
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
||||||
out.add(new Tag(name, value));
|
out.add(new Tag(name, value));
|
||||||
}
|
}
|
||||||
|
if (blockEnd != -1 && c.p != blockEnd) throw new IllegalArgumentException("Avro tag block size mismatch");
|
||||||
}
|
}
|
||||||
|
if (!terminated) throw new IllegalArgumentException("Missing Avro array terminator");
|
||||||
if (!c.eof()) {
|
if (!c.eof()) {
|
||||||
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
|
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
|
||||||
}
|
}
|
||||||
@@ -312,6 +324,7 @@ public final class Ans104DataItem {
|
|||||||
while (true) {
|
while (true) {
|
||||||
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
|
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
|
||||||
int b = data[p++] & 0xff;
|
int b = data[p++] & 0xff;
|
||||||
|
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
|
||||||
raw |= (long) (b & 0x7f) << shift;
|
raw |= (long) (b & 0x7f) << shift;
|
||||||
if ((b & 0x80) == 0) break;
|
if ((b & 0x80) == 0) break;
|
||||||
shift += 7;
|
shift += 7;
|
||||||
@@ -324,7 +337,9 @@ public final class Ans104DataItem {
|
|||||||
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
|
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
|
||||||
throw new IllegalArgumentException("Bad Avro string length: " + len);
|
throw new IllegalArgumentException("Bad Avro string length: " + len);
|
||||||
}
|
}
|
||||||
String s = new String(data, p, (int) len, StandardCharsets.UTF_8);
|
String s;
|
||||||
|
try { s = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data, p, (int) len)).toString(); }
|
||||||
|
catch (java.nio.charset.CharacterCodingException e) { throw new IllegalArgumentException("Invalid UTF-8 Avro tag", e); }
|
||||||
p += (int) len;
|
p += (int) len;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -49,6 +49,9 @@ public final class BchBlockEntry {
|
|||||||
public final BodyRecord body;
|
public final BodyRecord body;
|
||||||
|
|
||||||
private final Ans104DataItem dataItem;
|
private final Ans104DataItem dataItem;
|
||||||
|
private final Ans104DataItem contentItem;
|
||||||
|
private final CoreRecord coreRecord;
|
||||||
|
private final ContentRecord contentRecord;
|
||||||
private final byte[] frameBytes;
|
private final byte[] frameBytes;
|
||||||
private final byte[] hash32;
|
private final byte[] hash32;
|
||||||
|
|
||||||
@@ -56,6 +59,9 @@ public final class BchBlockEntry {
|
|||||||
public BchBlockEntry(byte[] fullDataItemBytes) {
|
public BchBlockEntry(byte[] fullDataItemBytes) {
|
||||||
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
|
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
|
||||||
this.dataItem = new Ans104DataItem(fullDataItemBytes);
|
this.dataItem = new Ans104DataItem(fullDataItemBytes);
|
||||||
|
this.contentItem = null;
|
||||||
|
this.coreRecord = null;
|
||||||
|
this.contentRecord = null;
|
||||||
this.frameBytes = dataItem.data();
|
this.frameBytes = dataItem.data();
|
||||||
if (frameBytes.length < FRAME_HEADER_SIZE) {
|
if (frameBytes.length < FRAME_HEADER_SIZE) {
|
||||||
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
|
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
|
||||||
@@ -90,7 +96,57 @@ public final class BchBlockEntry {
|
|||||||
this.hash32 = BchCryptoVerifier.sha256(frameBytes);
|
this.hash32 = BchCryptoVerifier.sha256(frameBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
public Ans104DataItem getDataItem() { return dataItem; }
|
/** M1: явная точка входа для пары. Runtime переключается на неё в M2–M5. */
|
||||||
|
public static BchBlockEntry fromCoreContent(byte[] container) {
|
||||||
|
return new BchBlockEntry(CoreContentContainer.unpack(container));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BchBlockEntry(CoreContentContainer.Parts pair) {
|
||||||
|
this.dataItem = pair.core();
|
||||||
|
this.contentItem = pair.content();
|
||||||
|
// Подписи и связь пары проверяются до предоставления смыслового тела.
|
||||||
|
// Owner здесь self-claimed; вызывающий код обязан проверить авторизованный ключ.
|
||||||
|
var verified = CoreContentTransport.verifyPair(dataItem, dataItem.id32(), contentItem,
|
||||||
|
dataItem.owner32(), Instant.now().getEpochSecond());
|
||||||
|
this.coreRecord = verified.core();
|
||||||
|
this.contentRecord = verified.content();
|
||||||
|
this.frameBytes = coreRecord.toBytes();
|
||||||
|
this.frameCode = CoreRecord.FRAME_CODE;
|
||||||
|
this.prevHash32 = coreRecord.prevCoreHash32();
|
||||||
|
this.back32Hash32 = null; // Отсутствует в протоколе; не синтезируем.
|
||||||
|
this.blockSize = frameBytes.length;
|
||||||
|
this.blockNumber = coreRecord.blockNumber();
|
||||||
|
this.timestamp = coreRecord.timestamp();
|
||||||
|
this.type = (short) contentRecord.type();
|
||||||
|
this.subType = (short) contentRecord.subType();
|
||||||
|
this.version = (short) contentRecord.version();
|
||||||
|
this.bodyBytes = contentRecord.bodyBytes();
|
||||||
|
this.body = ContentBodyParser.parseForCore(coreRecord, contentRecord);
|
||||||
|
this.hash32 = coreRecord.coreHash32();
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isCoreContent() { return coreRecord != null; }
|
||||||
|
public CoreRecord getCoreRecord() {
|
||||||
|
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||||
|
return coreRecord;
|
||||||
|
}
|
||||||
|
public ContentRecord getContentRecord() {
|
||||||
|
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||||
|
return contentRecord;
|
||||||
|
}
|
||||||
|
public Ans104DataItem getCoreDataItem() {
|
||||||
|
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||||
|
return dataItem;
|
||||||
|
}
|
||||||
|
public Ans104DataItem getContentDataItem() {
|
||||||
|
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||||
|
return contentItem;
|
||||||
|
}
|
||||||
|
/** Legacy API: не позволяет принять одну подпись за проверку пары. */
|
||||||
|
public Ans104DataItem getDataItem() {
|
||||||
|
if (isCoreContent()) throw new IllegalStateException("Используйте явные CORE/CONTENT accessors");
|
||||||
|
return dataItem;
|
||||||
|
}
|
||||||
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
|
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
|
||||||
/** Kept as an alias for code/docs that called the old field preimage. */
|
/** Kept as an alias for code/docs that called the old field preimage. */
|
||||||
public byte[] getPreimageBytes() { return getFrameBytes(); }
|
public byte[] getPreimageBytes() { return getFrameBytes(); }
|
||||||
@@ -98,8 +154,8 @@ public final class BchBlockEntry {
|
|||||||
public byte[] getOwner32() { return dataItem.owner32(); }
|
public byte[] getOwner32() { return dataItem.owner32(); }
|
||||||
public byte[] getDataItemId32() { return dataItem.id32(); }
|
public byte[] getDataItemId32() { return dataItem.id32(); }
|
||||||
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
|
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
|
||||||
/** Full serialized ANS-104 DataItem. */
|
/** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
|
||||||
public byte[] toBytes() { return dataItem.rawBytes(); }
|
public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
|
|||||||
@@ -22,6 +22,13 @@ public final class BchCryptoVerifier {
|
|||||||
Objects.requireNonNull(block, "block == null");
|
Objects.requireNonNull(block, "block == null");
|
||||||
Objects.requireNonNull(publicKey32, "publicKey32 == null");
|
Objects.requireNonNull(publicKey32, "publicKey32 == null");
|
||||||
if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32");
|
if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32");
|
||||||
|
if (block.isCoreContent()) {
|
||||||
|
try {
|
||||||
|
CoreContentTransport.verifyPair(block.getCoreDataItem(), block.getDataItemId32(),
|
||||||
|
block.getContentDataItem(), publicKey32, java.time.Instant.now().getEpochSecond());
|
||||||
|
return true;
|
||||||
|
} catch (IllegalArgumentException e) { return false; }
|
||||||
|
}
|
||||||
return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature();
|
return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,8 @@ public final class BodyRecordParser {
|
|||||||
|
|
||||||
// TECH supports Header v1 and CreateChannel current format (ver=1).
|
// TECH supports Header v1 and CreateChannel current format (ver=1).
|
||||||
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
|
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
|
||||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) && 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();
|
return new HeaderBody(subType, version, bodyBytes).check();
|
||||||
}
|
}
|
||||||
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
|
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()); }
|
||||||
|
}
|
||||||
+36
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
+73
@@ -0,0 +1,73 @@
|
|||||||
|
package blockchain;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.List;
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
|
||||||
|
/** Новый транспорт; не переключает существующий runtime Frame v1. */
|
||||||
|
public final class CoreContentTransport {
|
||||||
|
private CoreContentTransport() {}
|
||||||
|
public static List<Ans104DataItem.Tag> coreTags(CoreRecord core) {
|
||||||
|
var tags = new ArrayList<Ans104DataItem.Tag>();
|
||||||
|
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE));
|
||||||
|
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_NUMBER_TAG_NAME, Integer.toString(core.blockNumber())));
|
||||||
|
if (core.line() != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_LINE_TAG_NAME, lineTag(core.line().lineCode())));
|
||||||
|
return List.copyOf(tags);
|
||||||
|
}
|
||||||
|
public static String lineTag(int code) {
|
||||||
|
return switch (code) {
|
||||||
|
case CoreRecord.PROFILE -> "P";
|
||||||
|
case CoreRecord.CONNECTION -> "C";
|
||||||
|
case CoreRecord.TECH -> "T";
|
||||||
|
default -> {
|
||||||
|
if (code < 0 || code > CoreRecord.MAX_BLOCK_NUMBER) throw new IllegalArgumentException("Неизвестный системный тег линии");
|
||||||
|
yield Integer.toString(code);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
private static void require(boolean ok, String message) { if (!ok) throw new IllegalArgumentException(message); }
|
||||||
|
private static void verify(Ans104DataItem item, byte[] expectedOwner, byte[] expectedId) {
|
||||||
|
require(item.ownerEquals(ProtocolHash.copy32(expectedOwner)), "Неавторизованный owner");
|
||||||
|
require(Arrays.equals(item.id32(), ProtocolHash.copy32(expectedId)), "DataItem ID не совпадает");
|
||||||
|
require(item.verifySignature(), "Неверная подпись ANS-104");
|
||||||
|
}
|
||||||
|
public static CoreRecord verifyCore(Ans104DataItem item, byte[] authorizedOwner, byte[] expectedId, long nowSeconds) {
|
||||||
|
verify(item, authorizedOwner, expectedId);
|
||||||
|
CoreRecord core = CoreRecord.parse(item.data()); core.checkTimestamp(nowSeconds);
|
||||||
|
List<Ans104DataItem.Tag> expected = coreTags(core);
|
||||||
|
for (String name : List.of("App", "n", "l")) {
|
||||||
|
var actual = item.tags().stream().filter(t -> t.name().equals(name)).toList();
|
||||||
|
var wanted = expected.stream().filter(t -> t.name().equals(name)).toList();
|
||||||
|
require(actual.equals(wanted), "Некорректный тег CORE: " + name);
|
||||||
|
}
|
||||||
|
require(item.tags().stream().noneMatch(t -> t.name().equals("t") || t.name().equals("c")), "Legacy теги CORE запрещены");
|
||||||
|
return core;
|
||||||
|
}
|
||||||
|
/** Только соответствие payload подписанному CORE; это не проверка собственной подписи CONTENT. */
|
||||||
|
public static ContentRecord verifyPayload(CoreRecord core, byte[] payload) {
|
||||||
|
require(payload != null && payload.length <= ContentRecord.MAX_PAYLOAD_SIZE, "Неверная длина CONTENT");
|
||||||
|
byte[] snapshot = payload.clone();
|
||||||
|
require(Arrays.equals(core.contentHash32(), ProtocolHash.sha256(snapshot)), "CONTENT hash не совпадает");
|
||||||
|
return ContentRecord.parse(snapshot);
|
||||||
|
}
|
||||||
|
/** authorizedOwner должен быть owner уже проверенного CORE, а не произвольный ключ CONTENT. */
|
||||||
|
public static ContentRecord verifyContent(CoreRecord core, Ans104DataItem item, byte[] authorizedOwner) {
|
||||||
|
verify(item, authorizedOwner, core.contentDataItemId32());
|
||||||
|
require(item.tags().stream().noneMatch(t -> List.of("App", "n", "l", "t", "c").contains(t.name())), "CONTENT не должен иметь поисковые теги SHiNE");
|
||||||
|
return verifyPayload(core, item.data());
|
||||||
|
}
|
||||||
|
public record VerifiedPair(CoreRecord core, ContentRecord content) {}
|
||||||
|
/** Криптографическая проверка пары; семантика проверяется ContentBodyParser отдельно. */
|
||||||
|
public static VerifiedPair verifyPair(Ans104DataItem coreItem, byte[] expectedCoreId, Ans104DataItem contentItem,
|
||||||
|
byte[] authorizedOwner, long nowSeconds) {
|
||||||
|
CoreRecord core = verifyCore(coreItem, authorizedOwner, expectedCoreId, nowSeconds);
|
||||||
|
return new VerifiedPair(core, verifyContent(core, contentItem, coreItem.owner32()));
|
||||||
|
}
|
||||||
|
/** Для локального тестового издателя; production сервер не получает приватный ключ пользователя. */
|
||||||
|
public static Ans104DataItem sign(byte[] payload, List<Ans104DataItem.Tag> tags, byte[] seed) {
|
||||||
|
byte[] owner = Ed25519Util.derivePublicKey(seed);
|
||||||
|
byte[] sig = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, payload), seed);
|
||||||
|
return new Ans104DataItem(Ans104DataItem.serializeEd25519(sig, owner, tags, payload));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
package blockchain;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/** Неизменяемый бинарный CORE v2; проверка ссылок на историю выполняется отдельно. */
|
||||||
|
public final class CoreRecord {
|
||||||
|
public static final int BASE_SIZE = 109, LINE_SIZE = 149, FRAME_CODE = 1;
|
||||||
|
public static final int MAX_BLOCK_NUMBER = Integer.MAX_VALUE - 1024;
|
||||||
|
public static final int PROFILE = Integer.MAX_VALUE - 2, CONNECTION = Integer.MAX_VALUE - 1, TECH = Integer.MAX_VALUE;
|
||||||
|
public static final long FUTURE_TOLERANCE_SECONDS = 60;
|
||||||
|
public record Line(int lineCode, int prevLineBlockNumber, byte[] prevLineCoreHash32) {
|
||||||
|
public Line {
|
||||||
|
if (lineCode < 0 || prevLineBlockNumber < 0 || prevLineBlockNumber > MAX_BLOCK_NUMBER)
|
||||||
|
throw new IllegalArgumentException("Неверный номер линии/предшественника");
|
||||||
|
prevLineCoreHash32 = ProtocolHash.copy32(prevLineCoreHash32);
|
||||||
|
}
|
||||||
|
@Override public byte[] prevLineCoreHash32() { return prevLineCoreHash32.clone(); }
|
||||||
|
@Override public boolean equals(Object other) {
|
||||||
|
return other instanceof Line l && lineCode == l.lineCode && prevLineBlockNumber == l.prevLineBlockNumber
|
||||||
|
&& Arrays.equals(prevLineCoreHash32, l.prevLineCoreHash32);
|
||||||
|
}
|
||||||
|
@Override public int hashCode() {
|
||||||
|
return 31 * (31 * lineCode + prevLineBlockNumber) + Arrays.hashCode(prevLineCoreHash32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private final byte[] prevCoreHash32, contentHash32, contentDataItemId32;
|
||||||
|
private final int blockNumber;
|
||||||
|
private final long timestamp;
|
||||||
|
private final Line line;
|
||||||
|
|
||||||
|
public CoreRecord(byte[] prevCoreHash32, int blockNumber, long timestamp, byte[] contentHash32,
|
||||||
|
byte[] contentDataItemId32, Line line) {
|
||||||
|
this.prevCoreHash32 = ProtocolHash.copy32(prevCoreHash32);
|
||||||
|
this.contentHash32 = ProtocolHash.copy32(contentHash32);
|
||||||
|
this.contentDataItemId32 = ProtocolHash.copy32(contentDataItemId32);
|
||||||
|
this.blockNumber = blockNumber; this.timestamp = timestamp; this.line = line;
|
||||||
|
if (blockNumber < 0 || blockNumber > MAX_BLOCK_NUMBER || timestamp < 0)
|
||||||
|
throw new IllegalArgumentException("Неверный номер CORE или timestamp");
|
||||||
|
if (blockNumber == 0 && (line != null || !Arrays.equals(this.prevCoreHash32, new byte[32])))
|
||||||
|
throw new IllegalArgumentException("Неверный genesis CORE");
|
||||||
|
if (line != null && (line.prevLineBlockNumber() >= blockNumber ||
|
||||||
|
(line.lineCode() > 0 && line.lineCode() <= MAX_BLOCK_NUMBER &&
|
||||||
|
(line.lineCode() >= blockNumber || line.prevLineBlockNumber() < line.lineCode()))))
|
||||||
|
throw new IllegalArgumentException("Неверная ссылка линии");
|
||||||
|
}
|
||||||
|
public static CoreRecord parse(byte[] bytes) {
|
||||||
|
if (bytes == null || (bytes.length != BASE_SIZE && bytes.length != LINE_SIZE))
|
||||||
|
throw new IllegalArgumentException("CORE должен иметь 109 или 149 байт");
|
||||||
|
ByteBuffer b = ByteBuffer.wrap(bytes);
|
||||||
|
if (Byte.toUnsignedInt(b.get()) != FRAME_CODE) throw new IllegalArgumentException("Неверный frameCode");
|
||||||
|
byte[] prev = read32(b); int n = b.getInt(); long t = b.getLong();
|
||||||
|
byte[] content = read32(b), id = read32(b);
|
||||||
|
Line line = b.hasRemaining() ? new Line(b.getInt(), b.getInt(), read32(b)) : null;
|
||||||
|
return new CoreRecord(prev, n, t, content, id, line);
|
||||||
|
}
|
||||||
|
private static byte[] read32(ByteBuffer b) { byte[] v = new byte[32]; b.get(v); return v; }
|
||||||
|
public byte[] toBytes() {
|
||||||
|
ByteBuffer b = ByteBuffer.allocate(line == null ? BASE_SIZE : LINE_SIZE);
|
||||||
|
b.put((byte) FRAME_CODE).put(prevCoreHash32).putInt(blockNumber).putLong(timestamp).put(contentHash32).put(contentDataItemId32);
|
||||||
|
if (line != null) b.putInt(line.lineCode()).putInt(line.prevLineBlockNumber()).put(line.prevLineCoreHash32());
|
||||||
|
return b.array();
|
||||||
|
}
|
||||||
|
public void checkTimestamp(long nowSeconds) {
|
||||||
|
if (nowSeconds < 0 || (timestamp > nowSeconds && timestamp - nowSeconds > FUTURE_TOLERANCE_SECONDS))
|
||||||
|
throw new IllegalArgumentException("CORE timestamp в будущем");
|
||||||
|
}
|
||||||
|
public int blockNumber() { return blockNumber; }
|
||||||
|
public long timestamp() { return timestamp; }
|
||||||
|
public Line line() { return line; }
|
||||||
|
public byte[] prevCoreHash32() { return prevCoreHash32.clone(); }
|
||||||
|
public byte[] contentHash32() { return contentHash32.clone(); }
|
||||||
|
public byte[] contentDataItemId32() { return contentDataItemId32.clone(); }
|
||||||
|
public byte[] coreHash32() { return ProtocolHash.sha256(toBytes()); }
|
||||||
|
}
|
||||||
@@ -1,17 +1,12 @@
|
|||||||
//package blockchain;
|
package blockchain;
|
||||||
//
|
|
||||||
///**
|
/** Канонические линии CORE v2; Frame v1 использует старую модель. */
|
||||||
// * LineIndex — канонические номера линий блокчейна.
|
public final class LineIndex {
|
||||||
// *
|
private LineIndex() {}
|
||||||
// * Линия = независимая последовательность блоков внутри одного блокчейна.
|
public static final int DEFAULT_CHANNEL = 0;
|
||||||
// */
|
public static final int USER_PROFILE = CoreRecord.PROFILE;
|
||||||
//public final class LineIndex {
|
public static final int CONNECTION = CoreRecord.CONNECTION;
|
||||||
//
|
public static final int TECH = CoreRecord.TECH;
|
||||||
// private LineIndex() {}
|
public static final int MAX_CHANNEL = CoreRecord.MAX_BLOCK_NUMBER;
|
||||||
//
|
public static boolean isChannel(int code) { return code >= 0 && code <= MAX_CHANNEL; }
|
||||||
// public static final short HEADER = 0; // genesis / идентификация
|
}
|
||||||
// public static final short TEXT = 1; // сообщения да надо
|
|
||||||
// public static final short REACTION = 2; // реакции не надо
|
|
||||||
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
|
|
||||||
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
|
|
||||||
//}
|
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
package blockchain;
|
||||||
|
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.security.NoSuchAlgorithmException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
public final class ProtocolHash {
|
||||||
|
private ProtocolHash() {}
|
||||||
|
public static byte[] copy32(byte[] bytes) {
|
||||||
|
if (bytes == null || bytes.length != 32) throw new IllegalArgumentException("Ожидается 32 байта");
|
||||||
|
return bytes.clone();
|
||||||
|
}
|
||||||
|
public static byte[] sha256(byte[] bytes) {
|
||||||
|
try { return MessageDigest.getInstance("SHA-256").digest(bytes); }
|
||||||
|
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||||
|
}
|
||||||
|
public static String hex32(byte[] bytes) { return HexFormat.of().formatHex(copy32(bytes)); }
|
||||||
|
public static byte[] fromHex32(String value) { return copy32(HexFormat.of().parseHex(value)); }
|
||||||
|
public static String base64url32(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(copy32(bytes)); }
|
||||||
|
public static byte[] fromBase64url32(String value) {
|
||||||
|
byte[] result = copy32(Base64.getUrlDecoder().decode(value));
|
||||||
|
if (!base64url32(result).equals(value)) throw new IllegalArgumentException("Неканонический base64url");
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
-1
@@ -9,7 +9,15 @@ package blockchain;
|
|||||||
public final class ShineProtocolTags {
|
public final class ShineProtocolTags {
|
||||||
private ShineProtocolTags() {}
|
private ShineProtocolTags() {}
|
||||||
|
|
||||||
public static final String NAMESPACE = "test5591";
|
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_NAME = "App";
|
||||||
public static final String APP_TAG_VALUE = NAMESPACE;
|
public static final String APP_TAG_VALUE = NAMESPACE;
|
||||||
public static final String CHANNEL_TAG_NAME = "c";
|
public static final String CHANNEL_TAG_NAME = "c";
|
||||||
|
|||||||
@@ -21,6 +21,9 @@ package blockchain.body;
|
|||||||
*/
|
*/
|
||||||
public interface BodyHasLine {
|
public interface BodyHasLine {
|
||||||
|
|
||||||
|
/** CORE не подписывает ordinal; до проверки канонического хвоста значение отсутствует. */
|
||||||
|
int UNRESOLVED_SEQUENCE = -1;
|
||||||
|
|
||||||
int lineCode();
|
int lineCode();
|
||||||
|
|
||||||
int prevLineBlockGlobalNumber();
|
int prevLineBlockGlobalNumber();
|
||||||
|
|||||||
+19
-4
@@ -1,6 +1,7 @@
|
|||||||
package blockchain.body;
|
package blockchain.body;
|
||||||
|
|
||||||
import blockchain.MsgSubType;
|
import blockchain.MsgSubType;
|
||||||
|
import blockchain.CoreRecord;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
@@ -16,6 +17,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
|||||||
public static final short VER = 1;
|
public static final short VER = 1;
|
||||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||||
|
|
||||||
|
private final boolean contentOnly;
|
||||||
public final short subType;
|
public final short subType;
|
||||||
public final short version;
|
public final short version;
|
||||||
public final int prevConnectionBlockNumber;
|
public final int prevConnectionBlockNumber;
|
||||||
@@ -27,16 +29,28 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
|||||||
public final byte[] toBlockHash32;
|
public final byte[] toBlockHash32;
|
||||||
|
|
||||||
public ConnectionBody(short subType, short version, byte[] bodyBytes) {
|
public ConnectionBody(short subType, short version, byte[] bodyBytes) {
|
||||||
|
this(subType, version, bodyBytes, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||||
|
public ConnectionBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||||
|
this.contentOnly = line != null;
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
|
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
|
||||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short");
|
BodyTargetSupport.ensureMin(bb, (4 + 32 + 4 + 1 + 1 + 2 + 4 + 32) - (contentOnly ? 40 : 0), "ConnectionBody too short");
|
||||||
|
if (contentOnly) {
|
||||||
|
this.prevConnectionBlockNumber = line.prevLineBlockNumber();
|
||||||
|
this.prevConnectionBlockHash32 = line.prevLineCoreHash32();
|
||||||
|
this.connectionSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||||
|
} else {
|
||||||
this.prevConnectionBlockNumber = bb.getInt();
|
this.prevConnectionBlockNumber = bb.getInt();
|
||||||
this.prevConnectionBlockHash32 = new byte[32];
|
this.prevConnectionBlockHash32 = new byte[32];
|
||||||
bb.get(this.prevConnectionBlockHash32);
|
bb.get(this.prevConnectionBlockHash32);
|
||||||
this.connectionSequence = bb.getInt();
|
this.connectionSequence = bb.getInt();
|
||||||
|
}
|
||||||
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
|
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
|
||||||
this.toLogin = t.login();
|
this.toLogin = t.login();
|
||||||
this.toForkNumber = t.forkNumber();
|
this.toForkNumber = t.forkNumber();
|
||||||
@@ -47,6 +61,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
|||||||
|
|
||||||
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
|
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
|
||||||
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
|
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
|
||||||
|
this.contentOnly = false;
|
||||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||||
this.prevConnectionBlockNumber = prevConnectionBlockNumber;
|
this.prevConnectionBlockNumber = prevConnectionBlockNumber;
|
||||||
@@ -64,15 +79,15 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
|||||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||||
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
|
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
|
||||||
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
|
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
|
||||||
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
|
if (!contentOnly && connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
|
||||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public byte[] toBytes() {
|
@Override public byte[] toBytes() {
|
||||||
check();
|
check();
|
||||||
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 40) + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
||||||
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
|
if (!contentOnly) bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
|
||||||
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||||
return bb.array();
|
return bb.array();
|
||||||
}
|
}
|
||||||
|
|||||||
+43
-5
@@ -1,6 +1,7 @@
|
|||||||
package blockchain.body;
|
package blockchain.body;
|
||||||
|
|
||||||
import blockchain.MsgSubType;
|
import blockchain.MsgSubType;
|
||||||
|
import blockchain.CoreRecord;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
@@ -37,9 +38,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
|
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
|
||||||
|
|
||||||
private static final byte[] ZERO32 = new byte[32];
|
private static final byte[] ZERO32 = new byte[32];
|
||||||
|
// Минимум для создания нового канала; исторические блоки 1–3 символа читаются.
|
||||||
|
public static final int MIN_NAME_LENGTH_FOR_CREATE = 4;
|
||||||
private static final int MAX_NAME_LENGTH = 32;
|
private static final int MAX_NAME_LENGTH = 32;
|
||||||
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
|
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
|
||||||
|
|
||||||
|
private final boolean contentOnly;
|
||||||
public final short subType;
|
public final short subType;
|
||||||
public final short version;
|
public final short version;
|
||||||
|
|
||||||
@@ -54,6 +58,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
public final short channelTypeVersion;
|
public final short channelTypeVersion;
|
||||||
|
|
||||||
public CreateChannelBody(short subType, short version, byte[] bodyBytes) {
|
public CreateChannelBody(short subType, short version, byte[] bodyBytes) {
|
||||||
|
this(subType, version, bodyBytes, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||||
|
public CreateChannelBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||||
|
this.contentOnly = line != null;
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
@@ -65,16 +75,23 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
|
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
|
||||||
throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
|
throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
|
||||||
}
|
}
|
||||||
if (bodyBytes.length < 4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) {
|
if (bodyBytes.length < (4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) - (contentOnly ? 44 : 0)) {
|
||||||
throw new IllegalArgumentException("CreateChannelBody too short");
|
throw new IllegalArgumentException("CreateChannelBody too short");
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
if (contentOnly) {
|
||||||
|
this.lineCode = 0;
|
||||||
|
this.prevLineNumber = line.prevLineBlockNumber();
|
||||||
|
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||||
|
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||||
|
} else {
|
||||||
this.lineCode = bb.getInt();
|
this.lineCode = bb.getInt();
|
||||||
this.prevLineNumber = bb.getInt();
|
this.prevLineNumber = bb.getInt();
|
||||||
this.prevLineHash32 = new byte[32];
|
this.prevLineHash32 = new byte[32];
|
||||||
bb.get(this.prevLineHash32);
|
bb.get(this.prevLineHash32);
|
||||||
this.thisLineNumber = bb.getInt();
|
this.thisLineNumber = bb.getInt();
|
||||||
|
}
|
||||||
|
|
||||||
int nameLen = Byte.toUnsignedInt(bb.get());
|
int nameLen = Byte.toUnsignedInt(bb.get());
|
||||||
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
|
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
|
||||||
@@ -84,7 +101,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
|
|
||||||
byte[] nameBytes = new byte[nameLen];
|
byte[] nameBytes = new byte[nameLen];
|
||||||
bb.get(nameBytes);
|
bb.get(nameBytes);
|
||||||
this.channelName = new String(nameBytes, StandardCharsets.UTF_8);
|
this.channelName = contentOnly ? BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName") : new String(nameBytes, StandardCharsets.UTF_8);
|
||||||
|
|
||||||
int descriptionLen = Short.toUnsignedInt(bb.getShort());
|
int descriptionLen = Short.toUnsignedInt(bb.getShort());
|
||||||
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
|
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
|
||||||
@@ -98,7 +115,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
} else {
|
} else {
|
||||||
byte[] descriptionBytes = new byte[descriptionLen];
|
byte[] descriptionBytes = new byte[descriptionLen];
|
||||||
bb.get(descriptionBytes);
|
bb.get(descriptionBytes);
|
||||||
this.channelDescription = normalizeDescription(new String(descriptionBytes, StandardCharsets.UTF_8));
|
this.channelDescription = normalizeDescription(contentOnly ? BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription") : new String(descriptionBytes, StandardCharsets.UTF_8));
|
||||||
}
|
}
|
||||||
this.channelTypeCode = bb.getShort();
|
this.channelTypeCode = bb.getShort();
|
||||||
this.channelTypeVersion = bb.getShort();
|
this.channelTypeVersion = bb.getShort();
|
||||||
@@ -115,6 +132,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
String channelDescription,
|
String channelDescription,
|
||||||
short channelTypeCode,
|
short channelTypeCode,
|
||||||
short channelTypeVersion) {
|
short channelTypeVersion) {
|
||||||
|
this.contentOnly = false;
|
||||||
Objects.requireNonNull(channelName, "channelName == null");
|
Objects.requireNonNull(channelName, "channelName == null");
|
||||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||||
|
|
||||||
@@ -140,6 +158,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
String normalizedName = normalizeDisplayName(channelName);
|
String normalizedName = normalizeDisplayName(channelName);
|
||||||
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
|
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
|
||||||
int cpLen = normalizedName.codePointCount(0, normalizedName.length());
|
int cpLen = normalizedName.codePointCount(0, normalizedName.length());
|
||||||
|
if (contentOnly && normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
|
||||||
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
|
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
|
||||||
|
|
||||||
String normalizedDescription = normalizeDescription(channelDescription);
|
String normalizedDescription = normalizeDescription(channelDescription);
|
||||||
@@ -155,7 +174,21 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
|
|
||||||
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody");
|
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody");
|
||||||
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
|
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
|
||||||
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
|
if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
|
||||||
|
return this;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Правило создания нового TECH_CREATE_CHANNEL (в отличие от чтения истории).
|
||||||
|
* check() намеренно принимает старые каналы с именами из 1–3 символов.
|
||||||
|
*/
|
||||||
|
public CreateChannelBody 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;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,6 +204,9 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public byte[] toBytes() {
|
public byte[] toBytes() {
|
||||||
|
// Новые блоки кодируются только с именем от 4 символов.
|
||||||
|
// Исторические блоки при чтении разбираются без повторного кодирования.
|
||||||
|
checkForCreate();
|
||||||
byte[] nameUtf8 = normalizeDisplayName(channelName).getBytes(StandardCharsets.UTF_8);
|
byte[] nameUtf8 = normalizeDisplayName(channelName).getBytes(StandardCharsets.UTF_8);
|
||||||
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
|
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
|
||||||
throw new IllegalArgumentException("channelName utf8 len must be 1..255");
|
throw new IllegalArgumentException("channelName utf8 len must be 1..255");
|
||||||
@@ -180,12 +216,14 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
|||||||
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
|
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
|
||||||
}
|
}
|
||||||
|
|
||||||
int cap = 4 + (4 + 32 + 4) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
|
int cap = (contentOnly ? 0 : 44) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
|
||||||
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
if (!contentOnly) {
|
||||||
bb.putInt(lineCode);
|
bb.putInt(lineCode);
|
||||||
bb.putInt(prevLineNumber);
|
bb.putInt(prevLineNumber);
|
||||||
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
|
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
|
||||||
bb.putInt(thisLineNumber);
|
bb.putInt(thisLineNumber);
|
||||||
|
}
|
||||||
bb.put((byte) nameUtf8.length);
|
bb.put((byte) nameUtf8.length);
|
||||||
bb.put(nameUtf8);
|
bb.put(nameUtf8);
|
||||||
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
|
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package blockchain.body;
|
package blockchain.body;
|
||||||
|
|
||||||
import blockchain.MsgSubType;
|
import blockchain.MsgSubType;
|
||||||
|
import blockchain.CoreRecord;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
@@ -49,6 +50,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
|
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
|
||||||
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
|
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
|
||||||
|
|
||||||
|
private final boolean contentOnly;
|
||||||
public final short subType;
|
public final short subType;
|
||||||
public final short version;
|
public final short version;
|
||||||
|
|
||||||
@@ -69,6 +71,12 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
public final String comment;
|
public final String comment;
|
||||||
|
|
||||||
public ForkBody(short subType, short version, byte[] bodyBytes) {
|
public ForkBody(short subType, short version, byte[] bodyBytes) {
|
||||||
|
this(subType, version, bodyBytes, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||||
|
public ForkBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||||
|
this.contentOnly = line != null;
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
@@ -79,16 +87,23 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
|
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
|
||||||
throw new IllegalArgumentException("ForkBody version must be 1");
|
throw new IllegalArgumentException("ForkBody version must be 1");
|
||||||
}
|
}
|
||||||
if (bodyBytes.length < FIXED_LEN) {
|
if (bodyBytes.length < FIXED_LEN - (contentOnly ? LINE_PREFIX_LEN : 0)) {
|
||||||
throw new IllegalArgumentException("ForkBody too short");
|
throw new IllegalArgumentException("ForkBody too short");
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
if (contentOnly) {
|
||||||
|
this.lineCode = 0;
|
||||||
|
this.prevLineNumber = line.prevLineBlockNumber();
|
||||||
|
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||||
|
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||||
|
} else {
|
||||||
this.lineCode = bb.getInt();
|
this.lineCode = bb.getInt();
|
||||||
this.prevLineNumber = bb.getInt();
|
this.prevLineNumber = bb.getInt();
|
||||||
this.prevLineHash32 = new byte[32];
|
this.prevLineHash32 = new byte[32];
|
||||||
bb.get(this.prevLineHash32);
|
bb.get(this.prevLineHash32);
|
||||||
this.thisLineNumber = bb.getInt();
|
this.thisLineNumber = bb.getInt();
|
||||||
|
}
|
||||||
|
|
||||||
this.parentBlockchainKey32 = new byte[32];
|
this.parentBlockchainKey32 = new byte[32];
|
||||||
bb.get(this.parentBlockchainKey32);
|
bb.get(this.parentBlockchainKey32);
|
||||||
@@ -111,7 +126,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
}
|
}
|
||||||
byte[] commentBytes = new byte[commentLen];
|
byte[] commentBytes = new byte[commentLen];
|
||||||
bb.get(commentBytes);
|
bb.get(commentBytes);
|
||||||
this.comment = new String(commentBytes, StandardCharsets.UTF_8);
|
this.comment = contentOnly ? BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment") : new String(commentBytes, StandardCharsets.UTF_8);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ForkBody(int lineCode,
|
public ForkBody(int lineCode,
|
||||||
@@ -128,6 +143,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
int discardedBlocksCount,
|
int discardedBlocksCount,
|
||||||
int reasonCode,
|
int reasonCode,
|
||||||
String comment) {
|
String comment) {
|
||||||
|
this.contentOnly = false;
|
||||||
this.subType = SUBTYPE;
|
this.subType = SUBTYPE;
|
||||||
this.version = VER;
|
this.version = VER;
|
||||||
this.lineCode = lineCode;
|
this.lineCode = lineCode;
|
||||||
@@ -157,7 +173,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
|
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
|
||||||
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
|
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
|
||||||
require32(prevLineHash32, "prevLineHash32");
|
require32(prevLineHash32, "prevLineHash32");
|
||||||
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
|
if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
|
||||||
|
|
||||||
require32(parentBlockchainKey32, "parentBlockchainKey32");
|
require32(parentBlockchainKey32, "parentBlockchainKey32");
|
||||||
require32(forkPointBlockHash32, "forkPointBlockHash32");
|
require32(forkPointBlockHash32, "forkPointBlockHash32");
|
||||||
@@ -186,11 +202,13 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
|||||||
public byte[] toBytes() {
|
public byte[] toBytes() {
|
||||||
check();
|
check();
|
||||||
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
|
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
|
||||||
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? FIXED_PAYLOAD_LEN : FIXED_LEN) + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
if (!contentOnly) {
|
||||||
bb.putInt(lineCode);
|
bb.putInt(lineCode);
|
||||||
bb.putInt(prevLineNumber);
|
bb.putInt(prevLineNumber);
|
||||||
bb.put(prevLineHash32);
|
bb.put(prevLineHash32);
|
||||||
bb.putInt(thisLineNumber);
|
bb.putInt(thisLineNumber);
|
||||||
|
}
|
||||||
bb.put(parentBlockchainKey32);
|
bb.put(parentBlockchainKey32);
|
||||||
bb.putInt(forkPointBlockNumber);
|
bb.putInt(forkPointBlockNumber);
|
||||||
bb.put(forkPointBlockHash32);
|
bb.put(forkPointBlockHash32);
|
||||||
|
|||||||
@@ -9,12 +9,13 @@ import java.util.Arrays;
|
|||||||
import java.util.Objects;
|
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):
|
* bodyBytes (BigEndian):
|
||||||
* [TAG_LEN] tag ASCII
|
* [TAG_LEN] tag ASCII
|
||||||
* [1] loginLength (uint8)
|
* [1] loginLength (uint8)
|
||||||
* [N] login UTF-8
|
* [N] login UTF-8
|
||||||
|
* [15] ASCII "license:CC0-1.0" (version=2 only)
|
||||||
* [32] initialBlockchainKey32
|
* [32] initialBlockchainKey32
|
||||||
*
|
*
|
||||||
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
|
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
|
||||||
@@ -23,7 +24,11 @@ import java.util.Objects;
|
|||||||
*/
|
*/
|
||||||
public final class HeaderBody implements BodyRecord {
|
public final class HeaderBody implements BodyRecord {
|
||||||
public static final short TYPE = 0;
|
public static final short TYPE = 0;
|
||||||
public static final short VER = 1;
|
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 int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||||
public static final short SUBTYPE_COMPAT = 0;
|
public static final short SUBTYPE_COMPAT = 0;
|
||||||
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
|
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 tag;
|
||||||
public final String login;
|
public final String login;
|
||||||
public final byte[] initialBlockchainKey32;
|
public final byte[] initialBlockchainKey32;
|
||||||
|
public final String license; // null for legacy HEADER v1
|
||||||
|
|
||||||
public HeaderBody(short subType, short version, byte[] bodyBytes) {
|
public HeaderBody(short subType, short version, byte[] bodyBytes) {
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1");
|
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("HeaderBody version must be 1 or 2");
|
||||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
|
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);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
byte[] tagBytes = new byte[TAG_LEN];
|
byte[] tagBytes = new byte[TAG_LEN];
|
||||||
@@ -53,33 +60,66 @@ public final class HeaderBody implements BodyRecord {
|
|||||||
this.tag = parsedTag;
|
this.tag = parsedTag;
|
||||||
|
|
||||||
int loginLen = Byte.toUnsignedInt(bb.get());
|
int loginLen = Byte.toUnsignedInt(bb.get());
|
||||||
if (loginLen <= 0 || bb.remaining() != loginLen + 32) 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];
|
byte[] loginBytes = new byte[loginLen];
|
||||||
bb.get(loginBytes);
|
bb.get(loginBytes);
|
||||||
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
|
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
|
||||||
|
if (version == VER_CC0) {
|
||||||
|
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];
|
this.initialBlockchainKey32 = new byte[32];
|
||||||
bb.get(this.initialBlockchainKey32);
|
bb.get(this.initialBlockchainKey32);
|
||||||
requireNonZeroKey(this.initialBlockchainKey32);
|
requireNonZeroKey(this.initialBlockchainKey32);
|
||||||
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
|
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) {
|
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(login, "login == null");
|
||||||
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
|
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
|
||||||
this.subType = SUBTYPE_COMPAT;
|
this.subType = SUBTYPE_COMPAT;
|
||||||
this.version = VER;
|
this.version = version;
|
||||||
this.tag = TAG;
|
this.tag = TAG;
|
||||||
this.login = login;
|
this.login = login;
|
||||||
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
|
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
|
||||||
|
this.license = version == VER_CC0 ? LICENSE_CC0 : null;
|
||||||
check();
|
check();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public HeaderBody check() {
|
public HeaderBody check() {
|
||||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||||
|
if (version != VER && version != VER_CC0) throw new IllegalArgumentException("Bad HeaderBody version");
|
||||||
|
if (version == VER_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");
|
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
||||||
if (!login.matches("^[A-Za-z0-9_]+$")) throw new IllegalArgumentException("Login must match ^[A-Za-z0-9_]+$");
|
|
||||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||||
|
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
|
||||||
|
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
|
||||||
|
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
|
||||||
|
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
|
||||||
|
if (!legacyLogin && !namespacedLogin) {
|
||||||
|
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
|
||||||
|
}
|
||||||
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
||||||
requireNonZeroKey(initialBlockchainKey32);
|
requireNonZeroKey(initialBlockchainKey32);
|
||||||
return this;
|
return this;
|
||||||
@@ -89,10 +129,11 @@ public final class HeaderBody implements BodyRecord {
|
|||||||
public byte[] toBytes() {
|
public byte[] toBytes() {
|
||||||
check();
|
check();
|
||||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).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(TAG_ASCII);
|
||||||
bb.put((byte) loginUtf8.length);
|
bb.put((byte) loginUtf8.length);
|
||||||
bb.put(loginUtf8);
|
bb.put(loginUtf8);
|
||||||
|
if (version == VER_CC0) bb.put(LICENSE_BYTES);
|
||||||
bb.put(initialBlockchainKey32);
|
bb.put(initialBlockchainKey32);
|
||||||
return bb.array();
|
return bb.array();
|
||||||
}
|
}
|
||||||
@@ -106,6 +147,6 @@ public final class HeaderBody implements BodyRecord {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public String toString() {
|
public String toString() {
|
||||||
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}";
|
return "HeaderBody{version=" + version + ", login='" + login + "', license=" + license + ", initialBlockchainKey32=<32 bytes>}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+19
-3
@@ -1,6 +1,7 @@
|
|||||||
package blockchain.body;
|
package blockchain.body;
|
||||||
|
|
||||||
import blockchain.MsgSubType;
|
import blockchain.MsgSubType;
|
||||||
|
import blockchain.CoreRecord;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
@@ -27,6 +28,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
|||||||
public static final short VER = 1;
|
public static final short VER = 1;
|
||||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||||
|
|
||||||
|
private final boolean contentOnly;
|
||||||
public final short subType;
|
public final short subType;
|
||||||
public final short version;
|
public final short version;
|
||||||
public final int lineCode;
|
public final int lineCode;
|
||||||
@@ -40,17 +42,30 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
|||||||
public final String message;
|
public final String message;
|
||||||
|
|
||||||
public TextLineBody(short subType, short version, byte[] bodyBytes) {
|
public TextLineBody(short subType, short version, byte[] bodyBytes) {
|
||||||
|
this(subType, version, bodyBytes, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||||
|
public TextLineBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||||
|
this.contentOnly = line != null;
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
this.version = version;
|
this.version = version;
|
||||||
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
|
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 2, "TextLineBody too short");
|
BodyTargetSupport.ensureMin(bb, (4 + 4 + 32 + 4 + 2) - (contentOnly ? 44 : 0), "TextLineBody too short");
|
||||||
|
if (contentOnly) {
|
||||||
|
this.lineCode = line.lineCode();
|
||||||
|
this.prevLineNumber = line.prevLineBlockNumber();
|
||||||
|
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||||
|
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||||
|
} else {
|
||||||
this.lineCode = bb.getInt();
|
this.lineCode = bb.getInt();
|
||||||
this.prevLineNumber = bb.getInt();
|
this.prevLineNumber = bb.getInt();
|
||||||
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
|
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
|
||||||
this.thisLineNumber = bb.getInt();
|
this.thisLineNumber = bb.getInt();
|
||||||
|
}
|
||||||
|
|
||||||
int st = subType & 0xFFFF;
|
int st = subType & 0xFFFF;
|
||||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
||||||
@@ -88,6 +103,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
|||||||
Integer toBlockGlobalNumber,
|
Integer toBlockGlobalNumber,
|
||||||
byte[] toBlockHash32,
|
byte[] toBlockHash32,
|
||||||
String message) {
|
String message) {
|
||||||
|
this.contentOnly = false;
|
||||||
Objects.requireNonNull(message, "message == null");
|
Objects.requireNonNull(message, "message == null");
|
||||||
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
|
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
|
||||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||||
@@ -144,8 +160,8 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
|||||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
|
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
|
||||||
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
|
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 44) + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
|
||||||
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
|
if (!contentOnly) bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
|
||||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
||||||
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
|
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
|
||||||
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
|
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
|
||||||
|
|||||||
+20
-3
@@ -1,6 +1,7 @@
|
|||||||
package blockchain.body;
|
package blockchain.body;
|
||||||
|
|
||||||
import blockchain.MsgSubType;
|
import blockchain.MsgSubType;
|
||||||
|
import blockchain.CoreRecord;
|
||||||
|
|
||||||
import java.nio.ByteBuffer;
|
import java.nio.ByteBuffer;
|
||||||
import java.nio.ByteOrder;
|
import java.nio.ByteOrder;
|
||||||
@@ -35,6 +36,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
|
|
||||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||||
|
|
||||||
|
private final boolean contentOnly;
|
||||||
public final short subType;
|
public final short subType;
|
||||||
public final short version;
|
public final short version;
|
||||||
|
|
||||||
@@ -46,6 +48,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
public final String paramValue;
|
public final String paramValue;
|
||||||
|
|
||||||
public UserParamBody(short subType, short version, byte[] bodyBytes) {
|
public UserParamBody(short subType, short version, byte[] bodyBytes) {
|
||||||
|
this(subType, version, bodyBytes, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||||
|
public UserParamBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||||
|
this.contentOnly = line != null;
|
||||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||||
|
|
||||||
this.subType = subType;
|
this.subType = subType;
|
||||||
@@ -59,16 +67,22 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
|
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
|
||||||
if (bodyBytes.length < 4 + 32 + 4 + 2 + 1 + 2 + 1) {
|
if (bodyBytes.length < (4 + 32 + 4 + 2 + 1 + 2 + 1) - (contentOnly ? 40 : 0)) {
|
||||||
throw new IllegalArgumentException("UserParamBody too short");
|
throw new IllegalArgumentException("UserParamBody too short");
|
||||||
}
|
}
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
|
||||||
|
if (contentOnly) {
|
||||||
|
this.prevProfileBlockNumber = line.prevLineBlockNumber();
|
||||||
|
this.prevProfileBlockHash32 = line.prevLineCoreHash32();
|
||||||
|
this.profileSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||||
|
} else {
|
||||||
this.prevProfileBlockNumber = bb.getInt();
|
this.prevProfileBlockNumber = bb.getInt();
|
||||||
this.prevProfileBlockHash32 = new byte[32];
|
this.prevProfileBlockHash32 = new byte[32];
|
||||||
bb.get(this.prevProfileBlockHash32);
|
bb.get(this.prevProfileBlockHash32);
|
||||||
this.profileSequence = bb.getInt();
|
this.profileSequence = bb.getInt();
|
||||||
|
}
|
||||||
|
|
||||||
int keyLen = Short.toUnsignedInt(bb.getShort());
|
int keyLen = Short.toUnsignedInt(bb.getShort());
|
||||||
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
|
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
|
||||||
@@ -98,6 +112,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
int profileSequence,
|
int profileSequence,
|
||||||
String paramKey,
|
String paramKey,
|
||||||
String paramValue) {
|
String paramValue) {
|
||||||
|
this.contentOnly = false;
|
||||||
|
|
||||||
Objects.requireNonNull(paramKey, "paramKey == null");
|
Objects.requireNonNull(paramKey, "paramKey == null");
|
||||||
Objects.requireNonNull(paramValue, "paramValue == null");
|
Objects.requireNonNull(paramValue, "paramValue == null");
|
||||||
@@ -123,7 +138,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
}
|
}
|
||||||
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
|
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
|
||||||
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
|
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
|
||||||
if (profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
|
if (!contentOnly && profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
|
||||||
|
|
||||||
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
|
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
|
||||||
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
|
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
|
||||||
@@ -140,14 +155,16 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
|
|||||||
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
|
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
|
||||||
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
|
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
|
||||||
|
|
||||||
int cap = 4 + 32 + 4
|
int cap = (contentOnly ? 0 : 40)
|
||||||
+ 2 + keyUtf8.length
|
+ 2 + keyUtf8.length
|
||||||
+ 2 + valUtf8.length;
|
+ 2 + valUtf8.length;
|
||||||
|
|
||||||
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
||||||
|
if (!contentOnly) {
|
||||||
bb.putInt(prevProfileBlockNumber);
|
bb.putInt(prevProfileBlockNumber);
|
||||||
bb.put(prevProfileBlockHash32);
|
bb.put(prevProfileBlockHash32);
|
||||||
bb.putInt(profileSequence);
|
bb.putInt(profileSequence);
|
||||||
|
}
|
||||||
bb.putShort((short) keyUtf8.length);
|
bb.putShort((short) keyUtf8.length);
|
||||||
bb.put(keyUtf8);
|
bb.put(keyUtf8);
|
||||||
bb.putShort((short) valUtf8.length);
|
bb.putShort((short) valUtf8.length);
|
||||||
|
|||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
package blockchain;
|
||||||
|
|
||||||
|
import blockchain.body.CreateChannelBody;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.ByteOrder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
final class CreateChannelBodyNameLengthTest {
|
||||||
|
|
||||||
|
private static CreateChannelBody newChannel(String name) {
|
||||||
|
return new CreateChannelBody(
|
||||||
|
0, 0, new byte[32], 1, name, "",
|
||||||
|
CreateChannelBody.CHANNEL_TYPE_PUBLIC,
|
||||||
|
CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void newChannelMustContainAtLeastFourCharacters() {
|
||||||
|
for (String name : new String[]{"a", "ab", "abc"}) {
|
||||||
|
CreateChannelBody body = newChannel(name);
|
||||||
|
assertDoesNotThrow(body::check, "Исторический декодер не должен блокировать: " + name);
|
||||||
|
assertThrows(IllegalArgumentException.class, body::checkForCreate, name);
|
||||||
|
assertThrows(IllegalArgumentException.class, body::toBytes, name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fourToThirtyTwoCharactersAreAccepted() {
|
||||||
|
for (String name : new String[]{"abcd", "tantra", "X".repeat(32)}) {
|
||||||
|
CreateChannelBody newBody = newChannel(name);
|
||||||
|
assertDoesNotThrow(newBody::checkForCreate, name);
|
||||||
|
CreateChannelBody fromHistory = assertInstanceOf(
|
||||||
|
CreateChannelBody.class,
|
||||||
|
BodyRecordParser.parse(CreateChannelBody.TYPE, CreateChannelBody.SUBTYPE,
|
||||||
|
CreateChannelBody.VER, newBody.toBytes())
|
||||||
|
);
|
||||||
|
assertEquals(name, fromHistory.channelName);
|
||||||
|
}
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> newChannel("x".repeat(33)).toBytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void historicalThreeCharacterBlockStillDecodes() {
|
||||||
|
// Байт-в-байт существующий формат, без использования сериализатора новых блоков.
|
||||||
|
byte[] name = "abc".getBytes(StandardCharsets.UTF_8);
|
||||||
|
ByteBuffer raw = ByteBuffer.allocate(4 + 4 + 32 + 4 + 1 + name.length + 2 + 4)
|
||||||
|
.order(ByteOrder.BIG_ENDIAN);
|
||||||
|
raw.putInt(0).putInt(0).put(new byte[32]).putInt(1);
|
||||||
|
raw.put((byte) name.length).put(name);
|
||||||
|
raw.putShort((short) 0);
|
||||||
|
raw.putShort(CreateChannelBody.CHANNEL_TYPE_PUBLIC);
|
||||||
|
raw.putShort(CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT);
|
||||||
|
|
||||||
|
CreateChannelBody parsed = assertInstanceOf(
|
||||||
|
CreateChannelBody.class,
|
||||||
|
BodyRecordParser.parse(CreateChannelBody.TYPE, CreateChannelBody.SUBTYPE,
|
||||||
|
CreateChannelBody.VER, raw.array())
|
||||||
|
);
|
||||||
|
assertEquals("abc", parsed.channelName);
|
||||||
|
assertDoesNotThrow(parsed::check);
|
||||||
|
assertThrows(IllegalArgumentException.class, parsed::checkForCreate);
|
||||||
|
}
|
||||||
|
}
|
||||||
+287
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -98,6 +98,73 @@ final class TargetLoginFormatTest {
|
|||||||
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void namespacedHeaderRoundTripAcceptsPaidAndFreeUsers() {
|
||||||
|
for (String login : new String[]{"alice@free", "AlexSmith@shine", "a_B@free", "abcdefghijklmnopqrstuvwxy@free"}) {
|
||||||
|
HeaderBody source = new HeaderBody(login, INITIAL_KEY);
|
||||||
|
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, source.toBytes()).check();
|
||||||
|
assertEquals(login, parsed.login);
|
||||||
|
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@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"}) {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new HeaderBody(login, INITIAL_KEY), login);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void signedReferencesPreserveArbitraryLoginCaseWithoutServerSideCaseEnforcement() {
|
||||||
|
// Адресация не зависит от регистра, но блок сохраняет выбранные автором байты.
|
||||||
|
for (String login : new String[]{"AlexSmith@shine", "alexsmith@shine"}) {
|
||||||
|
TextReplyBody reply = new TextReplyBody(MsgSubType.TEXT_REPLY, login, 1, 42, HASH, "тест");
|
||||||
|
assertEquals(login, new TextReplyBody(MsgSubType.TEXT_REPLY, TextReplyBody.VER, reply.toBytes()).check().toLogin());
|
||||||
|
|
||||||
|
ReactionBody like = new ReactionBody(MsgSubType.REACTION_LIKE, login, 1, 42, HASH);
|
||||||
|
assertEquals(login, new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, like.toBytes()).check().toLogin());
|
||||||
|
|
||||||
|
ConnectionBody follow = new ConnectionBody(0, HASH, 1, MsgSubType.CONNECTION_FOLLOW, login, 1, 0, HASH);
|
||||||
|
assertEquals(login, new ConnectionBody(MsgSubType.CONNECTION_FOLLOW, ConnectionBody.VER, follow.toBytes()).check().toLogin());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static byte[] hash(int seed) {
|
private static byte[] hash(int seed) {
|
||||||
byte[] out = new byte[32];
|
byte[] out = new byte[32];
|
||||||
Arrays.fill(out, (byte) seed);
|
Arrays.fill(out, (byte) seed);
|
||||||
|
|||||||
+83
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
+176
@@ -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();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
+182
@@ -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');
|
||||||
|
}
|
||||||
|
}
|
||||||
+152
@@ -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); }
|
||||||
|
}
|
||||||
|
}
|
||||||
+133
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -23,9 +23,35 @@ public final class DatabaseInitializer {
|
|||||||
public static final int SCHEMA_VERSION_1 = 1;
|
public static final int SCHEMA_VERSION_1 = 1;
|
||||||
public static final int SCHEMA_VERSION_31 = 31;
|
public static final int SCHEMA_VERSION_31 = 31;
|
||||||
public static final int SCHEMA_VERSION_32 = 32;
|
public static final int SCHEMA_VERSION_32 = 32;
|
||||||
|
public static final int SCHEMA_VERSION_33 = 33;
|
||||||
|
public static final int SCHEMA_VERSION_34 = 34;
|
||||||
|
public static final int SCHEMA_VERSION_35 = 35;
|
||||||
|
public static final int SCHEMA_VERSION_36 = 36;
|
||||||
|
public static final int SCHEMA_VERSION_37 = 37;
|
||||||
|
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_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V33_RESOURCE = "postgres/migration_v33.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V34_RESOURCE = "postgres/migration_v34.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V35_RESOURCE = "postgres/migration_v35.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V36_RESOURCE = "postgres/migration_v36.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V37_RESOURCE = "postgres/migration_v37.sql";
|
||||||
|
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() {}
|
private DatabaseInitializer() {}
|
||||||
|
|
||||||
@@ -125,10 +151,63 @@ public final class DatabaseInitializer {
|
|||||||
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
||||||
currentVersion = readCurrentSchemaVersion(conn);
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
}
|
}
|
||||||
if (currentVersion != SCHEMA_VERSION_32) {
|
if (currentVersion == SCHEMA_VERSION_32) {
|
||||||
throw new SQLException(
|
runSqlScript(conn, POSTGRES_MIGRATION_V33_RESOURCE);
|
||||||
"Unsupported SHiNE DB v2 schema version: expected 32, found " + currentVersion);
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
}
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_33) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V34_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_34) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V35_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_35) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V36_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_36) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V37_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_37) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_38) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V39_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_39) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V40_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
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 45, found " + currentVersion);
|
||||||
|
}
|
||||||
|
normalizeBlockchainStateKeysToBase64(conn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,6 +287,38 @@ public final class DatabaseInitializer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* blockchain_state — runtime-проекция: публичный blockchain key хранится
|
||||||
|
* строго как Base64(32). Ранний импорт free-регистраций ошибочно сохранял
|
||||||
|
* Base58, поэтому нормализация выполняется идемпотентно при старте.
|
||||||
|
*/
|
||||||
|
private static void normalizeBlockchainStateKeysToBase64(Connection conn) throws SQLException {
|
||||||
|
record StateKey(String login, int forkNumber, String key) {}
|
||||||
|
List<StateKey> entries = new ArrayList<>();
|
||||||
|
try (Statement st = conn.createStatement();
|
||||||
|
ResultSet rs = st.executeQuery("SELECT login, fork_number, blockchain_key FROM blockchain_state_store")) {
|
||||||
|
while (rs.next()) {
|
||||||
|
entries.add(new StateKey(rs.getString("login"), rs.getInt("fork_number"), rs.getString("blockchain_key")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try (var update = conn.prepareStatement("""
|
||||||
|
UPDATE blockchain_state_store
|
||||||
|
SET blockchain_key = ?
|
||||||
|
WHERE login = ? AND fork_number = ?
|
||||||
|
""")) {
|
||||||
|
for (StateKey entry : entries) {
|
||||||
|
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(entry.key());
|
||||||
|
if (normalized == null || normalized.equals(entry.key())) continue;
|
||||||
|
update.setString(1, normalized);
|
||||||
|
update.setString(2, entry.login());
|
||||||
|
update.setInt(3, entry.forkNumber());
|
||||||
|
update.addBatch();
|
||||||
|
}
|
||||||
|
update.executeBatch();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void runSqlScript(Connection conn, String resourcePath) throws SQLException {
|
private static void runSqlScript(Connection conn, String resourcePath) throws SQLException {
|
||||||
String sqlScript = loadClasspathResource(resourcePath);
|
String sqlScript = loadClasspathResource(resourcePath);
|
||||||
List<String> statements = splitSqlStatements(sqlScript);
|
List<String> statements = splitSqlStatements(sqlScript);
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import java.util.Locale;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
public final class ChannelNameRules {
|
public final class ChannelNameRules {
|
||||||
private static final int MIN_DISPLAY_NAME_LENGTH = 3;
|
private static final int MIN_DISPLAY_NAME_LENGTH = 4;
|
||||||
private static final int MAX_DISPLAY_NAME_LENGTH = 32;
|
private static final int MAX_DISPLAY_NAME_LENGTH = 32;
|
||||||
private static final Pattern DISPLAY_ALLOWED_PATTERN =
|
private static final Pattern DISPLAY_ALLOWED_PATTERN =
|
||||||
Pattern.compile("^[A-Za-z0-9_-]+$");
|
Pattern.compile("^[A-Za-z0-9_-]+$");
|
||||||
@@ -26,7 +26,7 @@ public final class ChannelNameRules {
|
|||||||
|
|
||||||
int length = normalized.codePointCount(0, normalized.length());
|
int length = normalized.codePointCount(0, normalized.length());
|
||||||
if (length < MIN_DISPLAY_NAME_LENGTH || length > MAX_DISPLAY_NAME_LENGTH) {
|
if (length < MIN_DISPLAY_NAME_LENGTH || length > MAX_DISPLAY_NAME_LENGTH) {
|
||||||
throw new IllegalArgumentException("channelName length must be 3..32");
|
throw new IllegalArgumentException("channelName length must be 4..32");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!DISPLAY_ALLOWED_PATTERN.matcher(normalized).matches()) {
|
if (!DISPLAY_ALLOWED_PATTERN.matcher(normalized).matches()) {
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public final class BlockchainStateDAO {
|
|||||||
last_block_hash,
|
last_block_hash,
|
||||||
updated_at_ms
|
updated_at_ms
|
||||||
FROM blockchain_state
|
FROM blockchain_state
|
||||||
WHERE login = ? AND fork_number = ?
|
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||||
""";
|
""";
|
||||||
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -187,18 +187,36 @@ 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.
|
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
|
||||||
*/
|
*/
|
||||||
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
|
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 = """
|
String sql = """
|
||||||
UPDATE blockchain_state_store
|
UPDATE blockchain_state_store
|
||||||
SET
|
SET
|
||||||
file_size_bytes = file_size_bytes + ?,
|
file_size_bytes = file_size_bytes + ?,
|
||||||
updated_at_ms = ?
|
updated_at_ms = ?
|
||||||
WHERE
|
WHERE
|
||||||
login = ? AND fork_number = ?
|
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)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
|
|||||||
ps.setString(3, r.login());
|
ps.setString(3, r.login());
|
||||||
ps.setInt(4, r.fork());
|
ps.setInt(4, r.fork());
|
||||||
ps.setLong(5, deltaBytes);
|
ps.setLong(5, deltaBytes);
|
||||||
|
ps.setLong(6, deltaBytes);
|
||||||
return ps.executeUpdate() > 0;
|
return ps.executeUpdate() > 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import java.sql.*;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
/** DAO for SHiNE Frame v1 blocks. block_bytes contains the complete ANS-104 DataItem. */
|
/** DAO for SHiNE blocks. block_bytes contains the complete signed CORE/CONTENT container. */
|
||||||
public final class BlocksDAO {
|
public final class BlocksDAO {
|
||||||
private static volatile BlocksDAO instance;
|
private static volatile BlocksDAO instance;
|
||||||
private final DbController db = DbController.getInstance();
|
private final DbController db = DbController.getInstance();
|
||||||
|
|||||||
@@ -67,12 +67,53 @@ public final class ChannelNameStateDAO {
|
|||||||
channel_root_block_hash,
|
channel_root_block_hash,
|
||||||
created_at_ms,
|
created_at_ms,
|
||||||
ava_ar,
|
ava_ar,
|
||||||
ava_sha256,
|
ava_pr,
|
||||||
ava_size,
|
ava_size,
|
||||||
meta_updated_at_ms
|
meta_updated_at_ms
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
bindInsert(ps, entry);
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Используется только при воспроизведении уже подписанной истории. В live AddBlock
|
||||||
|
* дубликат имени запрещён; при replay блок всё же нужно сохранить, иначе цепочка
|
||||||
|
* после него останется разорванной.
|
||||||
|
*/
|
||||||
|
public void insertOrReplaceWithNewerRoot(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||||
|
String sql = """
|
||||||
|
INSERT INTO channel_names_state (
|
||||||
|
slug, display_name, channel_description, owner_login, owner_bch_name,
|
||||||
|
channel_type_code, channel_type_version, channel_root_block_number,
|
||||||
|
channel_root_block_hash, created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (owner_bch_name, channel_type_code, slug) DO UPDATE SET
|
||||||
|
display_name = EXCLUDED.display_name,
|
||||||
|
channel_description = EXCLUDED.channel_description,
|
||||||
|
owner_login = EXCLUDED.owner_login,
|
||||||
|
channel_type_version = EXCLUDED.channel_type_version,
|
||||||
|
channel_root_block_number = EXCLUDED.channel_root_block_number,
|
||||||
|
channel_root_block_hash = EXCLUDED.channel_root_block_hash,
|
||||||
|
created_at_ms = EXCLUDED.created_at_ms,
|
||||||
|
ava_ar = EXCLUDED.ava_ar,
|
||||||
|
ava_pr = EXCLUDED.ava_pr,
|
||||||
|
ava_size = EXCLUDED.ava_size,
|
||||||
|
meta_updated_at_ms = EXCLUDED.meta_updated_at_ms,
|
||||||
|
is_deleted = FALSE,
|
||||||
|
deleted_at_ms = 0,
|
||||||
|
deleted_block_number = NULL
|
||||||
|
WHERE EXCLUDED.channel_root_block_number > channel_names_state.channel_root_block_number
|
||||||
|
""";
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
bindInsert(ps, entry);
|
||||||
|
ps.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void bindInsert(PreparedStatement ps, ChannelNameStateEntry entry) throws SQLException {
|
||||||
ps.setString(1, entry.getSlug());
|
ps.setString(1, entry.getSlug());
|
||||||
ps.setString(2, entry.getDisplayName());
|
ps.setString(2, entry.getDisplayName());
|
||||||
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
||||||
@@ -84,11 +125,9 @@ public final class ChannelNameStateDAO {
|
|||||||
ps.setBytes(9, entry.getChannelRootBlockHash());
|
ps.setBytes(9, entry.getChannelRootBlockHash());
|
||||||
ps.setLong(10, entry.getCreatedAtMs());
|
ps.setLong(10, entry.getCreatedAtMs());
|
||||||
ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr());
|
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(13, Math.max(0L, entry.getAvaSize()));
|
||||||
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
||||||
ps.executeUpdate();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
|
||||||
@@ -97,7 +136,7 @@ public final class ChannelNameStateDAO {
|
|||||||
SET display_name = ?,
|
SET display_name = ?,
|
||||||
channel_description = ?,
|
channel_description = ?,
|
||||||
ava_ar = ?,
|
ava_ar = ?,
|
||||||
ava_sha256 = ?,
|
ava_pr = ?,
|
||||||
ava_size = ?,
|
ava_size = ?,
|
||||||
meta_updated_at_ms = ?
|
meta_updated_at_ms = ?
|
||||||
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
|
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(1, entry.getDisplayName() == null ? "" : entry.getDisplayName());
|
||||||
ps.setString(2, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
ps.setString(2, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
|
||||||
ps.setString(3, entry.getAvaAr() == null ? "" : entry.getAvaAr());
|
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(5, Math.max(0L, entry.getAvaSize()));
|
||||||
ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs()));
|
||||||
ps.setString(7, entry.getOwnerLogin());
|
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.
|
* Recomputes server-owned unread counters for all public channels owned by one logical login.
|
||||||
* Signed read_count/read signature fields are preserved exactly. Safe to call repeatedly after replay.
|
* Clamp the effective read_count to the rebuilt history; invalidate a signature
|
||||||
|
* when its stored count changes. Keep the last accepted timestamp to reject stale requests.
|
||||||
*/
|
*/
|
||||||
public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException {
|
public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException {
|
||||||
String sql = """
|
String sql = """
|
||||||
@@ -317,6 +318,8 @@ public final class ChannelReadStateDAO {
|
|||||||
)
|
)
|
||||||
UPDATE channel_read_state crs
|
UPDATE channel_read_state crs
|
||||||
SET unread_count=GREATEST(0, counts.message_count-crs.read_count),
|
SET unread_count=GREATEST(0, counts.message_count-crs.read_count),
|
||||||
|
read_count=LEAST(crs.read_count, counts.message_count),
|
||||||
|
read_signature=CASE WHEN crs.read_count>counts.message_count THEN '' ELSE crs.read_signature END,
|
||||||
updated_at_ms=?
|
updated_at_ms=?
|
||||||
FROM counts
|
FROM counts
|
||||||
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
|
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ public final class ChannelSearchDAO {
|
|||||||
private ChannelSearchDAO() {}
|
private ChannelSearchDAO() {}
|
||||||
|
|
||||||
public record Match(String ownerLogin, String slug, String displayName, String description,
|
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) {}
|
int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {}
|
||||||
|
|
||||||
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
|
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
|
||||||
@@ -45,7 +45,7 @@ public final class ChannelSearchDAO {
|
|||||||
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
|
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description,
|
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,
|
cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash,
|
||||||
COALESCE(cs.subscribers_count, 0) AS subscribers_count
|
COALESCE(cs.subscribers_count, 0) AS subscribers_count
|
||||||
FROM channel_names_state cn
|
FROM channel_names_state cn
|
||||||
@@ -109,7 +109,7 @@ public final class ChannelSearchDAO {
|
|||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
while (rs.next()) matches.add(new Match(
|
while (rs.next()) matches.add(new Match(
|
||||||
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"),
|
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("owner_bch_name"), rs.getInt("channel_root_block_number"),
|
||||||
rs.getString("root_hash"), rs.getInt("subscribers_count")
|
rs.getString("root_hash"), rs.getInt("subscribers_count")
|
||||||
));
|
));
|
||||||
|
|||||||
@@ -164,9 +164,9 @@ public final class ConnectionsStateDAO {
|
|||||||
""";
|
""";
|
||||||
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, login);
|
ps.setString(1, login.trim().toLowerCase(java.util.Locale.ROOT));
|
||||||
ps.setInt(2, relType);
|
ps.setInt(2, relType);
|
||||||
ps.setString(3, toLogin);
|
ps.setString(3, toLogin.trim().toLowerCase(java.util.Locale.ROOT));
|
||||||
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
||||||
ps.setBytes(5, toBlockHash);
|
ps.setBytes(5, toBlockHash);
|
||||||
ps.executeUpdate();
|
ps.executeUpdate();
|
||||||
|
|||||||
@@ -213,7 +213,7 @@ public final class CurrentUsersDAO {
|
|||||||
String sql = """
|
String sql = """
|
||||||
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
||||||
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
|
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
|
||||||
FROM solana_user_pda_current su
|
FROM user_identity_current su
|
||||||
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
|
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
|
||||||
WHERE (? IS NULL OR su.is_server = ?)
|
WHERE (? IS NULL OR su.is_server = ?)
|
||||||
AND (
|
AND (
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package shine.db.dao;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
/** Единая авторитетная проекция: FREE_CERT не притворяется Solana PDA. */
|
||||||
|
public final class RegistrationIdentityDAO {
|
||||||
|
public record ResolvedIdentity(String fullLogin, String rootKey, String blockchainKey,
|
||||||
|
String clientKey, String registrationSource, String registrationStatus,
|
||||||
|
String namespace, String accessServerLogin, boolean hasSolanaPda) {
|
||||||
|
public boolean isFree() { return "FREE_CERT".equals(registrationStatus); }
|
||||||
|
}
|
||||||
|
private static final RegistrationIdentityDAO INSTANCE = new RegistrationIdentityDAO();
|
||||||
|
public static RegistrationIdentityDAO getInstance() { return INSTANCE; }
|
||||||
|
private RegistrationIdentityDAO() {}
|
||||||
|
|
||||||
|
public ResolvedIdentity get(String login) throws SQLException {
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) { return get(c, login); }
|
||||||
|
}
|
||||||
|
public ResolvedIdentity get(Connection c, String login) throws SQLException {
|
||||||
|
if (login == null || login.isBlank()) return null;
|
||||||
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT i.login, i.root_key, i.blockchain_key, i.client_key,
|
||||||
|
i.registration_source, i.registration_status, i.namespace,
|
||||||
|
i.solana_pda_address, n.default_server_login,
|
||||||
|
s.server_login AS actual_access_server
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||||
|
LEFT JOIN user_access_servers_current s ON s.user_login=i.login
|
||||||
|
WHERE i.normalized_login=LOWER(BTRIM(?))
|
||||||
|
ORDER BY s.server_login ASC
|
||||||
|
LIMIT 1
|
||||||
|
""")) {
|
||||||
|
ps.setString(1, login);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (!rs.next()) return null;
|
||||||
|
boolean hasPda = rs.getString("solana_pda_address") != null;
|
||||||
|
String status = rs.getString("registration_status");
|
||||||
|
String server = "FREE_CERT".equals(status) ? rs.getString("default_server_login")
|
||||||
|
: rs.getString("actual_access_server");
|
||||||
|
if ("FREE_CERT".equals(status) && hasPda)
|
||||||
|
throw new SQLException("Inconsistent free user: Solana PDA must be absent");
|
||||||
|
if (!"FREE_CERT".equals(status) && !hasPda)
|
||||||
|
throw new SQLException("Inconsistent paid user: Solana PDA is missing");
|
||||||
|
return new ResolvedIdentity(rs.getString("login"), rs.getString("root_key"),
|
||||||
|
rs.getString("blockchain_key"), rs.getString("client_key"),
|
||||||
|
rs.getString("registration_source"), status, rs.getString("namespace"), server, hasPda);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public boolean isFreeCertificate(String login) throws SQLException {
|
||||||
|
ResolvedIdentity identity = get(login);
|
||||||
|
return identity != null && identity.isFree();
|
||||||
|
}
|
||||||
|
}
|
||||||
+19
-3
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
|
|||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, blockchainName);
|
ps.setString(1, blockchainName);
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
if (!rs.next()) {
|
if (rs.next()) return mapRow(rs);
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ public final class SubscriptionsDAO {
|
|||||||
FROM connections_state cs
|
FROM connections_state cs
|
||||||
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
|
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
|
||||||
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
|
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
|
||||||
WHERE cs.login = ? AND cs.rel_type = ?
|
WHERE LOWER(cs.login) = LOWER(?) AND cs.rel_type = ?
|
||||||
|
|
||||||
UNION
|
UNION
|
||||||
|
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
package shine.db.dao;
|
|
||||||
|
|
||||||
import shine.db.DbController;
|
|
||||||
import shine.db.entities.TestFreeAvatarUploadEntry;
|
|
||||||
|
|
||||||
import java.sql.Connection;
|
|
||||||
import java.sql.PreparedStatement;
|
|
||||||
import java.sql.ResultSet;
|
|
||||||
import java.sql.SQLException;
|
|
||||||
|
|
||||||
public final class TestFreeAvatarUploadsDAO {
|
|
||||||
|
|
||||||
private static volatile TestFreeAvatarUploadsDAO instance;
|
|
||||||
private final DbController db = DbController.getInstance();
|
|
||||||
|
|
||||||
private TestFreeAvatarUploadsDAO() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public static TestFreeAvatarUploadsDAO getInstance() {
|
|
||||||
if (instance == null) {
|
|
||||||
synchronized (TestFreeAvatarUploadsDAO.class) {
|
|
||||||
if (instance == null) instance = new TestFreeAvatarUploadsDAO();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
public TestFreeAvatarUploadEntry getByLogin(Connection c, String login) throws SQLException {
|
|
||||||
String sql = """
|
|
||||||
SELECT login, used_count, updated_at_ms, last_tx_id
|
|
||||||
FROM test_free_avatar_uploads
|
|
||||||
WHERE LOWER(login) = LOWER(?)
|
|
||||||
LIMIT 1
|
|
||||||
""";
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
|
||||||
ps.setString(1, login);
|
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
|
||||||
if (!rs.next()) return null;
|
|
||||||
return mapRow(rs);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public TestFreeAvatarUploadEntry getByLogin(String login) throws SQLException {
|
|
||||||
try (Connection c = db.getConnection()) {
|
|
||||||
return getByLogin(c, login);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void upsertUsage(Connection c, String login, int usedCount, long updatedAtMs, String lastTxId) throws SQLException {
|
|
||||||
String sql = """
|
|
||||||
INSERT INTO test_free_avatar_uploads (login, used_count, updated_at_ms, last_tx_id)
|
|
||||||
VALUES (?, ?, ?, ?)
|
|
||||||
ON CONFLICT(login) DO UPDATE SET
|
|
||||||
used_count = excluded.used_count,
|
|
||||||
updated_at_ms = excluded.updated_at_ms,
|
|
||||||
last_tx_id = excluded.last_tx_id
|
|
||||||
""";
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
|
||||||
ps.setString(1, login);
|
|
||||||
ps.setInt(2, usedCount);
|
|
||||||
ps.setLong(3, updatedAtMs);
|
|
||||||
ps.setString(4, lastTxId);
|
|
||||||
ps.executeUpdate();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public void upsertUsage(String login, int usedCount, long updatedAtMs, String lastTxId) throws SQLException {
|
|
||||||
try (Connection c = db.getConnection()) {
|
|
||||||
upsertUsage(c, login, usedCount, updatedAtMs, lastTxId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private static TestFreeAvatarUploadEntry mapRow(ResultSet rs) throws SQLException {
|
|
||||||
return new TestFreeAvatarUploadEntry(
|
|
||||||
rs.getString("login"),
|
|
||||||
rs.getInt("used_count"),
|
|
||||||
rs.getLong("updated_at_ms"),
|
|
||||||
rs.getString("last_tx_id")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+12
-10
@@ -46,26 +46,28 @@ public final class UserAccessServersCurrentDAO {
|
|||||||
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT
|
SELECT
|
||||||
u.login AS user_login,
|
i.login AS user_login,
|
||||||
s.login AS server_login,
|
s.login AS server_login,
|
||||||
s.server_address AS server_url,
|
s.server_address AS server_url,
|
||||||
s.client_key AS server_client_key
|
s.client_key AS server_client_key
|
||||||
FROM solana_user_pda_current u
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||||
CROSS JOIN LATERAL (
|
CROSS JOIN LATERAL (
|
||||||
SELECT BTRIM(a.login_value) AS server_login
|
SELECT CASE WHEN i.registration_status = 'FREE_CERT'
|
||||||
|
THEN ns.default_server_login
|
||||||
|
ELSE (SELECT BTRIM(a.login_value)
|
||||||
FROM jsonb_array_elements_text(
|
FROM jsonb_array_elements_text(
|
||||||
CASE
|
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||||
WHEN BTRIM(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb
|
WITH ORDINALITY AS a(login_value, ord)
|
||||||
ELSE u.access_servers_json::jsonb
|
WHERE a.ord = 1)
|
||||||
END
|
END AS server_login
|
||||||
) WITH ORDINALITY AS a(login_value, ord)
|
|
||||||
WHERE a.ord = 1
|
|
||||||
) primary_access
|
) primary_access
|
||||||
JOIN solana_user_pda_current s
|
JOIN solana_user_pda_current s
|
||||||
ON s.normalized_login = LOWER(primary_access.server_login)
|
ON s.normalized_login = LOWER(primary_access.server_login)
|
||||||
AND s.is_server = TRUE
|
AND s.is_server = TRUE
|
||||||
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
||||||
WHERE u.normalized_login = LOWER(BTRIM(?))
|
WHERE i.normalized_login = LOWER(BTRIM(?))
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""";
|
""";
|
||||||
try (Connection c = db.getConnection();
|
try (Connection c = db.getConnection();
|
||||||
|
|||||||
+13
-4
@@ -10,6 +10,7 @@ import java.sql.SQLException;
|
|||||||
import java.sql.Types;
|
import java.sql.Types;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
public final class UserNotificationsStateDAO {
|
public final class UserNotificationsStateDAO {
|
||||||
private static volatile UserNotificationsStateDAO instance;
|
private static volatile UserNotificationsStateDAO instance;
|
||||||
@@ -45,7 +46,7 @@ public final class UserNotificationsStateDAO {
|
|||||||
""";
|
""";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
int i = 1;
|
int i = 1;
|
||||||
ps.setString(i++, e.getOwnerLogin());
|
ps.setString(i++, normalizedLogin(e.getOwnerLogin()));
|
||||||
ps.setString(i++, e.getNotificationKind());
|
ps.setString(i++, e.getNotificationKind());
|
||||||
ps.setLong(i++, e.getCreatedAtMs());
|
ps.setLong(i++, e.getCreatedAtMs());
|
||||||
ps.setString(i++, e.getSourceLogin());
|
ps.setString(i++, e.getSourceLogin());
|
||||||
@@ -74,7 +75,7 @@ public final class UserNotificationsStateDAO {
|
|||||||
""";
|
""";
|
||||||
List<UserNotificationEntry> out = new ArrayList<>();
|
List<UserNotificationEntry> out = new ArrayList<>();
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, ownerLogin);
|
ps.setString(1, normalizedLogin(ownerLogin));
|
||||||
ps.setString(2, kind);
|
ps.setString(2, kind);
|
||||||
ps.setInt(3, Math.max(1, limit));
|
ps.setInt(3, Math.max(1, limit));
|
||||||
try (ResultSet rs = ps.executeQuery()) {
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
@@ -96,7 +97,7 @@ public final class UserNotificationsStateDAO {
|
|||||||
""";
|
""";
|
||||||
List<UserNotificationEntry> out = new ArrayList<>();
|
List<UserNotificationEntry> out = new ArrayList<>();
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
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));
|
ps.setLong(4, Math.max(0, cutoffMs));
|
||||||
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
|
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 {
|
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 > ?";
|
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
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; }
|
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"));
|
e.setSourceText(rs.getString("source_text"));
|
||||||
return e;
|
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;
|
String sql;
|
||||||
if ("owned".equals(mode)) {
|
if ("owned".equals(mode)) {
|
||||||
sql="""
|
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.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
|
||||||
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
|
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
|
||||||
FROM channel_names_state cn
|
FROM channel_names_state cn
|
||||||
@@ -125,7 +125,7 @@ public final class UserProfileStateDAO {
|
|||||||
""";
|
""";
|
||||||
} else if ("following".equals(mode)) {
|
} else if ("following".equals(mode)) {
|
||||||
sql="""
|
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.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
|
||||||
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
|
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
|
||||||
FROM connections_state cs
|
FROM 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);
|
ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset);
|
||||||
try(ResultSet rs=ps.executeQuery()){
|
try(ResultSet rs=ps.executeQuery()){
|
||||||
while(rs.next()) out.add(new ChannelCard(
|
while(rs.next()) out.add(new ChannelCard(
|
||||||
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_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.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")
|
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"));}
|
private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));}
|
||||||
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
|
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
|
||||||
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
|
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
|
||||||
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)
|
* - login + fork_number (physical fork identity; bch_name is derived only for display/API)
|
||||||
* - block_number (глобальный номер в этой цепочке)
|
* - block_number (глобальный номер в этой цепочке)
|
||||||
* - block_bytes (полный блок: preimage + signature)
|
* - block_bytes (контейнер двух оригинальных подписанных ANS-104)
|
||||||
* - block_hash (32 байта вычисленный SHA-256(preimage))
|
* - block_hash (32 байта вычисленный SHA-256(CORE payload))
|
||||||
* - block_signature (64 байта)
|
* - block_signature (64 байта, подпись CORE)
|
||||||
*
|
*
|
||||||
* Опционально:
|
* Опционально:
|
||||||
* - line_code / prev_line_number / prev_line_hash / this_line_number
|
* - line_code / prev_line_number / prev_line_hash / this_line_number
|
||||||
|
|||||||
+7
-2
@@ -1,6 +1,7 @@
|
|||||||
package shine.db.entities;
|
package shine.db.entities;
|
||||||
|
|
||||||
import java.util.Base64;
|
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);
|
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
|
||||||
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
|
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
|
||||||
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
|
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;
|
this.forkNumber=parsedFork;
|
||||||
}
|
}
|
||||||
public int getForkNumber() { return forkNumber; }
|
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 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 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 String getBlockchainKey() { return blockchainKey; }
|
||||||
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
|
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
|
||||||
|
|||||||
+5
-5
@@ -14,7 +14,7 @@ public class ChannelNameStateEntry {
|
|||||||
private byte[] channelRootBlockHash;
|
private byte[] channelRootBlockHash;
|
||||||
private long createdAtMs;
|
private long createdAtMs;
|
||||||
private String avaAr;
|
private String avaAr;
|
||||||
private String avaSha256;
|
private String avaPr;
|
||||||
private long avaSize;
|
private long avaSize;
|
||||||
private long metaUpdatedAtMs;
|
private long metaUpdatedAtMs;
|
||||||
|
|
||||||
@@ -106,12 +106,12 @@ public class ChannelNameStateEntry {
|
|||||||
this.avaAr = avaAr;
|
this.avaAr = avaAr;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String getAvaSha256() {
|
public String getAvaPr() {
|
||||||
return avaSha256;
|
return avaPr;
|
||||||
}
|
}
|
||||||
|
|
||||||
public void setAvaSha256(String avaSha256) {
|
public void setAvaPr(String avaPr) {
|
||||||
this.avaSha256 = avaSha256;
|
this.avaPr = avaPr;
|
||||||
}
|
}
|
||||||
|
|
||||||
public long getAvaSize() {
|
public long getAvaSize() {
|
||||||
|
|||||||
-50
@@ -1,50 +0,0 @@
|
|||||||
package shine.db.entities;
|
|
||||||
|
|
||||||
public class TestFreeAvatarUploadEntry {
|
|
||||||
private String login;
|
|
||||||
private int usedCount;
|
|
||||||
private long updatedAtMs;
|
|
||||||
private String lastTxId;
|
|
||||||
|
|
||||||
public TestFreeAvatarUploadEntry() {
|
|
||||||
}
|
|
||||||
|
|
||||||
public TestFreeAvatarUploadEntry(String login, int usedCount, long updatedAtMs, String lastTxId) {
|
|
||||||
this.login = login;
|
|
||||||
this.usedCount = usedCount;
|
|
||||||
this.updatedAtMs = updatedAtMs;
|
|
||||||
this.lastTxId = lastTxId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getLogin() {
|
|
||||||
return login;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLogin(String login) {
|
|
||||||
this.login = login;
|
|
||||||
}
|
|
||||||
|
|
||||||
public int getUsedCount() {
|
|
||||||
return usedCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUsedCount(int usedCount) {
|
|
||||||
this.usedCount = usedCount;
|
|
||||||
}
|
|
||||||
|
|
||||||
public long getUpdatedAtMs() {
|
|
||||||
return updatedAtMs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUpdatedAtMs(long updatedAtMs) {
|
|
||||||
this.updatedAtMs = updatedAtMs;
|
|
||||||
}
|
|
||||||
|
|
||||||
public String getLastTxId() {
|
|
||||||
return lastTxId;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setLastTxId(String lastTxId) {
|
|
||||||
this.lastTxId = lastTxId;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -18,7 +18,7 @@ public final class CurrentUsersSql {
|
|||||||
current_users.blockchain_key AS blockchain_key,
|
current_users.blockchain_key AS blockchain_key,
|
||||||
current_users.client_key AS client_key,
|
current_users.client_key AS client_key,
|
||||||
current_users.is_server AS is_server
|
current_users.is_server AS is_server
|
||||||
FROM solana_user_pda_current current_users
|
FROM user_identity_current current_users
|
||||||
) %s
|
) %s
|
||||||
""".formatted(alias);
|
""".formatted(alias);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,213 @@
|
|||||||
|
-- SHiNE DB v33: общий индекс идентичностей, namespace и сертификаты.
|
||||||
|
-- ТОЛЬКО dev/test до проверки всей серверной авторизации.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE TABLE user_identity_current (
|
||||||
|
login TEXT PRIMARY KEY,
|
||||||
|
normalized_login TEXT NOT NULL UNIQUE,
|
||||||
|
namespace TEXT,
|
||||||
|
registration_source TEXT NOT NULL CHECK (registration_source IN ('SOLANA', 'ARWEAVE')),
|
||||||
|
registration_status TEXT NOT NULL CHECK (registration_status IN ('PAID_DIRECT', 'FREE_CERT', 'PAID_UPGRADED')),
|
||||||
|
solana_pda_address TEXT UNIQUE,
|
||||||
|
free_data_item_id TEXT UNIQUE,
|
||||||
|
root_key TEXT NOT NULL,
|
||||||
|
client_key TEXT NOT NULL,
|
||||||
|
blockchain_key TEXT NOT NULL,
|
||||||
|
blockchain_name TEXT NOT NULL,
|
||||||
|
is_server BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
registered_at_ms BIGINT NOT NULL,
|
||||||
|
updated_at_ms BIGINT NOT NULL,
|
||||||
|
CHECK ((registration_status = 'FREE_CERT' AND solana_pda_address IS NULL AND free_data_item_id IS NOT NULL)
|
||||||
|
OR (registration_status <> 'FREE_CERT' AND solana_pda_address IS NOT NULL))
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_user_identity_namespace ON user_identity_current(namespace);
|
||||||
|
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, root_key, client_key, blockchain_key, blockchain_name,
|
||||||
|
is_server, registered_at_ms, updated_at_ms
|
||||||
|
)
|
||||||
|
SELECT login, normalized_login,
|
||||||
|
CASE WHEN position('@' in login) > 0 THEN split_part(login, '@', 2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID_DIRECT', pda_address, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, created_at_ms, updated_at_ms
|
||||||
|
FROM solana_user_pda_current
|
||||||
|
ON CONFLICT (login) DO NOTHING;
|
||||||
|
|
||||||
|
CREATE TABLE shine_namespace_current (
|
||||||
|
namespace TEXT PRIMARY KEY,
|
||||||
|
pda_address TEXT NOT NULL UNIQUE,
|
||||||
|
namespace_type SMALLINT NOT NULL CHECK(namespace_type IN (1,2)),
|
||||||
|
min_localpart_len SMALLINT NOT NULL CHECK (min_localpart_len BETWEEN 1 AND 30),
|
||||||
|
registration_fee_lamports NUMERIC(20,0) NOT NULL CHECK (registration_fee_lamports >= 0),
|
||||||
|
registrar_pubkey TEXT,
|
||||||
|
default_server_login TEXT,
|
||||||
|
slot BIGINT NOT NULL,
|
||||||
|
last_tx_signature TEXT NOT NULL DEFAULT '',
|
||||||
|
raw_data_base64 TEXT NOT NULL,
|
||||||
|
CHECK ((namespace_type = 1 AND registrar_pubkey IS NULL AND default_server_login IS NULL)
|
||||||
|
OR (namespace_type = 2 AND registrar_pubkey IS NOT NULL AND default_server_login IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE free_registration_certificate (
|
||||||
|
data_item_id TEXT PRIMARY KEY,
|
||||||
|
login TEXT NOT NULL UNIQUE REFERENCES user_identity_current(login),
|
||||||
|
namespace TEXT NOT NULL REFERENCES shine_namespace_current(namespace),
|
||||||
|
email_sha256 BYTEA NOT NULL UNIQUE CHECK (octet_length(email_sha256) = 32),
|
||||||
|
inner_signature BYTEA NOT NULL CHECK (octet_length(inner_signature) = 64),
|
||||||
|
raw_signed_data_item BYTEA NOT NULL,
|
||||||
|
publication_status TEXT NOT NULL CHECK (publication_status IN ('TURBO_ACCEPTED','ARWEAVE_SEEN','ARWEAVE_CONFIRMED')),
|
||||||
|
registered_at_ms BIGINT NOT NULL,
|
||||||
|
last_seen_at_ms BIGINT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_free_registration_namespace ON free_registration_certificate(namespace);
|
||||||
|
|
||||||
|
-- Существующие объекты (в том числе десятки FK) должны ссылаться на логическую
|
||||||
|
-- идентичность, иначе бесплатный пользователь не сможет иметь профиль/связи/каналы.
|
||||||
|
-- Воссоздаём существующие FK с теми же ON DELETE/UPDATE и deferrable-настройками.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
item RECORD;
|
||||||
|
definition TEXT;
|
||||||
|
BEGIN
|
||||||
|
FOR item IN SELECT c.conname, c.conrelid::regclass AS child_table,
|
||||||
|
pg_get_constraintdef(c.oid) AS definition
|
||||||
|
FROM pg_constraint c
|
||||||
|
WHERE c.contype = 'f' AND c.confrelid = 'solana_user_pda_current'::regclass
|
||||||
|
LOOP
|
||||||
|
definition := replace(item.definition,
|
||||||
|
'REFERENCES solana_user_pda_current(', 'REFERENCES user_identity_current(');
|
||||||
|
IF definition = item.definition THEN
|
||||||
|
RAISE EXCEPTION 'Unexpected FK expression: %', item.definition;
|
||||||
|
END IF;
|
||||||
|
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', item.child_table, item.conname);
|
||||||
|
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I %s', item.child_table, item.conname, definition);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Любое поступившее из Solana состояние дополняет существующую идентичность.
|
||||||
|
-- Бесплатный → платный допускается ТОЛЬКО при совпадении всех публичных ключей;
|
||||||
|
-- старые on-chain key rotations разрешены, если статус уже платный.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
|
||||||
|
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', CASE WHEN old_user.free_data_item_id IS NOT NULL THEN 'PAID_UPGRADED' ELSE 'PAID_DIRECT' END,
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER trg_sync_identity_from_solana
|
||||||
|
BEFORE INSERT OR UPDATE ON solana_user_pda_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_sync_identity_from_solana();
|
||||||
|
|
||||||
|
-- Free namespace: сервер доступа задаётся namespace, а не клиентским полем.
|
||||||
|
-- Реальный сервер должен иметь on-chain PDA и открытый адрес.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF p_user_login IS NULL OR btrim(p_user_login) = '' THEN RETURN; END IF;
|
||||||
|
DELETE FROM user_access_servers_current WHERE lower(user_login) = lower(p_user_login);
|
||||||
|
INSERT INTO user_access_servers_current (
|
||||||
|
user_login, server_login, server_url, server_client_key, user_record_number,
|
||||||
|
user_updated_at_ms, server_record_number, server_updated_at_ms, refreshed_at_ms)
|
||||||
|
SELECT i.login, srv.login, srv.server_address, srv.client_key,
|
||||||
|
COALESCE(u.record_number, 0), i.updated_at_ms,
|
||||||
|
srv.record_number, srv.updated_at_ms,
|
||||||
|
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||||
|
CROSS JOIN LATERAL (
|
||||||
|
SELECT CASE WHEN i.registration_status = 'FREE_CERT' THEN ns.default_server_login
|
||||||
|
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||||
|
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||||
|
WITH ORDINALITY AS a(value, position) WHERE position=1) END AS login
|
||||||
|
) effective
|
||||||
|
JOIN solana_user_pda_current srv
|
||||||
|
ON lower(srv.login) = lower(effective.login) AND srv.is_server = true
|
||||||
|
AND btrim(coalesce(srv.server_address, '')) <> ''
|
||||||
|
WHERE lower(i.login) = lower(p_user_login)
|
||||||
|
ON CONFLICT (user_login, server_login) DO UPDATE SET
|
||||||
|
server_url=EXCLUDED.server_url, server_client_key=EXCLUDED.server_client_key,
|
||||||
|
user_record_number=EXCLUDED.user_record_number,
|
||||||
|
user_updated_at_ms=EXCLUDED.user_updated_at_ms,
|
||||||
|
server_record_number=EXCLUDED.server_record_number,
|
||||||
|
server_updated_at_ms=EXCLUDED.server_updated_at_ms,
|
||||||
|
refreshed_at_ms=EXCLUDED.refreshed_at_ms;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_server(p_server_login TEXT)
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE u RECORD;
|
||||||
|
BEGIN
|
||||||
|
IF p_server_login IS NULL OR btrim(p_server_login) = '' THEN RETURN; END IF;
|
||||||
|
DELETE FROM user_access_servers_current WHERE lower(server_login) = lower(p_server_login);
|
||||||
|
FOR u IN
|
||||||
|
SELECT i.login FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current p ON p.login=i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace=i.namespace
|
||||||
|
WHERE lower(p_server_login) = lower(
|
||||||
|
CASE WHEN i.registration_status='FREE_CERT' THEN ns.default_server_login
|
||||||
|
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||||
|
COALESCE(NULLIF(p.access_servers_json,''),'[]')::jsonb)
|
||||||
|
WITH ORDINALITY AS a(value, position) WHERE position=1) END)
|
||||||
|
LOOP PERFORM shine_refresh_user_access_servers_for_user(u.login); END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_all()
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE u RECORD;
|
||||||
|
BEGIN
|
||||||
|
TRUNCATE TABLE user_access_servers_current;
|
||||||
|
FOR u IN SELECT login FROM user_identity_current LOOP
|
||||||
|
PERFORM shine_refresh_user_access_servers_for_user(u.login);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_free_routing_from_identity()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.registration_status = 'FREE_CERT' THEN
|
||||||
|
PERFORM shine_refresh_user_access_servers_for_user(NEW.login);
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER trg_refresh_free_routing_from_identity
|
||||||
|
AFTER INSERT OR UPDATE ON user_identity_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_refresh_free_routing_from_identity();
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version=33,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- SHiNE v34. Отдельный checkpoint Arweave сертификатов, не смешивать с блоками.
|
||||||
|
BEGIN;
|
||||||
|
CREATE TABLE IF NOT EXISTS free_registration_arweave_sync_state (
|
||||||
|
id SMALLINT PRIMARY KEY CHECK (id=1),
|
||||||
|
last_block_height BIGINT NOT NULL DEFAULT 0 CHECK (last_block_height>=0),
|
||||||
|
updated_at_ms BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
INSERT INTO free_registration_arweave_sync_state (id,last_block_height,updated_at_ms)
|
||||||
|
VALUES (1,0,0) ON CONFLICT (id) DO NOTHING;
|
||||||
|
UPDATE db_schema_version SET schema_version=34,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
-- v35: один полноценный статус для всех зарегистрированных в Solana.
|
||||||
|
-- Старые регистрационные сертификаты Arweave и дата исходной регистрации сохраняются.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- Сначала снимаем старое ограничение, затем переводим существующие строки.
|
||||||
|
ALTER TABLE user_identity_current
|
||||||
|
DROP CONSTRAINT user_identity_current_registration_status_check;
|
||||||
|
UPDATE user_identity_current
|
||||||
|
SET registration_status = 'PAID'
|
||||||
|
WHERE registration_status IN ('PAID_DIRECT', 'PAID_UPGRADED');
|
||||||
|
ALTER TABLE user_identity_current
|
||||||
|
ADD CONSTRAINT user_identity_current_registration_status_check
|
||||||
|
CHECK (registration_status IN ('FREE_CERT', 'PAID'));
|
||||||
|
|
||||||
|
-- Важнее миграции существующих строк: при следующих Solana sync/upsert
|
||||||
|
-- и обычный платный, и ранее бесплатный пользователь получают тот же PAID.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
|
||||||
|
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID',
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version
|
||||||
|
SET schema_version=35,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)
|
||||||
|
WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- v36: регистрационная запись хранит исходный регистр; все ссылки FK
|
||||||
|
-- приводятся к её точному login. Исторические строки не мигрируются.
|
||||||
|
-- На новой базе исходные имена PDA/сертификатов и FK согласованы.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_canonicalize_identity_fk_login()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
field_name TEXT := TG_ARGV[0];
|
||||||
|
requested_login TEXT;
|
||||||
|
canonical_login TEXT;
|
||||||
|
BEGIN
|
||||||
|
requested_login := to_jsonb(NEW)->>field_name;
|
||||||
|
IF requested_login IS NULL OR btrim(requested_login) = '' THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT i.login INTO canonical_login
|
||||||
|
FROM user_identity_current i
|
||||||
|
WHERE i.normalized_login = lower(btrim(requested_login))
|
||||||
|
LIMIT 1;
|
||||||
|
IF canonical_login IS NOT NULL THEN
|
||||||
|
-- Меняем только проекцию/связь в SQL, никогда не байты подписанного блока.
|
||||||
|
NEW := jsonb_populate_record(NEW, jsonb_build_object(field_name, canonical_login));
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
tab_name TEXT;
|
||||||
|
col_name TEXT;
|
||||||
|
spec TEXT;
|
||||||
|
trigger_name TEXT;
|
||||||
|
BEGIN
|
||||||
|
FOREACH spec IN ARRAY ARRAY[
|
||||||
|
'user_access_servers_current:user_login',
|
||||||
|
'user_access_servers_current:server_login',
|
||||||
|
'active_sessions:login',
|
||||||
|
'esp_pairing_settings:login',
|
||||||
|
'esp_pairing_requests:login',
|
||||||
|
'users_params:login',
|
||||||
|
'user_settings:login',
|
||||||
|
'channel_read_state:viewer_login',
|
||||||
|
'test_free_avatar_uploads:login',
|
||||||
|
-- blockchain_state — compatibility view; trigger может существовать
|
||||||
|
-- только на физической таблице хранения.
|
||||||
|
'blockchain_state_store:login',
|
||||||
|
'user_stats_state:login',
|
||||||
|
'user_push_tokens:login',
|
||||||
|
'key_rotation_sessions:login'
|
||||||
|
] LOOP
|
||||||
|
tab_name := split_part(spec, ':', 1);
|
||||||
|
col_name := split_part(spec, ':', 2);
|
||||||
|
trigger_name := 'trg_canonical_identity_' || tab_name || '_' || col_name;
|
||||||
|
EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I', trigger_name, tab_name);
|
||||||
|
EXECUTE format(
|
||||||
|
'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OF %I ON %I FOR EACH ROW EXECUTE FUNCTION shine_canonicalize_identity_fk_login(%L)',
|
||||||
|
trigger_name, col_name, tab_name, col_name
|
||||||
|
);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version = 36,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
-- v37: оригинальный регистр имени фиксируется при первой регистрации.
|
||||||
|
-- Нормализованное имя остаётся единственным ключом уникальности.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_identity_login_immutable()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'UPDATE' AND (NEW.login IS DISTINCT FROM OLD.login
|
||||||
|
OR NEW.normalized_login IS DISTINCT FROM OLD.normalized_login) THEN
|
||||||
|
RAISE EXCEPTION 'Registered login spelling is immutable: %', OLD.login;
|
||||||
|
END IF;
|
||||||
|
IF NEW.normalized_login IS DISTINCT FROM lower(btrim(NEW.login)) THEN
|
||||||
|
RAISE EXCEPTION 'normalized_login must match registered login: %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS trg_identity_login_immutable ON user_identity_current;
|
||||||
|
CREATE TRIGGER trg_identity_login_immutable
|
||||||
|
BEFORE INSERT OR UPDATE ON user_identity_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_identity_login_immutable();
|
||||||
|
|
||||||
|
-- FREE_CERT -> Solana: имя должно совпадать побайтно, включая регистр.
|
||||||
|
-- Источником имени остаётся первая регистрация, а не очередная синхронизация.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.login <> NEW.login THEN
|
||||||
|
RAISE EXCEPTION 'Registered login case mismatch: % vs %', old_user.login, NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID',
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version = 37,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- v38: blockchain_state_store.blockchain_key — runtime Base64(32).
|
||||||
|
-- Исторические Base58-значения нормализуются Java bootstrapper-ом,
|
||||||
|
-- поскольку PostgreSQL не содержит встроенного корректного Base58 decoder.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
UPDATE db_schema_version
|
||||||
|
SET schema_version = 38,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- SHiNE DB v39: допускает временный opt-in на повторное использование email
|
||||||
|
-- для free-регистрации. По умолчанию это всё равно запрещено проверками runtime.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
ALTER TABLE free_registration_certificate
|
||||||
|
DROP CONSTRAINT IF EXISTS free_registration_certificate_email_sha256_key;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_free_registration_email_sha256
|
||||||
|
ON free_registration_certificate(email_sha256);
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version = 39 WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
-- SHiNE DB v40: код валюты и актуализация стоимости namespace.
|
||||||
|
-- Исторический namespace 1.0 не содержит currency_code и означает SOL (код 1).
|
||||||
|
BEGIN;
|
||||||
|
ALTER TABLE shine_namespace_current
|
||||||
|
ADD COLUMN currency_code SMALLINT NOT NULL DEFAULT 1
|
||||||
|
CHECK (currency_code = 1);
|
||||||
|
UPDATE db_schema_version SET schema_version = 40 WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -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;
|
||||||
@@ -2334,11 +2334,15 @@ CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_blo
|
|||||||
|
|
||||||
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
||||||
|
v_canonical_login TEXT;
|
||||||
BEGIN
|
BEGIN
|
||||||
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
||||||
|
-- В FK остаётся исходный регистр владельца, но поиск/сопоставления регистронезависимы.
|
||||||
|
SELECT login INTO v_canonical_login FROM user_identity_current WHERE normalized_login=lower(btrim(p_login)) LIMIT 1;
|
||||||
|
IF v_canonical_login IS NULL THEN RETURN; END IF;
|
||||||
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
||||||
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
||||||
SELECT p_login,
|
SELECT v_canonical_login,
|
||||||
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
||||||
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||||
@@ -2485,15 +2489,15 @@ DECLARE positive_rel_type INTEGER; channel_bch TEXT;
|
|||||||
BEGIN
|
BEGIN
|
||||||
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
|
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
|
||||||
DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=NEW.msg_sub_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
|
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
|
||||||
VALUES(NEW.login,NEW.msg_sub_type,NEW.to_login,NEW.to_block_number,NEW.to_block_hash);
|
VALUES(lower(NEW.login),NEW.msg_sub_type,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash);
|
||||||
ELSE
|
ELSE
|
||||||
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
|
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
|
||||||
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=positive_rel_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
||||||
END IF;
|
END IF;
|
||||||
PERFORM shine_refresh_user_stats(NEW.login);
|
PERFORM shine_refresh_user_stats(lower(NEW.login));
|
||||||
PERFORM shine_refresh_user_stats(NEW.to_login);
|
PERFORM shine_refresh_user_stats(lower(NEW.to_login));
|
||||||
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
|
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
|
||||||
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
|
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
|
||||||
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
|
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
|
||||||
@@ -2506,22 +2510,22 @@ DECLARE previous_sub_type INTEGER;
|
|||||||
BEGIN
|
BEGIN
|
||||||
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
|
||||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash)
|
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash)
|
||||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
|
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
|
||||||
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=NEW.login AND reaction_type=1 AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=lower(NEW.login) AND reaction_type=1 AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
||||||
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
|
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
|
||||||
UPDATE message_stats SET likes_count=likes_count+1,
|
UPDATE message_stats SET likes_count=likes_count+1,
|
||||||
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
|
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
|
||||||
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
|
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
|
||||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
|
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
|
||||||
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
|
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
|
||||||
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
|
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
|
||||||
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
|
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
|
||||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
END IF;
|
END IF;
|
||||||
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
|
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
|
||||||
VALUES(NEW.login,1,NEW.to_login,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
VALUES(lower(NEW.login),1,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
||||||
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
|
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
|
||||||
RETURN NEW;
|
RETURN NEW;
|
||||||
END $$;
|
END $$;
|
||||||
@@ -2532,7 +2536,7 @@ BEGIN
|
|||||||
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
|
||||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
|
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
|
||||||
VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash,1)
|
VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,1)
|
||||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
|
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
|
||||||
RETURN NEW;
|
RETURN NEW;
|
||||||
END $$;
|
END $$;
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user