SHA256
Compare commits
62
Commits
ui-polish
...
97db033eb8
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
df0e9cef9b | ||
|
|
7a6ab3b35a | ||
|
|
aa5addb5d9 | ||
|
|
b67d06ce43 | ||
|
|
8d9a580f50 | ||
|
|
45eb77f431 | ||
|
|
2be6fe3ff9 | ||
|
|
a380900ec8 | ||
|
|
e77aaa3675 | ||
|
|
d25894149b |
+20
@@ -116,3 +116,23 @@ SHiNE-bundle-*.zip
|
||||
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
||||
*.bak.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,27 @@
|
||||
# AGENTS
|
||||
# Инструкции для агентов SHiNE
|
||||
|
||||
## Язык проекта
|
||||
- По умолчанию использовать русский язык во всех пользовательских текстах и технических пояснениях.
|
||||
- Пояснения к коммитам, 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 деплоя.
|
||||
| Область | Код | Правила и документация |
|
||||
| --- | --- | --- |
|
||||
| Сервер, WebSocket/API, PostgreSQL | `SHiNE-server/` | `SHiNE-server/AGENTS.md`, `docs/API/` |
|
||||
| Блокчейн, Arweave | `SHiNE-server/shine-server-blockchain/` | `docs/Blockchain/README.md` |
|
||||
| Личные сообщения | сервер и `shine-UI/` | `docs/Personal_Messages/README.md`, локальный `AGENTS.md` |
|
||||
| Браузерный UI | `shine-UI/` | `shine-UI/AGENTS.md`, `docs/UI-Design/README.md` |
|
||||
| Solana/Anchor | `shine-solana/shine/` | локальный `AGENTS.md`, `docs/Solana_Architecture/README.md` |
|
||||
| ESP32 | `ESP32/` | `ESP32/AGENTS.md`, инструкции конкретного устройства |
|
||||
| Деплой и резервные копии | `deploy/` | `deploy/AGENTS.md`, `deploy/backup/AGENTS.md` |
|
||||
| Тестовый издатель | `tools/test-publisher/` | локальный `AGENTS.md` |
|
||||
|
||||
## Сервис агента-кодера
|
||||
- Локальный 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`.
|
||||
Общий каталог — `docs/README.md`; карта компонентов и потоков данных — `docs/ARCHITECTURE.md`. Правила сопровождения документов — `docs/CONTRIBUTING_DOCS.md`; после правки документации запускать `python3 scripts/check_docs.py`. Планы в `TODO/` не считать описанием действующего поведения или разрешением на реализацию.
|
||||
|
||||
## ESP32 UI homeserver
|
||||
- Для UI-скетча устройства `ESP32-S3-Touch-AMOLED-2.16` документ-спецификация и Arduino-скетч должны всегда оставаться синхронными.
|
||||
- Актуальный документ по экранной логике, состояниям, кнопкам, полям, статусам и ограничениям UI считать источником истины для скетча.
|
||||
- При изменении документа обязательно в том же наборе изменений приводить в соответствие скетч.
|
||||
- При изменении скетча обязательно в том же наборе изменений обновлять документ, если поменялись экраны, тексты, переходы, статусы, кнопки, поля или поведение.
|
||||
- Для нового ESP32 UI-прототипа homeserver использовать русский язык как основной и отдельно следить, чтобы текст реально отображался на устройстве, а не только логически присутствовал в коде.
|
||||
## Постоянные правила
|
||||
|
||||
## Solana-модуль
|
||||
- В проекте есть отдельный Solana/Anchor-модуль в папке `shine-solana/shine/`.
|
||||
- Модуль логически связан с SHiNE, но не должен автоматически подключаться к сборке или деплою основного сервера без отдельного решения.
|
||||
- В Solana-модуле действуют локальные инструкции `shine-solana/shine/AGENTS.md`; при изменениях внутри модуля сначала читать их.
|
||||
- В git добавлять исходники, lock-файлы, настройки проекта и документацию Solana-модуля, но не добавлять локальные ключи, `.git`, `.idea`, `.gradle`, `target`, `node_modules`, `test-ledger`, логи, временные run-отчёты и `.env`-конфиги.
|
||||
- Для Solana deploy/push использовать правила из локального `shine-solana/shine/AGENTS.md`; не смешивать deploy Solana-модуля со скриптами основного server/UI deploy из `deploy/scripts/`.
|
||||
- Для регистрации пользователей в Solana (программа `shine_users`) единая актуальная инструкция по деплою/инициализации, адресам программ, и куда их прописывать в UI/сервере находится в:
|
||||
- `docs/Инициализация_Solana_регистрации/README.md`
|
||||
- Этот файл считать основной справкой (single source of truth) по деплою и первичной инициализации Solana-регистрации в текущем проекте.
|
||||
- Актуальная архитектурная справка по устройству Solana-программ, PDA-счетам, ролям DAO и движению средств находится в:
|
||||
- `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/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 сервера
|
||||
- Актуальная документация по публичному JSON/WebSocket API сервера находится в `docs/API/`.
|
||||
- При любом изменении серверного API/эндпоинтов/операций `op` обязательно обновлять соответствующие документы в `docs/API/`.
|
||||
- Перед изменением самого серверного API обязательно явно предупредить пользователя, какие операции, поля запросов/ответов или коды ошибок будут изменены, и запросить отдельное подтверждение.
|
||||
- Без явного подтверждения пользователя формат серверного API не менять; допускается только приведение документации в соответствие уже существующему коду.
|
||||
- Если добавляется новая операция `op`, нужно обновить общий список операций в `docs/API/09_Operations_Index.md` или создать его, если файла ещё нет.
|
||||
|
||||
## Документация 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-файле подробно описывать:
|
||||
- какие файлы и участки отключены;
|
||||
- что осталось в коде как заготовка;
|
||||
- какие документы нужно обновить при возврате;
|
||||
- с какого сценария продолжать разработку;
|
||||
- из какого коммита брать последнюю полную реализацию.
|
||||
|
||||
## Коммуникация по новым задачам
|
||||
- При получении нового задания кратко подтвердить понимание задачи, если это помогает синхронизироваться.
|
||||
- До начала реализации задавать уточняющие вопросы только когда без ответа есть риск сделать не то или затронуть опасную область.
|
||||
- Если задача понятна и не требует отдельного подтверждения по другим правилам проекта, переходить к реализации сразу.
|
||||
- Если есть уместные идеи/улучшения — кратко предложить их; если полезных идей нет, ничего дополнительно не предлагать.
|
||||
- Прежде чем править подсистему, прочитать её локальный `AGENTS.md` и действующую документацию через `docs/README.md`. Архивные отчёты и старые планы не использовать как текущий контракт. При расхождении документа с кодом проверить реализацию и исправить документ либо явно отметить неопределённость.
|
||||
- Изменение поведения, формата, API, конфигурации или пользовательского сценария сопровождать обновлением соответствующего документа в том же наборе изменений. Не выдавать план, черновик или тестовое состояние за действующую функцию.
|
||||
- Формат блокчейна и контракт серверного API изменять только после отдельного явного согласия пользователя; документировать изменения в `docs/Blockchain/` и `docs/API/`. Для добавления блока использовать `AddBlock` с актуальной вершиной цепочки.
|
||||
- Любые изменения и деплой production (`shineup.me`, `server2.shineup.me`) — только после отдельного явного согласия пользователя. Перед деплоем прочитать `deploy/AGENTS.md` и проверить резервную копию. Для деплоя использовать скрипты `deploy/scripts/`.
|
||||
- Секреты, приватные ключи, локальные конфиги, сборочные артефакты и логи не добавлять в git.
|
||||
- Коммиты, версии и merge выполнять по `COMMIT_AND_VERSION_RULES.md`. Не делать коммит или push без необходимости для задачи.
|
||||
|
||||
@@ -32,15 +32,6 @@
|
||||
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
|
||||
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
|
||||
|
||||
## Версионирование при merge или прямом коммите в `main`
|
||||
|
||||
- Для попадания изменений в `main` действует отдельная схема инкремента.
|
||||
- Нужно увеличивать вторую цифру версии и обнулять третью.
|
||||
- Пример: `1.2.346` → `1.3.0`.
|
||||
- Если в наборе изменений менялся только UI, обновлять только `client.version`.
|
||||
- Если в наборе изменений менялся только сервер, обновлять только `server.version`.
|
||||
- Если соответствующая часть не менялась, её версию не трогать.
|
||||
|
||||
## Правила для git commit и git push
|
||||
|
||||
- Обычные коммиты делать стандартным `git commit`; токен для локального коммита не нужен и не используется.
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MODE="${1:-potentiometer-adc-test}"
|
||||
PORT="${PORT:-}"
|
||||
|
||||
case "$MODE" in
|
||||
potentiometer-adc-test)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test"
|
||||
;;
|
||||
buzzer-gpio6-test)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/buzzer_gpio6_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-buzzer-gpio6-test"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown mode: $MODE" >&2
|
||||
echo "Known modes: potentiometer-adc-test, buzzer-gpio6-test" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z "$PORT" ]]; then
|
||||
PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')"
|
||||
fi
|
||||
|
||||
if [[ -z "$PORT" ]]; then
|
||||
echo "No serial port found. Set PORT=/dev/ttyACM0 explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
FQBN="esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi"
|
||||
|
||||
echo "== Mode: $MODE"
|
||||
echo "== Sketch: $SKETCH_DIR"
|
||||
echo "== Port: $PORT"
|
||||
echo "== FQBN: $FQBN"
|
||||
|
||||
arduino-cli compile \
|
||||
--fqbn "$FQBN" \
|
||||
--build-path "$BUILD_DIR" \
|
||||
"$SKETCH_DIR"
|
||||
|
||||
arduino-cli upload \
|
||||
--fqbn "$FQBN" \
|
||||
-p "$PORT" \
|
||||
--input-dir "$BUILD_DIR" \
|
||||
"$SKETCH_DIR"
|
||||
|
||||
echo
|
||||
echo "== Done."
|
||||
@@ -0,0 +1,3 @@
|
||||
# AGENTS
|
||||
|
||||
This folder contains a temporary GPIO6 buzzer diagnostic for ESP32-S3-LCD-2. Keep screen/serial strings in English.
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
// Buzzer module wiring: GND -> GND, VCC -> 3V3, I/O -> P1 IO6 / GPIO6.
|
||||
static constexpr uint8_t PIN_BUZZER = 6;
|
||||
static constexpr uint32_t STEP_MS = 1800;
|
||||
static uint8_t gStep = 0;
|
||||
static uint32_t gChangedMs = 0;
|
||||
|
||||
static void applyStep(uint8_t step) {
|
||||
ledcDetach(PIN_BUZZER);
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
delay(80);
|
||||
switch (step) {
|
||||
case 0:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, HIGH);
|
||||
Serial.println("TEST 1: GPIO6 HIGH - active-high module should sound");
|
||||
break;
|
||||
case 1:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("TEST 2: GPIO6 LOW - active-low module should sound");
|
||||
break;
|
||||
case 2:
|
||||
ledcAttach(PIN_BUZZER, 1800, 8);
|
||||
ledcWriteTone(PIN_BUZZER, 1800);
|
||||
ledcWrite(PIN_BUZZER, 180);
|
||||
Serial.println("TEST 3: GPIO6 PWM 1800 Hz - passive module should sound");
|
||||
break;
|
||||
default:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("SILENCE");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("GPIO6 BUZZER TEST: HIGH, LOW, PWM, SILENCE. Each step lasts 1.8 seconds.");
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (millis() - gChangedMs < STEP_MS) return;
|
||||
gStep = (gStep + 1) % 4;
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
# AGENTS
|
||||
|
||||
## Назначение папки
|
||||
|
||||
Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`.
|
||||
|
||||
Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`.
|
||||
|
||||
## Обязательная синхронизация
|
||||
|
||||
При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`.
|
||||
|
||||
Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений.
|
||||
|
||||
## Язык экрана
|
||||
|
||||
Экранные строки в скетче оставлять на английском языке.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Potentiometer ADC Test for ESP32-S3-LCD-2
|
||||
|
||||
Тестовый скетч для Waveshare `ESP32-S3-LCD-2`.
|
||||
|
||||
Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`.
|
||||
|
||||
## Пины
|
||||
|
||||
Используются пины с разъёма `P1` платы:
|
||||
|
||||
- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра.
|
||||
- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима.
|
||||
- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`.
|
||||
- `GND` — земля.
|
||||
|
||||
Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant.
|
||||
|
||||
## Режимы
|
||||
|
||||
Переключение:
|
||||
|
||||
- touch-кнопка `3-WIRE`;
|
||||
- touch-кнопка `2-WIRE`;
|
||||
- серийная команда `m`;
|
||||
- короткое нажатие `BOOT / GPIO0`.
|
||||
|
||||
Сброс min/max:
|
||||
|
||||
- touch-кнопка `RESET`;
|
||||
- серийная команда `r`.
|
||||
|
||||
## 3-Wire Mode
|
||||
|
||||
Правильное подключение:
|
||||
|
||||
- один край потенциометра -> `3V3`;
|
||||
- второй край потенциометра -> `GND`;
|
||||
- средний ползунок -> `GPIO2 / IO2`.
|
||||
|
||||
Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`.
|
||||
|
||||
## 2-Wire Mode
|
||||
|
||||
Грубое подключение:
|
||||
|
||||
- один край потенциометра -> `GPIO6 / IO6`;
|
||||
- средний ползунок -> `GPIO2 / IO2`;
|
||||
- второй край не подключать.
|
||||
|
||||
`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс.
|
||||
|
||||
## Экранные данные
|
||||
|
||||
На экране выводятся:
|
||||
|
||||
- режим и схема пинов;
|
||||
- raw ADC и millivolts;
|
||||
- абсолютный процент от `0..3300 mV`;
|
||||
- калиброванный процент по найденному min/max;
|
||||
- min/max/span;
|
||||
- EMA-сглаживание;
|
||||
- примерная оценка сопротивления;
|
||||
- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`;
|
||||
- координаты последнего touch;
|
||||
- serial-подсказка.
|
||||
|
||||
## Сборка
|
||||
|
||||
Из папки `main-device`:
|
||||
|
||||
```bash
|
||||
./burn.sh potentiometer-adc-test
|
||||
```
|
||||
+348
@@ -0,0 +1,348 @@
|
||||
#include <Arduino.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include <Wire.h>
|
||||
#include <bsp_cst816.h>
|
||||
|
||||
#define PIN_LCD_SCLK 39
|
||||
#define PIN_LCD_MOSI 38
|
||||
#define PIN_LCD_MISO 40
|
||||
#define PIN_LCD_DC 42
|
||||
#define PIN_LCD_RST -1
|
||||
#define PIN_LCD_CS 45
|
||||
#define PIN_LCD_BL 1
|
||||
|
||||
#define PIN_TP_SDA 48
|
||||
#define PIN_TP_SCL 47
|
||||
|
||||
#define PIN_ADC_WIPER 2
|
||||
#define PIN_DRIVE_2WIRE 6
|
||||
#define PIN_BOOT_BUTTON 0
|
||||
|
||||
static const uint16_t DISP_W = 320;
|
||||
static const uint16_t DISP_H = 240;
|
||||
static const uint32_t ADC_FULL_MV = 3300;
|
||||
static const float POT_OHMS = 50000.0f;
|
||||
static const float ROUGH_PULLDOWN_OHMS = 45000.0f;
|
||||
|
||||
static const uint16_t C_BG = 0x0841;
|
||||
static const uint16_t C_PANEL = 0x18E3;
|
||||
static const uint16_t C_CARD = 0x2126;
|
||||
static const uint16_t C_TEXT = 0xF7BE;
|
||||
static const uint16_t C_MUTE = 0x8C71;
|
||||
static const uint16_t C_ACCENT = 0x05DF;
|
||||
static const uint16_t C_OK = 0x47E8;
|
||||
static const uint16_t C_WARN = 0xFD20;
|
||||
static const uint16_t C_BAD = 0xF986;
|
||||
static const uint16_t C_BORDER = 0x4208;
|
||||
|
||||
struct Rect {
|
||||
int16_t x;
|
||||
int16_t y;
|
||||
int16_t w;
|
||||
int16_t h;
|
||||
};
|
||||
|
||||
enum class Mode : uint8_t {
|
||||
ThreeWire,
|
||||
TwoWire,
|
||||
};
|
||||
|
||||
struct Sample {
|
||||
uint16_t raw;
|
||||
uint32_t mv;
|
||||
uint16_t rawMinBurst;
|
||||
uint16_t rawMaxBurst;
|
||||
};
|
||||
|
||||
Arduino_DataBus *bus = new Arduino_ESP32SPI(
|
||||
PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO);
|
||||
Arduino_GFX *gfx = new Arduino_ST7789(
|
||||
bus, PIN_LCD_RST, 1, true, 240, 320);
|
||||
|
||||
static const Rect BTN_3WIRE = {10, 38, 94, 30};
|
||||
static const Rect BTN_2WIRE = {113, 38, 94, 30};
|
||||
static const Rect BTN_RESET = {216, 38, 94, 30};
|
||||
|
||||
static Mode gMode = Mode::ThreeWire;
|
||||
static uint32_t gLastUiMs = 0;
|
||||
static uint32_t gLastSerialMs = 0;
|
||||
static uint32_t gMinMv = 0xFFFFFFFF;
|
||||
static uint32_t gMaxMv = 0;
|
||||
static float gEmaMv = 0.0f;
|
||||
static bool gHasEma = false;
|
||||
static bool gTouchOk = false;
|
||||
static uint16_t gLastTouchX = 0;
|
||||
static uint16_t gLastTouchY = 0;
|
||||
static bool gBootWasDown = false;
|
||||
static uint32_t gBootLastChangeMs = 0;
|
||||
|
||||
static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) {
|
||||
gfx->setTextSize(size);
|
||||
gfx->setTextColor(color);
|
||||
gfx->setCursor(x, y);
|
||||
gfx->print(text);
|
||||
}
|
||||
|
||||
static void drawButton(const Rect &r, const char *label, bool active) {
|
||||
uint16_t fill = active ? C_ACCENT : C_CARD;
|
||||
uint16_t text = active ? C_BG : C_TEXT;
|
||||
gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill);
|
||||
gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER);
|
||||
int16_t tx = r.x + 10;
|
||||
int16_t ty = r.y + 10;
|
||||
drawText(tx, ty, label, text, 1);
|
||||
}
|
||||
|
||||
static bool contains(const Rect &r, uint16_t x, uint16_t y) {
|
||||
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
|
||||
}
|
||||
|
||||
static const char *modeName() {
|
||||
return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE";
|
||||
}
|
||||
|
||||
static void resetRange() {
|
||||
gMinMv = 0xFFFFFFFF;
|
||||
gMaxMv = 0;
|
||||
gHasEma = false;
|
||||
}
|
||||
|
||||
static void configurePins() {
|
||||
pinMode(PIN_ADC_WIPER, INPUT);
|
||||
analogReadResolution(12);
|
||||
analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db);
|
||||
|
||||
if (gMode == Mode::TwoWire) {
|
||||
pinMode(PIN_DRIVE_2WIRE, OUTPUT);
|
||||
digitalWrite(PIN_DRIVE_2WIRE, HIGH);
|
||||
pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN);
|
||||
} else {
|
||||
pinMode(PIN_DRIVE_2WIRE, INPUT);
|
||||
pinMode(PIN_ADC_WIPER, INPUT);
|
||||
}
|
||||
}
|
||||
|
||||
static void setMode(Mode mode) {
|
||||
if (gMode == mode) return;
|
||||
gMode = mode;
|
||||
configurePins();
|
||||
resetRange();
|
||||
}
|
||||
|
||||
static Sample readSample() {
|
||||
const uint8_t count = 32;
|
||||
uint32_t rawSum = 0;
|
||||
uint32_t mvSum = 0;
|
||||
uint16_t rawMin = 4095;
|
||||
uint16_t rawMax = 0;
|
||||
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
uint16_t raw = analogRead(PIN_ADC_WIPER);
|
||||
uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER);
|
||||
rawSum += raw;
|
||||
mvSum += mv;
|
||||
if (raw < rawMin) rawMin = raw;
|
||||
if (raw > rawMax) rawMax = raw;
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
|
||||
Sample s;
|
||||
s.raw = rawSum / count;
|
||||
s.mv = mvSum / count;
|
||||
s.rawMinBurst = rawMin;
|
||||
s.rawMaxBurst = rawMax;
|
||||
return s;
|
||||
}
|
||||
|
||||
static uint8_t percentFromMv(uint32_t mv) {
|
||||
if (mv >= ADC_FULL_MV) return 100;
|
||||
return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV);
|
||||
}
|
||||
|
||||
static uint8_t calibratedPercent(uint32_t mv, uint32_t span) {
|
||||
if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0;
|
||||
uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span;
|
||||
return (uint8_t)min<uint32_t>(pct, 100);
|
||||
}
|
||||
|
||||
static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) {
|
||||
if (mv < 30) return "OPEN/GND";
|
||||
if (mv > 3250) return "SATURATED";
|
||||
if (span < 20) return "NO SPAN";
|
||||
if (pctAbs < 15) return "LOW";
|
||||
if (pctAbs > 85) return "HIGH";
|
||||
return "MID";
|
||||
}
|
||||
|
||||
static float estimateOhms(uint32_t mv) {
|
||||
if (gMode == Mode::ThreeWire) {
|
||||
return POT_OHMS * ((float)percentFromMv(mv) / 100.0f);
|
||||
}
|
||||
if (mv < 5) return -1.0f;
|
||||
if (mv >= ADC_FULL_MV) return 0.0f;
|
||||
return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f);
|
||||
}
|
||||
|
||||
static void drawStaticUi() {
|
||||
gfx->fillScreen(C_BG);
|
||||
drawText(10, 8, "POT ADC TEST", C_TEXT, 2);
|
||||
drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1);
|
||||
drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire);
|
||||
drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire);
|
||||
drawButton(BTN_RESET, "RESET", false);
|
||||
|
||||
gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER);
|
||||
gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER);
|
||||
gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER);
|
||||
}
|
||||
|
||||
static void drawBar(uint8_t pct, uint16_t color) {
|
||||
int x = 18;
|
||||
int y = 123;
|
||||
int w = 284;
|
||||
int h = 10;
|
||||
gfx->fillRect(x, y, w, h, C_BORDER);
|
||||
gfx->fillRect(x, y, (w * pct) / 100, h, color);
|
||||
}
|
||||
|
||||
static void updateUi() {
|
||||
Sample s = readSample();
|
||||
if (s.mv < gMinMv) gMinMv = s.mv;
|
||||
if (s.mv > gMaxMv) gMaxMv = s.mv;
|
||||
uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0;
|
||||
|
||||
if (!gHasEma) {
|
||||
gEmaMv = (float)s.mv;
|
||||
gHasEma = true;
|
||||
} else {
|
||||
gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f;
|
||||
}
|
||||
|
||||
uint8_t pctAbs = percentFromMv(s.mv);
|
||||
uint8_t pctCal = calibratedPercent(s.mv, span);
|
||||
float ohms = estimateOhms(s.mv);
|
||||
const char *status = statusText(s.mv, span, pctAbs);
|
||||
uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK :
|
||||
strcmp(status, "NO SPAN") == 0 ? C_WARN :
|
||||
strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT;
|
||||
|
||||
char line[96];
|
||||
gfx->fillRect(9, 77, 302, 62, C_BG);
|
||||
snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName());
|
||||
drawText(16, 84, line, C_ACCENT, 1);
|
||||
snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu",
|
||||
s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f));
|
||||
drawText(16, 101, line, C_TEXT, 1);
|
||||
snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u",
|
||||
pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst));
|
||||
drawText(16, 115, line, C_TEXT, 1);
|
||||
drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor);
|
||||
|
||||
gfx->fillRect(9, 149, 302, 52, C_BG);
|
||||
snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV",
|
||||
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span);
|
||||
drawText(16, 156, line, C_TEXT, 1);
|
||||
if (ohms < 0) {
|
||||
snprintf(line, sizeof(line), "ohm: open/too high status:%s", status);
|
||||
} else {
|
||||
snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s",
|
||||
ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status);
|
||||
}
|
||||
drawText(16, 172, line, statusColor, 1);
|
||||
snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r",
|
||||
gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY);
|
||||
drawText(16, 188, line, C_MUTE, 1);
|
||||
|
||||
gfx->fillRect(9, 209, 302, 22, C_BG);
|
||||
if (gMode == Mode::ThreeWire) {
|
||||
drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1);
|
||||
} else {
|
||||
drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1);
|
||||
}
|
||||
|
||||
Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n",
|
||||
modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal,
|
||||
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span,
|
||||
(unsigned)(s.rawMaxBurst - s.rawMinBurst), status);
|
||||
}
|
||||
|
||||
static void handleTouch() {
|
||||
bsp_touch_read();
|
||||
uint16_t x = 0;
|
||||
uint16_t y = 0;
|
||||
if (!bsp_touch_get_coordinates(&x, &y)) return;
|
||||
gLastTouchX = x;
|
||||
gLastTouchY = y;
|
||||
|
||||
if (contains(BTN_3WIRE, x, y)) {
|
||||
setMode(Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
} else if (contains(BTN_2WIRE, x, y)) {
|
||||
setMode(Mode::TwoWire);
|
||||
drawStaticUi();
|
||||
} else if (contains(BTN_RESET, x, y)) {
|
||||
resetRange();
|
||||
}
|
||||
}
|
||||
|
||||
static void handleBootButton() {
|
||||
bool down = digitalRead(PIN_BOOT_BUTTON) == LOW;
|
||||
uint32_t now = millis();
|
||||
if (down != gBootWasDown && now - gBootLastChangeMs > 40) {
|
||||
gBootWasDown = down;
|
||||
gBootLastChangeMs = now;
|
||||
if (!down) {
|
||||
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void handleSerial() {
|
||||
while (Serial.available() > 0) {
|
||||
char c = (char)Serial.read();
|
||||
if (c == 'm' || c == 'M') {
|
||||
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
} else if (c == 'r' || c == 'R') {
|
||||
resetRange();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(100);
|
||||
Serial.println("ESP32-S3-LCD-2 potentiometer ADC test");
|
||||
Serial.println("Commands: m=switch mode, r=reset min/max");
|
||||
|
||||
pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP);
|
||||
configurePins();
|
||||
|
||||
if (!gfx->begin()) {
|
||||
Serial.println("gfx->begin() failed");
|
||||
}
|
||||
pinMode(PIN_LCD_BL, OUTPUT);
|
||||
digitalWrite(PIN_LCD_BL, HIGH);
|
||||
|
||||
Wire.begin(PIN_TP_SDA, PIN_TP_SCL);
|
||||
gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H);
|
||||
|
||||
drawStaticUi();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
handleSerial();
|
||||
handleBootButton();
|
||||
if (gTouchOk) handleTouch();
|
||||
|
||||
uint32_t now = millis();
|
||||
if (now - gLastUiMs >= 250) {
|
||||
updateUi();
|
||||
gLastUiMs = now;
|
||||
}
|
||||
if (now - gLastSerialMs >= 5000) {
|
||||
Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6.");
|
||||
gLastSerialMs = now;
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ case "${MODE}" in
|
||||
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
|
||||
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
|
||||
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
|
||||
breath-dual-mode-monitor) SKETCH_DIR="${ROOT_DIR}/test_sketches/breath_dual_mode_monitor" ;;
|
||||
usb-contact-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_test" ;;
|
||||
usb-contact-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_debug_test" ;;
|
||||
usb-contact-resistance-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_resistance_test" ;;
|
||||
@@ -55,21 +54,13 @@ case "${MODE}" in
|
||||
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
||||
*)
|
||||
echo "Unknown mode: ${MODE}" >&2
|
||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, breath-dual-mode-monitor, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
|
||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z "${PORT}" ]]; then
|
||||
if ! PORT="$(detect_port)"; then
|
||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||
exit 3
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "== Mode: ${MODE}"
|
||||
echo "== Sketch: ${SKETCH_DIR}"
|
||||
echo "== Port: ${PORT}"
|
||||
echo "== FQBN: ${FQBN}"
|
||||
|
||||
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
||||
@@ -93,6 +84,20 @@ if ! arduino-cli compile "${compile_args[@]}"; then
|
||||
arduino-cli compile --clean "${compile_args[@]}"
|
||||
fi
|
||||
|
||||
if [[ "${NO_UPLOAD:-0}" == "1" ]]; then
|
||||
echo "== Done: compiled without upload (NO_UPLOAD=1)."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -z "${PORT}" ]]; then
|
||||
if ! PORT="$(detect_port)"; then
|
||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||
exit 3
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "== Port: ${PORT}"
|
||||
|
||||
arduino-cli upload \
|
||||
-p "${PORT}" \
|
||||
--fqbn "${FQBN}" \
|
||||
|
||||
@@ -15,7 +15,6 @@
|
||||
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
||||
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
||||
- `breath_dual_mode_monitor/` - dual-mode breath monitor в стиле GFX-скетча: старт USB-датчика или внешних кнопок `KEY3/BOOT`, настройки лимита и громкости, повторяющиеся звуковые предупреждения
|
||||
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
||||
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
||||
- `usb_contact_resistance_test/` - тест измерения сопротивления между USB D-/D+ через ADC на GPIO20; рассчитан на внешний известный резистор 10 kΩ с D+ на GND
|
||||
@@ -33,7 +32,6 @@
|
||||
- `./burn.sh lvgl-official-based-test`
|
||||
- `./burn.sh lvgl-subserver-touch-test`
|
||||
- `./burn.sh lvgl-russian-font-test`
|
||||
- `./burn.sh breath-dual-mode-monitor`
|
||||
- `./burn.sh usb-contact-test`
|
||||
- `./burn.sh usb-contact-debug-test`
|
||||
- `./burn.sh usb-contact-resistance-test`
|
||||
|
||||
@@ -125,7 +125,11 @@ Initial screen:
|
||||
- title: `BREATH MONITOR`
|
||||
- state: `READY`
|
||||
- action button: `START USB SENSOR`
|
||||
- action button: `START BUTTONS`
|
||||
- action button: `START MANUAL MONITOR`
|
||||
- action button: `START POT 3-WIRE`
|
||||
- action button: `START POT 2-WIRE`
|
||||
- action button: `START POT CAL`
|
||||
- action button: `START PIN DIAG`
|
||||
|
||||
After `START USB SENSOR`:
|
||||
|
||||
@@ -137,15 +141,54 @@ After `START USB SENSOR`:
|
||||
- a short `KEY3 / GPIO18` press opens or closes settings in USB sensor mode
|
||||
- the bottom line shows the durations of the last 5 accepted USB sensor cycles
|
||||
|
||||
After `START BUTTONS`:
|
||||
After `START MANUAL MONITOR`:
|
||||
|
||||
- `KEY3 / GPIO18` is the external `INHALE` button, active LOW
|
||||
- `BOOT / GPIO0` is the external `EXHALE` button, active LOW
|
||||
- do not hold `BOOT` while booting or resetting the board
|
||||
- the mode title is `MANUAL MONITOR`
|
||||
- accepted manual phases strictly alternate: `INHALE`, then `EXHALE`; a repeated current button or `EXHALE` before the first `INHALE` is ignored without a beep or timer reset
|
||||
- each accepted button press plays one quiet confirmation beep and starts a fresh `Phase time` timer for that inhale or exhale
|
||||
- the working screen does not show touch `INHALE`/`EXHALE` buttons
|
||||
- long-holding `KEY3 / INHALE` for about 850 ms opens settings; the long press still counts as an inhale press
|
||||
- while settings are open, the next `KEY3 / INHALE` press closes settings and also counts as an inhale press
|
||||
|
||||
After `START POT 3-WIRE`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` and works as the 3.3 V side of the potentiometer test
|
||||
- `GPIO20 / USB D+` is configured as ADC input and must be connected to the potentiometer wiper
|
||||
- `USB GND` must be connected to the other edge pin of the potentiometer
|
||||
- the screen shows position `0..100%`, a bar, ADC raw value, measured millivolts, and estimated `0..50 kΩ` resistance
|
||||
- if ADC saturates or reaches an unsafe high-voltage threshold, the firmware releases `D-` and `D+` to `INPUT`, beeps, and shows `USB/PIN FAULT`
|
||||
- this is only best-effort software protection; ESP32-S3 GPIO pins are not 5 V tolerant, so external wiring must still prevent 5 V from reaching `D+` or `D-`
|
||||
|
||||
After `START POT 2-WIRE`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
|
||||
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
|
||||
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
|
||||
- the screen shows rough position, raw ADC, millivolts, and rough estimated resistance
|
||||
- this mode is intentionally approximate because the ESP32 internal pulldown value is not precise and can vary between boards
|
||||
- use `START POT 3-WIRE` for stable and more linear future breath sensing
|
||||
|
||||
After `START POT CAL`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
|
||||
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
|
||||
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
|
||||
- the firmware tracks the observed minimum and maximum ADC millivolts
|
||||
- the screen shows a calibrated `0..100%` position within the observed range, current millivolts, raw ADC, min-max range, and state
|
||||
- `KEY3 / GPIO18` resets the learned min-max calibration
|
||||
- this mode is for relative position testing on weak or shifted USB-pin ranges; it does not report real resistance
|
||||
|
||||
After `START PIN DIAG`:
|
||||
|
||||
- the firmware runs two alternating USB pin drive/read checks
|
||||
- Test A drives `GPIO19 / USB D-` HIGH and reads `GPIO20 / USB D+` as ADC
|
||||
- Test B drives `GPIO20 / USB D+` HIGH and reads `GPIO19 / USB D-` as ADC
|
||||
- shorting `D-` and `D+` should make the ADC side rise if the pins are actually controllable as GPIO
|
||||
- if both tests stay near 0 mV, the USB cable/host, USB PHY, or board wiring is likely holding the lines and the USB data pins are not usable as an analog sensor in that setup
|
||||
|
||||
In both modes:
|
||||
|
||||
- one breathing cycle is measured from one `EXHALE` tap to the next `EXHALE` tap
|
||||
@@ -156,4 +199,5 @@ In both modes:
|
||||
- the lower numeric fields use a larger font than before
|
||||
- if the average of the last up to 5 completed cycles is shorter than the selected limit, warning beeps are played like in the USB contact breath monitor
|
||||
- if the current cycle reaches 60 seconds, 5 loud warning beeps are played, then after 5 seconds another 5 loud warning beeps are played, repeating until the user changes phase / exits the long cycle
|
||||
- in manual monitor mode, a single loud warning beep is also played at 35, 40, 45, 50, and 55 seconds of an unchanged inhale or exhale; the repeated five-beep alarm starts at 60 seconds
|
||||
- settings keep the same sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
|
||||
|
||||
@@ -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-среде.
|
||||
@@ -1,7 +1,29 @@
|
||||
# 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",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.5.0",
|
||||
"@solana/web3.js": "^1.98.4"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "shine-browser-plugin-wallet",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.",
|
||||
"main": "popup.js",
|
||||
"scripts": {
|
||||
@@ -8,7 +9,7 @@
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.5.0",
|
||||
"@solana/web3.js": "^1.98.4"
|
||||
|
||||
@@ -15,6 +15,17 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
|
||||
- `shine-server-config/` — конфигурация сервера
|
||||
- `shine-server-log/` — логирование
|
||||
- `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)
|
||||
|
||||
|
||||
+100
-3
@@ -2,6 +2,7 @@ package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.BchBlockEntry;
|
||||
import server.archive.registration.VerifiedFreeRegistrationImporter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
@@ -9,6 +10,7 @@ import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||
import server.sync.BlockchainResyncGuard;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
import shine.db.dao.ArweaveBlockImportDAO;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
@@ -36,7 +38,7 @@ import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
||||
* or inside a direct server-created ANS-104 bundle.
|
||||
*/
|
||||
@@ -50,6 +52,8 @@ public final class ArweaveBlockSyncService {
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build();
|
||||
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
|
||||
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
|
||||
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||
@@ -68,6 +72,7 @@ public final class ArweaveBlockSyncService {
|
||||
public void runCycle() throws Exception {
|
||||
recoverInterruptedCanonicalRebuilds();
|
||||
discover();
|
||||
discoverFreeRegistrations();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
@@ -116,6 +121,12 @@ public final class ArweaveBlockSyncService {
|
||||
|
||||
try {
|
||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
continue; // Не парсить регистрацию как BchBlockEntry.
|
||||
}
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
@@ -172,6 +183,18 @@ public final class ArweaveBlockSyncService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
try {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
} catch (Exception e) {
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
||||
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
||||
queued++;
|
||||
@@ -474,10 +497,84 @@ public final class ArweaveBlockSyncService {
|
||||
}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"));
|
||||
}
|
||||
|
||||
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 query = "query { transactions(tags:[{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}], block:{min:" + minHeight + "}, first:"
|
||||
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
|
||||
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
|
||||
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
|
||||
+ cfg.syncPageSize() + ", after:" + after
|
||||
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
||||
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
||||
|
||||
+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));
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
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;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
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);
|
||||
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);
|
||||
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;}
|
||||
};
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
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 = List.of(
|
||||
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
|
||||
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); }
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/** Выдаётся только после успешной проверки 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);
|
||||
}
|
||||
}
|
||||
+251
@@ -0,0 +1,251 @@
|
||||
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;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
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;
|
||||
}
|
||||
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 ORDER BY namespace
|
||||
"""); 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 (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() + ")");
|
||||
}
|
||||
}
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
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, ?, 100000, 0, -1, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login);
|
||||
// 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.APP_TAG_VALUE))
|
||||
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.APP_TAG_VALUE
|
||||
+ ", 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");
|
||||
}
|
||||
}
|
||||
+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) { }
|
||||
}
|
||||
}
|
||||
+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");
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -9,7 +9,7 @@ package blockchain;
|
||||
public final class ShineProtocolTags {
|
||||
private ShineProtocolTags() {}
|
||||
|
||||
public static final String NAMESPACE = "test5591";
|
||||
public static final String NAMESPACE = "test5592";
|
||||
public static final String APP_TAG_NAME = "App";
|
||||
public static final String APP_TAG_VALUE = NAMESPACE;
|
||||
public static final String CHANNEL_TAG_NAME = "c";
|
||||
|
||||
+19
@@ -37,6 +37,8 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
|
||||
|
||||
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;
|
||||
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
|
||||
|
||||
@@ -159,6 +161,20 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
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;
|
||||
}
|
||||
|
||||
private static String normalizeDisplayName(String value) {
|
||||
if (value == null) return "";
|
||||
return value.trim().replaceAll("\\s+", " ");
|
||||
@@ -171,6 +187,9 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
@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");
|
||||
|
||||
@@ -78,8 +78,14 @@ public final class HeaderBody implements BodyRecord {
|
||||
public HeaderBody check() {
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
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);
|
||||
// В 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");
|
||||
requireNonZeroKey(initialBlockchainKey32);
|
||||
return this;
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+32
@@ -98,6 +98,38 @@ final class TargetLoginFormatTest {
|
||||
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 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) {
|
||||
byte[] out = new byte[32];
|
||||
Arrays.fill(out, (byte) seed);
|
||||
|
||||
@@ -23,9 +23,25 @@ public final class DatabaseInitializer {
|
||||
public static final int SCHEMA_VERSION_1 = 1;
|
||||
public static final int SCHEMA_VERSION_31 = 31;
|
||||
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 String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||
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";
|
||||
|
||||
private DatabaseInitializer() {}
|
||||
|
||||
@@ -125,10 +141,43 @@ public final class DatabaseInitializer {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
||||
currentVersion = readCurrentSchemaVersion(conn);
|
||||
}
|
||||
if (currentVersion != SCHEMA_VERSION_32) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 32, found " + currentVersion);
|
||||
if (currentVersion == SCHEMA_VERSION_32) {
|
||||
runSqlScript(conn, POSTGRES_MIGRATION_V33_RESOURCE);
|
||||
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) {
|
||||
throw new SQLException(
|
||||
"Unsupported SHiNE DB v2 schema version: expected 40, found " + currentVersion);
|
||||
}
|
||||
normalizeBlockchainStateKeysToBase64(conn);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,6 +257,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 {
|
||||
String sqlScript = loadClasspathResource(resourcePath);
|
||||
List<String> statements = splitSqlStatements(sqlScript);
|
||||
|
||||
@@ -4,7 +4,7 @@ import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
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 Pattern DISPLAY_ALLOWED_PATTERN =
|
||||
Pattern.compile("^[A-Za-z0-9_-]+$");
|
||||
@@ -26,7 +26,7 @@ public final class ChannelNameRules {
|
||||
|
||||
int length = normalized.codePointCount(0, normalized.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()) {
|
||||
|
||||
@@ -43,7 +43,7 @@ public final class BlockchainStateDAO {
|
||||
last_block_hash,
|
||||
updated_at_ms
|
||||
FROM blockchain_state
|
||||
WHERE login = ? AND fork_number = ?
|
||||
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
""";
|
||||
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -197,7 +197,7 @@ public final class BlockchainStateDAO {
|
||||
file_size_bytes = file_size_bytes + ?,
|
||||
updated_at_ms = ?
|
||||
WHERE
|
||||
login = ? AND fork_number = ?
|
||||
LOWER(login) = LOWER(?) AND fork_number = ?
|
||||
AND (file_size_bytes + ?) <= size_limit
|
||||
""";
|
||||
|
||||
|
||||
@@ -164,9 +164,9 @@ public final class ConnectionsStateDAO {
|
||||
""";
|
||||
|
||||
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.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);
|
||||
ps.setBytes(5, toBlockHash);
|
||||
ps.executeUpdate();
|
||||
|
||||
@@ -213,7 +213,7 @@ public final class CurrentUsersDAO {
|
||||
String sql = """
|
||||
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
||||
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)
|
||||
WHERE (? IS NULL OR su.is_server = ?)
|
||||
AND (
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package shine.db.dao;
|
||||
|
||||
import shine.db.DbController;
|
||||
import shine.db.MsgSubType;
|
||||
import shine.db.entities.SignedMessageEntry;
|
||||
|
||||
@@ -17,6 +18,7 @@ import java.util.Map;
|
||||
|
||||
public final class DmDialogStateDAO {
|
||||
private static volatile DmDialogStateDAO instance;
|
||||
private final DbController db = DbController.getInstance();
|
||||
|
||||
private DmDialogStateDAO() {}
|
||||
|
||||
@@ -129,6 +131,26 @@ public final class DmDialogStateDAO {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Снимок счётчика после записи DM. Используется только сервером для push/WS, не отдаёт текст сообщения. */
|
||||
public NotificationState getNotificationState(String ownerLogin, String peerLogin) throws SQLException {
|
||||
try (Connection c = db.getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT unread_count, updated_at_ms
|
||||
FROM dm_dialog_state
|
||||
WHERE LOWER(owner_login) = LOWER(?) AND LOWER(peer_login) = LOWER(?)
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, normalize(ownerLogin));
|
||||
ps.setString(2, normalize(peerLogin));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return null;
|
||||
return new NotificationState(Math.max(0, rs.getInt("unread_count")), rs.getLong("updated_at_ms"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public record NotificationState(int unreadCount, long versionMs) {}
|
||||
|
||||
public void refreshFromEntry(Connection c, SignedMessageEntry entry) throws SQLException {
|
||||
if (entry == null) return;
|
||||
refreshConversationPair(c, entry.getFromLogin(), entry.getToLogin());
|
||||
@@ -274,7 +296,7 @@ public final class DmDialogStateDAO {
|
||||
last_message_time_ms = EXCLUDED.last_message_time_ms,
|
||||
unread_count = EXCLUDED.unread_count,
|
||||
last_read_receipt_time_ms = EXCLUDED.last_read_receipt_time_ms,
|
||||
updated_at_ms = EXCLUDED.updated_at_ms
|
||||
updated_at_ms = GREATEST(dm_dialog_state.updated_at_ms + 1, EXCLUDED.updated_at_ms)
|
||||
""")) {
|
||||
ps.setString(1, summary.ownerLogin());
|
||||
ps.setString(2, summary.peerLogin());
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -111,7 +111,7 @@ public final class SubscriptionsDAO {
|
||||
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 cs.login = ? AND cs.rel_type = ?
|
||||
WHERE LOWER(cs.login) = LOWER(?) AND cs.rel_type = ?
|
||||
|
||||
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")
|
||||
);
|
||||
}
|
||||
}
|
||||
+13
-11
@@ -46,26 +46,28 @@ public final class UserAccessServersCurrentDAO {
|
||||
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
||||
String sql = """
|
||||
SELECT
|
||||
u.login AS user_login,
|
||||
i.login AS user_login,
|
||||
s.login AS server_login,
|
||||
s.server_address AS server_url,
|
||||
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 (
|
||||
SELECT BTRIM(a.login_value) AS server_login
|
||||
FROM jsonb_array_elements_text(
|
||||
CASE
|
||||
WHEN BTRIM(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb
|
||||
ELSE u.access_servers_json::jsonb
|
||||
END
|
||||
) WITH ORDINALITY AS a(login_value, ord)
|
||||
WHERE a.ord = 1
|
||||
SELECT CASE WHEN i.registration_status = 'FREE_CERT'
|
||||
THEN ns.default_server_login
|
||||
ELSE (SELECT BTRIM(a.login_value)
|
||||
FROM jsonb_array_elements_text(
|
||||
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||
WITH ORDINALITY AS a(login_value, ord)
|
||||
WHERE a.ord = 1)
|
||||
END AS server_login
|
||||
) primary_access
|
||||
JOIN solana_user_pda_current s
|
||||
ON s.normalized_login = LOWER(primary_access.server_login)
|
||||
AND s.is_server = TRUE
|
||||
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
||||
WHERE u.normalized_login = LOWER(BTRIM(?))
|
||||
WHERE i.normalized_login = LOWER(BTRIM(?))
|
||||
LIMIT 1
|
||||
""";
|
||||
try (Connection c = db.getConnection();
|
||||
|
||||
-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.client_key AS client_key,
|
||||
current_users.is_server AS is_server
|
||||
FROM solana_user_pda_current current_users
|
||||
FROM user_identity_current current_users
|
||||
) %s
|
||||
""".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;
|
||||
@@ -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 $$
|
||||
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
||||
v_canonical_login TEXT;
|
||||
BEGIN
|
||||
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,
|
||||
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(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),
|
||||
@@ -2485,15 +2489,15 @@ DECLARE positive_rel_type INTEGER; channel_bch TEXT;
|
||||
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_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)
|
||||
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
|
||||
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;
|
||||
PERFORM shine_refresh_user_stats(NEW.login);
|
||||
PERFORM shine_refresh_user_stats(NEW.to_login);
|
||||
PERFORM shine_refresh_user_stats(lower(NEW.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
|
||||
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;
|
||||
@@ -2506,22 +2510,22 @@ DECLARE previous_sub_type INTEGER;
|
||||
BEGIN
|
||||
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;
|
||||
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;
|
||||
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
|
||||
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,
|
||||
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
|
||||
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),
|
||||
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;
|
||||
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;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
@@ -2532,7 +2536,7 @@ BEGIN
|
||||
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;
|
||||
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;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
@@ -30,6 +30,7 @@ dependencies {
|
||||
|
||||
implementation project(':shine-server-crypto') // модуль сервера для работы с криптографией
|
||||
implementation project(':shine-server-blockchain') // модуль для работы с блокчейном
|
||||
implementation project(':shine-server-solana-users-sync') // Нормализованный адрес PDA
|
||||
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
||||
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
||||
|
||||
|
||||
+30
@@ -91,6 +91,9 @@ import server.logic.ws_protocol.JSON.handlers.channels.ChannelNamesStateBootstra
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelMessages_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetMessageThread_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetMessageLikes_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetSupportTotals_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetSupportStats_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetSupportHistory_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetPersonalDiary_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
|
||||
@@ -104,6 +107,9 @@ import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelMe
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetGroupDialog_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageThread_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageLikes_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportTotals_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportStats_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportHistory_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetPersonalDiary_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
|
||||
@@ -169,6 +175,8 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchain
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
|
||||
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Handler;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
@@ -186,6 +194,14 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
||||
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
|
||||
|
||||
// --- Registration V2: 6 согласованных публичных операций ---
|
||||
Map.entry("GetNamespaces", new Net_Registration_Handler("GetNamespaces")),
|
||||
Map.entry("CheckRegistrationLogin", new Net_Registration_Handler("CheckRegistrationLogin")),
|
||||
Map.entry("CheckRegistrationEmail", new Net_Registration_Handler("CheckRegistrationEmail")),
|
||||
Map.entry("StartFreeRegistration", new Net_Registration_Handler("StartFreeRegistration")),
|
||||
Map.entry("ConfirmFreeRegistration", new Net_Registration_Handler("ConfirmFreeRegistration")),
|
||||
Map.entry("GetRegistrationStatus", new Net_Registration_Handler("GetRegistrationStatus")),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
||||
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
|
||||
@@ -244,6 +260,9 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("GetPersonalDiary", new Net_GetPersonalDiary_Handler()),
|
||||
Map.entry("GetMessageThread", new Net_GetMessageThread_Handler()),
|
||||
Map.entry("GetMessageLikes", new Net_GetMessageLikes_Handler()),
|
||||
Map.entry("GetSupportTotals", new Net_GetSupportTotals_Handler()),
|
||||
Map.entry("GetSupportStats", new Net_GetSupportStats_Handler()),
|
||||
Map.entry("GetSupportHistory", new Net_GetSupportHistory_Handler()),
|
||||
Map.entry("GetGroupDialog", new Net_GetGroupDialog_Handler()),
|
||||
Map.entry("ListGroupChats200", new Net_ListGroupChats200_Handler()),
|
||||
Map.entry("GetChannelsCounters", new Net_GetChannelsCounters_Handler()),
|
||||
@@ -291,6 +310,14 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
||||
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
|
||||
|
||||
// --- Registration V2 ---
|
||||
Map.entry("GetNamespaces", Net_Registration_Request.class),
|
||||
Map.entry("CheckRegistrationLogin", Net_Registration_Request.class),
|
||||
Map.entry("CheckRegistrationEmail", Net_Registration_Request.class),
|
||||
Map.entry("StartFreeRegistration", Net_Registration_Request.class),
|
||||
Map.entry("ConfirmFreeRegistration", Net_Registration_Request.class),
|
||||
Map.entry("GetRegistrationStatus", Net_Registration_Request.class),
|
||||
|
||||
// --- auth ---
|
||||
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
||||
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
|
||||
@@ -349,6 +376,9 @@ public final class JsonHandlerRegistry {
|
||||
Map.entry("GetPersonalDiary", Net_GetPersonalDiary_Request.class),
|
||||
Map.entry("GetMessageThread", Net_GetMessageThread_Request.class),
|
||||
Map.entry("GetMessageLikes", Net_GetMessageLikes_Request.class),
|
||||
Map.entry("GetSupportTotals", Net_GetSupportTotals_Request.class),
|
||||
Map.entry("GetSupportStats", Net_GetSupportStats_Request.class),
|
||||
Map.entry("GetSupportHistory", Net_GetSupportHistory_Request.class),
|
||||
Map.entry("GetGroupDialog", Net_GetGroupDialog_Request.class),
|
||||
Map.entry("ListGroupChats200", Net_ListGroupChats200_Request.class),
|
||||
Map.entry("GetChannelsCounters", Net_GetChannelsCounters_Request.class),
|
||||
|
||||
+12
-4
@@ -76,9 +76,12 @@ public final class JsonInboundProcessor {
|
||||
return out;
|
||||
}
|
||||
|
||||
// DEBUG: сырой вход (обрезаем, чтобы не убить лог)
|
||||
// Не писать email, challenge и ключи в лог даже на DEBUG.
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId, shorten(json, 1200));
|
||||
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId,
|
||||
json.contains("FreeRegistration") || json.contains("RegistrationEmail")
|
||||
|| json.contains("RegistrationLogin") || json.contains("GetNamespaces")
|
||||
|| json.contains("GetRegistrationStatus") ? "<registration payload redacted>" : shorten(json, 1200));
|
||||
}
|
||||
|
||||
// 1) Парсим общий пакет
|
||||
@@ -178,7 +181,7 @@ public final class JsonInboundProcessor {
|
||||
} catch (Exception mapErr) {
|
||||
// Важно: вот это часто “теряется”, если не логировать отдельно
|
||||
log.error("❌ JSON map error (op={}, requestId={}, login={}, sessionId={}): merged={}",
|
||||
op, safe(requestId), ctxLogin, ctxSessionId, shorten(merged.toString(), 1200), mapErr);
|
||||
op, safe(requestId), ctxLogin, ctxSessionId, "<redacted>", mapErr);
|
||||
|
||||
Net_Exception_Response err = NetExceptionResponseFactory.error(
|
||||
op,
|
||||
@@ -202,7 +205,7 @@ public final class JsonInboundProcessor {
|
||||
// DEBUG: нормализованный запрос (уже распарсен)
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("REQ OBJ (login={}, sessionId={}, op={}, requestId={}): {}",
|
||||
ctxLogin, ctxSessionId, safe(op), safe(requestId), shorten(safeToString(request), 1200));
|
||||
ctxLogin, ctxSessionId, safe(op), safe(requestId), isRegistrationOperation(op) ? "<registration payload redacted>" : shorten(safeToString(request), 1200));
|
||||
}
|
||||
|
||||
// REMOTE-пользователь успешно авторизован, но этот сервер не является
|
||||
@@ -372,6 +375,11 @@ public final class JsonInboundProcessor {
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isRegistrationOperation(String op) {
|
||||
return op != null && (op.endsWith("Registration") || op.startsWith("CheckRegistration")
|
||||
|| op.equals("GetNamespaces") || op.equals("GetRegistrationStatus"));
|
||||
}
|
||||
|
||||
private static String safe(String s) {
|
||||
return s != null ? s : "";
|
||||
}
|
||||
|
||||
+22
-37
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import utils.config.SolanaProgramsConfig;
|
||||
import shine.db.dao.RegistrationIdentityDAO;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
@@ -34,6 +35,10 @@ public final class SolanaUserPdaImportService {
|
||||
public static SessionTypeCheckResult checkSessionTypeAgainstPda(String loginRaw, String sessionKeyApi, int requestedSessionType) throws Exception {
|
||||
String login = normalizeLogin(loginRaw);
|
||||
if (login == null) return SessionTypeCheckResult.noRecord();
|
||||
// У FREE_CERT нет Solana PDA. Это НЕ означает отсутствие идентичности:
|
||||
// AuthChallenge и подпись clientKey уже проверяются через общий индекс.
|
||||
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity != null && identity.isFree()) return SessionTypeCheckResult.noRecord();
|
||||
|
||||
ParsedSolanaUser parsed = fetchFromSolana(login);
|
||||
if (parsed == null) return SessionTypeCheckResult.noRecord();
|
||||
@@ -103,54 +108,34 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
private static byte[] fetchRawUserPda(String login) throws Exception {
|
||||
String loginB58 = toBase58(login.getBytes(StandardCharsets.UTF_8));
|
||||
String lenB58 = toBase58(new byte[]{(byte) login.length()});
|
||||
|
||||
String reqJson = """
|
||||
{
|
||||
"jsonrpc":"2.0",
|
||||
"id":1,
|
||||
"method":"getProgramAccounts",
|
||||
"params":[
|
||||
"%s",
|
||||
{
|
||||
"encoding":"base64",
|
||||
"filters":[
|
||||
{"memcmp":{"offset":61,"bytes":"%s"}},
|
||||
{"memcmp":{"offset":62,"bytes":"%s"}}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""".formatted(SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID, lenB58, loginB58);
|
||||
|
||||
// Запись хранит исходный регистр, но адрес PDA зависит только от lowercase.
|
||||
String address = sync.util.SolanaPdaUtil.findUserPdaV2(login, SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID);
|
||||
String reqJson = MAPPER.writeValueAsString(Map.of(
|
||||
"jsonrpc", "2.0", "id", 1,
|
||||
"method", "getAccountInfo",
|
||||
"params", List.of(address, Map.of("encoding", "base64", "commitment", "confirmed"))));
|
||||
HttpRequest req = HttpRequest.newBuilder()
|
||||
.uri(URI.create(SolanaProgramsConfig.SOLANA_RPC_URL))
|
||||
.header("Content-Type", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(reqJson))
|
||||
.build();
|
||||
|
||||
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||
throw new IllegalStateException("Solana RPC HTTP status=" + resp.statusCode());
|
||||
}
|
||||
|
||||
JsonNode root = MAPPER.readTree(resp.body());
|
||||
if (root.hasNonNull("error")) {
|
||||
throw new IllegalStateException("Solana RPC error: " + root.get("error").toString());
|
||||
throw new IllegalStateException("Solana RPC error: " + root.get("error"));
|
||||
}
|
||||
|
||||
JsonNode result = root.path("result");
|
||||
if (!result.isArray() || result.isEmpty()) return null;
|
||||
|
||||
for (JsonNode item : result) {
|
||||
JsonNode dataNode = item.path("account").path("data");
|
||||
if (!dataNode.isArray() || dataNode.size() < 1) continue;
|
||||
String b64 = dataNode.get(0).asText("");
|
||||
if (b64.isBlank()) continue;
|
||||
return Base64.getDecoder().decode(b64);
|
||||
JsonNode account = root.path("result").path("value");
|
||||
if (account.isMissingNode() || account.isNull()) return null;
|
||||
if (!SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID.equals(account.path("owner").asText())) {
|
||||
throw new IllegalStateException("PDA принадлежит другой программе");
|
||||
}
|
||||
return null;
|
||||
JsonNode data = account.path("data");
|
||||
if (!data.isArray() || data.isEmpty()) return null;
|
||||
String b64 = data.get(0).asText("");
|
||||
return b64.isBlank() ? null : Base64.getDecoder().decode(b64);
|
||||
}
|
||||
|
||||
private static ParsedSolanaUser parseUserPda(byte[] raw) {
|
||||
@@ -253,7 +238,7 @@ public final class SolanaUserPdaImportService {
|
||||
}
|
||||
|
||||
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
|
||||
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||
String blockchainName = normalizeLogin(login) + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||
return new ParsedSolanaUser(
|
||||
login,
|
||||
blockchainName,
|
||||
@@ -360,7 +345,7 @@ public final class SolanaUserPdaImportService {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Нужен для memcmp.bytes в Solana RPC.
|
||||
// Вспомогательная base58-конверсия для других совместимых полей.
|
||||
private static String toBase58(byte[] input) {
|
||||
final char[] alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||
int zeros = 0;
|
||||
|
||||
+62
-6
@@ -37,11 +37,13 @@ import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.ChannelNameStateDAO;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.dao.UserNotificationsStateDAO;
|
||||
import shine.db.dao.UserParamsDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.ChannelNameStateEntry;
|
||||
import shine.db.entities.CurrentUserEntry;
|
||||
import shine.db.entities.UserNotificationEntry;
|
||||
import shine.db.entities.UserParamEntry;
|
||||
import utils.blockchain.BlockchainNameUtil;
|
||||
@@ -68,6 +70,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
|
||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||
private final CurrentUsersDAO currentUsersDAO = CurrentUsersDAO.getInstance();
|
||||
private final UserParamsDAO userParamsDAO = UserParamsDAO.getInstance();
|
||||
private final ChannelNameStateDAO channelNameStateDAO = ChannelNameStateDAO.getInstance();
|
||||
|
||||
@@ -202,6 +205,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
|
||||
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
|
||||
case "bad_block_body" -> "Некорректное тело блока";
|
||||
case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
|
||||
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
|
||||
case "bad_channel_name" -> "Некорректное название канала";
|
||||
case "bad_block_number" -> "Некорректный номер блока";
|
||||
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
|
||||
@@ -255,7 +260,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
}
|
||||
|
||||
// 1) state обязателен
|
||||
final BlockchainStateEntry st;
|
||||
BlockchainStateEntry st;
|
||||
try {
|
||||
st = stateDAO.getByBlockchainName(blockchainName);
|
||||
} catch (Exception e) {
|
||||
@@ -264,6 +269,37 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
|
||||
}
|
||||
|
||||
if (st == null) {
|
||||
// Runtime-проекция могла отсутствовать у пользователей, зарегистрированных
|
||||
// ранней версией free-регистрации. Восстанавливаем только для точно
|
||||
// существующего владельца этой цепочки; сам блок всё равно проходит
|
||||
// полную проверку ключа и подписи ниже.
|
||||
try {
|
||||
CurrentUserEntry user = currentUsersDAO.getByBlockchainName(blockchainName);
|
||||
if (user != null) {
|
||||
BlockchainStateEntry recovered = new BlockchainStateEntry();
|
||||
recovered.setBlockchainName(user.getBlockchainName());
|
||||
recovered.setLogin(user.getLogin());
|
||||
recovered.setBlockchainKey(user.getBlockchainKey());
|
||||
recovered.setSizeLimit(100_000L);
|
||||
recovered.setFileSizeBytes(0L);
|
||||
recovered.setLastBlockNumber(-1);
|
||||
recovered.setLastBlockHash(new byte[32]);
|
||||
recovered.setUpdatedAtMs(System.currentTimeMillis());
|
||||
stateDAO.insertIfMissing(recovered);
|
||||
st = stateDAO.getByBlockchainName(blockchainName);
|
||||
if (st != null) {
|
||||
log.warn("AddBlock: восстановлена отсутствующая blockchain_state для login={}, blockchainName={}",
|
||||
user.getLogin(), blockchainName);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("AddBlock: не удалось восстановить blockchain_state (login={}, blockchainName={})",
|
||||
login, blockchainName, e);
|
||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
|
||||
}
|
||||
}
|
||||
|
||||
if (st == null) {
|
||||
log.warn("AddBlock: blockchain_state_not_found (login={}, blockchainName={}, reqGlobalNumber={})",
|
||||
login, blockchainName, globalNumberFromReq);
|
||||
@@ -351,8 +387,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
if (!(block.body instanceof HeaderBody headerBody)) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_required_as_block_zero", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
if (!login.equals(headerBody.login)) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
|
||||
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
|
||||
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
|
||||
try {
|
||||
CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
|
||||
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|
||||
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("AddBlock: cannot verify registered HEADER login for {}", blockchainName, e);
|
||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "header_identity_lookup_failed", serverLastNum, serverLastHashHex);
|
||||
}
|
||||
} else if (block.body instanceof HeaderBody) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_must_be_block_zero", serverLastNum, serverLastHashHex);
|
||||
@@ -375,9 +420,20 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
||||
final String normalizedName;
|
||||
final String slug;
|
||||
try {
|
||||
normalizedName = channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_PERSONAL & 0xFFFF)
|
||||
? ChannelNameRules.requireValidDisplayNameForCreate(createChannelBody.channelName)
|
||||
: ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName);
|
||||
String historicalName = ChannelNameRules.normalizeDisplayName(createChannelBody.channelName);
|
||||
boolean legacyReplayName = replayMode
|
||||
&& historicalName.codePointCount(0, historicalName.length())
|
||||
< CreateChannelBody.MIN_NAME_LENGTH_FOR_CREATE;
|
||||
if (legacyReplayName) {
|
||||
// Только воспроизведение старых подписанных DataItem: не ломаем ресинк истории.
|
||||
// Новый AddBlock (replayMode=false) обязательно проверяет минимум 4 символа.
|
||||
normalizedName = historicalName;
|
||||
} else {
|
||||
createChannelBody.checkForCreate();
|
||||
normalizedName = channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_PERSONAL & 0xFFFF)
|
||||
? ChannelNameRules.requireValidDisplayNameForCreate(createChannelBody.channelName)
|
||||
: ChannelNameRules.requireValidPublicDisplayNameForCreate(createChannelBody.channelName);
|
||||
}
|
||||
slug = ChannelNameRules.toCanonicalSlug(normalizedName);
|
||||
} catch (IllegalArgumentException badName) {
|
||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_name", serverLastNum, serverLastHashHex);
|
||||
|
||||
+6
-2
@@ -66,14 +66,18 @@ public final class BlockchainWriter {
|
||||
try (Connection c = shine.db.DbController.getInstance().getConnection()) {
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
blocksDAO.insert(c, be);
|
||||
|
||||
// blocks_store имеет внешний ключ (login, fork_number) на
|
||||
// blockchain_state_store. Сначала создаём/обновляем runtime-state:
|
||||
// это позволяет без отдельной предварительной записи принять
|
||||
// самый первый HEADER ранее импортированной цепочки.
|
||||
st.setLastBlockNumber(block.blockNumber);
|
||||
st.setLastBlockHash(block.getHash32());
|
||||
st.setFileSizeBytes(st.getFileSizeBytes() + rawDataItem.length);
|
||||
st.setUpdatedAtMs(nowMs);
|
||||
stateDAO.upsert(c, st);
|
||||
|
||||
blocksDAO.insert(c, be);
|
||||
|
||||
if (userParamEntry != null) userParamsDAO.upsertIfNewer(c, userParamEntry);
|
||||
if (channelNameStateEntry != null) channelNameStateDAO.insert(c, channelNameStateEntry);
|
||||
if (channelMetaUpdateEntry != null) channelNameStateDAO.updateMeta(c, channelMetaUpdateEntry);
|
||||
|
||||
+4
-4
@@ -13,10 +13,10 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.dao.CurrentUsersDAO;
|
||||
import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
import shine.db.entities.CurrentUserEntry;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
@@ -26,7 +26,7 @@ import java.util.List;
|
||||
public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
|
||||
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
|
||||
private final BlockchainStateDAO states = BlockchainStateDAO.getInstance();
|
||||
private final SolanaUserPdaCurrentDAO users = SolanaUserPdaCurrentDAO.getInstance();
|
||||
private final CurrentUsersDAO users = CurrentUsersDAO.getInstance();
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
|
||||
@@ -36,7 +36,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
|
||||
}
|
||||
try {
|
||||
String login = ctx.getLogin().trim();
|
||||
SolanaUserPdaCurrentEntry user = users.getByLogin(login);
|
||||
CurrentUserEntry user = users.getByLogin(login);
|
||||
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 404, "BLOCKCHAIN_NOT_FOUND", "Текущий блокчейн пользователя не найден");
|
||||
}
|
||||
|
||||
+27
-12
@@ -16,6 +16,8 @@ import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Locale;
|
||||
|
||||
final class ChannelsReadSupport {
|
||||
static final int MSG_TYPE_TEXT = 1;
|
||||
@@ -39,6 +41,19 @@ final class ChannelsReadSupport {
|
||||
}
|
||||
}
|
||||
|
||||
// Пользовательское отображение — из реестра, не из normalized blocks.login.
|
||||
// Кэш ограничен временем одного ответа и не требует дополнительных запросов на каждый пост.
|
||||
static String officialLogin(Connection c, Map<String, String> cache, String raw) throws SQLException {
|
||||
if (raw == null || raw.isBlank()) return raw;
|
||||
String key = raw.trim().toLowerCase(Locale.ROOT);
|
||||
String value = cache.get(key);
|
||||
if (value != null) return value;
|
||||
value = canonicalLogin(c, raw);
|
||||
if (value == null || value.isBlank()) value = raw;
|
||||
cache.put(key, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException {
|
||||
ChannelMeta meta = new ChannelMeta();
|
||||
meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF;
|
||||
@@ -86,7 +101,7 @@ final class ChannelsReadSupport {
|
||||
String sql = """
|
||||
SELECT block_bytes FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -141,7 +156,7 @@ final class ChannelsReadSupport {
|
||||
String sql = """
|
||||
SELECT COUNT(*) AS cnt FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
String login=loginFromChainName(ownerBch); ps.setString(1,login); ps.setInt(2,MSG_TYPE_TEXT); ps.setInt(3,MsgSubType.TEXT_POST); ps.setInt(4,MsgSubType.TEXT_REPOST); ps.setInt(5,MsgSubType.TEXT_ENTRYPOINT); ps.setInt(6,MsgSubType.TEXT_EXERCISE); ps.setInt(7,MsgSubType.TEXT_SERVICE); ps.setInt(8,MsgSubType.TEXT_COURSE); ps.setInt(9,lineCode); ps.setString(10,login);
|
||||
@@ -161,7 +176,7 @@ final class ChannelsReadSupport {
|
||||
String sql="""
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number DESC LIMIT 1
|
||||
""";
|
||||
try(PreparedStatement ps=c.prepareStatement(sql)){String login=loginFromChainName(ownerBch);ps.setString(1,login);ps.setInt(2,MSG_TYPE_TEXT);ps.setInt(3,MsgSubType.TEXT_POST);ps.setInt(4,MsgSubType.TEXT_REPOST);ps.setInt(5,MsgSubType.TEXT_ENTRYPOINT);ps.setInt(6,MsgSubType.TEXT_EXERCISE);ps.setInt(7,MsgSubType.TEXT_SERVICE);ps.setInt(8,MsgSubType.TEXT_COURSE);ps.setInt(9,lineCode);ps.setString(10,login);try(ResultSet rs=ps.executeQuery()){if(!rs.next())return null;PostBlock pb=new PostBlock();pb.login=rs.getString("login");pb.bchName=rs.getString("bch_name");pb.blockNumber=rs.getInt("block_number");pb.blockHash=rs.getBytes("block_hash");pb.blockBytes=rs.getBytes("block_bytes");return pb;}}
|
||||
@@ -173,7 +188,7 @@ final class ChannelsReadSupport {
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
|
||||
AND to_block_number=? AND to_block_hash=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number DESC
|
||||
LIMIT 1
|
||||
""";
|
||||
@@ -224,7 +239,7 @@ final class ChannelsReadSupport {
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number
|
||||
""" + order + (bounded ? " LIMIT ?" : "");
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -275,7 +290,7 @@ final class ChannelsReadSupport {
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
|
||||
AND to_block_number=? AND to_block_hash=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -328,7 +343,7 @@ final class ChannelsReadSupport {
|
||||
AND LOWER(to_login) = LOWER(?)
|
||||
AND to_block_number = ?
|
||||
AND to_block_hash = ?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
|
||||
""";
|
||||
int ratingsCount = 0;
|
||||
try (PreparedStatement ps = c.prepareStatement(ratingsSql)) {
|
||||
@@ -375,7 +390,7 @@ final class ChannelsReadSupport {
|
||||
String sql = """
|
||||
SELECT block_bytes FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND block_number=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -452,7 +467,7 @@ final class ChannelsReadSupport {
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND block_number=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
LIMIT 1
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(rootSql)) {
|
||||
@@ -504,7 +519,7 @@ final class ChannelsReadSupport {
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
@@ -544,7 +559,7 @@ final class ChannelsReadSupport {
|
||||
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
|
||||
FROM blocks
|
||||
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND line_code=?
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(deleteSql)) {
|
||||
@@ -580,7 +595,7 @@ final class ChannelsReadSupport {
|
||||
|
||||
String partnerBchSql = """
|
||||
SELECT blockchain_name
|
||||
FROM solana_user_pda_current
|
||||
FROM user_identity_current
|
||||
WHERE LOWER(login) = LOWER(?)
|
||||
LIMIT 1
|
||||
""";
|
||||
|
||||
+6
-3
@@ -20,6 +20,8 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetChannelMessages_Handler.class);
|
||||
@@ -44,6 +46,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
boolean asc = req.getSort() == null || !"desc".equalsIgnoreCase(req.getSort());
|
||||
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
Map<String, String> officialLogins = new HashMap<>();
|
||||
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
||||
if (viewerLogin == null || viewerLogin.isBlank()) {
|
||||
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
||||
@@ -58,7 +61,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
|
||||
Net_GetChannelMessages_Response.Channel channel = new Net_GetChannelMessages_Response.Channel();
|
||||
channel.setOwnerBlockchainName(ownerBch);
|
||||
channel.setOwnerLogin(BlockchainNameUtil.loginFromBlockchainName(ownerBch));
|
||||
channel.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, BlockchainNameUtil.loginFromBlockchainName(ownerBch)));
|
||||
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, ownerBch, lineCode);
|
||||
channel.setChannelName(meta.channelName);
|
||||
channel.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
||||
@@ -88,7 +91,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
eventRef.setBlockNumber(event.blockNumber);
|
||||
eventRef.setBlockHash(ChannelsReadSupport.toHex(event.blockHash));
|
||||
outEvent.setMessageRef(eventRef);
|
||||
outEvent.setAuthorLogin(event.login);
|
||||
outEvent.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, event.login));
|
||||
outEvent.setAuthorBlockchainName(event.bchName);
|
||||
outEvent.setLineStep(event.lineStep);
|
||||
outEvent.setCreatedAtMs(event.createdAtMs);
|
||||
@@ -133,7 +136,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||
msgRef.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
||||
item.setMessageRef(msgRef);
|
||||
item.setMsgSubType(post.msgSubType);
|
||||
item.setAuthorLogin(post.login);
|
||||
item.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, post.login));
|
||||
item.setAuthorBlockchainName(post.bchName);
|
||||
item.setLineStep(post.thisLineNumber);
|
||||
item.setTargetBlockchainName(post.toBchName);
|
||||
|
||||
+11
-8
@@ -21,6 +21,8 @@ import java.util.Comparator;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetMessageThread_Handler.class);
|
||||
@@ -37,6 +39,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
int childLimit = req.getLimitChildrenPerNode() == null ? 50 : Math.max(1, req.getLimitChildrenPerNode());
|
||||
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
Map<String, String> officialLogins = new HashMap<>();
|
||||
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
||||
if (viewerLogin == null || viewerLogin.isBlank()) {
|
||||
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
||||
@@ -51,7 +54,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
|
||||
resp.setFocus(toNode(c, focusRow, viewerLogin));
|
||||
resp.setFocus(toNode(c, focusRow, viewerLogin, officialLogins));
|
||||
|
||||
List<Net_GetMessageThread_Response.MessageNode> ancestors = new ArrayList<>();
|
||||
PostRow cur = focusRow;
|
||||
@@ -68,12 +71,12 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
|
||||
}
|
||||
if (parent == null) break;
|
||||
ancestors.add(0, toNode(c, parent, viewerLogin));
|
||||
ancestors.add(0, toNode(c, parent, viewerLogin, officialLogins));
|
||||
cur = parent;
|
||||
}
|
||||
resp.setAncestors(ancestors);
|
||||
|
||||
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin));
|
||||
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin, officialLogins));
|
||||
return resp;
|
||||
} catch (Exception e) {
|
||||
log.error("GetMessageThread failed", e);
|
||||
@@ -97,14 +100,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
return null;
|
||||
}
|
||||
|
||||
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin) throws Exception {
|
||||
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin, Map<String, String> officialLogins) throws Exception {
|
||||
if (depthDown <= 0) return List.of();
|
||||
List<PostRow> replies = findRepliesAndRatings(c, parent.bchName, parent.blockNumber, parent.blockHash, childLimit);
|
||||
List<Net_GetMessageThread_Response.MessageNodeTree> out = new ArrayList<>();
|
||||
for (PostRow row : replies) {
|
||||
Net_GetMessageThread_Response.MessageNodeTree t = new Net_GetMessageThread_Response.MessageNodeTree();
|
||||
t.setNode(toNode(c, row, viewerLogin));
|
||||
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin));
|
||||
t.setNode(toNode(c, row, viewerLogin, officialLogins));
|
||||
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin, officialLogins));
|
||||
out.add(t);
|
||||
}
|
||||
return out;
|
||||
@@ -233,14 +236,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||
return row;
|
||||
}
|
||||
|
||||
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin) throws Exception {
|
||||
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin, Map<String, String> officialLogins) throws Exception {
|
||||
Net_GetMessageThread_Response.MessageNode node = new Net_GetMessageThread_Response.MessageNode();
|
||||
Net_GetChannelMessages_Response.BlockRef ref = new Net_GetChannelMessages_Response.BlockRef();
|
||||
ref.setBlockNumber(row.blockNumber);
|
||||
ref.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
||||
node.setMessageRef(ref);
|
||||
node.setMsgSubType(row.msgSubType);
|
||||
node.setAuthorLogin(row.login);
|
||||
node.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, row.login));
|
||||
node.setAuthorBlockchainName(row.bchName);
|
||||
node.setLineStep(row.thisLineNumber);
|
||||
node.setTargetBlockchainName(row.toBchName);
|
||||
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportHistory_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportHistory_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Публичная постраничная история Stars из финализированного Helius-индекса. */
|
||||
public final class Net_GetSupportHistory_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetSupportHistory_Handler.class);
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext context) {
|
||||
Net_GetSupportHistory_Request req = (Net_GetSupportHistory_Request) baseRequest;
|
||||
String login = req.getLogin() == null ? "" : req.getLogin().trim();
|
||||
if (login.isEmpty() || login.length() > 255 || login.chars().anyMatch(Character::isISOControl)) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||
"bad_login", "Некорректный логин");
|
||||
}
|
||||
int limit = req.getLimit() == null ? 20 : req.getLimit();
|
||||
int offset = req.getOffset() == null ? 0 : req.getOffset();
|
||||
if (limit < 1 || limit > 50 || offset < 0 || offset > 10_000) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||
"bad_pagination", "Некорректные параметры страницы истории");
|
||||
}
|
||||
Net_GetSupportHistory_Response response = new Net_GetSupportHistory_Response();
|
||||
response.setOp(req.getOp()); response.setRequestId(req.getRequestId());
|
||||
response.setStatus(WireCodes.Status.OK);
|
||||
response.setLogin(login); response.setReady(false);
|
||||
response.setTransfers(List.of()); response.setHasMore(false);
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT history_complete FROM solana_support_sync_state WHERE id=1");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next() || !rs.getBoolean(1)) return response;
|
||||
}
|
||||
response.setReady(true);
|
||||
List<Net_GetSupportHistory_Response.Transfer> entries = new ArrayList<>();
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT signature,instruction_index,slot,block_time,kind,sender_login,recipient_login,
|
||||
amount_lamports,amount_star_cents,recipient_star_cents,dao_star_cents,target_type,
|
||||
channel_block_number,channel_block_hash,message_block_number,message_block_hash
|
||||
FROM solana_support_transfers
|
||||
WHERE lower(sender_login)=? OR lower(recipient_login)=?
|
||||
ORDER BY slot DESC, instruction_index DESC, signature DESC LIMIT ? OFFSET ?
|
||||
""")) {
|
||||
String name = login.toLowerCase(Locale.ROOT);
|
||||
ps.setString(1, name); ps.setString(2, name);
|
||||
ps.setInt(3, limit + 1); ps.setInt(4, offset);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
Long time = rs.getObject(4) == null ? null : rs.getLong(4);
|
||||
entries.add(new Net_GetSupportHistory_Response.Transfer(
|
||||
rs.getString(1), rs.getInt(2), rs.getLong(3), time,
|
||||
rs.getString(5), rs.getString(6), rs.getString(7),
|
||||
rs.getBigDecimal(8).toBigIntegerExact().toString(),
|
||||
rs.getBigDecimal(9).toBigIntegerExact().toString(),
|
||||
rs.getBigDecimal(10).toBigIntegerExact().toString(),
|
||||
rs.getBigDecimal(11).toBigIntegerExact().toString(),
|
||||
rs.getInt(12),
|
||||
rs.getBigDecimal(13) == null ? null : rs.getBigDecimal(13).toBigIntegerExact().toString(),
|
||||
rs.getString(14),
|
||||
rs.getBigDecimal(15) == null ? null : rs.getBigDecimal(15).toBigIntegerExact().toString(),
|
||||
rs.getString(16)));
|
||||
}
|
||||
}
|
||||
}
|
||||
response.setHasMore(entries.size() > limit);
|
||||
response.setTransfers(entries.size() > limit ? entries.subList(0, limit) : entries);
|
||||
return response;
|
||||
} catch (SQLException e) {
|
||||
log.error("GetSupportHistory failed", e);
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR,
|
||||
"support_history_unavailable", "История поддержки временно недоступна");
|
||||
}
|
||||
}
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportStats_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportStats_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Публичные три суммы из локальной PostgreSQL без RPC на каждый профиль.
|
||||
* Индексатор формирует кеш только из финализированных on-chain донатов.
|
||||
*/
|
||||
public final class Net_GetSupportStats_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetSupportStats_Handler.class);
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
var req = (Net_GetSupportStats_Request) baseRequest;
|
||||
String login = req.getLogin() == null ? "" : req.getLogin().trim();
|
||||
if (login.isEmpty() || login.length() > 255 || login.chars().anyMatch(c -> Character.isISOControl(c))) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||
"bad_login", "Некорректный логин");
|
||||
}
|
||||
var result = new Net_GetSupportStats_Response();
|
||||
result.setOp(req.getOp());
|
||||
result.setRequestId(req.getRequestId());
|
||||
result.setStatus(WireCodes.Status.OK);
|
||||
result.setLogin(login);
|
||||
result.setAvailable(false);
|
||||
result.setReady(false);
|
||||
result.setSupportSentStarCents("0");
|
||||
result.setSupportReceivedStarCents("0");
|
||||
result.setDaoDirectStarCents("0");
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT history_complete FROM solana_support_sync_state WHERE id=1")) {
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next() || !rs.getBoolean(1)) return result;
|
||||
}
|
||||
}
|
||||
result.setReady(true);
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT 1 FROM solana_user_pda_current WHERE normalized_login=? LIMIT 1")) {
|
||||
ps.setString(1, login.toLowerCase(Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) return result; // Free-пользователю не придумываем статистику
|
||||
}
|
||||
}
|
||||
result.setAvailable(true);
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT support_sent, support_received, dao_direct
|
||||
FROM solana_support_user_stats WHERE normalized_login=?
|
||||
""")) {
|
||||
ps.setString(1, login.toLowerCase(Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
result.setSupportSentStarCents(rs.getBigDecimal(1).toBigIntegerExact().toString());
|
||||
result.setSupportReceivedStarCents(rs.getBigDecimal(2).toBigIntegerExact().toString());
|
||||
result.setDaoDirectStarCents(rs.getBigDecimal(3).toBigIntegerExact().toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
result.setReady(true);
|
||||
return result;
|
||||
} catch (SQLException failure) {
|
||||
log.error("GetSupportStats failed for {}", login, failure);
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR,
|
||||
"support_stats_unavailable", "Статистика поддержки недоступна");
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportTotals_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetSupportTotals_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
import shine.db.DbController;
|
||||
import java.sql.*;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Публичные итоги только после проверки канала, автора и фактических блоков.
|
||||
* Сырые идентификаторы из Solana-инструкций НЕ являются доказательством авторства.
|
||||
*/
|
||||
public final class Net_GetSupportTotals_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_GetSupportTotals_Handler.class);
|
||||
@Override public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||
var request = (Net_GetSupportTotals_Request) baseRequest;
|
||||
String hash = request.getChannelRootBlockHash();
|
||||
Long number = request.getChannelRootBlockNumber();
|
||||
if (hash == null || !hash.matches("(?i)[0-9a-f]{64}") || number == null || number < 0 || number > Integer.MAX_VALUE) {
|
||||
return NetExceptionResponseFactory.error(request, WireCodes.Status.BAD_REQUEST,
|
||||
"bad_selector", "Некорректный идентификатор канала");
|
||||
}
|
||||
var response = new Net_GetSupportTotals_Response();
|
||||
response.setOp(request.getOp());
|
||||
response.setRequestId(request.getRequestId());
|
||||
response.setStatus(WireCodes.Status.OK);
|
||||
response.setChannelReceivedStarCents("0");
|
||||
response.setMessages(List.of());
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
// Для каждой транзакции проверяем существование канала и соответствие
|
||||
// получателя оригинальному владельцу или автору блока публикации.
|
||||
String sql = """
|
||||
SELECT COALESCE(SUM(t.recipient_star_cents),0) AS total
|
||||
FROM solana_support_transfers t
|
||||
JOIN channel_names_state cn
|
||||
ON cn.channel_root_block_number = ?
|
||||
AND encode(cn.channel_root_block_hash,'hex') = ?
|
||||
AND t.channel_block_number = cn.channel_root_block_number
|
||||
AND t.channel_block_hash = encode(cn.channel_root_block_hash,'hex')
|
||||
WHERE t.kind='USER' AND (
|
||||
(t.target_type = 1 AND lower(t.recipient_login)=lower(cn.owner_login))
|
||||
OR (t.target_type = 2 AND EXISTS (
|
||||
SELECT 1 FROM blocks b WHERE b.block_number = t.message_block_number
|
||||
AND encode(b.block_hash,'hex')=t.message_block_hash
|
||||
AND lower(b.login)=lower(t.recipient_login)
|
||||
AND b.bch_name=cn.owner_bch_name
|
||||
))
|
||||
)
|
||||
""";
|
||||
try (PreparedStatement p = c.prepareStatement(sql)) {
|
||||
p.setLong(1, number); p.setString(2, hash.toLowerCase(Locale.ROOT));
|
||||
try (ResultSet r = p.executeQuery()) {
|
||||
if (r.next()) response.setChannelReceivedStarCents(r.getBigDecimal(1).toBigIntegerExact().toString());
|
||||
}
|
||||
}
|
||||
String messagesSql = """
|
||||
SELECT t.message_block_number, t.message_block_hash,
|
||||
SUM(t.recipient_star_cents) AS total
|
||||
FROM solana_support_transfers t
|
||||
JOIN channel_names_state cn
|
||||
ON cn.channel_root_block_number = ?
|
||||
AND encode(cn.channel_root_block_hash,'hex') = ?
|
||||
AND t.channel_block_number=cn.channel_root_block_number
|
||||
AND t.channel_block_hash=encode(cn.channel_root_block_hash,'hex')
|
||||
WHERE t.kind='USER' AND t.target_type=2
|
||||
AND EXISTS (SELECT 1 FROM blocks b
|
||||
WHERE b.block_number=t.message_block_number
|
||||
AND encode(b.block_hash,'hex')=t.message_block_hash
|
||||
AND lower(b.login)=lower(t.recipient_login)
|
||||
AND b.bch_name=cn.owner_bch_name)
|
||||
GROUP BY t.message_block_number,t.message_block_hash
|
||||
ORDER BY total DESC LIMIT 2000
|
||||
""";
|
||||
List<Net_GetSupportTotals_Response.MessageTotal> items = new ArrayList<>();
|
||||
try (PreparedStatement p = c.prepareStatement(messagesSql)) {
|
||||
p.setLong(1, number); p.setString(2, hash.toLowerCase(Locale.ROOT));
|
||||
try (ResultSet r = p.executeQuery()) {
|
||||
while (r.next()) items.add(new Net_GetSupportTotals_Response.MessageTotal(
|
||||
r.getBigDecimal(1).toBigIntegerExact().toString(), r.getString(2),
|
||||
r.getBigDecimal(3).toBigIntegerExact().toString()));
|
||||
}
|
||||
}
|
||||
response.setMessages(items);
|
||||
return response;
|
||||
} catch (SQLException e) {
|
||||
log.error("GetSupportTotals failed", e);
|
||||
return NetExceptionResponseFactory.error(request, WireCodes.Status.INTERNAL_ERROR,
|
||||
"support_totals_unavailable", "Статистика поддержки пока недоступна");
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
-5
@@ -19,6 +19,8 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(Net_ListSubscriptionsFeed_Handler.class);
|
||||
@@ -59,11 +61,12 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||
|
||||
private List<Net_ListSubscriptionsFeed_Response.ChannelSummary> buildSummaries(Connection c, String viewerLogin, List<ChannelKey> keys) throws Exception {
|
||||
List<Net_ListSubscriptionsFeed_Response.ChannelSummary> out = new ArrayList<>();
|
||||
Map<String, String> officialLogins = new HashMap<>();
|
||||
for (ChannelKey key : keys) {
|
||||
Net_ListSubscriptionsFeed_Response.ChannelSummary row = new Net_ListSubscriptionsFeed_Response.ChannelSummary();
|
||||
Net_ListSubscriptionsFeed_Response.ChannelRef channelRef = new Net_ListSubscriptionsFeed_Response.ChannelRef();
|
||||
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, key.ownerBch, key.rootNumber);
|
||||
channelRef.setOwnerLogin(key.ownerLogin);
|
||||
channelRef.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, key.ownerLogin));
|
||||
channelRef.setOwnerBlockchainName(key.ownerBch);
|
||||
channelRef.setChannelName(meta.channelName);
|
||||
channelRef.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
||||
@@ -108,7 +111,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||
lm.setMessageRef(msgRef);
|
||||
lm.setText(textInfo.text);
|
||||
lm.setCreatedAtMs(textInfo.createdAtMs);
|
||||
lm.setAuthorLogin(actual.login);
|
||||
lm.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, actual.login));
|
||||
lm.setAuthorBlockchainName(actual.bchName);
|
||||
row.setLastMessage(lm);
|
||||
}
|
||||
@@ -118,10 +121,11 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||
return out;
|
||||
}
|
||||
|
||||
// Общий реестр включает FREE_CERT и пользователей, зарегистрированных через Solana.
|
||||
private List<ChannelKey> loadOwnChannels(Connection c, String canonicalLogin) throws Exception {
|
||||
List<ChannelKey> out = new ArrayList<>();
|
||||
String activeBch = null;
|
||||
try (PreparedStatement ps=c.prepareStatement("SELECT blockchain_name FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1")){
|
||||
try (PreparedStatement ps=c.prepareStatement("SELECT blockchain_name FROM user_identity_current WHERE LOWER(login)=LOWER(?) LIMIT 1")){
|
||||
ps.setString(1,canonicalLogin);try(ResultSet rs=ps.executeQuery()){if(rs.next())activeBch=rs.getString(1);}
|
||||
}
|
||||
if(activeBch==null||activeBch.isBlank())return out;
|
||||
@@ -136,11 +140,11 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||
List<ChannelKey> out = new ArrayList<>();
|
||||
String sql = """
|
||||
SELECT cs.to_login,
|
||||
COALESCE(cn.owner_bch_name,(SELECT su.blockchain_name FROM solana_user_pda_current su WHERE LOWER(su.login)=LOWER(cs.to_login) LIMIT 1)) AS to_bch_name,
|
||||
COALESCE(cn.owner_bch_name,(SELECT su.blockchain_name FROM user_identity_current su WHERE LOWER(su.login)=LOWER(cs.to_login) LIMIT 1)) AS to_bch_name,
|
||||
COALESCE(cs.to_block_number,0) AS root_number, cs.to_block_hash
|
||||
FROM connections_state cs
|
||||
LEFT 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 cs.login=? AND cs.rel_type=?
|
||||
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=?
|
||||
ORDER BY cs.to_login, root_number
|
||||
""";
|
||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** Публичная история подтверждённых пожертвований; пагинация ограничена сервером. */
|
||||
public final class Net_GetSupportHistory_Request extends Net_Request {
|
||||
private String login;
|
||||
private Integer limit;
|
||||
private Integer offset;
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String v) { login = v; }
|
||||
public Integer getLimit() { return limit; }
|
||||
public void setLimit(Integer v) { limit = v; }
|
||||
public Integer getOffset() { return offset; }
|
||||
public void setOffset(Integer v) { offset = v; }
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import java.util.List;
|
||||
|
||||
/** Денежные суммы передаются строками: JS Number не вмещает u64. */
|
||||
public final class Net_GetSupportHistory_Response extends Net_Response {
|
||||
private String login;
|
||||
private boolean ready;
|
||||
private boolean hasMore;
|
||||
private List<Transfer> transfers;
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String v) { login = v; }
|
||||
public boolean isReady() { return ready; }
|
||||
public void setReady(boolean v) { ready = v; }
|
||||
public boolean isHasMore() { return hasMore; }
|
||||
public void setHasMore(boolean v) { hasMore = v; }
|
||||
public List<Transfer> getTransfers() { return transfers; }
|
||||
public void setTransfers(List<Transfer> v) { transfers = v; }
|
||||
public record Transfer(String signature, int instructionIndex, long slot, Long blockTime,
|
||||
String kind, String senderLogin, String recipientLogin, String amountLamports,
|
||||
String amountStarCents, String recipientStarCents, String daoStarCents,
|
||||
int targetType, String channelBlockNumber, String channelBlockHash,
|
||||
String messageBlockNumber, String messageBlockHash) { }
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** Публичная статистика поддержки Paid-пользователя, логин SHiNE. */
|
||||
public final class Net_GetSupportStats_Request extends Net_Request {
|
||||
private String login;
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String value) { login = value; }
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
|
||||
/** Суммы передаются строками в сотых долях Stars: JS Number теряет точность u64. */
|
||||
public final class Net_GetSupportStats_Response extends Net_Response {
|
||||
private String login;
|
||||
private boolean available;
|
||||
private boolean ready;
|
||||
private String supportSentStarCents;
|
||||
private String supportReceivedStarCents;
|
||||
private String daoDirectStarCents;
|
||||
|
||||
public String getLogin() { return login; }
|
||||
public void setLogin(String value) { login = value; }
|
||||
public boolean isAvailable() { return available; }
|
||||
public void setAvailable(boolean value) { available = value; }
|
||||
public boolean isReady() { return ready; }
|
||||
public void setReady(boolean value) { ready = value; }
|
||||
public String getSupportSentStarCents() { return supportSentStarCents; }
|
||||
public void setSupportSentStarCents(String value) { supportSentStarCents = value; }
|
||||
public String getSupportReceivedStarCents() { return supportReceivedStarCents; }
|
||||
public void setSupportReceivedStarCents(String value) { supportReceivedStarCents = value; }
|
||||
public String getDaoDirectStarCents() { return daoDirectStarCents; }
|
||||
public void setDaoDirectStarCents(String value) { daoDirectStarCents = value; }
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** Агрегаты поддержки только по проверенной корневой ссылке канала. */
|
||||
public class Net_GetSupportTotals_Request extends Net_Request {
|
||||
private String channelRootBlockHash;
|
||||
private Long channelRootBlockNumber;
|
||||
public String getChannelRootBlockHash() { return channelRootBlockHash; }
|
||||
public void setChannelRootBlockHash(String value) { channelRootBlockHash = value; }
|
||||
public Long getChannelRootBlockNumber() { return channelRootBlockNumber; }
|
||||
public void setChannelRootBlockNumber(Long value) { channelRootBlockNumber = value; }
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import java.util.List;
|
||||
|
||||
public class Net_GetSupportTotals_Response extends Net_Response {
|
||||
private String channelReceivedStarCents;
|
||||
private List<MessageTotal> messages;
|
||||
public String getChannelReceivedStarCents() { return channelReceivedStarCents; }
|
||||
public void setChannelReceivedStarCents(String value) { channelReceivedStarCents = value; }
|
||||
public List<MessageTotal> getMessages() { return messages; }
|
||||
public void setMessages(List<MessageTotal> value) { messages = value; }
|
||||
public record MessageTotal(String blockNumber, String blockHash, String receivedStarCents) {}
|
||||
}
|
||||
+17
@@ -11,6 +11,23 @@ import java.util.Base64;
|
||||
final class KeyRotationApiSupport {
|
||||
private KeyRotationApiSupport() {}
|
||||
|
||||
/** Free identity не имеет Solana PDA и не вправе менять ключи/форки. */
|
||||
static server.logic.ws_protocol.JSON.entyties.Net_Response denyFreeRotation(
|
||||
server.logic.ws_protocol.JSON.entyties.Net_Request req, String login) {
|
||||
try {
|
||||
var identity = shine.db.dao.RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity == null) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 404, "KEY_ROTATION_USER_NOT_FOUND", "Пользователь не найден");
|
||||
if (identity.isFree()) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 403, "KEY_ROTATION_PAID_ONLY", "Для смены ключей необходима регистрация в Solana");
|
||||
return null;
|
||||
} catch (java.sql.SQLException e) {
|
||||
// fail closed при неготовой миграции / ошибке БД
|
||||
return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||
req, 503, "KEY_ROTATION_IDENTITY_UNAVAILABLE", "Невозможно проверить полномочия пользователя");
|
||||
}
|
||||
}
|
||||
|
||||
static String normalizePublicKey32(String raw) {
|
||||
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
|
||||
if (normalized == null || normalized.isBlank()) {
|
||||
|
||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationAbort_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
|
||||
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
|
||||
|
||||
+2
@@ -44,6 +44,8 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
|
||||
}
|
||||
|
||||
+2
@@ -22,6 +22,8 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
String login = ctx.getLogin().trim();
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||
|
||||
+2
@@ -47,6 +47,8 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
|
||||
KeyRotationSessionEntry initial;
|
||||
|
||||
+14
-1
@@ -24,6 +24,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
|
||||
final String signature;
|
||||
@@ -39,7 +41,18 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
|
||||
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_ACTIVE", "Активная ротация отсутствует");
|
||||
}
|
||||
|
||||
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) {
|
||||
// Solana sync и rebuild работают независимо от уведомления клиента.
|
||||
// При повторе после подтверждённой PDA возвращаем реальный этап, а не 409.
|
||||
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED
|
||||
|| current.getStatus() == KeyRotationStatus.REBUILDING_SERVER
|
||||
|| current.getStatus() == KeyRotationStatus.WALLET_MIGRATION
|
||||
|| current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION
|
||||
|| current.getStatus() == KeyRotationStatus.FINALIZING) {
|
||||
String stored = current.getPdaRotationSignature();
|
||||
if (stored != null && !stored.isBlank() && !stored.equals(signature)) {
|
||||
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_PDA_SIGNATURE_CONFLICT",
|
||||
"Для этой ротации уже сохранена другая Solana transaction signature");
|
||||
}
|
||||
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
|
||||
if (fresh != null) ctx.setCurrentUser(fresh);
|
||||
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
|
||||
|
||||
+2
@@ -39,6 +39,8 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
String login = ctx.getLogin().trim();
|
||||
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
|
||||
if (currentSessionId.isEmpty()) {
|
||||
|
||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
|
||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||
}
|
||||
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||
if (freeCheck != null) return freeCheck;
|
||||
try {
|
||||
String login = ctx.getLogin().trim();
|
||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
|
||||
/** API доступно анонимному клиенту, но без разрешения приватных операций. */
|
||||
public final class Net_Registration_Handler implements JsonMessageHandler {
|
||||
private final String operation;
|
||||
private static final java.util.Map<ConnectionContext, long[]> LIMITS =
|
||||
java.util.Collections.synchronizedMap(new java.util.WeakHashMap<>());
|
||||
private static long globalMinute=-1;
|
||||
private static int globalHits=0;
|
||||
private static boolean throttled(ConnectionContext ctx) {
|
||||
long minute=System.currentTimeMillis()/60000L;
|
||||
synchronized (LIMITS) {
|
||||
if(globalMinute!=minute){globalMinute=minute;globalHits=0;}
|
||||
if(++globalHits>1200) return true;
|
||||
if(ctx==null) return false;
|
||||
long[] bucket=LIMITS.computeIfAbsent(ctx, c->new long[]{minute,0});
|
||||
if(bucket[0]!=minute){bucket[0]=minute;bucket[1]=0;}
|
||||
return ++bucket[1]>30;
|
||||
}
|
||||
}
|
||||
public Net_Registration_Handler(String operation) { this.operation=operation; }
|
||||
@Override public Net_Response handle(Net_Request base, ConnectionContext ctx) throws Exception {
|
||||
Net_Registration_Request request=(Net_Registration_Request)base;
|
||||
if (throttled(ctx)) return NetExceptionResponseFactory.error(request,429,"RATE_LIMITED","Слишком много запросов регистрации");
|
||||
RegistrationApiBridge.Service service=RegistrationApiBridge.get();
|
||||
if (service==null) return NetExceptionResponseFactory.error(request,503,"REGISTRATION_UNAVAILABLE","Регистрация на сервере пока не настроена");
|
||||
try {
|
||||
java.util.Map<String,Object> values=service.execute(operation,request);
|
||||
Net_Registration_Response out=new Net_Registration_Response();
|
||||
out.setOp(request.getOp()); out.setRequestId(request.getRequestId());
|
||||
out.setStatus(WireCodes.Status.OK); out.setValues(values);
|
||||
return out;
|
||||
} catch (IllegalArgumentException e) {
|
||||
// Без echo исходного email, чтобы не публиковать PII в ответе/логе.
|
||||
return NetExceptionResponseFactory.error(request,400,"INVALID_REGISTRATION_INPUT","Данные регистрации не прошли проверку");
|
||||
} catch (IllegalStateException e) {
|
||||
return NetExceptionResponseFactory.error(request,409,"REGISTRATION_CONFLICT","Регистрация недоступна или данные уже заняты");
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
|
||||
/** JSON payload; публичные данные пользователя, пароли/приватные ключи не принимаются. */
|
||||
public final class Net_Registration_Request extends Net_Request {
|
||||
private String fullLogin;
|
||||
private String email;
|
||||
private String rootPublicKeyB64;
|
||||
private String blockchainPublicKeyB64;
|
||||
private String clientPublicKeyB64;
|
||||
private String challengeId;
|
||||
private String code;
|
||||
public String getFullLogin() { return fullLogin; }
|
||||
public void setFullLogin(String v) { fullLogin = v; }
|
||||
public String getEmail() { return email; }
|
||||
public void setEmail(String v) { email = v; }
|
||||
public String getRootPublicKeyB64() { return rootPublicKeyB64; }
|
||||
public void setRootPublicKeyB64(String v) { rootPublicKeyB64 = v; }
|
||||
public String getBlockchainPublicKeyB64() { return blockchainPublicKeyB64; }
|
||||
public void setBlockchainPublicKeyB64(String v) { blockchainPublicKeyB64 = v; }
|
||||
public String getClientPublicKeyB64() { return clientPublicKeyB64; }
|
||||
public void setClientPublicKeyB64(String v) { clientPublicKeyB64 = v; }
|
||||
public String getChallengeId() { return challengeId; }
|
||||
public void setChallengeId(String v) { challengeId = v; }
|
||||
public String getCode() { return code; }
|
||||
public void setCode(String v) { code = v; }
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import java.util.Map;
|
||||
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||
|
||||
/** Значения результата помещаются на верхний уровень объекта перед стандартной WS-обёрткой. */
|
||||
public final class Net_Registration_Response extends Net_Response {
|
||||
private Map<String, Object> values = Map.of();
|
||||
public void setValues(Map<String,Object> values) { this.values = Map.copyOf(values); }
|
||||
@JsonAnyGetter public Map<String,Object> getValues() { return values; }
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/** SPI: HTTP/WS модуль не зависит от archive-модуля, устраняя циклический Gradle dependency. */
|
||||
public final class RegistrationApiBridge {
|
||||
@FunctionalInterface public interface Service {
|
||||
Map<String, Object> execute(String operation, Net_Registration_Request request) throws Exception;
|
||||
}
|
||||
private static volatile Service service;
|
||||
private RegistrationApiBridge() {}
|
||||
public static void install(Service implementation) { service = java.util.Objects.requireNonNull(implementation); }
|
||||
public static void uninstall() { service = null; }
|
||||
public static Service get() { return service; }
|
||||
}
|
||||
+1
@@ -32,6 +32,7 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
|
||||
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
|
||||
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
|
||||
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
|
||||
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
|
||||
|
||||
return resp;
|
||||
}
|
||||
|
||||
+4
@@ -26,6 +26,10 @@ public class Net_GetServerInfo_Response extends Net_Response {
|
||||
private String description;
|
||||
private String origin;
|
||||
private String extraInfo;
|
||||
private String solanaCluster;
|
||||
|
||||
public String getSolanaCluster() { return solanaCluster; }
|
||||
public void setSolanaCluster(String cluster) { this.solanaCluster = cluster; }
|
||||
|
||||
public String getUrl() { return url; }
|
||||
public void setUrl(String url) { this.url = url; }
|
||||
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.tempToTest;
|
||||
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_TestGetFreeAvatarQuota_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_TestGetFreeAvatarQuota_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
|
||||
public class Net_TestGetFreeAvatarQuota_Handler implements JsonMessageHandler {
|
||||
|
||||
private final TestFreeAvatarArweaveService service = new TestFreeAvatarArweaveService();
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) throws Exception {
|
||||
Net_TestGetFreeAvatarQuota_Request req = (Net_TestGetFreeAvatarQuota_Request) baseRequest;
|
||||
if (ctx == null || !ctx.isAuthenticatedUser()) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Требуется авторизация");
|
||||
}
|
||||
|
||||
String login = String.valueOf(ctx.getLogin() == null ? "" : ctx.getLogin()).trim();
|
||||
TestFreeAvatarArweaveService.Quota quota = service.getQuota(login);
|
||||
|
||||
Net_TestGetFreeAvatarQuota_Response resp = new Net_TestGetFreeAvatarQuota_Response();
|
||||
resp.setOp(req.getOp());
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
resp.setEnabled(quota.enabled());
|
||||
resp.setLimit(quota.limit());
|
||||
resp.setUsedCount(quota.usedCount());
|
||||
resp.setRemainingCount(quota.remainingCount());
|
||||
resp.setMaxBytes(service.getMaxBytes());
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
-60
@@ -1,60 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.tempToTest;
|
||||
|
||||
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_TestUploadFreeAvatar_Request;
|
||||
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_TestUploadFreeAvatar_Response;
|
||||
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||
import server.logic.ws_protocol.WireCodes;
|
||||
|
||||
import java.util.Base64;
|
||||
|
||||
public class Net_TestUploadFreeAvatar_Handler implements JsonMessageHandler {
|
||||
|
||||
private final TestFreeAvatarArweaveService service = new TestFreeAvatarArweaveService();
|
||||
|
||||
@Override
|
||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) throws Exception {
|
||||
Net_TestUploadFreeAvatar_Request req = (Net_TestUploadFreeAvatar_Request) baseRequest;
|
||||
if (ctx == null || !ctx.isAuthenticatedUser()) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED, "NOT_AUTHENTICATED", "Требуется авторизация");
|
||||
}
|
||||
|
||||
String fileBase64 = String.valueOf(req.getFileBytesBase64() == null ? "" : req.getFileBytesBase64()).trim();
|
||||
String contentType = String.valueOf(req.getContentType() == null ? "" : req.getContentType()).trim();
|
||||
if (fileBase64.isBlank() || contentType.isBlank()) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "Нужно передать contentType и fileBytesBase64.");
|
||||
}
|
||||
|
||||
byte[] fileBytes;
|
||||
try {
|
||||
fileBytes = Base64.getDecoder().decode(fileBase64);
|
||||
} catch (IllegalArgumentException e) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_BASE64", "fileBytesBase64 должен быть корректным Base64.");
|
||||
}
|
||||
|
||||
String login = String.valueOf(ctx.getLogin() == null ? "" : ctx.getLogin()).trim();
|
||||
try {
|
||||
TestFreeAvatarArweaveService.UploadResult result = service.uploadAvatar(login, contentType, fileBytes, req.getSha256Hex());
|
||||
Net_TestUploadFreeAvatar_Response resp = new Net_TestUploadFreeAvatar_Response();
|
||||
resp.setOp(req.getOp());
|
||||
resp.setRequestId(req.getRequestId());
|
||||
resp.setStatus(WireCodes.Status.OK);
|
||||
resp.setTxId(result.txId());
|
||||
resp.setSha256Hex(result.sha256Hex());
|
||||
resp.setUsedCount(result.usedCount());
|
||||
resp.setRemainingCount(result.remainingCount());
|
||||
resp.setLimit(result.limit());
|
||||
resp.setGateway(result.gateway());
|
||||
return resp;
|
||||
} catch (TestFreeAvatarArweaveService.FreeAvatarLimitExceededException e) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "FREE_AVATAR_LIMIT_EXHAUSTED", e.getMessage());
|
||||
} catch (IllegalArgumentException e) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_AVATAR_FILE", e.getMessage());
|
||||
} catch (IllegalStateException e) {
|
||||
return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR, "FREE_AVATAR_TEMP_DISABLED", e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
-391
@@ -1,391 +0,0 @@
|
||||
package server.logic.ws_protocol.JSON.handlers.tempToTest;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import shine.db.dao.TestFreeAvatarUploadsDAO;
|
||||
import shine.db.entities.TestFreeAvatarUploadEntry;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.PrivateKey;
|
||||
import java.security.Signature;
|
||||
import java.security.interfaces.RSAPrivateCrtKey;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
import java.security.spec.RSAPrivateCrtKeySpec;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
public final class TestFreeAvatarArweaveService {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(TestFreeAvatarArweaveService.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final HttpClient HTTP = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.build();
|
||||
private static final Base64.Decoder B64URL = Base64.getUrlDecoder();
|
||||
private static final Base64.Encoder B64URL_NOPAD = Base64.getUrlEncoder().withoutPadding();
|
||||
private static final int DEFAULT_LIMIT = 3;
|
||||
private static final int DEFAULT_MAX_BYTES = 128 * 1024;
|
||||
private static final String DEFAULT_GATEWAY = "https://arweave.net";
|
||||
private static final ConcurrentHashMap<String, Object> LOGIN_LOCKS = new ConcurrentHashMap<>();
|
||||
|
||||
private final AppConfig config = AppConfig.getInstance();
|
||||
private final TestFreeAvatarUploadsDAO quotaDao = TestFreeAvatarUploadsDAO.getInstance();
|
||||
|
||||
public Quota getQuota(String login) throws SQLException {
|
||||
int limit = getLimitPerUser();
|
||||
TestFreeAvatarUploadEntry entry = quotaDao.getByLogin(login);
|
||||
int used = entry == null ? 0 : Math.max(0, entry.getUsedCount());
|
||||
int remaining = Math.max(0, limit - used);
|
||||
return new Quota(limit, used, remaining, isEnabled());
|
||||
}
|
||||
|
||||
public UploadResult uploadAvatar(String login, String contentType, byte[] fileBytes, String expectedSha256Hex)
|
||||
throws Exception {
|
||||
if (!isEnabled()) {
|
||||
throw new IllegalStateException("Временная бесплатная загрузка аватаров сейчас отключена на сервере.");
|
||||
}
|
||||
|
||||
String cleanLogin = String.valueOf(login == null ? "" : login).trim();
|
||||
if (cleanLogin.isBlank()) {
|
||||
throw new IllegalArgumentException("Пустой login для бесплатной загрузки аватара.");
|
||||
}
|
||||
|
||||
String cleanType = normalizeContentType(contentType);
|
||||
validatePayload(cleanType, fileBytes);
|
||||
String actualSha256Hex = sha256Hex(fileBytes);
|
||||
String expectedSha = String.valueOf(expectedSha256Hex == null ? "" : expectedSha256Hex).trim().toLowerCase();
|
||||
if (!expectedSha.isBlank() && !actualSha256Hex.equals(expectedSha)) {
|
||||
throw new IllegalArgumentException("SHA-256 файла не совпадает с присланным клиентом.");
|
||||
}
|
||||
|
||||
Object lock = LOGIN_LOCKS.computeIfAbsent(cleanLogin.toLowerCase(), key -> new Object());
|
||||
synchronized (lock) {
|
||||
Quota before = getQuota(cleanLogin);
|
||||
if (before.remainingCount() <= 0) {
|
||||
throw new FreeAvatarLimitExceededException("Вы исчерпали бесплатный лимит аватарок.");
|
||||
}
|
||||
|
||||
ArweaveConfig arConfig = loadArweaveConfig();
|
||||
String txId = postAvatarTransaction(arConfig, cleanLogin, cleanType, fileBytes);
|
||||
|
||||
int usedAfter = before.usedCount() + 1;
|
||||
int remainingAfter = Math.max(0, before.limit() - usedAfter);
|
||||
quotaDao.upsertUsage(cleanLogin, usedAfter, System.currentTimeMillis(), txId);
|
||||
return new UploadResult(txId, actualSha256Hex, usedAfter, remainingAfter, before.limit(), arConfig.gateway());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isEnabled() {
|
||||
return config.getBoolean("test.freeAvatar.enabled", true);
|
||||
}
|
||||
|
||||
public int getLimitPerUser() {
|
||||
int configured = config.getInt("test.freeAvatar.limitPerUser", DEFAULT_LIMIT);
|
||||
return Math.max(1, configured);
|
||||
}
|
||||
|
||||
public int getMaxBytes() {
|
||||
int configured = config.getInt("test.freeAvatar.maxBytes", DEFAULT_MAX_BYTES);
|
||||
return Math.max(1024, configured);
|
||||
}
|
||||
|
||||
private String postAvatarTransaction(ArweaveConfig arConfig, String login, String contentType, byte[] data)
|
||||
throws IOException, InterruptedException, GeneralSecurityException {
|
||||
String gateway = arConfig.gateway();
|
||||
String anchor = getRequiredText(gateway, "/tx_anchor");
|
||||
String reward = getRequiredText(gateway, "/price/" + data.length);
|
||||
if (!reward.matches("^\\d+$")) {
|
||||
throw new IllegalStateException("Arweave gateway вернул некорректную цену загрузки.");
|
||||
}
|
||||
|
||||
if (!arConfig.address().isBlank()) {
|
||||
String balance = getRequiredText(gateway, "/wallet/" + arConfig.address() + "/balance");
|
||||
if (balance.matches("^\\d+$")) {
|
||||
BigInteger balanceWinston = new BigInteger(balance);
|
||||
BigInteger rewardWinston = new BigInteger(reward);
|
||||
if (balanceWinston.compareTo(rewardWinston) < 0) {
|
||||
throw new IllegalStateException("На серверном Arweave-кошельке недостаточно AR для бесплатной загрузки аватара.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
byte[] dataRoot = singleChunkDataRoot(data);
|
||||
List<List<byte[]>> tagList = new ArrayList<>();
|
||||
List<Map<String, String>> jsonTags = new ArrayList<>();
|
||||
appendTag(jsonTags, tagList, "Content-Type", contentType);
|
||||
appendTag(jsonTags, tagList, "App-Name", "SHiNE");
|
||||
appendTag(jsonTags, tagList, "SHiNE-Type", "avatar-free-test");
|
||||
appendTag(jsonTags, tagList, "SHiNE-Profile-Login", login);
|
||||
|
||||
byte[] signaturePayload = deepHash(List.of(
|
||||
utf8("2"),
|
||||
b64UrlDecode(arConfig.owner()),
|
||||
new byte[0],
|
||||
utf8("0"),
|
||||
utf8(reward),
|
||||
b64UrlDecode(anchor),
|
||||
tagList,
|
||||
utf8(Integer.toString(data.length)),
|
||||
dataRoot
|
||||
));
|
||||
|
||||
byte[] rawSignature = signPayload(arConfig.privateKey(), signaturePayload);
|
||||
String txId = b64UrlEncode(sha256(rawSignature));
|
||||
|
||||
Map<String, Object> body = new LinkedHashMap<>();
|
||||
body.put("format", 2);
|
||||
body.put("id", txId);
|
||||
body.put("last_tx", anchor);
|
||||
body.put("owner", arConfig.owner());
|
||||
body.put("tags", jsonTags);
|
||||
body.put("target", "");
|
||||
body.put("quantity", "0");
|
||||
body.put("data_root", b64UrlEncode(dataRoot));
|
||||
body.put("data_size", Integer.toString(data.length));
|
||||
body.put("data", b64UrlEncode(data));
|
||||
body.put("reward", reward);
|
||||
body.put("signature", b64UrlEncode(rawSignature));
|
||||
|
||||
String bodyJson = MAPPER.writeValueAsString(body);
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(gateway + "/tx"))
|
||||
.timeout(Duration.ofSeconds(40))
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(bodyJson, StandardCharsets.UTF_8))
|
||||
.build();
|
||||
HttpResponse<String> response = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
int status = response.statusCode();
|
||||
if (status != 200 && status != 208) {
|
||||
throw new IllegalStateException("Arweave отклонил транзакцию: HTTP " + status + " " + safeBody(response.body()));
|
||||
}
|
||||
return txId;
|
||||
}
|
||||
|
||||
private ArweaveConfig loadArweaveConfig() throws IOException, GeneralSecurityException {
|
||||
String rawGateway = String.valueOf(config.getParam("test.freeAvatar.gateway") == null
|
||||
? DEFAULT_GATEWAY
|
||||
: config.getParam("test.freeAvatar.gateway")).trim();
|
||||
String gateway = rawGateway.isBlank() ? DEFAULT_GATEWAY : rawGateway.replaceAll("/+$", "");
|
||||
|
||||
String walletPathRaw = String.valueOf(config.getParam("test.freeAvatar.walletJwkPath") == null
|
||||
? ""
|
||||
: config.getParam("test.freeAvatar.walletJwkPath")).trim();
|
||||
if (walletPathRaw.isBlank()) {
|
||||
throw new IllegalStateException("Не задан test.freeAvatar.walletJwkPath в настройках сервера.");
|
||||
}
|
||||
|
||||
JsonNode jwk = MAPPER.readTree(Files.readString(Path.of(walletPathRaw), StandardCharsets.UTF_8));
|
||||
String owner = requiredText(jwk, "n");
|
||||
PrivateKey privateKey = buildPrivateKeyFromJwk(jwk);
|
||||
String computedAddress = b64UrlEncode(sha256(b64UrlDecode(owner)));
|
||||
|
||||
String expectedAddress = String.valueOf(config.getParam("test.freeAvatar.walletAddress") == null
|
||||
? ""
|
||||
: config.getParam("test.freeAvatar.walletAddress")).trim();
|
||||
if (!expectedAddress.isBlank() && !expectedAddress.equals(computedAddress)) {
|
||||
throw new IllegalStateException("test.freeAvatar.walletAddress не совпадает с адресом из JWK.");
|
||||
}
|
||||
|
||||
return new ArweaveConfig(gateway, owner, computedAddress, privateKey);
|
||||
}
|
||||
|
||||
private static PrivateKey buildPrivateKeyFromJwk(JsonNode jwk) throws GeneralSecurityException {
|
||||
RSAPrivateCrtKeySpec spec = new RSAPrivateCrtKeySpec(
|
||||
asBigInt(requiredText(jwk, "n")),
|
||||
asBigInt(requiredText(jwk, "e")),
|
||||
asBigInt(requiredText(jwk, "d")),
|
||||
asBigInt(requiredText(jwk, "p")),
|
||||
asBigInt(requiredText(jwk, "q")),
|
||||
asBigInt(requiredText(jwk, "dp")),
|
||||
asBigInt(requiredText(jwk, "dq")),
|
||||
asBigInt(requiredText(jwk, "qi"))
|
||||
);
|
||||
return KeyFactory.getInstance("RSA").generatePrivate(spec);
|
||||
}
|
||||
|
||||
private static byte[] signPayload(PrivateKey key, byte[] payload) throws GeneralSecurityException {
|
||||
Signature signature = Signature.getInstance("RSASSA-PSS");
|
||||
signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1));
|
||||
signature.initSign(key);
|
||||
signature.update(payload);
|
||||
return signature.sign();
|
||||
}
|
||||
|
||||
private static byte[] singleChunkDataRoot(byte[] data) throws GeneralSecurityException {
|
||||
byte[] dataHash = sha256(data);
|
||||
byte[] left = sha256(dataHash);
|
||||
byte[] right = sha256(intToBuffer32(data.length));
|
||||
return sha256(concat(left, right));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static byte[] deepHash(Object data) throws GeneralSecurityException {
|
||||
if (data instanceof List<?> list) {
|
||||
byte[] tag = concat(utf8("list"), utf8(Integer.toString(list.size())));
|
||||
return deepHashChunks(list, sha384(tag));
|
||||
}
|
||||
if (!(data instanceof byte[] bytes)) {
|
||||
throw new IllegalArgumentException("deepHash поддерживает только byte[] и list.");
|
||||
}
|
||||
byte[] tag = concat(utf8("blob"), utf8(Integer.toString(bytes.length)));
|
||||
byte[] tagged = concat(sha384(tag), sha384(bytes));
|
||||
return sha384(tagged);
|
||||
}
|
||||
|
||||
private static byte[] deepHashChunks(List<?> chunks, byte[] acc) throws GeneralSecurityException {
|
||||
if (chunks.isEmpty()) return acc;
|
||||
byte[] pair = concat(acc, deepHash(chunks.get(0)));
|
||||
return deepHashChunks(chunks.subList(1, chunks.size()), sha384(pair));
|
||||
}
|
||||
|
||||
private static void appendTag(List<Map<String, String>> jsonTags, List<List<byte[]>> tagList, String name, String value) {
|
||||
byte[] nameBytes = utf8(name);
|
||||
byte[] valueBytes = utf8(value);
|
||||
Map<String, String> item = new LinkedHashMap<>();
|
||||
item.put("name", b64UrlEncode(nameBytes));
|
||||
item.put("value", b64UrlEncode(valueBytes));
|
||||
jsonTags.add(item);
|
||||
tagList.add(List.of(nameBytes, valueBytes));
|
||||
}
|
||||
|
||||
private static String getRequiredText(String gateway, String path) throws IOException, InterruptedException {
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(gateway + path))
|
||||
.timeout(Duration.ofSeconds(20))
|
||||
.GET()
|
||||
.build();
|
||||
HttpResponse<String> response = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
throw new IllegalStateException("Arweave gateway вернул HTTP " + response.statusCode() + " для " + path);
|
||||
}
|
||||
String body = String.valueOf(response.body() == null ? "" : response.body()).trim();
|
||||
if (body.isBlank()) {
|
||||
throw new IllegalStateException("Arweave gateway вернул пустой ответ для " + path);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
private void validatePayload(String contentType, byte[] fileBytes) {
|
||||
if (fileBytes == null || fileBytes.length == 0) {
|
||||
throw new IllegalArgumentException("Файл аватара пустой.");
|
||||
}
|
||||
if (fileBytes.length > getMaxBytes()) {
|
||||
throw new IllegalArgumentException("Файл слишком большой для бесплатной загрузки. Максимум " + getMaxBytes() + " байт.");
|
||||
}
|
||||
if (!isSupportedContentType(contentType)) {
|
||||
throw new IllegalArgumentException("Поддерживаются только JPEG, PNG или WebP.");
|
||||
}
|
||||
}
|
||||
|
||||
private static boolean isSupportedContentType(String contentType) {
|
||||
return "image/jpeg".equals(contentType)
|
||||
|| "image/png".equals(contentType)
|
||||
|| "image/webp".equals(contentType);
|
||||
}
|
||||
|
||||
private static String normalizeContentType(String contentType) {
|
||||
return String.valueOf(contentType == null ? "" : contentType).trim().toLowerCase();
|
||||
}
|
||||
|
||||
private static String requiredText(JsonNode node, String field) {
|
||||
String value = node == null ? "" : String.valueOf(node.path(field).asText("")).trim();
|
||||
if (value.isBlank()) {
|
||||
throw new IllegalStateException("В JWK отсутствует поле " + field + ".");
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private static BigInteger asBigInt(String b64Url) {
|
||||
return new BigInteger(1, b64UrlDecode(b64Url));
|
||||
}
|
||||
|
||||
private static byte[] b64UrlDecode(String value) {
|
||||
return B64URL.decode(String.valueOf(value == null ? "" : value).trim());
|
||||
}
|
||||
|
||||
private static String b64UrlEncode(byte[] value) {
|
||||
return B64URL_NOPAD.encodeToString(value);
|
||||
}
|
||||
|
||||
private static byte[] utf8(String value) {
|
||||
return String.valueOf(value == null ? "" : value).getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... arrays) {
|
||||
int total = 0;
|
||||
for (byte[] array : arrays) total += array.length;
|
||||
byte[] out = new byte[total];
|
||||
int offset = 0;
|
||||
for (byte[] array : arrays) {
|
||||
System.arraycopy(array, 0, out, offset, array.length);
|
||||
offset += array.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] intToBuffer32(int value) {
|
||||
byte[] out = new byte[32];
|
||||
long current = Integer.toUnsignedLong(value);
|
||||
for (int i = out.length - 1; i >= 0; i--) {
|
||||
out[i] = (byte) (current & 0xffL);
|
||||
current >>>= 8;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] sha256(byte[] data) throws GeneralSecurityException {
|
||||
return MessageDigest.getInstance("SHA-256").digest(data);
|
||||
}
|
||||
|
||||
private static byte[] sha384(byte[] data) throws GeneralSecurityException {
|
||||
return MessageDigest.getInstance("SHA-384").digest(data);
|
||||
}
|
||||
|
||||
private static String sha256Hex(byte[] data) throws GeneralSecurityException {
|
||||
byte[] hash = sha256(data);
|
||||
StringBuilder sb = new StringBuilder(hash.length * 2);
|
||||
for (byte b : hash) sb.append(String.format("%02x", b));
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private static String safeBody(String body) {
|
||||
String text = String.valueOf(body == null ? "" : body).replace('\n', ' ').replace('\r', ' ').trim();
|
||||
if (text.length() <= 220) return text;
|
||||
return text.substring(0, 220) + "...";
|
||||
}
|
||||
|
||||
public record Quota(int limit, int usedCount, int remainingCount, boolean enabled) {
|
||||
}
|
||||
|
||||
public record UploadResult(String txId, String sha256Hex, int usedCount, int remainingCount, int limit, String gateway) {
|
||||
}
|
||||
|
||||
private record ArweaveConfig(String gateway, String owner, String address, PrivateKey privateKey) {
|
||||
}
|
||||
|
||||
public static final class FreeAvatarLimitExceededException extends RuntimeException {
|
||||
public FreeAvatarLimitExceededException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user