Compare commits

...
Author SHA256 Message Date
AidarKC eae8280062 Немного поправил UI и сделал скетч ESP32 для регистрации 2026-12-03 09:01:47 +03:00
AidarKC c61cbf239c Унифицировать HEADER в формате 1.0 2026-12-02 17:57:28 +03:00
AidarKC 58e4bac3c8 Обновить тесты актуальных форматов 2026-12-02 17:41:20 +03:00
AidarKC 34a9c88d91 Перевести протокол на App test5599 и PDA 1.0 2026-12-02 17:36:25 +03:00
AidarKC 61c33c8fec Исправить подпись user PDA формата 1.0 2026-12-02 17:26:25 +03:00
AidarKC 9dec8293cd Оплачивать регистрацию сервера blockchain-ключом 2026-12-02 17:18:36 +03:00
AidarKC 0c85948556 Подготовить программы и user PDA к публичной версии 1.0 2026-12-02 15:15:39 +03:00
AidarKC ad4949d2ac Добавить безопасную очистку user PDA перед запуском 1.0 2026-12-02 15:06:27 +03:00
AidarKC d8ef68836d Обновить казну и управление Shine Payments 2026-12-02 14:50:17 +03:00
AidarKC a9fa1cd2a2 Исправить отображение и учёт поддержки сообщений 2026-12-02 02:13:01 +03:00
AidarKC 7cf0170de7 Уточнить правило версии после merge 2026-12-02 00:11:06 +03:00
AidarKC fae8cdd2bf Убрать повторное обновление версии при merge в main 2026-12-02 00:09:26 +03:00
AidarKC c5f640b2a9 Сделать Solana RPC необязательным в UI-деплое 2026-12-02 00:08:09 +03:00
AidarKC af0beccb4a Обновить учёт поддержки, лайки и профиль перед MVP 2026-12-02 00:01:51 +03:00
AidarKC d05d9db8a2 Слить PR #4: голосовые сообщения и карточка поддержки 2026-12-01 22:29:58 +03:00
PixelandClaude Opus 5.5 dd461eaa16 Смерджить карточку «Поддержка» и текст о шифровании в голосовые сообщения
Объединены ветки ui/dm-voice и ui/support-card-ethereal для одного PR.
Конфликты: index.html — в список стилей вошли оба файла (dm-voice.css и
profile-support.css); VERSION.properties — client 1.21.8, server 1.17.6.
chat-view.js, словари ru/en, ui-icon.js и WALLET_SHINE_SUPPORT.md слились
автоматически.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:19:38 +03:00
PixelandClaude Opus 5.5 5e61ca20cb Смерджить свежий main в голосовые сообщения
Подтянуты изменения main до d9a91875 (аудит API, учёт публикации блоков,
звонки и настройки). Конфликт только в VERSION.properties: client 1.21.7,
server 1.17.5 — выше main и PR очереди выплат.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 21:18:41 +03:00
aidar d58af23ebb Merge pull request 'Защитить очередь выплат и учёт донатов (client 1.21.6, server 1.17.4)' (#3) from fix/solana-payments-queue into main
Reviewed-on: #3
2026-12-01 18:07:25 +00:00
PixelandClaude Opus 5.5 85b860a138 Смерджить свежий main в очередь выплат
Подтянуты изменения main до d9a91875 (аудит API, учёт публикации блоков,
доработки звонков и настроек). Конфликт только в VERSION.properties:
версии подняты выше main и прежних значений ветки — client 1.21.6,
server 1.17.4. Словари ru/en слились автоматически.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:54:08 +03:00
PixelandClaude Opus 5.5 016aff7169 Индексатор донатов: учитывать только события shine_users верхнего уровня
SupportHistoryIndexer сверял строки SHINE_STARS_V1 из логов любой программы
(indexOf по всей строке). Memo с текстом события, чужая программа с такой же
строкой или вызов shine_users через CPI давали «лишнее» событие, и индексатор
навсегда останавливался ошибкой несовпадения.

Теперь стек вызовов строится по строкам «Program <base58> invoke [N]» /
«success|failed» (строки, напечатанные программой, его не сдвигают), и
учитываются только строки, начинающиеся с «Program log: SHINE_STARS_V1|»,
которые напечатала сама shine_users на глубине 1. Тесты: подделка через Memo
и чужую программу, CPI-вызов, вложенный перевод System Program.

Java-тесты ещё не запускались (нет JDK на этой машине).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:40:14 +03:00
PixelandClaude Opus 5.5 370cb79078 Очередь выплат: минимум 0,1 SOL, запрет системных получателей, автопропуск
- shine_payments: минимальная покупка тикета 0,1 SOL для всех способов
  покупки (ошибка 37 TicketPurchaseTooSmall).
- Получателем нельзя указать System Program, sysvar, встроенные и SPL-программы,
  сжигатель и программы SHiNE (RESERVED_RECIPIENTS): покупка, тикет менеджера,
  смена получателя.
- step_payout: если получатель не может принять перевод (исполняемый,
  зарезервированный или после зачисления ниже rent-минимума), тикет закрывается
  пропуском: вызвавший получает награду, деньги остаются в inflow vault,
  байт статуса тикета = 2, лог SHINE_PAYMENTS_TICKET_SKIPPED.
- Модульные тесты программы (Cargo.toml: включён test).
- UI кошелька и очереди: статус «закрыт без выплаты», проверка минимума до
  отправки; тестовые страницы web/: статус пропуска, минимум и тексты ошибок.
- Документация: shine_payments.md, FUNDS_FLOW.md, обзор архитектуры.

Сборка и тесты Rust ещё не запускались (нет toolchain на этой машине).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 20:40:13 +03:00
AidarKC d9a9187506 Смерджить аудит API и учёт публикации блоков в main 2026-12-01 20:39:36 +03:00
AidarKC a320c12bdd Добавить учёт публикации блоков и обновить загрузку UI 2026-12-01 20:39:18 +03:00
AidarKC 3fa1e681d9 Исправить восстановление выбранной сессии 2026-12-01 12:13:59 +03:00
PixelandClaude Opus 5.5 c778ab8a39 Слить ветку docs/api-contract-audit (Айдар) в ui/dm-voice
Подтянуты 10 коммитов Айдара от 29–30.11: сверка контрактов API с
обработчиками, проверка звука в браузере, подпись сигналов звонка,
ширина чата, меню настроек, скрытие тестовых версий связей.
Автоматически слиты app.js, словари ru/en и chat.css; конфликт только в
VERSION.properties — у Айдара продолжается откатившаяся линия
(1.20.82 / 1.16.51), взяты значения выше обеих сторон: client 1.21.4,
server 1.17.2 (ветка меняет и UI, и сервер).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 23:35:18 +03:00
AidarKC e32d424eda Исправить интерфейс видеозвонка 2026-11-30 12:33:29 +03:00
AidarKC 1e52b4dd2a Исправить подпись сигналов звонка и ширину чата 2026-11-30 12:03:21 +03:00
AidarKC c175a54a01 Добавить проверку звука в браузере 2026-11-30 11:55:36 +03:00
AidarKC 3f3e93c87d Убрать настройку таймаута звонка 2026-11-30 11:38:18 +03:00
AidarKC 1621537d77 Доработать меню настроек и проверку серверов 2026-11-30 11:36:39 +03:00
AidarKC 10d9d0a45a Скрыть тестовые версии связей по умолчанию 2026-11-30 11:09:55 +03:00
AidarKC e11c39e933 Уточнить схемы ответов API 2026-11-30 00:09:51 +03:00
AidarKC a1eae4c3a2 Добавить ссылки на контракты операций 2026-11-29 23:52:39 +03:00
AidarKC de0af29b6d Сверить контракты API с обработчиками 2026-11-29 23:39:45 +03:00
AidarKC 8cf09e69af Убрать устаревшие статусы API 2026-11-29 23:22:04 +03:00
AidarKC 3e826e87cd Актуализировать документацию и проверку requestId 2026-11-29 23:20:56 +03:00
PixelandClaude Opus 5.5 920f0d7217 Слить свежий main в ui/dm-voice
Подтянуты 4 коммита main (CORE/CONTENT, пополнение SOL). Конфликт только
в VERSION.properties: в main версии ушли назад (1.20.77 / 1.16.45 против
1.21.0 / 1.17.0 в точке ветвления), поэтому взяты значения выше обеих
сторон — client 1.21.3, server 1.17.1 (слияние приносит изменения и UI,
и сервера).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:08:16 +03:00
PixelandClaude Opus 5.5 e7349c7bf4 Вернуть очередь файлов с подписью и срок хранения вложений в личке
Коммит 780ca539 (18.11) случайно удалил из chat-view.js функции из
2dd0ed6d (17.11). Возвращены поверх текущего main (подпись в
sendFileAttachmentMessage уже была добавлена вместе с «Поделиться»):

- выбранные файлы копятся в очереди над полем ввода, лишний убирается,
  текст поля уходит подписью, всё отправляется одним сообщением;
- если не удалась загрузка — очередь и подпись остаются для повтора;
  если файлы загружены, а DM не ушёл — повтор без новой загрузки;
- у вложений DM v3 строка «Вложение доступно ещё N дн.», пока срок
  не истёк (срок — из DM_FILE_RETENTION_MS);
- ключи file_remove, remaining_less_day, remaining_days (ru/en).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:07:21 +03:00
PixelandClaude Opus 5.5 1c59b82ff7 Голосовые в личке: волна громкости, жесты записи, пауза и удаление
- Пузырь голосового показывает волну громкости с плавной закраской
  проигранной части; тап по волне перематывает (для webm без duration —
  по полю dur).
- Запись: удержание — запись, отпускание — отправка, влево — отмена с
  эффектом корзины (полоса рассыпается в пыльцу), вверх — замок с паузой,
  удалением и отправкой. Тап показывает подсказку, Enter/пробел сразу
  включают замок, Esc отменяет. Живая волна: столбик раз в 110 мс,
  плавный сдвиг и рост.
- Формат: необязательное поле wf у kind=voice (64 уровня по 5 бит,
  base64url), старые клиенты его игнорируют; получатель проверяет строку.
- Opus 32 кбит/с вместо ~170: файлы в 3–4 раза легче. Тост «Голосовое
  отправлено» убран — подтверждение даёт пузырь в ленте.
- app.js не перемонтирует текущий экран во время записи/отправки
  голосового: повторный рендер того же пути откладывается до конца записи.
- Код вынесен из chat-view.js в components/dm-voice-{recorder,card,waveform}.js,
  стили — в styles/features/dm-voice.css; старые стили записи удалены.
- Возвращены отмена и пауза, потерянные в 780ca539 (18.11).
- Документация: Personal_Messages/README.md, Технические_вставки_DM_v1.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 19:04:00 +03:00
AidarKC af5b5cc6b5 Смерджить обновление CORE/CONTENT
# Conflicts:
#	VERSION.properties
2026-11-29 18:17:47 +03:00
AidarKC d120c6ecd7 Применить обновление документации CORE/CONTENT 2026-11-29 18:17:21 +03:00
AidarKC 09789fdf2f Зафиксировать текущие изменения CORE/CONTENT 2026-11-29 18:16:49 +03:00
PixelandClaude Opus 5.5 4d78e87447 Новый текст о шифровании в начале личного чата
Шесть абзацев заменены тремя пунктами: Zero-Knowledge Architecture,
Self-Custody & Open Source, Absolute Control (ru/en). Формулировка
«не имеет доступа к содержимому чатов» — сервер видит метаданные,
но не содержимое. Тест обновлён под редакцию от 27.11.2026.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:15:04 +03:00
PixelandClaude Opus 5.5 55f2d11721 Карточка «Поддержка» в профиле: блок-строка, раскрытие и эффекты
- Под «Сменить профиль» блок-строка с суммами ♡ · ↗ · ✦ в цветах метрик,
  тап раскрывает стеклянную карточку с суммами и историей переводов.
- Раскрытие с подкруткой в видимую область, сияние: кометы «пополнения»,
  блик по рамке со вспышкой, орбита; reduced-motion — статичный вид.
- Стили вынесены в styles/features/profile-support.css, эффекты —
  в js/components/support-shine-effects.js.
- formatStarAmount() — число без символа звезды для вёрстки с SVG-иконкой.
- Ключ screens.support_phase2.summary (ru/en), подписи без emoji.
- DESIGN.md §11.3 и WALLET_SHINE_SUPPORT.md обновлены.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 18:14:59 +03:00
AidarKC 3309cdb6ba Скорректировать тестовое пополнение SOL 2026-11-29 00:09:55 +03:00
AidarKC 10fe1430fe Подготовить main к версии 1.21.0 2026-11-28 12:41:16 +03:00
AidarKC 83c607d995 Слить feature/new-block-format в main 2026-11-28 12:41:02 +03:00
AidarKC faebecacb6 Добавить выбор namespace при регистрации 2026-11-28 12:40:30 +03:00
AidarKC ebd5d37039 Добавлена «Отправить через» в Android 2026-11-28 02:02:28 +03:00
AidarKC 34e5fa1403 Доработать исследователь сети и кошелёк 2026-11-28 02:00:01 +03:00
AidarKC d1ca64d1c1 Добавлен канал личных публикаций 2026-11-28 01:18:53 +03:00
AidarKC 7d3f5db206 Добавить предпросмотр DM в push-уведомлениях 2026-11-27 15:52:51 +03:00
AidarKC 91a8bb9c3c Отключить мультиаккаунтность и уточнить статусы профиля 2026-11-27 13:22:15 +03:00
AidarKC ae430e84c7 HEADER v3, primary аккаунты и подтверждения 2026-11-27 12:29:24 +03:00
AidarKC f9e7c4ef94 Новый формат блоков CORE/CONTENT test5595 2026-11-27 10:04:22 +03:00
AidarKC d3a84dd451 Слить доработки регистрации и UI 2026-11-21 17:14:49 +03:00
AidarKC 653015b2e7 Улучшить ввод пароля при входе и регистрации 2026-11-21 17:14:46 +03:00
AidarKC 8ac8f04128 Сохранить окружение t2 при deploy 2026-11-21 01:10:13 +03:00
AidarKC 80c70ebcdc Ограничить бесплатную регистрацию namespace сервера 2026-11-21 01:09:37 +03:00
AidarKC 792f368175 Проверить вложения и блоки в каналах 2026-11-21 00:24:25 +03:00
AidarKC 859dbee1f1 Добавить Canvas v4 для исследования связей 2026-11-19 21:13:24 +03:00
AidarKC 8f3b81c368 Исправить регистр ключей и ответные связи 2026-11-19 18:45:57 +03:00
AidarKC 0274183730 Исправить отображение веток комментариев 2026-11-19 16:11:23 +03:00
AidarKC c9f54224bb Обновить тестовый деплой и текст регистрации 2026-11-18 16:23:28 +03:00
AidarKC 02c705d41e Улучшить ссылки и прокрутку личных чатов 2026-11-18 15:50:14 +03:00
AidarKC 76bbc9d023 Обновить shine-users и синхронизацию пользователей 2026-11-18 15:28:07 +03:00
AidarKC 780ca53931 Сделаны переводы другим пользователям 2026-11-18 12:07:13 +03:00
AidarKC fc86c6190e Зафиксировать план будущего формата DM-вложений 2026-11-17 23:08:26 +03:00
AidarKC 2dd0ed6d59 Улучшить вложения и запись голосовых в личной переписке 2026-11-17 15:34:36 +03:00
AidarKC 1f06629838 Увеличить размер частей DM до 64 МиБ 2026-11-17 01:09:16 +03:00
AidarKC c477560632 Добавить лицензию CC0 1.0 2026-11-16 23:50:28 +03:00
AidarKC 548160f7f8 Обновить уведомление безопасности личных чатов 2026-11-16 21:18:03 +03:00
AidarKC a86a380dc7 Обновить окно ошибки запуска UI 2026-11-16 21:14:05 +03:00
AidarKC d9fdaf1930 Включить диагностику ошибок браузера 2026-11-16 12:13:42 +03:00
AidarKC 102feccb2e Очистить устаревший черновик регистрации 2026-11-16 10:59:27 +03:00
AidarKC 1b86bca19a Обновить хранение вложений R2 2026-11-16 10:47:43 +03:00
AidarKC fed28527ae Убрать ложное предупреждение о ротации ключей 2026-11-16 10:03:17 +03:00
AidarKC 2aa770a07b Добавить fallback хранения ключей при сбое IndexedDB 2026-11-16 09:57:41 +03:00
AidarKC 4362c0a015 Исправить завершение регистрации и кнопку повтора 2026-11-16 09:51:57 +03:00
AidarKC 2983ac89e6 Исправить восстановление входа при занятом WebSocket 2026-11-16 09:42:26 +03:00
AidarKC 4a6e072946 Обновить публичные идентификаторы файлов 2026-11-15 15:45:33 +03:00
AidarKC ac6a2e5b3f Исправить восстановление сессии после переподключения 2026-11-15 15:34:10 +03:00
AidarKC e01da7ae87 Исправить восстановление сессии после переподключения WS 2026-11-15 14:35:28 +03:00
AidarKC 70540ff041 Перевести вложения DM на R2 и обновить файловый API 2026-11-15 14:33:52 +03:00
AidarKC 3ecec25fce Исправить отображение публичных медиа-вложений
Добавить предпросмотр изображений и видео из R2 и Arweave; неподдерживаемые форматы оставить доступными как файлы.
2026-11-15 02:24:15 +03:00
AidarKC 2f5736e67d WIP: добавить MVP загрузки вложений в Cloudflare R2
Работа ещё не готова: предпросмотр публичных R2-вложений в UI пока не завершён.
2026-11-15 00:48:41 +03:00
AidarKC 97db033eb8 Перевести донаты на Stars и обновить Devnet 2026-11-14 00:55:02 +03:00
AidarKC c972a975fd Доработать UI личных сообщений 2026-11-14 00:14:27 +03:00
AidarKC 42a05a7a67 Добавить поддержку SHiNE в кошелёк 2026-11-13 18:52:26 +03:00
AidarKC 2a72842a7a Доделать донаты и статистику поддержки 2026-11-12 12:15:35 +03:00
AidarKC c97df82538 Добавить систему поддержки SHiNE 2026-11-12 11:01:31 +03:00
AidarKC 6b120731a3 Исправили кнопку компактной перерисовки 2026-11-11 01:19:53 +03:00
AidarKC d39d2777d1 Добавили компактную перерисовку связей V3 2026-11-11 01:09:37 +03:00
AidarKC afece72444 Добавили свечение односторонних связей 2026-11-11 01:07:37 +03:00
AidarKC 6031d95fe8 Исправили цвет сияющих связей 2026-11-11 01:05:15 +03:00
AidarKC 84f2400bef Сохранили цвет сияющих связей V3 2026-11-11 00:56:37 +03:00
AidarKC e7f6e0580c Исправили отображение связей V3 2026-11-11 00:52:46 +03:00
AidarKC 689321da1a Добавили скрипт для добавления тестовых пользователей 2026-11-11 00:51:49 +03:00
605 changed files with 43387 additions and 9434 deletions
+12
View File
@@ -136,3 +136,15 @@ shine-UI/assets/navbar_preview.png
*.jks *.jks
*.keystore *.keystore
*keypair*.json *keypair*.json
# Private production runbooks and target-specific wrappers (keep locally)
/SHiNE-server/application.properties
/deploy/PRODUCTION_SERVERS.md
/deploy/DEPLOY_SERVER_INSTRUCTIONS.md
/deploy/scripts/production_shineupme_server.sh
/deploy/scripts/production_shineupme_ui.sh
/deploy/scripts/production_server2_server.sh
/deploy/scripts/production_server2_ui.sh
# Локальная история разработки форматов blockchain; не публиковать
/protocol-format-history/
+6
View File
@@ -1,3 +1,9 @@
# Актуальная архитектура SHiNE
Начинать с [Blockchain](docs/Blockchain/README.md) и [общей архитектуры](docs/ARCHITECTURE.md). Активный runtime CORE/CONTENT, App=test5599. Прямая межсерверная репликация блоков не используется. Не менять протокол или независимые подсистемы без согласования. Интеграционную приёмку и production deploy выполнять отдельно с разрешения пользователя.
---
# Инструкции для агентов SHiNE # Инструкции для агентов SHiNE
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке. Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
+5 -1
View File
@@ -19,18 +19,22 @@
## Базовое правило для обычных коммитов ## Базовое правило для обычных коммитов
- Перед каждым новым коммитом обязательно обновлять версии в `VERSION.properties`. - Версии обновляются только вместе с изменениями соответствующего продукта: UI — `client.version`, сервер — `server.version`.
- Если менялся только UI, увеличивать только `client.version`. - Если менялся только UI, увеличивать только `client.version`.
- Если менялся только сервер, увеличивать только `server.version`. - Если менялся только сервер, увеличивать только `server.version`.
- Если менялись и UI, и сервер, увеличивать обе версии. - Если менялись и UI, и сервер, увеличивать обе версии.
- Для обычных коммитов вне `main` использовать стандартный patch-инкремент: `+1` к последнему числовому сегменту. - Для обычных коммитов вне `main` использовать стандартный patch-инкремент: `+1` к последнему числовому сегменту.
- Пример: `1.2.346` → `1.2.347`. - Пример: `1.2.346` → `1.2.347`.
- Коммиты только с документацией, настройками процесса или служебными файлами не требуют изменения `VERSION.properties`.
## Правило для `main` ## Правило для `main`
- Ветка `main` предназначена только для стабильных версий. - Ветка `main` предназначена только для стабильных версий.
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки. - По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение. - Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
- При merge рабочей ветки в `main` не нужно дополнительно изменять `VERSION.properties` и создавать отдельный коммит только ради версии.
- Версия в `main` приходит из уже подготовленного коммита рабочей ветки; после merge достаточно проверить, что она соответствует слитым изменениям.
## Правила для git commit и git push ## Правила для git commit и git push
@@ -35,6 +35,7 @@ case "${MODE}" in
simple) SKETCH_DIR="${ROOT_DIR}/simple_av_test" ;; simple) SKETCH_DIR="${ROOT_DIR}/simple_av_test" ;;
argon2) SKETCH_DIR="${ROOT_DIR}/argon2_sd_test" ;; argon2) SKETCH_DIR="${ROOT_DIR}/argon2_sd_test" ;;
homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;; homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
registration-signer) SKETCH_DIR="${ROOT_DIR}/shine_registration_signer" ;;
shine-homeserver-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;; shine-homeserver-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
shine-homeserver-ui-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;; shine-homeserver-ui-main) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
legacy-homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_ui" ;; legacy-homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_ui" ;;
@@ -54,7 +55,7 @@ case "${MODE}" in
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;; lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
*) *)
echo "Unknown mode: ${MODE}" >&2 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, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2 echo "Use one of: registration-signer, 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 exit 2
;; ;;
esac esac
@@ -78,6 +79,11 @@ compile_args=(
"${SKETCH_DIR}" "${SKETCH_DIR}"
) )
if [[ "${MODE}" == "registration-signer" && "${REGISTRAR_DEV_UNENCRYPTED:-0}" == "1" ]]; then
echo "WARNING: test-only registrar build; plaintext NVS, never provision a production key" >&2
compile_args=(--build-property "compiler.cpp.extra_flags=-DSHINE_REGISTRAR_INSECURE_DEV" "${compile_args[@]}")
fi
echo "== Compile: fast incremental build" echo "== Compile: fast incremental build"
if ! arduino-cli compile "${compile_args[@]}"; then if ! arduino-cli compile "${compile_args[@]}"; then
echo "== Compile: fast build failed, retrying clean build" echo "== Compile: fast build failed, retrying clean build"
@@ -0,0 +1,83 @@
#pragma once
#include <cstdint>
#include <cstddef>
#include <vector>
#include <string>
#include <algorithm>
// Remote AddBlock body is the existing type/subtype/version + semantic body.
// This helper has no network/state dependencies; hashes and Ed25519 are supplied
// by the existing firmware crypto libraries (or the offline vector test).
namespace shine_core {
using Bytes = std::vector<uint8_t>;
using Hash = bool (*)(const uint8_t*, size_t, uint8_t*);
using Sign = bool (*)(const Bytes&, const uint8_t*, uint8_t*);
inline void putBE(Bytes& out, uint64_t n, unsigned count) {
for (unsigned i=count; i>0; --i) out.push_back(uint8_t(n >> ((i-1)*8)));
}
inline void putLE(Bytes& out, uint64_t n, unsigned count) {
for (unsigned i=0; i<count; ++i) out.push_back(uint8_t(n >> (i*8)));
}
inline uint32_t getBE(const uint8_t* p) {
return (uint32_t(p[0])<<24)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<8)|p[3];
}
inline Bytes text(const std::string& s) { return Bytes(s.begin(),s.end()); }
inline void avroLong(Bytes& out, size_t n) {
uint64_t x=uint64_t(n)*2;
while (x>=128) { out.push_back(uint8_t(x)|0x80); x>>=7; }
out.push_back(uint8_t(x));
}
inline void avroString(Bytes& out,const std::string& s) {
avroLong(out,s.size());out.insert(out.end(),s.begin(),s.end());
}
inline bool deepBlob(const Bytes& data,Hash sha384,uint8_t* out) {
Bytes tag=text("blob"+std::to_string(data.size()));uint8_t pair[96];
return sha384(tag.data(),tag.size(),pair)&&sha384(data.data(),data.size(),pair+48)&&sha384(pair,96,out);
}
inline bool makeItem(const Bytes& data,const Bytes& tags,size_t count,const uint8_t* owner,const uint8_t* secret,
Hash sha384,Sign sign,Bytes& out) {
const Bytes children[]={text("dataitem"),text("1"),text("2"),Bytes(owner,owner+32),Bytes(),Bytes(),tags,data};
const Bytes list=text("list8");uint8_t acc[48],pair[96],sig[64];
if(!sha384(list.data(),list.size(),acc))return false;
for(const Bytes& child:children){
std::copy(acc,acc+48,pair);
if(!deepBlob(child,sha384,pair+48)||!sha384(pair,96,acc))return false;
}
if(!sign(Bytes(acc,acc+48),secret,sig))return false;
out.clear();putLE(out,2,2);out.insert(out.end(),sig,sig+64);out.insert(out.end(),owner,owner+32);
out.push_back(0);out.push_back(0);putLE(out,count,8);putLE(out,tags.size(),8);
out.insert(out.end(),tags.begin(),tags.end());out.insert(out.end(),data.begin(),data.end());return true;
}
inline bool buildPair(uint16_t type,uint16_t subtype,uint16_t version,const Bytes& body,
uint32_t number,uint64_t timestamp,const uint8_t* prev,const uint8_t* owner,const uint8_t* secret,
const std::string& app,Hash sha256,Hash sha384,Sign sign,Bytes& out) {
constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647;
const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4;
const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130);
if((version!=1&&!(header&&(version==2||version==3)))||number>MAX_NUMBER||header!=(number==0)||(type==0&&!header&&!tech)||body.size()>8*1024*1024-124)return false;
if(header&&std::any_of(prev,prev+32,[](uint8_t b){return b!=0;}))return false;
const size_t prefix=fixed?40:(tech||channel?44:0),offset=fixed?0:4;
if(body.size()<prefix)return false;
uint32_t code=0,previous=0;
if(prefix){
if(tech&&getBE(body.data())!=0)return false;
code=type==3?CONNECTION:type==4?PROFILE:tech?TECH:getBE(body.data());
previous=getBE(body.data()+offset);
if(previous>=number||(channel&&(code>MAX_NUMBER||(code>0&&(code>=number||previous<code)))))return false;
}
Bytes content{1};putBE(content,type,2);putBE(content,subtype,2);putBE(content,version,2);
content.insert(content.end(),body.begin()+prefix,body.end());
Bytes contentItem,coreItem;uint8_t contentHash[32],contentId[32];
if(!makeItem(content,Bytes{0},0,owner,secret,sha384,sign,contentItem)||
!sha256(content.data(),content.size(),contentHash)||!sha256(contentItem.data()+2,64,contentId))return false;
Bytes core{1};core.insert(core.end(),prev,prev+32);putBE(core,number,4);putBE(core,timestamp,8);
core.insert(core.end(),contentHash,contentHash+32);core.insert(core.end(),contentId,contentId+32);
if(prefix){putBE(core,code,4);putBE(core,previous,4);core.insert(core.end(),body.begin()+offset+4,body.begin()+offset+36);}
Bytes tags;const size_t count=prefix?3:2;avroLong(tags,count);avroString(tags,"App");avroString(tags,app);
avroString(tags,"n");avroString(tags,std::to_string(number));
if(prefix){avroString(tags,"l");avroString(tags,code==PROFILE?"P":code==CONNECTION?"C":code==TECH?"T":std::to_string(code));}
tags.push_back(0);
if(!makeItem(core,tags,count,owner,secret,sha384,sign,coreItem))return false;
out.clear();putBE(out,coreItem.size(),4);out.insert(out.end(),coreItem.begin(),coreItem.end());out.insert(out.end(),contentItem.begin(),contentItem.end());return true;
}
} // namespace shine_core
@@ -9,6 +9,8 @@
#include <TouchDrvCSTXXX.hpp> #include <TouchDrvCSTXXX.hpp>
#include <mbedtls/gcm.h> #include <mbedtls/gcm.h>
#include <mbedtls/sha256.h> #include <mbedtls/sha256.h>
#include <mbedtls/sha512.h>
#include "shine_core_content.h"
#include <mbedtls/base64.h> #include <mbedtls/base64.h>
#include <Ed25519.h> #include <Ed25519.h>
#include <sodium.h> #include <sodium.h>
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
continue; continue;
} }
std::vector<uint8_t> preimage;
preimage.reserve(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
appendUint16BE(preimage, 0);
preimage.insert(preimage.end(), prevHash32, prevHash32 + 32);
int32_t blockSize = (int32_t)(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
appendInt32BE(preimage, blockSize);
appendInt32BE(preimage, nextBlockNumber);
appendInt64BE(preimage, (int64_t)(shineNowMs() / 1000ULL));
appendUint16BE(preimage, msgType);
appendUint16BE(preimage, msgSubType);
appendUint16BE(preimage, msgVersion);
preimage.insert(preimage.end(), bodyBytes.begin(), bodyBytes.end());
uint8_t blockchainSeed[32] = {}; uint8_t blockchainSeed[32] = {};
uint8_t blockchainPub[32] = {}; uint8_t blockchainPub[32] = {};
uint8_t blockchainSec[64] = {}; uint8_t blockchainSec[64] = {};
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
continue; continue;
} }
uint8_t hash32[32] = {}; std::vector<uint8_t> fullBlock;
sha256calc(preimage.data(), preimage.size(), hash32); const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
uint8_t signature[64] = {}; return mbedtls_sha256(data, len, out, 0) == 0;
if (!signMessageEd25519(std::vector<uint8_t>(hash32, hash32 + 32), blockchainSec, signature)) { };
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign AddBlock hash\",\"requestId\":\"") const auto hash384 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
uint8_t buffer[64] = {};
if (mbedtls_sha512(data, len, buffer, 1) != 0) return false;
memcpy(out, buffer, 48);
return true;
};
const auto sign = +[](const std::vector<uint8_t>& data, const uint8_t* key, uint8_t* sig) -> bool {
return signMessageEd25519(data, key, sig);
};
// Same semantic remote body and signal contract; only the signed wire bytes change.
if (resolvedBlockchainName != blockchainName || nextBlockNumber < 0 ||
!shine_core::buildPair(msgType, msgSubType, msgVersion, bodyBytes, (uint32_t)nextBlockNumber,
shineNowMs()/1000ULL, prevHash32, blockchainPub, blockchainSec,
"test5599", hash256, hash384, sign, fullBlock)) {
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign CORE/CONTENT pair\",\"requestId\":\"")
+ jsonEscape(item.signalRequestId) + "\"}"; + jsonEscape(item.signalRequestId) + "\"}";
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData); sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
continue; continue;
} }
std::vector<uint8_t> fullBlock = preimage;
fullBlock.push_back(0x01);
fullBlock.push_back(0x00);
fullBlock.insert(fullBlock.end(), signature, signature + 64);
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName) String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "\",\"blockNumber\":" + String((long long)nextBlockNumber)
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash) + ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}"; + "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
String addBlockResp; String addBlockResp;
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS); bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
const bool uncertain = !addBlockOk;
if (uncertain) {
// Retry the identical container, not the semantic request or a new timestamp.
addBlockResp = "";
addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
}
uint64_t statusCode = 0; uint64_t statusCode = 0;
jsonInt64Field(addBlockResp, "status", statusCode); jsonInt64Field(addBlockResp, "status", statusCode);
String serverLastHash; String serverLastHash;
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
jsonStringField(addBlockResp, "message", errorMessage); jsonStringField(addBlockResp, "message", errorMessage);
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber); jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
if (uncertain && (!addBlockOk || statusCode != 200)) {
const String readReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "}";
String readResp, readBytes;
uint64_t readStatus = 0;
if (shineWsRequest(gShineWs, "GetBlockchainBlock", readReq, readResp, SHINE_RPC_TIMEOUT_MS)) {
jsonInt64Field(readResp, "status", readStatus);
jsonStringField(readResp, "blockBytesB64", readBytes);
if (readStatus == 200 && readBytes == bytesToBase64String(fullBlock.data(), fullBlock.size())) {
jsonStringField(readResp, "blockHash", serverLastHash);
serverLastNumber = (uint64_t)nextBlockNumber;
addBlockOk = true;
statusCode = 200;
}
}
if (!addBlockOk || statusCode != 200) {
errorCode = "addblock_outcome_unknown";
errorMessage = "AddBlock outcome unknown; refresh history before retrying";
}
}
if (!addBlockOk || statusCode != 200) { if (!addBlockOk || statusCode != 200) {
if (errorCode.isEmpty()) { if (errorCode.isEmpty()) {
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed"; errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
@@ -0,0 +1,39 @@
# SHiNE Registration Signer 1.0
Самостоятельный скетч для Waveshare ESP32-S3-Touch-AMOLED-2.16, не использует старые функции homeserver или кошелька. Сохраняет только подписанные сертификаты, а не произвольные сообщения. LVGL 8, тот же драйвер CO5300, CST92xx, AXP2101 и распиновка SDMMC 1-bit (CLK 2, CMD 1, D0 3) из старого скетча. GPIO2 освобождается после запуска дисплея.
## Сборка
В окружении разработчика с уже установленными библиотеками платы (Arduino ESP32 core 3.3.5, официальный demo libraries, LVGL, sodium) установить дополнительные Arduino-библиотеки `WebSockets` (Links2004) и `ArduinoJson` 7.x:
```sh
arduino-cli lib install WebSockets ArduinoJson
cd ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device
NO_UPLOAD=1 ./burn.sh registration-signer
```
Сертификаты TLS проверяются через встроенный публичный CA `registrar_ca.h` (ISRG Root X1). Если endpoint использует другой CA, заменить trust anchor на проверенный корень, пересобрать. Не отключать проверку. `wss://host[:port]/ws`, без `ws://`. Для действительного TLS нужен SNTP. Неверный сертификат должен приводить к отказу соединения.
### Хранение ключа в прототипе
32-байтный secret seed Ed25519 в Base58 и сохранённые пароли Wi-Fi записываются во внутреннюю NVS ESP32 без требования Secure Boot, Flash Encryption или NVS Encryption. Экран VIEW KEYS показывает приватный ключ. Устройство следует использовать только как прототип с тестовым ключом, пока не настроено защищённое хранение.
## Установка
1. Вставить новую SD-карту FAT, включить устройство, открыть SETTINGS. В WI-FI выбрать доступную сеть и ввести пароль; сеть сохраняется только после успешного подключения. Настроить SERVER URL (достаточно хоста `t2.shineup.me`, прошивка добавит `wss://` и `/ws`) и NAMESPACE (без @). В SECRET KEY BASE58 ввести 32-байтный Ed25519 seed в Base58; прошивка сама восстанавливает полный секретный и публичный ключи. VIEW KEYS показывает публичный ключ и 32-байтный seed в Base58. Для настройки Solana registrar_pubkey использовать показанный публичный ключ. Все поля отображаются открытым текстом, а при повторном редактировании прежнее значение сохраняется целиком.
2. В Solana установить соответствующий публичный ключ нового namespace; в серверном конфиге выбрать external, настроить Resend и Turbo как раньше. Подключить устройство; проверить `/status`.
3. Главный экран показывает состояние Wi-Fi и авторизованного подключения к серверу, причину OFFLINE и время после последнего успешного Ping. Кнопка PING отправляет внеочередной запрос.
## SD формат 1.0
`/registrations/example.free.txt` — бинарный файл: major=1 (u8), minor=0 (u8), длина полного логина (u8), ASCII логин с @, Unix ms (u64 BE), длина raw signed DataItem (u32 BE), raw ANS-104. Имя в lowercase, оригинальный регистр сохраняется внутри. Внутренний и внешний Ed25519 уже в DataItem. SD не содержит приватного ключа. Email SHA-256 — часть публичного сертификата.
При совпадении всех полей включая оригинальный регистр, ключи и email hash возвращаются сохранённые bytes после проверки обеих подписей; при несовпадении 409. Новая выдача: файл .tmp, flush/close, rename, повторное чтение и сравнение, обновление NVS учёта, только затем отправка. Незавершённый .tmp блокирует выдачу до ручного разбора. Не удалять ранее выданные записи. Утрата истории относительно счётчика NVS блокирует выдачу. Перед каждой выдачей пересчитывается история; большие SD-архивы потребуют оптимизации индекса, иначе возможно превышение серверного тайм-аута. Не извлекать SD во время работы.
Лимит: 10 новых сертификатов за скользящие 5 часов. Время выдачи хранится на SD, в NVS — максимальная отметка и счётчик. При откате часов выдача блокируется. Повтор сохранённого сертификата не расходует квоту. Это защита от скомпрометированного сервера, а не полноценная защита от физического удаления/подмены SD или подмены NTP; не давать посторонним физический доступ.
`App=test5599` — текущая эпоха проекта, `certificate_v1.h` должен изменяться согласованно с `ShineProtocolTags.CORE_NAMESPACE`, если эпоха будет изменена. Ранее подписанная запись для login остаётся неизменной; новый сертификат для того же login автоматически не создаётся.
## Приёмка
До production проверить: сборку обеих частей, экран/клавиатуру и SD после инициализации AMOLED, WSS и отклонение неверной CA/hostname, авторизацию верного/чужого ключа, перезагрузку, повтор запроса с теми же данными, конфликт регистра, лимит 10/5ч после перезапуска, отключение сети/SD и потерю ответа, ошибку NVS, Pause, публикацию Turbo и импорт, статус. `host-tests/run.sh` сравнивает сертификат с Java reference vector. Host-тест не заменяет сборку ESP/проверку реального устройства.
@@ -0,0 +1,54 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace regkey {
static constexpr char ALPHABET[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
inline std::string encode(const uint8_t *data, size_t length) {
size_t zeros = 0;
while (zeros < length && data[zeros] == 0) ++zeros;
std::vector<uint8_t> digits;
for (size_t i = zeros; i < length; ++i) {
unsigned carry = data[i];
for (auto &digit : digits) {
carry += 256U * digit;
digit = carry % 58U;
carry /= 58U;
}
while (carry) { digits.push_back(carry % 58U); carry /= 58U; }
}
std::string result(zeros, '1');
for (auto it = digits.rbegin(); it != digits.rend(); ++it) result += ALPHABET[*it];
return result;
}
inline bool decode32(const char *text, uint8_t out[32]) {
if (!text || !*text) return false;
const size_t length = strlen(text);
if (length > 45) return false;
size_t zeros = 0;
while (zeros < length && text[zeros] == '1') ++zeros;
std::vector<uint8_t> bytes;
for (size_t i = zeros; i < length; ++i) {
const char *found = strchr(ALPHABET, text[i]);
if (!found) return false;
unsigned carry = found - ALPHABET;
for (auto &byte : bytes) {
carry += 58U * byte;
byte = carry & 255U;
carry >>= 8U;
}
while (carry) { bytes.push_back(carry & 255U); carry >>= 8U; }
if (zeros + bytes.size() > 32) return false;
}
if (zeros + bytes.size() != 32) return false;
memset(out, 0, 32);
for (size_t i = 0; i < bytes.size(); ++i) out[31 - i] = bytes[i];
return encode(out, 32) == text;
}
} // namespace regkey
@@ -0,0 +1,29 @@
#pragma once
#include <vector>
#include <string>
#include <cstring>
#include <stdint.h>
#include <sodium.h>
#include <mbedtls/sha512.h>
// Точное соответствие FreeRegistrationCertificateV1.java / Ans104DataItem.java.
namespace regv1 {
using Bytes=std::vector<uint8_t>;
inline Bytes bytes(const std::string &s){return Bytes(s.begin(),s.end());}
inline void append(Bytes &a,const Bytes &b){a.insert(a.end(),b.begin(),b.end());}
inline void append(Bytes &a,const uint8_t *p,size_t n){a.insert(a.end(),p,p+n);}
inline void integer(Bytes &a,uint64_t n,unsigned count,bool little){for(unsigned i=0;i<count;i++)a.push_back(uint8_t(n>>(8*(little?i:count-1-i))));}
inline Bytes sha384(const Bytes &a){uint8_t digest[64]={};mbedtls_sha512(a.data(),a.size(),digest,1);return Bytes(digest,digest+48);}
inline Bytes combineHash(const Bytes &a,const Bytes &b){Bytes t=a;append(t,b);return sha384(t);}
inline Bytes blob(const Bytes &a){return combineHash(sha384(bytes("blob"+std::to_string(a.size()))),sha384(a));}
inline void avro(Bytes &a,uint64_t n){n*=2;while(n>127){a.push_back((n&127)|128);n>>=7;}a.push_back(n);}
inline void avroString(Bytes &a,const std::string &s){avro(a,s.size());append(a,bytes(s));}
inline Bytes tags(){Bytes a;avro(a,3);avroString(a,"App");avroString(a,"test5599");avroString(a,"t");avroString(a,"reg");avroString(a,"Protocol");avroString(a,"SHiNE-Free-Registration-V1");avro(a,0);return a;}
inline Bytes outerMessage(const Bytes &owner,const Bytes &data){Bytes a=sha384(bytes("list8"));for(const auto &v:std::vector<Bytes>{bytes("dataitem"),bytes("1"),bytes("2"),owner,{}, {},tags(),data})a=combineHash(a,blob(v));return a;}
inline bool validLogin(const std::string &login){auto at=login.find('@');if(login.size()>30||at==0||at==std::string::npos||at+1==login.size())return false;for(size_t i=0;i<login.size();i++){if(i==at)continue;char c=login[i];if(!((c>='a'&&c<='z')||(c>='0'&&c<='9')||c=='_'||(i<at&&c>='A'&&c<='Z')))return false;}return true;}
inline Bytes identity(const std::string &login,const Bytes &root,const Bytes &chain,const Bytes &client){if(!validLogin(login)||root.size()!=32||chain.size()!=32||client.size()!=32)return {};Bytes a={1,0,uint8_t(login.size())};append(a,bytes(login));append(a,root);append(a,chain);append(a,client);return a;}
inline Bytes innerMessage(const Bytes &fields){Bytes a=bytes("SHiNE_FREE_REG_V1");a.push_back(0);append(a,fields);return a;}
inline Bytes sign(const Bytes &msg,const uint8_t secret[64]){Bytes sig(64);if(crypto_sign_detached(sig.data(),nullptr,msg.data(),msg.size(),secret)!=0)return {};return sig;}
inline Bytes issue(const Bytes &fields,const Bytes &emailHash,const uint8_t owner[32],const uint8_t secret[64]){if(fields.empty()||emailHash.size()!=32)return {};Bytes inner=sign(innerMessage(fields),secret);if(inner.size()!=64)return {};Bytes data=fields;append(data,inner);append(data,emailHash);Bytes pub(owner,owner+32),outer=sign(outerMessage(pub,data),secret);if(outer.size()!=64)return {};Bytes result={2,0};append(result,outer);append(result,pub);result.push_back(0);result.push_back(0);integer(result,3,8,true);Bytes t=tags();integer(result,t.size(),8,true);append(result,t);append(result,data);return result;}
inline bool matches(const Bytes &raw,const Bytes &fields,const Bytes &emailHash,const uint8_t owner[32]){Bytes t=tags();size_t off=116+t.size();if(fields.empty()||emailHash.size()!=32||raw.size()!=off+fields.size()+96||raw[0]!=2||raw[1]!=0||memcmp(raw.data()+66,owner,32))return false;Bytes head={0,0};integer(head,3,8,true);integer(head,t.size(),8,true);append(head,t);if(memcmp(raw.data()+98,head.data(),head.size())||memcmp(raw.data()+off,fields.data(),fields.size())||memcmp(raw.data()+off+fields.size()+64,emailHash.data(),32))return false;Bytes inner=innerMessage(fields),data(raw.begin()+off,raw.end()),pub(owner,owner+32),outer=outerMessage(pub,data);return crypto_sign_verify_detached(raw.data()+off+fields.size(),inner.data(),inner.size(),owner)==0&&crypto_sign_verify_detached(raw.data()+2,outer.data(),outer.size(),owner)==0;}
}
@@ -0,0 +1 @@
02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f
@@ -0,0 +1,4 @@
#include "certificate_v1.h"
#include <cassert>
#include <cstdio>
int main(){using namespace regv1;assert(sodium_init()>=0);uint8_t seed[32],pub[32],secret[64];Bytes r(32),b(32),c(32),e(32);for(int i=0;i<32;i++){seed[i]=i;r[i]=i+32;b[i]=i+64;c[i]=i+96;e[i]=i+128;}assert(crypto_sign_seed_keypair(pub,secret,seed)==0);auto fields=identity("Example@free",r,b,c);auto raw=issue(fields,e,pub,secret);assert(matches(raw,fields,e,pub));auto bad=raw;bad[2]^=1;assert(!matches(bad,fields,e,pub));bad=raw;bad.back()^=1;assert(!matches(bad,fields,e,pub));assert(!validLogin("../evil@free"));assert(!validLogin("Example@Free"));for(auto v:raw)printf("%02x",v);puts("");}
@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
# Linux: g++, libsodium-dev, libmbedtls-dev (mbedTLS 3.x).
g++ -std=c++17 -I"$HERE/.." "$HERE/certificate_vector.cpp" -lsodium -lmbedcrypto -o "$TMP/vector"
"$TMP/vector" > "$TMP/actual.hex"
cmp "$HERE/certificate_v1.hex" "$TMP/actual.hex"
echo 'PASS: ESP32 certificate equals Java reference vector, tamper rejection'
@@ -0,0 +1,35 @@
#pragma once
// Публичный trust anchor ISRG Root X1. Заменить при использовании другой доверенной CA.
static const char REGISTRAR_CA[] = R"PEM(
-----BEGIN CERTIFICATE-----
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW
T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH
B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC
B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv
KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn
OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn
jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw
qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI
rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV
HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq
hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL
ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ
3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK
NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5
ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur
TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC
jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc
oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq
4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA
mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d
emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=
-----END CERTIFICATE-----
)PEM";
@@ -0,0 +1,377 @@
#include <Arduino.h>
#include <Wire.h>
#include <WiFi.h>
#include <Preferences.h>
#include <SD_MMC.h>
#include <WebSocketsClient.h>
#include <ArduinoJson.h>
#include <Arduino_GFX_Library.h>
#include <TouchDrvCSTXXX.hpp>
#include <lvgl.h>
#include <mbedtls/base64.h>
#include <mbedtls/sha256.h>
#include <sdkconfig.h>
#include <esp_flash_encrypt.h>
#include <esp_secure_boot.h>
#include <driver/gpio.h>
#include <time.h>
#include <sys/time.h>
#include <algorithm>
#define XPOWERS_CHIP_AXP2101
#include "XPowersLib.h"
#include "certificate_v1.h"
#include "registrar_ca.h"
#include "base58_key.h"
enum Screen {HOME,MENU,WIFI_OVERVIEW,WIFI_SCAN,EDITOR,KEYS};
enum EditKind {EDIT_WIFI,EDIT_URL,EDIT_NAMESPACE,EDIT_SECRET};
using regv1::Bytes;
static constexpr uint64_t WINDOW_MS=5ULL*60*60*1000;
static constexpr size_t LIMIT=10;
static Preferences prefs;
static WebSocketsClient ws;
static String ssid,wifiPass,endpoint,ns,host,path,lastLogin="-",lastError="";
static uint16_t port=443;
static uint8_t seed[32]={},owner[32]={},secret[64]={};
static bool uiReady=false,keyReady=false,sdReady=false,paused=false,authorized=false,connecting=false,secureStorage=false;
static uint32_t seq=0,pingAt=0,pingSent=0,authAt=0,wifiAt=0,refreshAt=0;
static String pingId,authId,serverReason="Waiting for Wi-Fi";
static uint32_t lastPingAckAt=0,wsAttemptAt=0;
static std::vector<uint64_t> recent;
static uint64_t total=0,lastRecorded=0;
static Arduino_DataBus *bus=new Arduino_ESP32QSPI(12,38,4,5,6,7);
static Arduino_CO5300 *gfx=new Arduino_CO5300(bus,2,0,480,480,0,0,0,0);
static TouchDrvCST92xx touch;
static XPowersPMU power;
static bool powerReady=false;
static lv_disp_draw_buf_t drawBuf;
static String b64(const uint8_t *p,size_t n){size_t len=0;std::vector<uint8_t> b(4*((n+2)/3)+1);if(mbedtls_base64_encode(b.data(),b.size(),&len,p,n))return "";b[len]=0;return String((char*)b.data());}
static bool decode(const String &s,Bytes &b,size_t expected){if(s.length()>4*((expected+2)/3))return false;b.resize(expected);size_t n=0;return !mbedtls_base64_decode(b.data(),b.size(),&n,(const uint8_t*)s.c_str(),s.length())&&n==expected;}
static uint64_t nowMs(){struct timeval tv;gettimeofday(&tv,nullptr);return tv.tv_sec>1700000000LL?uint64_t(tv.tv_sec)*1000+tv.tv_usec/1000:0;}
static bool safeTime(){uint64_t t=nowMs();return t&&t>=lastRecorded;}
static bool validNamespace(const String &s){return regv1::validLogin(std::string("x@")+s.c_str());}
static String filename(const String &login){String f=login;f.toLowerCase();f.replace('@','.');return "/registrations/"+f+".txt";}
static uint64_t readInt(const Bytes &b,size_t off,size_t n){uint64_t v=0;for(size_t i=0;i<n;i++)v=(v<<8)|b[off+i];return v;}
static void keepTime(uint64_t t){recent.push_back(t);std::sort(recent.begin(),recent.end());if(recent.size()>LIMIT)recent.erase(recent.begin());lastRecorded=std::max(lastRecorded,t);}
static size_t used(){uint64_t t=nowMs();size_t n=0;for(auto v:recent)if(v>t||t-v<WINDOW_MS)n++;return n;}
static bool readRecord(const String &path,String &login,uint64_t &when,Bytes &raw){
File f=SD_MMC.open(path,FILE_READ);if(!f||f.isDirectory()||f.size()<16||f.size()>8192)return false;
Bytes b(f.size());if(f.read(b.data(),b.size())!=b.size())return false;f.close();
size_t n=b[2];if(b[0]!=1||b[1]!=0||n==0||n>30||b.size()<15+n)return false;
login="";for(size_t i=0;i<n;i++)login+=(char)b[3+i];if(!regv1::validLogin(login.c_str())||filename(login)!=path)return false;
when=readInt(b,3+n,8);size_t len=readInt(b,11+n,4);if(when<1700000000000ULL||len==0||len>4096||b.size()!=15+n+len)return false;
raw.assign(b.begin()+15+n,b.end());return true;
}
static bool loadHistory(){
recent.clear();total=0;lastRecorded=prefs.getULong64("lastIssue",0);
if(!SD_MMC.exists("/registrations")&&!SD_MMC.mkdir("/registrations"))return false;
File dir=SD_MMC.open("/registrations");if(!dir||!dir.isDirectory())return false;
for(File f=dir.openNextFile();f;f=dir.openNextFile()){
String name=f.name();bool isDir=f.isDirectory();f.close();if(isDir)continue;
if(name.endsWith(".tmp")){lastError="Interrupted SD write; inspect card";return false;}
if(!name.endsWith(".txt"))continue;
String p=name.startsWith("/")?name:String("/registrations/")+name;
String login;uint64_t t;Bytes raw;if(!readRecord(p,login,t,raw))return false;keepTime(t);total++;
}
// NVS сохраняет минимальный счётчик; утрата файлов не сбрасывает лимит молча.
if(total<prefs.getULong64("issued",0))return false;
if(total!=prefs.getULong64("issued",0)&&prefs.putULong64("issued",total)!=8)return false;
if(lastRecorded!=prefs.getULong64("lastIssue",0)&&prefs.putULong64("lastIssue",lastRecorded)!=8)return false;
return true;
}
static bool storeRecord(const String &login,uint64_t when,const Bytes &raw){
String target=filename(login),tmp=target+".tmp";if(SD_MMC.exists(target)||SD_MMC.exists(tmp))return false;
Bytes b={1,0,uint8_t(login.length())};regv1::append(b,regv1::bytes(login.c_str()));regv1::integer(b,when,8,false);regv1::integer(b,raw.size(),4,false);regv1::append(b,raw);
File f=SD_MMC.open(tmp,FILE_WRITE);if(!f)return false;bool ok=f.write(b.data(),b.size())==b.size();f.flush();f.close();
if(!ok||!SD_MMC.rename(tmp,target))return false;
String check;uint64_t t;Bytes data;if(!readRecord(target,check,t,data)||check!=login||t!=when||data!=raw)return false;
keepTime(when);total++;lastLogin=login;
return prefs.putULong64("lastIssue",lastRecorded)==8&&prefs.putULong64("issued",total)==8;
}
static String nextId(){return "esp-"+String(++seq);}
static void sendJson(JsonDocument &d){String s;serializeJson(d,s);if(!ws.sendTXT(s))ws.disconnect();}
static void request(const char *op,const String &id,JsonDocument &d){d["op"]=op;d["requestId"]=id;sendJson(d);}
static void result(const String &id,int status,const Bytes &raw={}){JsonDocument d;d["status"]=status;d["payload"].to<JsonObject>();if(status==200)d["payload"]["dataItemB64"]=b64(raw.data(),raw.size());request("RegistrarSignResult",id,d);}
static void signRegistration(const String &id,JsonObjectConst p){
if(!authorized||!keyReady||!sdReady){result(id,503);return;}
String login=p["login"]|"";if(!regv1::validLogin(login.c_str())){result(id,400);return;}
if(login.substring(login.indexOf('@')+1)!=ns){result(id,403);return;}
Bytes root,chain,client,email;
if(!decode(p["rootPublicKey"]|"",root,32)||!decode(p["blockchainPublicKey"]|"",chain,32)||!decode(p["clientPublicKey"]|"",client,32)||!decode(p["emailSha256"]|"",email,32)){result(id,400);return;}
if(!loadHistory()){sdReady=false;lastError="SD history unavailable";result(id,500);return;}
Bytes identity=regv1::identity(login.c_str(),root,chain,client);String file=filename(login);
if(SD_MMC.exists(file)){
String old;uint64_t when;Bytes raw;if(!readRecord(file,old,when,raw)){sdReady=false;result(id,500);return;}
if(old!=login||!regv1::matches(raw,identity,email,owner)){result(id,409);return;}
result(id,200,raw);return;
}
uint64_t issuedAt=nowMs();if(!issuedAt||issuedAt<lastRecorded){result(id,503);return;}if(used()>=LIMIT){result(id,429);return;}
// Проверка SD перед подписанием: карта не должна быть извлечена или заменена незаметно.
if(!SD_MMC.exists("/registrations")){sdReady=false;result(id,500);return;}
Bytes raw=regv1::issue(identity,email,owner,secret);
if(raw.empty()||!storeRecord(login,issuedAt,raw)){sdReady=false;lastError="SD/NVS commit failed";result(id,500);return;}
result(id,200,raw);
}
static void event(WStype_t type,uint8_t *payload,size_t len){
if(type==WStype_DISCONNECTED){authorized=false;pingId="";if(WiFi.status()==WL_CONNECTED&&(serverReason.startsWith("Connecting")||serverReason=="Connected and authorized"))serverReason="WebSocket disconnected; retrying";return;}
if(type==WStype_ERROR){authorized=false;serverReason="TLS/WebSocket connection error";return;}
if(type==WStype_CONNECTED){authorized=false;pingId="";authAt=millis();serverReason="Requesting registrar challenge";authId=nextId();JsonDocument d;d["payload"]["namespace"]=ns;request("RegistrarChallenge",authId,d);return;}
if(type!=WStype_TEXT||len>8192)return;
JsonDocument d;if(deserializeJson(d,payload,len))return;
String op=d["op"]|"",id=d["requestId"]|"";int status=d["status"]|0;JsonObjectConst p=d["payload"].as<JsonObjectConst>();
if(op=="RegistrarChallenge"&&id==authId&&!authorized){
String nonce=p["nonce"]|"",server=p["serverLogin"]|"";if(status!=200||nonce.length()!=43||server.isEmpty()||server.length()>128||!safeTime()){serverReason=status!=200?"Challenge rejected: "+String(status):"Invalid server challenge";ws.disconnect();return;}
for(size_t i=0;i<nonce.length();i++){char c=nonce[i];if(!isalnum((unsigned char)c)&&c!='_'&&c!='-'){ws.disconnect();return;}}
uint64_t t=nowMs();String msg="SHINE_REGISTRAR_CONNECT_V1:"+server+":"+ns+":"+String((unsigned long long)t)+":"+nonce;
Bytes sig=regv1::sign(regv1::bytes(msg.c_str()),secret);if(sig.size()!=64){ws.disconnect();return;}
JsonDocument out;out["payload"]["version"]="1.0";out["payload"]["namespace"]=ns;out["payload"]["timeMs"]=t;out["payload"]["signatureB64"]=b64(sig.data(),sig.size());authId=nextId();serverReason="Authenticating registrar";request("RegistrarConnect",authId,out);
}else if(op=="RegistrarConnect"&&id==authId){if(status!=200){serverReason="Registrar auth rejected: "+String(status);lastError=serverReason;ws.disconnect();return;}authorized=true;pingAt=millis();serverReason="Connected and authorized";lastError="";}
else if(op=="Ping"&&authorized&&id==pingId){if(status==200){pingId="";lastPingAckAt=millis();serverReason="Connected and authorized";}else{serverReason="Ping rejected: "+String(status);ws.disconnect();}}
else if(op=="RegistrarSignRegistration"&&authorized&&!id.isEmpty())signRegistration(id,p);
}
static bool parseEndpoint(){if(!endpoint.startsWith("wss://"))return false;int slash=endpoint.indexOf('/',6);String authority=slash<0?endpoint.substring(6):endpoint.substring(6,slash);path=slash<0?"/ws":endpoint.substring(slash);if(path!="/ws"||authority.isEmpty())return false;int colon=authority.indexOf(':');host=colon<0?authority:authority.substring(0,colon);long n=colon<0?443:authority.substring(colon+1).toInt();if(n<1||n>65535||host.isEmpty())return false;for(size_t i=0;i<host.length();i++){char c=host[i];if(!isalnum((unsigned char)c)&&c!='.'&&c!='-')return false;}port=n;return true;}
static void stopNetwork(){ws.disconnect();connecting=false;authorized=false;pingId="";serverReason="Reconnecting after settings change";}
static constexpr int MAX_WIFI_PROFILES=8;
static String knownSsids[MAX_WIFI_PROFILES],knownPasswords[MAX_WIFI_PROFILES];
static uint32_t wifiScanAt=0,wifiConnectAt=0;
static bool wifiScanning=false,wifiTrying=false;
static int wifiCandidate=-1,wifiOrder[MAX_WIFI_PROFILES],wifiOrderCount=0,wifiOrderPos=0;
static void saveWifiProfiles(){
bool ok=true;
for(int i=0;i<MAX_WIFI_PROFILES;i++){
String a="net"+String(i),b="pass"+String(i);
ok=prefs.putString(a.c_str(),knownSsids[i])==knownSsids[i].length()&&ok;
ok=prefs.putString(b.c_str(),knownPasswords[i])==knownPasswords[i].length()&&ok;
}
if(!ok)lastError="Wi-Fi storage failed";
}
static void rememberWifi(const String &name,const String &pass){
if(name.isEmpty())return;
int slot=-1;
for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==name){slot=i;break;}
if(slot<0)for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i].isEmpty()){slot=i;break;}
if(slot<0){for(int i=0;i<MAX_WIFI_PROFILES-1;i++){knownSsids[i]=knownSsids[i+1];knownPasswords[i]=knownPasswords[i+1];}slot=MAX_WIFI_PROFILES-1;}
knownSsids[slot]=name;knownPasswords[slot]=pass;saveWifiProfiles();
}
static void beginWifiCandidate(int index){
wifiCandidate=index;wifiTrying=true;wifiConnectAt=millis();
WiFi.disconnect(false,false);WiFi.begin(knownSsids[index].c_str(),knownPasswords[index].c_str());
}
static void manageWifi(){
if(WiFi.status()==WL_CONNECTED){if(wifiTrying&&wifiCandidate>=0){ssid=knownSsids[wifiCandidate];wifiPass=knownPasswords[wifiCandidate];prefs.putString("ssid",ssid);prefs.putString("wifiPass",wifiPass);}wifiTrying=false;wifiScanning=false;return;}
if(wifiTrying){
if(millis()-wifiConnectAt<12000)return;
wifiTrying=false;WiFi.disconnect(false,false);
if(++wifiOrderPos<wifiOrderCount){beginWifiCandidate(wifiOrder[wifiOrderPos]);return;}
WiFi.scanDelete();wifiScanAt=millis();return;
}
if(wifiScanning){
int count=WiFi.scanComplete();if(count==WIFI_SCAN_RUNNING)return;
wifiScanning=false;
wifiOrderCount=0;wifiOrderPos=0;
if(count>0){
for(int pass=0;pass<2;pass++)for(int i=0;i<MAX_WIFI_PROFILES;i++){
if(knownSsids[i].isEmpty()||(pass==0)!=(knownSsids[i]==ssid))continue;
for(int j=0;j<count;j++)if(knownSsids[i]==WiFi.SSID(j)){wifiOrder[wifiOrderCount++]=i;break;}
}
}
WiFi.scanDelete();wifiScanAt=millis();
if(wifiOrderCount)beginWifiCandidate(wifiOrder[0]);return;
}
if(wifiScanAt&&millis()-wifiScanAt<15000)return;
bool any=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(!knownSsids[i].isEmpty())any=true;
if(!any)return;
WiFi.mode(WIFI_STA);WiFi.scanNetworks(true);wifiScanning=true;wifiScanAt=millis();
}
static void manageNetwork(){
manageWifi();
if(WiFi.status()!=WL_CONNECTED){if(connecting){ws.disconnect();connecting=false;}authorized=false;serverReason="Waiting for Wi-Fi";return;}
if(!keyReady||!validNamespace(ns)||!parseEndpoint()||!safeTime()){if(connecting){ws.disconnect();connecting=false;}authorized=false;serverReason=!keyReady?"Registration key missing":!validNamespace(ns)?"Invalid namespace":!parseEndpoint()?"Invalid server address":"Waiting for network time (NTP)";return;}
if(!connecting){serverReason="Connecting to "+host+":"+String(port)+" (TLS)";wsAttemptAt=millis();ws.beginSslWithCA(host.c_str(),port,path.c_str(),REGISTRAR_CA);ws.onEvent(event);ws.setReconnectInterval(5000);connecting=true;}
ws.loop();
if(!ws.isConnected()&&millis()-wsAttemptAt>15000&&(serverReason.startsWith("Connecting")||serverReason.startsWith("WebSocket disconnected")))serverReason="Cannot reach "+host+" (DNS/TLS/port)";
if(ws.isConnected()&&!authorized&&millis()-authAt>12000){serverReason="Registrar auth timed out";ws.disconnect();return;}
if(authorized&&!pingId.isEmpty()&&millis()-pingSent>10000){serverReason="Ping timed out";ws.disconnect();return;}
if(authorized&&pingId.isEmpty()&&millis()-pingAt>=45000){JsonDocument d;d["payload"]["ts"]=nowMs();pingId=nextId();pingAt=pingSent=millis();request("Ping",pingId,d);}
}
static void flushDisplay(lv_disp_drv_t *d,const lv_area_t *a,lv_color_t *c){
#if LV_COLOR_16_SWAP
gfx->draw16bitBeRGBBitmap(a->x1,a->y1,(uint16_t*)&c->full,a->x2-a->x1+1,a->y2-a->y1+1);
#else
gfx->draw16bitRGBBitmap(a->x1,a->y1,(uint16_t*)&c->full,a->x2-a->x1+1,a->y2-a->y1+1);
#endif
lv_disp_flush_ready(d);
}
static void readTouch(lv_indev_drv_t *,lv_indev_data_t *d){int16_t x=0,y=0;d->state=touch.getPoint(&x,&y,1)>0?LV_INDEV_STATE_PR:LV_INDEV_STATE_REL;d->point.x=x;d->point.y=y;}
static void tick(void *){lv_tick_inc(2);}
static void home();
static void settings();
static lv_obj_t *button(lv_obj_t *parent,const char *label,lv_event_cb_t cb){lv_obj_t *b=lv_btn_create(parent);lv_obj_t *l=lv_label_create(b);lv_label_set_text(l,label);lv_obj_center(l);lv_obj_add_event_cb(b,cb,LV_EVENT_CLICKED,nullptr);return b;}
static Screen screen=HOME;
static EditKind editKind=EDIT_URL;
static int menuIndex=0,scanCount=0,keyboardPage=0;
static String scanNames[20],selectedWifi,editValue,uiMessage;
static bool keyboardSymbols=false,keyboardShift=false;
static lv_obj_t *editorInput=nullptr,*keyboard=nullptr,*statusLabel=nullptr,*editorHint=nullptr;
static void drawScreen();
static void baseScreen(Screen next){screen=next;lv_obj_clean(lv_scr_act());statusLabel=nullptr;editorInput=nullptr;keyboard=nullptr;editorHint=nullptr;lv_obj_set_style_bg_color(lv_scr_act(),lv_color_hex(0x101820),0);lv_obj_set_style_text_color(lv_scr_act(),lv_color_hex(0xe4f0ef),0);}
static void title(const char *s){auto l=lv_label_create(lv_scr_act());lv_label_set_text(l,s);lv_obj_align(l,LV_ALIGN_TOP_MID,0,14);}
static void message(const String &s,int y){auto l=lv_label_create(lv_scr_act());lv_obj_set_width(l,440);lv_label_set_long_mode(l,LV_LABEL_LONG_WRAP);lv_label_set_text(l,s.c_str());lv_obj_set_pos(l,20,y);}
static void updateHome();
static void sendPingNow(){
if(!authorized||!ws.isConnected()){serverReason="Ping unavailable: server offline";updateHome();return;}
if(!pingId.isEmpty()){serverReason="Ping already pending";updateHome();return;}
JsonDocument d;d["payload"]["ts"]=nowMs();pingId=nextId();pingAt=pingSent=millis();serverReason="Ping sent; awaiting reply";request("Ping",pingId,d);updateHome();
}
static void updateHome(){
if(!statusLabel)return;
bool wifiOnline=WiFi.status()==WL_CONNECTED,serverOnline=authorized&&ws.isConnected();
String s="Wi-Fi: "+String(wifiOnline?"#28B463 ONLINE#":"#E74C3C OFFLINE#");
if(wifiOnline)s+=" ("+WiFi.SSID()+")";
s+="\nServer: "+String(serverOnline?"#28B463 ONLINE#":"#E74C3C OFFLINE#");
s+="\n"+serverReason;
s+="\nLast ping: "+String(lastPingAckAt?String((millis()-lastPingAckAt)/1000)+"s ago":"never");
s+="\nSD card: "+String(sdReady?"OK":"ERROR")+"\nNamespace: @"+ns;
s+="\nKey: "+String(keyReady?"SET":"NOT SET")+"\nIssued: "+String((unsigned long long)total);
s+="\nLast 5 hours: "+String(used())+"/10\nLast: "+lastLogin;
s+="\n"+String(serverOnline&&sdReady&&safeTime()?"READY":"NOT READY");
if(!lastError.isEmpty())s+="\n"+lastError;
if(powerReady&&power.isBatteryConnect())s+="\nBattery: "+String(power.getBatteryPercent())+"%";
lv_label_set_text(statusLabel,s.c_str());
}
static void home(){
baseScreen(HOME);title("SHiNE REGISTRAR 1.0");statusLabel=lv_label_create(lv_scr_act());
lv_obj_set_width(statusLabel,440);lv_label_set_long_mode(statusLabel,LV_LABEL_LONG_WRAP);lv_obj_set_pos(statusLabel,20,60);
lv_label_set_recolor(statusLabel,true);lv_obj_set_style_text_font(statusLabel,&lv_font_montserrat_16,0);
lv_obj_set_style_text_line_space(statusLabel,3,0);
auto b=button(lv_scr_act(),"SETTINGS",[](lv_event_t*){settings();});lv_obj_set_size(b,190,54);lv_obj_align(b,LV_ALIGN_BOTTOM_LEFT,20,-20);
b=button(lv_scr_act(),"PING",[](lv_event_t*){sendPingNow();});lv_obj_set_size(b,190,54);lv_obj_align(b,LV_ALIGN_BOTTOM_RIGHT,-20,-20);updateHome();
}
static void menuItem(lv_obj_t *parent,const char *label,int y,lv_event_cb_t cb){auto b=button(parent,label,cb);lv_obj_set_size(b,436,96);lv_obj_set_pos(b,22,y);lv_obj_set_style_bg_color(b,lv_color_hex(0x355C7D),0);}
static void openEditor(EditKind kind,const String &value){editKind=kind;editValue=value;uiMessage="";keyboardSymbols=false;keyboardShift=false;keyboardPage=0;drawScreen();}
static void settings(){screen=MENU;menuIndex=0;drawScreen();}
static void wifiOverview(){screen=WIFI_OVERVIEW;drawScreen();}
static void wifiScan(){
uiMessage="Scanning networks...";scanCount=0;
wifiScanning=false;wifiTrying=false;WiFi.scanDelete();WiFi.mode(WIFI_STA);int count=WiFi.scanNetworks();
for(int i=0;i<count&&scanCount<20;i++){String name=WiFi.SSID(i);if(name.isEmpty())continue;bool duplicate=false;for(int j=0;j<scanCount;j++)if(scanNames[j]==name)duplicate=true;if(!duplicate)scanNames[scanCount++]=name;}
WiFi.scanDelete();uiMessage=scanCount?String("Found ")+scanCount+" networks":"No networks found";drawScreen();
}
static void editorError(const String &error){uiMessage=error;if(editorHint)lv_label_set_text(editorHint,uiMessage.c_str());}
static void saveEditor(){
String value=lv_textarea_get_text(editorInput);
if(editKind==EDIT_WIFI){
if(selectedWifi.isEmpty()){editorError("Select a network first");return;}
wifiScanning=false;wifiTrying=false;WiFi.scanDelete();WiFi.disconnect(false,false);WiFi.begin(selectedWifi.c_str(),value.c_str());
uint32_t started=millis();while(WiFi.status()!=WL_CONNECTED&&millis()-started<12000)delay(100);
if(WiFi.status()!=WL_CONNECTED){WiFi.disconnect(false,false);editorError("Connection failed; check password");return;}
ssid=selectedWifi;wifiPass=value;rememberWifi(ssid,wifiPass);bool saved=prefs.putString("ssid",ssid)==ssid.length()&&prefs.putString("wifiPass",wifiPass)==wifiPass.length();bool profileSaved=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==ssid){String a="net"+String(i),b="pass"+String(i);profileSaved=prefs.getString(a.c_str(),"")==ssid&&prefs.getString(b.c_str(),"")==wifiPass;}if(!saved||!profileSaved||prefs.getString("ssid","")!=ssid||prefs.getString("wifiPass","")!=wifiPass){editorError("Wi-Fi connected but storage failed");return;}wifiTrying=false;wifiScanning=false;wifiScanAt=0;uiMessage="Connected: "+WiFi.localIP().toString();wifiOverview();return;
}
if(editKind==EDIT_URL){value.trim();String normalized=value.startsWith("wss://")?value:String("wss://")+value+"/ws";String previous=endpoint;endpoint=normalized;bool valid=parseEndpoint();endpoint=previous;parseEndpoint();if(!valid){editorError("Enter host, e.g. t2.shineup.me");return;}if(prefs.putString("endpoint",normalized)!=normalized.length()){editorError("Server storage failed");return;}endpoint=normalized;stopNetwork();uiMessage="Server address saved";settings();return;}
if(editKind==EDIT_NAMESPACE){if(!validNamespace(value)){editorError("Invalid namespace");return;}if(prefs.putString("namespace",value)!=value.length()){editorError("Namespace storage failed");return;}ns=value;stopNetwork();uiMessage="Namespace saved";settings();return;}
uint8_t newSeed[32]={},newOwner[32]={},newSecret[64]={};
if(!regkey::decode32(value.c_str(),newSeed)){editorError("Enter a 32-byte Base58 seed");return;}
if(crypto_sign_seed_keypair(newOwner,newSecret,newSeed)!=0){
sodium_memzero(newSeed,32);editorError("Key generation failed");return;
}
if(prefs.putBytes("seed",newSeed,32)!=32||prefs.getBytesLength("seed")!=32){
sodium_memzero(newSeed,32);sodium_memzero(newSecret,64);editorError("Key storage failed");return;
}
stopNetwork();memcpy(seed,newSeed,32);memcpy(secret,newSecret,64);memcpy(owner,newOwner,32);
sodium_memzero(newSeed,32);sodium_memzero(newSecret,64);prefs.remove("secretKey");prefs.remove("keyPassword");keyReady=true;
uiMessage="Registration key saved";settings();
}
static void keyCb(lv_event_t *e){const char *token=(const char*)lv_event_get_user_data(e);if(!token||!editorInput)return;String key=token;if(key=="<SAVE>"){saveEditor();return;}if(key=="<CANCEL>"){if(editKind==EDIT_WIFI)wifiOverview();else settings();return;}if(key=="<DEL>"){lv_textarea_del_char(editorInput);return;}if(key=="<CLR>"){lv_textarea_set_text(editorInput,"");return;}if(key=="<MODE>"){editValue=lv_textarea_get_text(editorInput);keyboardSymbols=!keyboardSymbols;keyboardPage=0;drawScreen();return;}if(key=="<SHIFT>"){editValue=lv_textarea_get_text(editorInput);keyboardShift=!keyboardShift;drawScreen();return;}if(key=="<PAGE>"){editValue=lv_textarea_get_text(editorInput);keyboardPage=1-keyboardPage;drawScreen();return;}if(key=="<SPACE>")key=" ";if(keyboardShift&&!keyboardSymbols)key.toUpperCase();lv_textarea_set_cursor_pos(editorInput,LV_TEXTAREA_CURSOR_LAST);lv_textarea_add_text(editorInput,key.c_str());}
static void keyButton(const char *label,const char *token,int x,int y,int w,int h){auto b=lv_btn_create(lv_scr_act());lv_obj_set_pos(b,x,y);lv_obj_set_size(b,w,h);lv_obj_set_style_bg_color(b,lv_color_hex(0x2A6F97),0);auto l=lv_label_create(b);lv_label_set_text(l,label);lv_obj_center(l);lv_obj_add_event_cb(b,keyCb,LV_EVENT_CLICKED,(void*)token);}
static void keyRow(const char *const *tokens,int count,int y){for(int i=0;i<count;i++){String label=tokens[i];if(label=="<SPACE>")label="SPACE";if(keyboardShift&&!keyboardSymbols)label.toUpperCase();keyButton(label.c_str(),tokens[i],20+i*92,y,84,62);}}
static void drawKeyboard(){
static const char *a0[]={"q","w","e","r","t"},*a1[]={"a","s","d","f","g"},*a2[]={"z","x","c","v","b"};
static const char *b0[]={"y","u","i","o","p"},*b1[]={"h","j","k","l"},*b2[]={"n","m",".","-"};
static const char *s0[]={"1","2","3","4","5"},*s1[]={"://","/",":","_","@"},*s2[]={".com",".net",".org",".me",".io"};
static const char *t0[]={"6","7","8","9","0"},*t1[]={"?","!","=","+","-"},*t2[]={"<SPACE>","#","~",":","/"};
if(!keyboardSymbols){if(!keyboardPage){keyRow(a0,5,120);keyRow(a1,5,188);keyRow(a2,5,256);}else{keyRow(b0,5,120);keyRow(b1,4,188);keyRow(b2,4,256);}}
else{if(!keyboardPage){keyRow(s0,5,120);keyRow(s1,5,188);keyRow(s2,5,256);}else{keyRow(t0,5,120);keyRow(t1,5,188);keyRow(t2,5,256);}}
keyButton(keyboardSymbols?"ABC":"123","<MODE>",20,328,84,62);keyButton(keyboardShift?"SHIFT*":"SHIFT","<SHIFT>",112,328,84,62);keyButton("DEL","<DEL>",204,328,76,62);keyButton("SAVE","<SAVE>",288,328,76,62);keyButton("CANCEL","<CANCEL>",372,328,88,62);
keyButton("OTHER KEYS", "<PAGE>",20,400,150,55);
editorHint=lv_label_create(lv_scr_act());lv_obj_set_width(editorHint,280);lv_obj_set_pos(editorHint,185,405);lv_label_set_text(editorHint,uiMessage.isEmpty()?"Page 1 / 2":uiMessage.c_str());
}
static void menuSelectCb(lv_event_t *e){
int item=(int)(intptr_t)lv_event_get_user_data(e);
if(item==0){screen=WIFI_OVERVIEW;drawScreen();}
else if(item==1){String display=endpoint;if(display.startsWith("wss://"))display.remove(0,6);if(display.endsWith("/ws"))display.remove(display.length()-3);screen=EDITOR;openEditor(EDIT_URL,display);}
else if(item==2){screen=EDITOR;openEditor(EDIT_NAMESPACE,ns);}
else if(item==3){screen=EDITOR;openEditor(EDIT_SECRET,keyReady?String(regkey::encode(seed,32).c_str()):String(""));}
else {screen=KEYS;drawScreen();}
}
static void wifiSelectCb(lv_event_t *e){
int i=(int)(intptr_t)lv_event_get_user_data(e);
if(i<0||i>=scanCount)return;
selectedWifi=scanNames[i];String saved;
for(int j=0;j<MAX_WIFI_PROFILES;j++)if(knownSsids[j]==selectedWifi)saved=knownPasswords[j];
screen=EDITOR;openEditor(EDIT_WIFI,saved);
}
static void drawScreen(){
if(screen==HOME){home();return;}
if(screen==MENU){
baseScreen(MENU);title("SETTINGS");message(uiMessage.isEmpty()?"Select an item":uiMessage,55);
const char *labels[]={"WI-FI","SERVER URL","NAMESPACE","SECRET KEY BASE58","VIEW KEYS"};
for(int i=0;i<2;i++){
int index=menuIndex+i;auto b=lv_btn_create(lv_scr_act());lv_obj_set_size(b,300,104);lv_obj_set_pos(b,20,115+i*122);lv_obj_set_style_bg_color(b,lv_color_hex(0x355C7D),0);
auto l=lv_label_create(b);lv_label_set_text(l,labels[index]);lv_obj_center(l);lv_obj_add_event_cb(b,menuSelectCb,LV_EVENT_CLICKED,(void*)(intptr_t)index);
}
auto up=button(lv_scr_act(),"UP",[](lv_event_t*){if(menuIndex>0){menuIndex--;drawScreen();}});lv_obj_set_size(up,115,96);lv_obj_set_pos(up,345,120);
auto down=button(lv_scr_act(),"DOWN",[](lv_event_t*){if(menuIndex<3){menuIndex++;drawScreen();}});lv_obj_set_size(down,115,96);lv_obj_set_pos(down,345,246);
message(String("Items ")+String(menuIndex+1)+"-"+String(menuIndex+2)+" of 5",365);
auto back=button(lv_scr_act(),"BACK",[](lv_event_t*){home();});lv_obj_set_size(back,200,60);lv_obj_align(back,LV_ALIGN_BOTTOM_MID,0,-8);return;
}
if(screen==WIFI_OVERVIEW){
baseScreen(WIFI_OVERVIEW);title("WI-FI");message(WiFi.status()==WL_CONNECTED?String("ONLINE: ")+WiFi.SSID():"OFFLINE",65);
int saved=0;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(!knownSsids[i].isEmpty())saved++;
message("Saved networks: "+String(saved),100);message(uiMessage,135);
auto b=button(lv_scr_act(),"SELECT NETWORK",[](lv_event_t*){screen=WIFI_SCAN;wifiScan();});lv_obj_set_size(b,436,68);lv_obj_set_pos(b,22,195);
b=button(lv_scr_act(),"BACK",[](lv_event_t*){settings();});lv_obj_set_size(b,200,65);lv_obj_align(b,LV_ALIGN_BOTTOM_MID,0,-25);return;
}
if(screen==WIFI_SCAN){
baseScreen(WIFI_SCAN);title("SELECT NETWORK");message(uiMessage,55);
auto list=lv_obj_create(lv_scr_act());lv_obj_set_pos(list,15,90);lv_obj_set_size(list,450,280);lv_obj_set_flex_flow(list,LV_FLEX_FLOW_COLUMN);
for(int i=0;i<scanCount;i++){
auto b=lv_btn_create(list);lv_obj_set_width(b,LV_PCT(100));auto l=lv_label_create(b);lv_label_set_text(l,scanNames[i].c_str());lv_obj_center(l);
lv_obj_add_event_cb(b,wifiSelectCb,LV_EVENT_CLICKED,(void*)(intptr_t)i);
}
auto b=button(lv_scr_act(),"SCAN AGAIN",[](lv_event_t*){wifiScan();});lv_obj_set_size(b,210,65);lv_obj_set_pos(b,20,390);
b=button(lv_scr_act(),"BACK",[](lv_event_t*){wifiOverview();});lv_obj_set_size(b,210,65);lv_obj_set_pos(b,250,390);return;
}
if(screen==EDITOR){
baseScreen(EDITOR);title(editKind==EDIT_WIFI?"ENTER WI-FI PASSWORD":editKind==EDIT_URL?"SERVER URL":editKind==EDIT_NAMESPACE?"NAMESPACE":"SECRET KEY BASE58");
editorInput=lv_textarea_create(lv_scr_act());lv_obj_set_size(editorInput,436,58);lv_obj_set_pos(editorInput,22,48);lv_textarea_set_one_line(editorInput,true);
lv_textarea_set_max_length(editorInput,editKind==EDIT_URL?250:128);lv_textarea_set_password_mode(editorInput,false);
lv_textarea_set_text(editorInput,editValue.c_str());lv_textarea_set_cursor_pos(editorInput,LV_TEXTAREA_CURSOR_LAST);drawKeyboard();return;
}
if(screen==KEYS){
baseScreen(KEYS);title("REGISTRATION KEYS");auto panel=lv_obj_create(lv_scr_act());lv_obj_set_pos(panel,12,55);lv_obj_set_size(panel,456,340);
String pub=keyReady?String(regkey::encode(owner,32).c_str()):"Not set",priv=keyReady?String(regkey::encode(seed,32).c_str()):"Not set";
auto l=lv_label_create(panel);lv_obj_set_width(l,LV_PCT(100));lv_label_set_long_mode(l,LV_LABEL_LONG_WRAP);
lv_label_set_text(l,(String("Public key (Base58):\n")+pub+"\n\nSecret seed (Base58, 32 bytes):\n"+priv).c_str());
auto b=button(lv_scr_act(),"BACK",[](lv_event_t*){settings();});lv_obj_set_size(b,200,65);lv_obj_align(b,LV_ALIGN_BOTTOM_MID,0,-12);return;
}
}
void setup(){Serial.begin(115200);sodium_init();Wire.begin(15,14);powerReady=power.begin(Wire,AXP2101_SLAVE_ADDRESS,15,14);if(powerReady){power.disableIRQ(XPOWERS_AXP2101_ALL_IRQ);power.setChargeTargetVoltage(3);power.enableBattDetection();power.enableBattVoltageMeasure();}
gfx->begin();bus->writeC8D8(0x36,0xA0);gfx->setBrightness(180);gfx->fillScreen(0);touch.setPins(11,-1);touch.begin(Wire,CST92XX_SLAVE_ADDRESS,15,14);touch.setMaxCoordinates(480,480);touch.setSwapXY(true);touch.setMirrorXY(true,false);
lv_init();const uint32_t count=480*40;auto a=(lv_color_t*)heap_caps_malloc(count*sizeof(lv_color_t),MALLOC_CAP_DMA);auto b=(lv_color_t*)heap_caps_malloc(count*sizeof(lv_color_t),MALLOC_CAP_DMA);if(!a||!b)return;lv_disp_draw_buf_init(&drawBuf,a,b,count);static lv_disp_drv_t disp;lv_disp_drv_init(&disp);disp.hor_res=480;disp.ver_res=480;disp.flush_cb=flushDisplay;disp.draw_buf=&drawBuf;lv_disp_drv_register(&disp);static lv_indev_drv_t input;lv_indev_drv_init(&input);input.type=LV_INDEV_TYPE_POINTER;input.read_cb=readTouch;lv_indev_drv_register(&input);const esp_timer_create_args_t args={.callback=tick,.name="registrar_tick"};esp_timer_handle_t timer;esp_timer_create(&args,&timer);esp_timer_start_periodic(timer,2000);
#if defined(CONFIG_NVS_ENCRYPTION) && CONFIG_NVS_ENCRYPTION
secureStorage=esp_flash_encryption_enabled()&&esp_secure_boot_enabled();
#else
secureStorage=false;
#endif
if(!prefs.begin("shine-reg-v1",false)){home();lastError="NVS unavailable";uiReady=true;return;}ssid=prefs.getString("ssid","");wifiPass=prefs.getString("wifiPass","");endpoint=prefs.getString("endpoint","");ns=prefs.getString("namespace","free");paused=false;prefs.remove("paused");for(int i=0;i<MAX_WIFI_PROFILES;i++){String a="net"+String(i),b="pass"+String(i);knownSsids[i]=prefs.getString(a.c_str(),"");knownPasswords[i]=prefs.getString(b.c_str(),"");}if(!ssid.isEmpty()){bool found=false;for(int i=0;i<MAX_WIFI_PROFILES;i++)if(knownSsids[i]==ssid)found=true;if(!found){knownSsids[0]=ssid;knownPasswords[0]=wifiPass;}}
if(prefs.getBytesLength("seed")==32&&prefs.getBytes("seed",seed,32)==32){
keyReady=crypto_sign_seed_keypair(owner,secret,seed)==0;
}else if(prefs.getBytesLength("secretKey")==64&&prefs.getBytes("secretKey",secret,64)==64){
uint8_t checkSecret[64];memcpy(seed,secret,32);
keyReady=crypto_sign_seed_keypair(owner,checkSecret,seed)==0&&sodium_memcmp(secret,checkSecret,64)==0;
sodium_memzero(checkSecret,64);
}
gpio_reset_pin(GPIO_NUM_2);pinMode(1,INPUT_PULLUP);pinMode(3,INPUT_PULLUP);SD_MMC.setPins(2,1,3);sdReady=SD_MMC.begin("/sdcard",true)&&loadHistory();if(!sdReady&&lastError.isEmpty())lastError="SD history unavailable";
WiFi.mode(WIFI_STA);WiFi.setAutoReconnect(true);configTime(0,0,"pool.ntp.org","time.cloudflare.com");home();uiReady=true;}
void loop(){if(!uiReady){delay(1000);return;}lv_timer_handler();manageNetwork();if(millis()-refreshAt>1000){refreshAt=millis();updateHome();}delay(5);}
@@ -0,0 +1,13 @@
# Registration Signer 1.0 — экран 480×480
Интерфейс английский. Home показывает Wi-Fi ONLINE/OFFLINE (при подключении — SSID), Server ONLINE/OFFLINE (только после успешной авторизации регистратора), причину отсутствия связи, Last ping (секунды после последнего успешного ответа, обновляются каждую секунду), SD card, Namespace, Key, Issued, Last 5 hours, Last, READY/NOT READY, Battery (если доступно), последнюю ошибку. ONLINE зелёный, OFFLINE красный. Внизу SETTINGS и PING. PING отправляет внеочередной запрос, если сервер авторизован; сообщение показывает отправку, ответ, отказ или тайм-аут. Паузы выдачи с экрана больше нет.
SETTINGS — меню по образцу старой основной прошивки; видны два крупных пункта слева шириной около двух третей экрана, справа кнопки UP/DOWN для прокрутки, снизу BACK для возврата на Home. Пункты: WI-FI, SERVER URL, NAMESPACE, SECRET KEY BASE58, VIEW KEYS. Жест вправо возвращает на Home. Каждый пункт открывает отдельный экран.
WI-FI показывает статус и число сохранённых сетей. SELECT NETWORK сканирует доступные SSID и открывает список. Выбор сети открывает редактор пароля; если сеть ранее сохранена, её пароль подставляется целиком. SAVE сразу пытается подключиться. Только после успешного подключения SSID и пароль сохраняются во внутренней NVS ESP32. Хранится до восьми сетей. После перезагрузки и при потере связи устройство ищет доступные сохранённые сети, сначала пробует последнюю успешную, затем остальные. Неудачный пароль остаётся в редакторе для исправления, но не сохраняется.
SERVER URL принимает имя хоста, например `t2.shineup.me`; прошивка сохраняет `wss://t2.shineup.me/ws`. Ранее сохранённые полные адреса `wss://host[:port]/ws` также можно редактировать. NAMESPACE — namespace без `@`. Каждый пункт сохраняется отдельно в NVS; ошибочное значение остаётся в редакторе с сообщением. Изменение URL или namespace переподключает сервер.
SECRET KEY BASE58 принимает видимый 32-байтный секретный seed Ed25519 в Base58. Из seed прошивка восстанавливает полный 64-байтный секретный ключ и публичный ключ. Для прототипа seed сохраняется в обычной NVS ESP32 без требования Secure Boot, Flash Encryption и NVS Encryption. VIEW KEYS показывает публичный ключ Base58 (32 байта) и секретный seed Base58 (32 байта). Ключи никогда не отправляются серверу: по WebSocket отправляется только подпись challenge и подписанный сертификат.
Редактор повторяет клавиатуру старой основной прошивки: буквенная и символьная страницы, переключение двух половин кнопкой OTHER KEYS, `123/ABC`, `SHIFT`, `DEL`, `SAVE`, `CANCEL`. Все поля отображаются открытым текстом. При повторном входе старый текст остаётся целиком, курсор установлен в конце. CANCEL возвращает без изменения. Ошибка сохранения не закрывает редактор. Общей кнопки Save для всех настроек нет.
+1 -1
View File
@@ -19,7 +19,7 @@ SHiNE — проект децентрализованного общения: б
## Самостоятельный запуск ## Самостоятельный запуск
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Публичное пошаговое руководство по установке всего комплекса ещё готовится. Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Для `./gradlew startLocal` скопируйте `application.properties.example` в `SHiNE-server/application.properties` и заполните параметры своей среды. При `java -jar` внешний `application.properties` ищется в текущем рабочем каталоге. Встроенный файл необязателен. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
## Документация ## Документация
+4 -4
View File
@@ -29,9 +29,9 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
## Настройка сервера в Solana (Solana PDA) ## Настройка сервера в Solana (Solana PDA)
Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.2 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint. Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.0 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint.
PDA 1.2 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave. PDA 1.0 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave.
Клиенты читают server PDA из Solana, получают опубликованный endpoint и подключаются к нему. Межсерверная доставка DM через access-server routing остаётся отдельным механизмом. Клиенты читают server PDA из Solana, получают опубликованный endpoint и подключаются к нему. Межсерверная доставка DM через access-server routing остаётся отдельным механизмом.
@@ -45,7 +45,7 @@ shine-UI/server-ui.html
- `shine-UI/server-ui/create-server-pda.html` — первичная регистрация серверного аккаунта; - `shine-UI/server-ui/create-server-pda.html` — первичная регистрация серверного аккаунта;
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса сервера. - `shine-UI/server-ui/update-server-pda.html` — обновление адреса сервера.
PDA 1.2 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root. PDA 1.0 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root.
Актуальные адреса программ Solana (devnet): Актуальные адреса программ Solana (devnet):
- `shine_users`: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6` - `shine_users`: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6`
@@ -55,7 +55,7 @@ PDA 1.2 использует три постоянные роли ключей:
## Синхронизация пользовательских blockchain ## Синхронизация пользовательских blockchain
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync пока может оставаться как inert legacy, но не должен включаться в runtime. Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync удалён; не восстанавливать его. `ListBlockchainHeads` остаётся read-only API тестового издателя.
## Деплой ## Деплой
@@ -0,0 +1,38 @@
package server.archive;
import blockchain.Ans104DataItem;
import blockchain.BchBlockEntry;
import blockchain.CoreContentContainer;
import blockchain.CoreContentTransport;
import java.time.Instant;
import java.util.Arrays;
/** Thin adapter for the existing archive queues. No signing, state or independent retry. */
final class ArchiveBlockPair {
private ArchiveBlockPair() {}
@FunctionalInterface interface Upload<R> {
R upload(byte[] raw, byte[] id) throws Exception;
}
@FunctionalInterface interface Download {
byte[] download(byte[] id) throws Exception;
}
/** Returns CORE acknowledgement only after both uploads succeed. */
static <R> R publish(byte[] container, byte[] expectedCoreId, Upload<R> uploader) throws Exception {
BchBlockEntry block = BchBlockEntry.fromCoreContent(container);
Ans104DataItem core = block.getCoreDataItem(), content = block.getContentDataItem();
if (!Arrays.equals(core.id32(), expectedCoreId)) throw new IllegalArgumentException("CORE id mismatch");
uploader.upload(content.rawBytes(), content.id32());
return uploader.upload(core.rawBytes(), core.id32());
}
/** Download by signed reference, not by search tag or the CORE bundle location. */
static byte[] download(byte[] coreRaw, byte[] expectedCoreId, Download downloader) throws Exception {
Ans104DataItem core = new Ans104DataItem(coreRaw);
var record = CoreContentTransport.verifyCore(core, core.owner32(), expectedCoreId, Instant.now().getEpochSecond());
Ans104DataItem content = new Ans104DataItem(downloader.download(record.contentDataItemId32()));
CoreContentTransport.verifyContent(record, content, core.owner32());
return CoreContentContainer.pack(core, content);
}
}
@@ -14,8 +14,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
/** /**
* Publisher с двумя путями доставки: * Publisher с двумя путями доставки:
* 1) Turbo — немедленная неблокирующая попытка для только что принятого блока; * Серверный Turbo publisher обслуживает candidate-блоки ротации ключей.
* 2) плановый fixed-delay цикл — страховочная добивка только зависших pending-записей. * Пользовательские CORE/CONTENT в режиме client_only загружает браузер.
*/ */
public final class ArweaveBlockPublisherScheduler { public final class ArweaveBlockPublisherScheduler {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class); private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
@@ -8,24 +8,22 @@ import shine.db.entities.BlockEntry;
import shine.db.entities.KeyRotationCandidateBlockEntry; import shine.db.entities.KeyRotationCandidateBlockEntry;
import server.sync.ArweavePublishSignal; import server.sync.ArweavePublishSignal;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
/** Publishes locally-created signed user DataItems through the configured transport. */ /** Серверный publisher candidate-блоков ротации; пользовательские пары ведёт браузер. */
public final class ArweaveBlockPublisherService { public final class ArweaveBlockPublisherService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherService.class); private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherService.class);
private final ArweaveBlocksConfig cfg; private final ArweaveBlocksConfig cfg;
private final BlocksDAO blocksDAO = BlocksDAO.getInstance(); private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance(); private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
private final ArweaveL1Uploader arweaveUploader;
private final TurboDataItemUploader turboUploader; private final TurboDataItemUploader turboUploader;
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) { public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
cfg.validatePublisher();
this.cfg = cfg; this.cfg = cfg;
this.arweaveUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.ARWEAVE ? new ArweaveL1Uploader(cfg) : null;
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null; this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
} }
@@ -42,22 +40,13 @@ public final class ArweaveBlockPublisherService {
if (entry == null) return true; if (entry == null) return true;
byte[] raw = entry.getBlockBytes(); byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false; if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id); TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis()); candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}", log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber()); result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
return true; return true;
} }
return false;
BlockEntry entry = blocksDAO.getPendingArweaveByDataItemId(id);
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
return true;
} }
public int runCycle() throws Exception { public int runCycle() throws Exception {
@@ -83,22 +72,12 @@ public final class ArweaveBlockPublisherService {
attempted += rotationCandidates.size(); attempted += rotationCandidates.size();
published += switch (cfg.publishMode()) { published += switch (cfg.publishMode()) {
case TURBO -> publishTurboRotation(rotationCandidates, onPublished); case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates); case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
case NONE -> 0; case NONE -> 0;
}; };
} }
int remaining = Math.max(0, maxItems - attempted); // Пользовательские блоки в режиме client_only публикует браузер.
if (remaining == 0) return published;
List<BlockEntry> candidates = blocksDAO.listPendingArweave(remaining);
candidates = candidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> publishDirectArweave(candidates);
case NONE -> 0;
};
return published; return published;
} }
@@ -110,7 +89,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId(); byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue; if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try { try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id); TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis()); candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id); onPublished.accept(id);
published++; published++;
@@ -135,7 +114,7 @@ public final class ArweaveBlockPublisherService {
byte[] id = e.getDataItemId(); byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue; if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try { try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id); TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis()); blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id); onPublished.accept(id);
published++; published++;
@@ -151,71 +130,4 @@ public final class ArweaveBlockPublisherService {
return published; return published;
} }
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
long estimated = 32;
for (KeyRotationCandidateBlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
long next = estimated + 64L + raw.length;
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
if (next > cfg.publishMaxBundleBytes()) {
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
continue;
}
items.add(raw);
ids.add(id);
estimated = next;
}
if (items.isEmpty()) return 0;
byte[] bundle = Ans104Bundle.write(items);
List<ArweaveL1Uploader.Tag> rootTags = List.of(
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
);
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
items.size(), result.txId(), bundle.length);
return items.size();
}
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
long estimated = 32;
for (BlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
long next = estimated + 64L + raw.length;
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
if (next > cfg.publishMaxBundleBytes()) {
log.error("One DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
e.getBchName(), e.getBlockNumber(), raw.length);
continue;
}
items.add(raw);
ids.add(id);
estimated = next;
}
if (items.isEmpty()) return 0;
byte[] bundle = Ans104Bundle.write(items);
List<ArweaveL1Uploader.Tag> rootTags = List.of(
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
);
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
blocksDAO.markArweavePublished(ids, System.currentTimeMillis());
log.info("Published {} SHiNE test DataItems in direct Arweave root tx {} (bundle={} bytes)",
items.size(), result.txId(), bundle.length);
return items.size();
}
} }
@@ -10,15 +10,18 @@ import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard; import server.sync.BlockchainResyncGuard;
import shine.db.DbController; import shine.db.DbController;
import shine.db.KeyEncodingUtil;
import utils.config.AppConfig; import utils.config.AppConfig;
import shine.db.dao.ArweaveBlockImportDAO; import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO; import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO; import shine.db.dao.BlocksDAO;
import shine.db.entities.BlockEntry;
import shine.db.dao.BlockchainForkSegmentsDAO; import shine.db.dao.BlockchainForkSegmentsDAO;
import shine.db.dao.CanonicalChainResolver; import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO; import shine.db.dao.ChannelReadStateDAO;
import shine.db.dao.BlockchainResyncCleanupDAO; import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO; import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.dao.RegistrationIdentityDAO;
import shine.db.entities.BlockchainStateEntry; import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry; import shine.db.entities.SolanaUserPdaCurrentEntry;
@@ -38,9 +41,8 @@ import java.time.Duration;
import java.util.*; import java.util.*;
/** /**
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes. * Discovers signed CORE items and registration certificates in the active App namespace.
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo * Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
* or inside a direct server-created ANS-104 bundle.
*/ */
public final class ArweaveBlockSyncService { public final class ArweaveBlockSyncService {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class); private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
@@ -114,14 +116,33 @@ public final class ArweaveBlockSyncService {
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage()); log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
continue; continue;
} }
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) { if (blocksDAO.existsByDataItemId(id32)) {
// Локально принятый блок должен получить подтверждение Arweave без повторного применения.
try {
DownloadedEvent published = downloadEvent(dataItemId);
BlockEntry local = blocksDAO.getByDataItemId(id32);
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
} else {
log.warn("Arweave DataItem {} differs from locally accepted bytes", dataItemId);
}
} catch (Exception e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
continue;
}
unresolvedDownloads.remove(dataItemId);
continue;
}
if (importDAO.exists(id32)) {
unresolvedDownloads.remove(dataItemId); unresolvedDownloads.remove(dataItemId);
continue; continue;
} }
try { try {
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId); DownloadedEvent downloaded = downloadEvent(dataItemId);
if (isRegistrationItem(downloaded.rawDataItem())) { if (downloaded.registration()) {
registrationImporter.importSigned(downloaded.rawDataItem(), registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED); VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
unresolvedDownloads.remove(dataItemId); unresolvedDownloads.remove(dataItemId);
@@ -162,14 +183,26 @@ public final class ArweaveBlockSyncService {
if (attempted >= cfg.syncPageSize()) break; if (attempted >= cfg.syncPageSize()) break;
attempted++; attempted++;
if (blocksDAO.existsByDataItemId(pending.id32()) || importDAO.exists(pending.id32())) { if (blocksDAO.existsByDataItemId(pending.id32())) {
try {
DownloadedEvent published = downloadEvent(pending.dataItemId());
BlockEntry local = blocksDAO.getByDataItemId(pending.id32());
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
unresolvedDownloads.remove(pending.dataItemId());
}
} catch (Exception e) { log.debug("Arweave pair {} still unavailable: {}", pending.dataItemId(), e.getMessage()); }
continue;
}
if (importDAO.exists(pending.id32())) {
unresolvedDownloads.remove(pending.dataItemId()); unresolvedDownloads.remove(pending.dataItemId());
continue; continue;
} }
DownloadedDataItem downloaded; DownloadedEvent downloaded;
try { try {
downloaded = downloadSignedDataItem(pending.dataItemId()); downloaded = downloadEvent(pending.dataItemId());
} catch (RetryableDataItemDownloadException e) { } catch (RetryableDataItemDownloadException e) {
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих. // Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
unresolvedDownloads.remove(pending.dataItemId()); unresolvedDownloads.remove(pending.dataItemId());
@@ -183,7 +216,7 @@ public final class ArweaveBlockSyncService {
continue; continue;
} }
if (isRegistrationItem(downloaded.rawDataItem())) { if (downloaded.registration()) {
try { try {
registrationImporter.importSigned(downloaded.rawDataItem(), registrationImporter.importSigned(downloaded.rawDataItem(),
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED); VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
@@ -225,7 +258,7 @@ public final class ArweaveBlockSyncService {
if (pending.isEmpty()) break; if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) { for (ArweaveBlockImportDAO.QueueItem q : pending) {
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue; if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin()); SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) { if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis()); importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue; continue;
@@ -249,15 +282,16 @@ public final class ArweaveBlockSyncService {
Ans104DataItem item; Ans104DataItem item;
BchBlockEntry parsedBlock; BchBlockEntry parsedBlock;
try { try {
item = new Ans104DataItem(q.rawDataItem()); parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
parsedBlock = new BchBlockEntry(q.rawDataItem()); item = parsedBlock.getCoreDataItem();
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
} catch (Exception e) { } catch (Exception e) {
// Should be impossible after metadata validation, but never trust persisted bytes blindly. // Should be impossible after metadata validation, but never trust persisted bytes blindly.
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis()); importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
progress = true; progress = true;
continue; continue;
} }
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32()); SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin()) || !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) { || forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
@@ -278,6 +312,14 @@ public final class ArweaveBlockSyncService {
continue; continue;
} }
String reason = result.reasonCode(); String reason = result.reasonCode();
if ("bad_block_number".equals(reason)) {
BlockEntry existing = blocksDAO.getByNumber(physicalUser.getBlockchainName(), parsedBlock.blockNumber);
if (existing != null && !Arrays.equals(existing.getBlockBytes(), q.rawDataItem())) {
importDAO.reject(q.dataItemId(), "conflict_same_number_different_core", System.currentTimeMillis());
progress = true;
continue;
}
}
if ("bad_block_number".equals(reason) || "bad_prev_hash".equals(reason) if ("bad_block_number".equals(reason) || "bad_prev_hash".equals(reason)
|| "prev_line_block_not_found".equals(reason) || "channel_not_found".equals(reason) || "prev_line_block_not_found".equals(reason) || "channel_not_found".equals(reason)
|| "chain_resync_in_progress".equals(reason)) { || "chain_resync_in_progress".equals(reason)) {
@@ -328,14 +370,11 @@ public final class ArweaveBlockSyncService {
} }
try { try {
// Metadata is trusted only after complete ANS-104 validation. // Metadata is trusted only after complete ANS-104 validation.
Ans104DataItem item = new Ans104DataItem(raw); BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
Ans104DataItem item = b.getCoreDataItem();
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch"); if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
throw new IllegalArgumentException("bad App tag");
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
BchBlockEntry b = new BchBlockEntry(raw);
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32()); SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) { if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis()); importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue; continue;
@@ -352,7 +391,7 @@ public final class ArweaveBlockSyncService {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1"); if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1) if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch"); throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32); SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
if (parent == null || parent.getBlockchainName() == null if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin())) || !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch"); throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
@@ -388,9 +427,64 @@ public final class ArweaveBlockSyncService {
} }
} }
/**
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
*/
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
if (solana != null) return solana;
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
return null;
}
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
if (solana != null) return solana;
if (owner32 == null || owner32.length != 32) return null;
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT login, blockchain_key
FROM user_identity_current
WHERE registration_status='FREE_CERT' AND blockchain_key=?
LIMIT 1
""")) {
ps.setString(1, blockchainKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
}
}
}
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
if (solana != null) return solana;
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
String login = blockchainName.substring(0, blockchainName.length() - 4);
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
}
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
owner.setLogin(login);
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
owner.setPaidLimitBytes(0L);
return owner;
}
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception { private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry(); int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L); s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork); BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName()); BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return; if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
@@ -414,7 +508,7 @@ public final class ArweaveBlockSyncService {
while(rs.next())logins.add(rs.getString(1)); while(rs.next())logins.add(rs.getString(1));
} }
for(String login:logins){ for(String login:logins){
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login); SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
if(u==null||u.getBlockchainName()==null)continue; if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName())); replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
} }
@@ -467,7 +561,7 @@ public final class ArweaveBlockSyncService {
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){ try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){ ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n); int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n); BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0"); if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n); if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n); if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
@@ -477,17 +571,17 @@ public final class ArweaveBlockSyncService {
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login); if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
} }
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{ private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login); SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login); String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{ try{
validateGenericStaging(login); validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login); cleanupDAO.cleanupLoginForCanonicalReplay(login);
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null; long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){ try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){ ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw); int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
String bch=login+"-"+String.format("%03d",f); String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;} if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode()); Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash; cumulative+=raw.length;prevNumber=n;prevHash=hash;
}} }}
@@ -565,6 +659,17 @@ public final class ArweaveBlockSyncService {
return item.tags().contains(new Ans104DataItem.Tag("t", "reg")); return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
} }
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
if (isRegistrationItem(first.rawDataItem())) {
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
}
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
return new DownloadedEvent(first.rootTxId(), container, false);
}
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception { private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
return graphQlPage(minHeight, cursor, false); return graphQlPage(minHeight, cursor, false);
} }
@@ -763,6 +868,7 @@ public final class ArweaveBlockSyncService {
private record PendingDownload(String dataItemId, byte[] id32, long height) {} private record PendingDownload(String dataItemId, byte[] id32, long height) {}
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {} private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {} private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
private static final class RetryableDataItemDownloadException extends IOException { private static final class RetryableDataItemDownloadException extends IOException {
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
} }
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME; public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE; public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME; public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
public static ArweaveBlocksConfig load() { public static ArweaveBlocksConfig load() {
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
public boolean publishEnabled() { return publishMode != PublishMode.NONE; } public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
public void validatePublisher() { public void validatePublisher() {
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) { if (publishMode == PublishMode.ARWEAVE) {
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave"); throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
} }
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) { if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo"); throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
@@ -0,0 +1,70 @@
package server.archive;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shine.db.dao.BlockPublicationsDAO;
import shine.db.dao.BlocksDAO;
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.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/** Проверяет Turbo без загрузки или переподписи пользовательских блоков. */
public final class BlockPublicationVerifierScheduler {
private static final Logger log = LoggerFactory.getLogger(BlockPublicationVerifierScheduler.class);
private static final ObjectMapper json = new ObjectMapper();
private static final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
private static ScheduledExecutorService executor;
private BlockPublicationVerifierScheduler() {}
public static synchronized void startOrLog() {
if (executor != null) return;
String base = ArweaveBlocksConfig.load().syncTurboApiBase().replaceAll("/+$", "");
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "shine-block-publication-verifier"); t.setDaemon(true); return t;
});
executor.scheduleWithFixedDelay(() -> {
try { verify(base); }
catch (Exception e) { log.warn("Cannot verify pending Turbo publications", e); }
}, 10, 30, TimeUnit.SECONDS);
}
private static void verify(String base) throws Exception {
BlockPublicationsDAO dao = BlockPublicationsDAO.getInstance();
long now = System.currentTimeMillis();
List<BlockPublicationsDAO.Row> rows = dao.due(100, now);
for (BlockPublicationsDAO.Row row : rows) {
try {
boolean content = row.contentConfirmed() || available(base, row.contentId());
boolean core = row.coreConfirmed() || available(base, row.coreId());
if (content || core) dao.verified(row, content, core, now);
else dao.attempted(row, "Turbo ещё не видит подписанную пару", now);
if (content && core) BlocksDAO.getInstance().markArweavePublished(
List.of(java.util.Base64.getUrlDecoder().decode(row.coreId())), now);
} catch (Exception e) { dao.attempted(row, e.getMessage(), now); }
}
}
private static boolean available(String base, String id) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(base + "/tx/" + id + "/status"))
.timeout(Duration.ofSeconds(15)).GET().build();
HttpResponse<String> res = http.send(req, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 404) return false;
if (res.statusCode() != 200) throw new IllegalStateException("Turbo status HTTP " + res.statusCode());
JsonNode node = json.readTree(res.body());
String status = node.path("status").asText("");
return status.equals("PENDING") || status.equals("CONFIRMED") || status.equals("BUNDLED") || status.equals("FINALIZED");
}
public static synchronized void close() {
if (executor != null) executor.shutdownNow();
executor = null;
}
}
@@ -0,0 +1,83 @@
package server.archive.registration;
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationServiceException;
import utils.crypto.Ed25519Util;
import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.security.SecureRandom;
/** Один активный аппаратный регистратор; транспорт не имеет доступа к приватному ключу. */
public final class ExternalRegistrar implements RegistrationCertificateSigner, AutoCloseable {
public interface Peer {
boolean open();
void send(Map<String,Object> request) throws Exception;
void disconnect();
}
public record Challenge(String nonce, long expiresAtMs, String serverLogin) {}
private record Pending(Peer peer, CompletableFuture<byte[]> result) {}
private final DataSource db;
private final String namespace, serverLogin;
private final byte[] initialKey;
private final Map<String,Pending> pending = new ConcurrentHashMap<>();
private Peer peer;
private long lastPing;
private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{Thread t=new Thread(r,"registrar-watchdog");t.setDaemon(true);return t;});
public ExternalRegistrar(DataSource db,String namespace,String serverLogin) throws Exception {
this.db=db; this.namespace=namespace; this.serverLogin=serverLogin.trim();
this.initialKey=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,this.serverLogin);
timer.scheduleAtFixedRate(this::expire,5,5,TimeUnit.SECONDS);
}
public String namespace(){return namespace;}
public byte[] publicKey32(){return initialKey.clone();}
public Challenge challenge(String ns) {
if(!namespace.equals(ns)) throw new IllegalArgumentException("Wrong namespace");
byte[] nonce=new byte[32]; new SecureRandom().nextBytes(nonce);
return new Challenge(Base64.getUrlEncoder().withoutPadding().encodeToString(nonce),System.currentTimeMillis()+30000,serverLogin);
}
public boolean authenticate(Challenge c,String ns,long timeMs,byte[] sig) throws Exception {
long now=System.currentTimeMillis();
if(c==null || !namespace.equals(ns) || now>c.expiresAtMs() || timeMs<now-60000 || timeMs>now+60000) return false;
byte[] current=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin);
if(!Arrays.equals(current,initialKey)) return false; // ротация ключа требует перезапуска конфигурации
String msg="SHINE_REGISTRAR_CONNECT_V1:"+serverLogin+":"+ns+":"+timeMs+":"+c.nonce();
return Ed25519Util.verify(msg.getBytes(StandardCharsets.UTF_8),sig,current);
}
public synchronized boolean attach(Peer p) {
if(!p.open() || (connected() && peer!=p)) return false;
if(peer!=null && peer!=p)detach(peer);
peer=p; lastPing=System.nanoTime(); return true;
}
public synchronized boolean connected(){return peer!=null && peer.open() && System.nanoTime()-lastPing<TimeUnit.SECONDS.toNanos(100);}
public synchronized void ping(Peer p){if(peer==p)lastPing=System.nanoTime();}
public synchronized boolean isPeer(Peer p){return peer==p && connected();}
public synchronized void detach(Peer p){
if(peer==p)peer=null;
pending.forEach((id,job)->{if(job.peer()==p && pending.remove(id,job))job.result().completeExceptionally(new RegistrationServiceException(503));});
}
private void expire(){Peer stale; synchronized(this){stale=connected()?null:peer;if(stale!=null)detach(stale);} if(stale!=null)stale.disconnect();}
public void result(Peer p,String id,int status,byte[] raw){
Pending job=pending.get(id);
if(job==null || job.peer()!=p || !isPeer(p) || !pending.remove(id,job))return;
if(status==200 && raw!=null && raw.length<=4096)job.result().complete(raw);
else job.result().completeExceptionally(new RegistrationServiceException(switch(status){case 400,403,409,429,500,503->status;default->500;}));
}
@Override public byte[] issue(String login,byte[] root,byte[] blockchain,byte[] client,byte[] emailHash) throws Exception {
if(!login.endsWith("@"+namespace)) throw new IllegalArgumentException("Wrong namespace");
if(!Arrays.equals(initialKey,FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin))) throw new RegistrationServiceException(503);
String id=UUID.randomUUID().toString();
Pending job;
synchronized(this){if(!connected())throw new RegistrationServiceException(503);job=new Pending(peer,new CompletableFuture<>());pending.put(id,job);}
try {
job.peer().send(Map.of("op","RegistrarSignRegistration","requestId",id,"payload",Map.of(
"login",login,"rootPublicKey",b64(root),"blockchainPublicKey",b64(blockchain),"clientPublicKey",b64(client),"emailSha256",b64(emailHash))));
return job.result().get(25,TimeUnit.SECONDS);
} catch(ExecutionException e){if(e.getCause() instanceof RegistrationServiceException x)throw x;throw new RegistrationServiceException(503);}
catch(InterruptedException e){Thread.currentThread().interrupt();throw new RegistrationServiceException(503);}
catch(Exception e){throw new RegistrationServiceException(503);}
finally{pending.remove(id,job);}
}
private static String b64(byte[] b){return Base64.getEncoder().encodeToString(b);}
@Override public void close(){timer.shutdownNow();Peer p; synchronized(this){p=peer;if(p!=null)detach(p);} if(p!=null)p.disconnect();}
}
@@ -23,17 +23,22 @@ import java.util.logging.Logger;
public final class FreeRegistrationApiBootstrap { public final class FreeRegistrationApiBootstrap {
private static volatile FreeRegistrationWorkflow workflow; private static volatile FreeRegistrationWorkflow workflow;
private static volatile LocalRegistrarSigner signer; private static volatile LocalRegistrarSigner signer;
private static volatile ExternalRegistrar external;
public static ExternalRegistrar externalRegistrar() { return external; }
private FreeRegistrationApiBootstrap() {} private FreeRegistrationApiBootstrap() {}
public static synchronized void startOrThrow() throws Exception { public static synchronized void startOrThrow() throws Exception {
if (workflow != null) return; if (workflow != null) return;
AppConfig cfg=AppConfig.getInstance(); AppConfig cfg=AppConfig.getInstance();
LocalRegistrarSigner newSigner=null; LocalRegistrarSigner newSigner=null;
ExternalRegistrar newExternal=null;
FreeRegistrationIssuer issuer=null; FreeRegistrationIssuer issuer=null;
FreeRegistrationPublisher publisher=null; FreeRegistrationPublisher publisher=null;
RegistrationEmailSender emailSender=null; RegistrationEmailSender emailSender=null;
AllowedEmailDomains allowedEmailDomains=null; AllowedEmailDomains allowedEmailDomains=null;
if (cfg.getBoolean("freeRegistration.enabled",false)) { String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
if (freeRegistrationEnabled) {
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile"); String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt"; if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
// Относительный путь — от WorkingDirectory процесса Java. // Относительный путь — от WorkingDirectory процесса Java.
@@ -43,8 +48,16 @@ public final class FreeRegistrationApiBootstrap {
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load(); ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO) if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
throw new IllegalStateException("Free registration requires Turbo transport"); throw new IllegalStateException("Free registration requires Turbo transport");
String mode=cfg.getStringOrEmpty("freeRegistration.signerMode").trim();
if ("external".equals(mode)) {
newExternal = new ExternalRegistrar(dbSource(), freeNamespace, cfg.getStringOrEmpty("server.SHiNE.login"));
issuer = new FreeRegistrationIssuer(dbSource(), newExternal, allowEmailReuse);
} else if (mode.isEmpty() || "local".equals(mode)) {
newSigner=LocalRegistrarSigner.fromConfig(cfg); newSigner=LocalRegistrarSigner.fromConfig(cfg);
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
cfg.getStringOrEmpty("server.SHiNE.login"));
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse); issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
} else throw new IllegalStateException("Unknown freeRegistration.signerMode");
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport), publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
new VerifiedFreeRegistrationImporter(allowEmailReuse)); new VerifiedFreeRegistrationImporter(allowEmailReuse));
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория. // Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
@@ -58,15 +71,18 @@ public final class FreeRegistrationApiBootstrap {
} }
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender, FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
cfg.getBoolean("freeRegistration.email.allowTestCode",false), cfg.getBoolean("freeRegistration.email.allowTestCode",false),
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains); cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
freeRegistrationEnabled ? freeNamespace : "");
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req)); RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
signer=newSigner; workflow=newWorkflow; signer=newSigner; external=newExternal; workflow=newWorkflow;
} }
public static synchronized void close() { public static synchronized void close() {
RegistrationApiBridge.uninstall(); RegistrationApiBridge.uninstall();
workflow=null; workflow=null;
if(signer!=null) signer.close(); if(signer!=null) signer.close();
signer=null; signer=null;
if(external!=null) external.close();
external=null;
} }
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception { public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
Map<String,Object> out=new LinkedHashMap<>(); Map<String,Object> out=new LinkedHashMap<>();
@@ -16,10 +16,7 @@ import java.util.Locale;
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */ /** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
public final class FreeRegistrationCertificateV1 { public final class FreeRegistrationCertificateV1 {
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8); private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
private static final List<Ans104DataItem.Tag> TAGS = List.of( private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public record Verified(String login, byte[] rootKey, byte[] blockchainKey, public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
byte[] clientKey, byte[] innerSignature, byte[] clientKey, byte[] innerSignature,
@@ -62,13 +59,19 @@ public final class FreeRegistrationCertificateV1 {
public static byte[] issue(String login, byte[] root32, byte[] blockchain32, public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
byte[] client32, String email, RegistrarSigner signer) { byte[] client32, String email, RegistrarSigner signer) {
return issueWithEmailHash(login, root32, blockchain32, client32, emailHash(email), signer);
}
public static byte[] issueWithEmailHash(String login, byte[] root32, byte[] blockchain32,
byte[] client32, byte[] emailHash, RegistrarSigner signer) {
require32(emailHash);
byte[] fields = identityFields(login, root32, blockchain32, client32); byte[] fields = identityFields(login, root32, blockchain32, client32);
byte[] inner = signer.sign(innerMessage(fields)); byte[] inner = signer.sign(innerMessage(fields));
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length"); if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
ByteArrayOutputStream payload = new ByteArrayOutputStream(); ByteArrayOutputStream payload = new ByteArrayOutputStream();
payload.writeBytes(fields); payload.writeBytes(fields);
payload.writeBytes(inner); payload.writeBytes(inner);
payload.writeBytes(emailHash(email)); payload.writeBytes(emailHash);
byte[] data = payload.toByteArray(); byte[] data = payload.toByteArray();
byte[] owner = signer.publicKey32(); byte[] owner = signer.publicKey32();
require32(owner); require32(owner);
@@ -11,7 +11,7 @@ import java.util.Arrays;
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */ /** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
public final class FreeRegistrationIssuer { public final class FreeRegistrationIssuer {
private final DataSource db; private final DataSource db;
private final RegistrarSigner signer; private final RegistrationCertificateSigner signer;
private final boolean allowEmailReuse; private final boolean allowEmailReuse;
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) { public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
@@ -19,11 +19,49 @@ public final class FreeRegistrationIssuer {
} }
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) { public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
this(db, new RegistrationCertificateSigner() {
public byte[] publicKey32() { return signer.publicKey32(); }
public byte[] issue(String login, byte[] root, byte[] blockchain, byte[] client, byte[] emailHash) {
return FreeRegistrationCertificateV1.issueWithEmailHash(login, root, blockchain, client, emailHash, signer);
}
}, allowEmailReuse);
}
public FreeRegistrationIssuer(DataSource db, RegistrationCertificateSigner signer, boolean allowEmailReuse) {
this.db = java.util.Objects.requireNonNull(db); this.db = java.util.Objects.requireNonNull(db);
this.signer = java.util.Objects.requireNonNull(signer); this.signer = java.util.Objects.requireNonNull(signer);
this.allowEmailReuse = allowEmailReuse; this.allowEmailReuse = allowEmailReuse;
} }
/** Проверяет привязку локального ключа и сервера до открытия бесплатной регистрации. */
static void validateConfiguredNamespace(DataSource db, RegistrarSigner signer, String namespace,
String localServerLogin) throws Exception {
if (!Arrays.equals(configuredNamespaceKey(db, namespace, localServerLogin), signer.publicKey32()))
throw new IllegalStateException("Registrar public key does not match configured namespace");
}
static byte[] configuredNamespaceKey(DataSource db, String namespace, String localServerLogin) throws Exception {
if (localServerLogin == null || localServerLogin.isBlank())
throw new IllegalStateException("server.SHiNE.login is required for free registration");
try (Connection conn = db.getConnection();
PreparedStatement statement = conn.prepareStatement("""
SELECT namespace_type, registrar_pubkey, default_server_login
FROM shine_namespace_current WHERE namespace = ?
""")) {
statement.setString(1, namespace);
try (ResultSet rs = statement.executeQuery()) {
if (!rs.next() || rs.getInt("namespace_type") != 2)
throw new IllegalStateException("Configured free registration namespace is unavailable");
byte[] namespaceKey = Base58Util.decode(rs.getString("registrar_pubkey"));
if (namespaceKey.length != 32) throw new IllegalStateException("Invalid namespace key");
String namespaceServer = rs.getString("default_server_login");
if (namespaceServer == null || !namespaceServer.equalsIgnoreCase(localServerLogin.trim()))
throw new IllegalStateException("Configured free namespace belongs to another access server");
return namespaceKey;
}
}
}
/** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */ /** Выдаётся только после успешной проверки challenge в FreeRegistrationWorkflow. */
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32, synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
byte[] client32, String email) throws Exception { byte[] client32, String email) throws Exception {
@@ -69,6 +107,12 @@ public final class FreeRegistrationIssuer {
} }
// Это только подписанный артефакт, не активная регистрация. Перед Turbo // Это только подписанный артефакт, не активная регистрация. Перед Turbo
// и локальным импортом обязательно повторять уникальность в транзакции БД. // и локальным импортом обязательно повторять уникальность в транзакции БД.
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer); byte[] signed = signer.issue(fullLogin, root32, blockchain32, client32, expectedEmail);
var verified = FreeRegistrationCertificateV1.verify(signed, signer.publicKey32());
if (!fullLogin.equals(verified.login()) || !Arrays.equals(root32, verified.rootKey()) ||
!Arrays.equals(blockchain32, verified.blockchainKey()) || !Arrays.equals(client32, verified.clientKey()) ||
!Arrays.equals(expectedEmail, verified.emailSha256()))
throw new IllegalStateException("Registrar returned mismatched certificate");
return signed;
} }
} }
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
private final boolean allowTestCode; private final boolean allowTestCode;
private final boolean allowEmailReuse; private final boolean allowEmailReuse;
private final AllowedEmailDomains allowedEmailDomains; private final AllowedEmailDomains allowedEmailDomains;
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
private final String freeRegistrationNamespace;
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse, RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) { AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch"); if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required"); if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
if (emailSender != null && allowedEmailDomains == null) if (emailSender != null && allowedEmailDomains == null)
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
this.emailSender = emailSender; this.emailSender = emailSender;
this.allowTestCode = allowTestCode; this.allowTestCode = allowTestCode;
this.allowEmailReuse = allowEmailReuse; this.allowEmailReuse = allowEmailReuse;
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
}
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
AllowedEmailDomains allowedEmailDomains) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
}
private static String normalizeConfiguredNamespace(String value) {
String namespace = value == null ? "" : value.trim();
if (namespace.isEmpty()) return "";
if (!namespace.matches("[a-z0-9_]+"))
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
return namespace;
} }
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher, public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) { RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
emailSender == null ? null : loadDefaultEmailDomains()); emailSender == null ? null : loadDefaultEmailDomains(), "");
} }
private static AllowedEmailDomains loadDefaultEmailDomains() { private static AllowedEmailDomains loadDefaultEmailDomains() {
try { try {
@@ -94,11 +109,16 @@ public final class FreeRegistrationWorkflow {
try (Connection c = DbController.getInstance().getConnection(); try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(""" PreparedStatement ps = c.prepareStatement("""
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
FROM shine_namespace_current ORDER BY namespace FROM shine_namespace_current
"""); ResultSet rs = ps.executeQuery()) { WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?)
ORDER BY namespace
""")) {
ps.setString(1, freeRegistrationNamespace);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3), 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))); rs.getString(4),rs.getInt(5),rs.getString(6)));
} }
}
return List.copyOf(result); return List.copyOf(result);
} }
public LoginCheck checkLogin(String login) throws Exception { public LoginCheck checkLogin(String login) throws Exception {
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
try (ResultSet rs=p.executeQuery()) { try (ResultSet rs=p.executeQuery()) {
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable"); 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); type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency"); if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum"); if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
} }
@@ -0,0 +1,7 @@
package server.archive.registration;
/** Выдаёт только полный регистрационный сертификат, не произвольную подпись. */
public interface RegistrationCertificateSigner {
byte[] publicKey32();
byte[] issue(String login, byte[] root, byte[] blockchain, byte[] client, byte[] emailHash) throws Exception;
}
@@ -122,9 +122,12 @@ public final class VerifiedFreeRegistrationImporter {
INSERT INTO blockchain_state_store ( INSERT INTO blockchain_state_store (
login, fork_number, blockchain_key, size_limit, file_size_bytes, login, fork_number, blockchain_key, size_limit, file_size_bytes,
last_block_number, last_block_hash, updated_at_ms) last_block_number, last_block_hash, updated_at_ms)
VALUES (?, 1, ?, 100000, 0, -1, ?, ?) VALUES (?, 1, ?, 0, 0, -1, ?, ?)
""")) { """)) {
insert.setString(1, login); // blockchain_state — техническая проекция chain: её ключ
// совпадает с normalized_login и blockchain_name, а не с
// отображаемым написанием login в сертификате.
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
// blockchain_state — runtime-слой: его ключ всегда Base64(32), // blockchain_state — runtime-слой: его ключ всегда Base64(32),
// как и у пользователей, импортированных из Solana PDA. // как и у пользователей, импортированных из Solana PDA.
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey())); insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
@@ -0,0 +1,43 @@
package server.archive;
import server.archive.registration.*;
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationServiceException;
import sync.util.Base58Util;
import utils.crypto.Ed25519Util;
import javax.sql.DataSource;
import java.sql.*;
import java.lang.reflect.Proxy;
import java.util.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.*;
public class ExternalRegistrarCheck {
static <T> T mock(Class<T> cls,java.lang.reflect.InvocationHandler h){return cls.cast(Proxy.newProxyInstance(cls.getClassLoader(),new Class[]{cls},h));}
static DataSource db(byte[] owner){return mock(DataSource.class,(obj,m,a)->{
if(!m.getName().equals("getConnection"))throw new UnsupportedOperationException(m.getName());
return mock(Connection.class,(o,method,args)->switch(method.getName()){
case "close","setReadOnly"->null;
case "prepareStatement"->mock(PreparedStatement.class,(po,pm,pa)->switch(pm.getName()){
case "close","setString"->null;
case "executeQuery"->mock(ResultSet.class,(ro,rm,ra)->switch(rm.getName()){
case "close"->null;case "next"->true;case "getInt"->2;case "getString"->ra[0].equals("registrar_pubkey")?Base58Util.encode(owner):"testserver";default->throw new UnsupportedOperationException(rm.getName());});
default->throw new UnsupportedOperationException(pm.getName());});
default->throw new UnsupportedOperationException(method.getName());});});}
static void require(boolean x){if(!x)throw new AssertionError();}
static void expect503(ExternalRegistrar reg) throws Exception {try{reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]);throw new AssertionError("Expected failure");}catch(RegistrationServiceException e){require(e.status()==503);}}
public static void main(String[] args)throws Exception{
byte[] seed=new byte[32],owner=Ed25519Util.derivePublicKey(seed);
try(ExternalRegistrar reg=new ExternalRegistrar(db(owner),"free","testserver")){
expect503(reg);var c=reg.challenge("free");long t=System.currentTimeMillis();byte[] msg=("SHINE_REGISTRAR_CONNECT_V1:testserver:free:"+t+":"+c.nonce()).getBytes(StandardCharsets.UTF_8);byte[] sig=Ed25519Util.sign(msg,seed);
require(reg.authenticate(c,"free",t,sig));sig[0]^=1;require(!reg.authenticate(c,"free",t,sig));
BlockingQueue<Map<String,Object>> queue=new LinkedBlockingQueue<>();
ExternalRegistrar.Peer peer=new ExternalRegistrar.Peer(){public boolean open(){return true;}public void send(Map<String,Object> request){queue.add(request);}public void disconnect(){}};
ExternalRegistrar.Peer stranger=new ExternalRegistrar.Peer(){public boolean open(){return true;}public void send(Map<String,Object> request){}public void disconnect(){}};
require(reg.attach(peer));require(!reg.attach(stranger));
var executor=Executors.newSingleThreadExecutor();try{
var f=executor.submit(()->reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]));
var request=queue.poll(2,TimeUnit.SECONDS);require(request!=null);String id=(String)request.get("requestId");
reg.result(stranger,id,200,new byte[]{9});require(!f.isDone());reg.result(peer,"unknown",200,new byte[]{9});require(!f.isDone());reg.result(peer,id,200,new byte[]{1,2});require(Arrays.equals(f.get(2,TimeUnit.SECONDS),new byte[]{1,2}));
var f2=executor.submit(()->reg.issue("Example@free",new byte[32],new byte[32],new byte[32],new byte[32]));require(queue.poll(2,TimeUnit.SECONDS)!=null);reg.detach(peer);try{f2.get(2,TimeUnit.SECONDS);throw new AssertionError("Expected disconnect");}catch(ExecutionException e){require(e.getCause() instanceof RegistrationServiceException x&&x.status()==503);}
}finally{executor.shutdownNow();}
}System.out.println("PASS: challenge signature, wrong key, disconnected, exclusive peer, request correlation, wrong peer, disconnect while pending");
}
}
@@ -19,7 +19,7 @@ public final class FreeRegistrationCertificateV1Check {
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client, byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
" Alice.Example+Tag@Example.COM ", signer); " Alice.Example+Tag@Example.COM ", signer);
var item = new Ans104DataItem(cert); var item = new Ans104DataItem(cert);
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE))
throw new AssertionError("Current App tag missing"); throw new AssertionError("Current App tag missing");
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32()); var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root) if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
@@ -37,7 +37,7 @@ public final class FreeRegistrationCertificateV1Check {
throw new AssertionError("Inner signature tampering accepted"); } throw new AssertionError("Inner signature tampering accepted"); }
catch (IllegalArgumentException expected) {} catch (IllegalArgumentException expected) {}
} }
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection"); + ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
} }
} }
@@ -0,0 +1,57 @@
package server.archive;
import blockchain.*;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
/** Offline tests with real signed fixtures and fake upload/download callbacks (no network). */
public final class M4ArchiveBlockPairCheck {
private static int checks;
private static final HexFormat HEX = HexFormat.of();
@FunctionalInterface interface Action { void run() throws Exception; }
private static void ok(boolean value) { checks++; if (!value) throw new AssertionError("check " + checks); }
private static void reject(Class<? extends Exception> type, Action action) throws Exception {
try { action.run(); } catch (Exception e) { ok(type.isInstance(e)); return; }
throw new AssertionError("Expected " + type);
}
public static void main(String[] args) throws Exception {
var lines = Files.readAllLines(Path.of(args[0]));
for (String line : lines.subList(1, lines.size())) {
String[] v = line.split("\t");
byte[] core = HEX.parseHex(v[6]), content = HEX.parseHex(v[8]);
byte[] coreId = new Ans104DataItem(core).id32(), contentId = new Ans104DataItem(content).id32();
byte[] pair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(content));
List<byte[]> sent = new ArrayList<>();
var ack = ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
ok(Arrays.equals(new Ans104DataItem(raw).id32(), id)); sent.add(raw); return HEX.formatHex(id);
});
ok(sent.size() == 2); ok(Arrays.equals(sent.get(0), content)); ok(Arrays.equals(sent.get(1), core));
ok(ack.equals(HEX.formatHex(coreId)));
sent.clear();
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
sent.add(raw); throw new IOException("CONTENT not accepted");
}));
ok(sent.size() == 1); ok(Arrays.equals(sent.get(0), content));
sent.clear();
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
sent.add(raw); if (Arrays.equals(id, coreId)) throw new IOException("CORE not accepted"); return null;
}));
ok(sent.size() == 2);
ArchiveBlockPair.publish(pair, coreId, (raw, id) -> { sent.add(raw); return null; });
ok(sent.size() == 4); ok(Arrays.equals(sent.get(0), sent.get(2))); ok(Arrays.equals(sent.get(1), sent.get(3)));
byte[] restored = ArchiveBlockPair.download(core, coreId, id -> { ok(Arrays.equals(id, contentId)); return content; });
ok(Arrays.equals(restored, pair));
reject(IOException.class, () -> ArchiveBlockPair.download(core, coreId, id -> { throw new IOException("CONTENT not visible yet"); }));
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> core));
byte[] damaged = content.clone(); damaged[damaged.length - 1] ^= 1;
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> damaged));
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, contentId, id -> { throw new AssertionError("Unverified CORE requested CONTENT"); }));
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(pair, contentId, (raw,id) -> { throw new AssertionError("Wrong CORE published"); }));
byte[] badPair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(damaged));
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(badPair, coreId, (raw,id) -> { throw new AssertionError("Invalid CONTENT published"); }));
}
System.out.println("PASS: " + checks + " archive pair checks (order, exact retry, missing CONTENT, wrong ID, signature/hash)");
}
}
@@ -0,0 +1,22 @@
package server.archive.registration;
import org.junit.jupiter.api.Test;
import utils.crypto.Ed25519Util;
import java.util.HexFormat;
import static org.junit.jupiter.api.Assertions.*;
class ExternalRegistrarVectorTest {
@Test void firmwareReferenceVector() {
byte[] seed=new byte[32],root=new byte[32],chain=new byte[32],client=new byte[32],email=new byte[32];
for(int i=0;i<32;i++){seed[i]=(byte)i;root[i]=(byte)(i+32);chain[i]=(byte)(i+64);client[i]=(byte)(i+96);email[i]=(byte)(i+128);}
try(var signer=new LocalRegistrarSigner(seed)) {
byte[] item=FreeRegistrationCertificateV1.issueWithEmailHash("Example@free",root,chain,client,email,signer);
assertEquals(EXPECTED,HexFormat.of().formatHex(item));
assertArrayEquals(email,FreeRegistrationCertificateV1.verify(item,signer.publicKey32()).emailSha256());
item[item.length-1]^=1;
assertThrows(IllegalArgumentException.class,()->FreeRegistrationCertificateV1.verify(item,signer.publicKey32()));
}
}
// Synthetic public test vector; never use its seed for a real namespace.
private static final String EXPECTED = "02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f";
}
@@ -0,0 +1,20 @@
package server.archive.registration;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
class FreeRegistrationNamespaceConfigurationTest {
@Test
void acceptsLowercaseNamespaceForLocalFreeRegistration() {
assertDoesNotThrow(() -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "testfree"));
}
@Test
void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() {
assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow(
null, null, null, false, false, null, "TestFree"));
}
}
@@ -56,7 +56,7 @@ public final class Ans104DataItem {
public Ans104DataItem(byte[] bytes) { public Ans104DataItem(byte[] bytes) {
Objects.requireNonNull(bytes, "bytes == null"); Objects.requireNonNull(bytes, "bytes == null");
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + 1) { if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8) {
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length); throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
} }
if (bytes.length > MAX_DATA_ITEM_BYTES) { if (bytes.length > MAX_DATA_ITEM_BYTES) {
@@ -126,7 +126,8 @@ public final class Ans104DataItem {
} }
public byte[] signingMessage() { public byte[] signingMessage() {
return buildSigningMessage(owner, target, anchor, tags, data); // Проверяем именно подписанные исходные байты, не повторную Avro-сериализацию.
return signingMessageRaw(owner, target, anchor, rawTags, data);
} }
/** /**
@@ -151,6 +152,10 @@ public final class Ans104DataItem {
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length); byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
byte[] rawTags = serializeAvroTags(safeTags); byte[] rawTags = serializeAvroTags(safeTags);
return signingMessageRaw(owner32, safeTarget, safeAnchor, rawTags, safeData);
}
private static byte[] signingMessageRaw(byte[] owner32, byte[] safeTarget, byte[] safeAnchor, byte[] rawTags, byte[] safeData) {
return deepHash(List.of( return deepHash(List.of(
utf8("dataitem"), utf8("dataitem"),
utf8("1"), utf8("1"),
@@ -270,15 +275,20 @@ public final class Ans104DataItem {
} }
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) { private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
if (raw.length == 0 && declaredCount == 0) return List.of();
AvroCursor c = new AvroCursor(raw); AvroCursor c = new AvroCursor(raw);
List<Tag> out = new ArrayList<>(); List<Tag> out = new ArrayList<>();
boolean terminated = false;
while (!c.eof()) { while (!c.eof()) {
long count = c.readLong(); long count = c.readLong();
if (count == 0) break; if (count == 0) { terminated = true; break; }
int blockEnd = -1;
if (count < 0) { if (count < 0) {
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
count = -count; count = -count;
long blockBytes = c.readLong(); long blockBytes = c.readLong();
if (blockBytes < 0) throw new IllegalArgumentException("Negative Avro tag block size"); if (blockBytes < 0 || blockBytes > raw.length - c.p) throw new IllegalArgumentException("Invalid Avro tag block size");
blockEnd = c.p + (int) blockBytes;
} }
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) { if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
throw new IllegalArgumentException("Too many Avro tags"); throw new IllegalArgumentException("Too many Avro tags");
@@ -291,7 +301,9 @@ public final class Ans104DataItem {
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes"); if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
out.add(new Tag(name, value)); out.add(new Tag(name, value));
} }
if (blockEnd != -1 && c.p != blockEnd) throw new IllegalArgumentException("Avro tag block size mismatch");
} }
if (!terminated) throw new IllegalArgumentException("Missing Avro array terminator");
if (!c.eof()) { if (!c.eof()) {
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags"); throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
} }
@@ -312,6 +324,7 @@ public final class Ans104DataItem {
while (true) { while (true) {
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long"); if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
int b = data[p++] & 0xff; int b = data[p++] & 0xff;
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
raw |= (long) (b & 0x7f) << shift; raw |= (long) (b & 0x7f) << shift;
if ((b & 0x80) == 0) break; if ((b & 0x80) == 0) break;
shift += 7; shift += 7;
@@ -324,7 +337,9 @@ public final class Ans104DataItem {
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) { if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
throw new IllegalArgumentException("Bad Avro string length: " + len); throw new IllegalArgumentException("Bad Avro string length: " + len);
} }
String s = new String(data, p, (int) len, StandardCharsets.UTF_8); String s;
try { s = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data, p, (int) len)).toString(); }
catch (java.nio.charset.CharacterCodingException e) { throw new IllegalArgumentException("Invalid UTF-8 Avro tag", e); }
p += (int) len; p += (int) len;
return s; return s;
} }
@@ -49,6 +49,9 @@ public final class BchBlockEntry {
public final BodyRecord body; public final BodyRecord body;
private final Ans104DataItem dataItem; private final Ans104DataItem dataItem;
private final Ans104DataItem contentItem;
private final CoreRecord coreRecord;
private final ContentRecord contentRecord;
private final byte[] frameBytes; private final byte[] frameBytes;
private final byte[] hash32; private final byte[] hash32;
@@ -56,6 +59,9 @@ public final class BchBlockEntry {
public BchBlockEntry(byte[] fullDataItemBytes) { public BchBlockEntry(byte[] fullDataItemBytes) {
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null"); Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
this.dataItem = new Ans104DataItem(fullDataItemBytes); this.dataItem = new Ans104DataItem(fullDataItemBytes);
this.contentItem = null;
this.coreRecord = null;
this.contentRecord = null;
this.frameBytes = dataItem.data(); this.frameBytes = dataItem.data();
if (frameBytes.length < FRAME_HEADER_SIZE) { if (frameBytes.length < FRAME_HEADER_SIZE) {
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length); throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
@@ -90,7 +96,57 @@ public final class BchBlockEntry {
this.hash32 = BchCryptoVerifier.sha256(frameBytes); this.hash32 = BchCryptoVerifier.sha256(frameBytes);
} }
public Ans104DataItem getDataItem() { return dataItem; } /** M1: явная точка входа для пары. Runtime переключается на неё в M2–M5. */
public static BchBlockEntry fromCoreContent(byte[] container) {
return new BchBlockEntry(CoreContentContainer.unpack(container));
}
private BchBlockEntry(CoreContentContainer.Parts pair) {
this.dataItem = pair.core();
this.contentItem = pair.content();
// Подписи и связь пары проверяются до предоставления смыслового тела.
// Owner здесь self-claimed; вызывающий код обязан проверить авторизованный ключ.
var verified = CoreContentTransport.verifyPair(dataItem, dataItem.id32(), contentItem,
dataItem.owner32(), Instant.now().getEpochSecond());
this.coreRecord = verified.core();
this.contentRecord = verified.content();
this.frameBytes = coreRecord.toBytes();
this.frameCode = CoreRecord.FRAME_CODE;
this.prevHash32 = coreRecord.prevCoreHash32();
this.back32Hash32 = null; // Отсутствует в протоколе; не синтезируем.
this.blockSize = frameBytes.length;
this.blockNumber = coreRecord.blockNumber();
this.timestamp = coreRecord.timestamp();
this.type = (short) contentRecord.type();
this.subType = (short) contentRecord.subType();
this.version = (short) contentRecord.version();
this.bodyBytes = contentRecord.bodyBytes();
this.body = ContentBodyParser.parseForCore(coreRecord, contentRecord);
this.hash32 = coreRecord.coreHash32();
}
public boolean isCoreContent() { return coreRecord != null; }
public CoreRecord getCoreRecord() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return coreRecord;
}
public ContentRecord getContentRecord() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return contentRecord;
}
public Ans104DataItem getCoreDataItem() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return dataItem;
}
public Ans104DataItem getContentDataItem() {
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
return contentItem;
}
/** Legacy API: не позволяет принять одну подпись за проверку пары. */
public Ans104DataItem getDataItem() {
if (isCoreContent()) throw new IllegalStateException("Используйте явные CORE/CONTENT accessors");
return dataItem;
}
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); } public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
/** Kept as an alias for code/docs that called the old field preimage. */ /** Kept as an alias for code/docs that called the old field preimage. */
public byte[] getPreimageBytes() { return getFrameBytes(); } public byte[] getPreimageBytes() { return getFrameBytes(); }
@@ -98,8 +154,8 @@ public final class BchBlockEntry {
public byte[] getOwner32() { return dataItem.owner32(); } public byte[] getOwner32() { return dataItem.owner32(); }
public byte[] getDataItemId32() { return dataItem.id32(); } public byte[] getDataItemId32() { return dataItem.id32(); }
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); } public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
/** Full serialized ANS-104 DataItem. */ /** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
public byte[] toBytes() { return dataItem.rawBytes(); } public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
@Override @Override
public String toString() { public String toString() {
@@ -22,6 +22,13 @@ public final class BchCryptoVerifier {
Objects.requireNonNull(block, "block == null"); Objects.requireNonNull(block, "block == null");
Objects.requireNonNull(publicKey32, "publicKey32 == null"); Objects.requireNonNull(publicKey32, "publicKey32 == null");
if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32"); if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32");
if (block.isCoreContent()) {
try {
CoreContentTransport.verifyPair(block.getCoreDataItem(), block.getDataItemId32(),
block.getContentDataItem(), publicKey32, java.time.Instant.now().getEpochSecond());
return true;
} catch (IllegalArgumentException e) { return false; }
}
return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature(); return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature();
} }
} }
@@ -16,9 +16,10 @@ public final class BodyRecordParser {
int v = version & 0xFFFF; int v = version & 0xFFFF;
int st = subType & 0xFFFF; int st = subType & 0xFFFF;
// TECH supports Header v1 and CreateChannel current format (ver=1). // TECH accepts only the current 1.0 body format.
if (t == (CreateChannelBody.TYPE & 0xFFFF)) { if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) && v == (HeaderBody.VER & 0xFFFF)) { if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
&& v == (HeaderBody.VER & 0xFFFF)) {
return new HeaderBody(subType, version, bodyBytes).check(); return new HeaderBody(subType, version, bodyBytes).check();
} }
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF) if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
@@ -0,0 +1,66 @@
package blockchain;
import blockchain.body.*;
/** Смысловой парсер новой эпохи. Не выполняет проверки существования целей и состояния БД. */
public final class ContentBodyParser {
private ContentBodyParser() {}
public static boolean isChannelText(int subType) {
return switch (subType) {
case MsgSubType.TEXT_POST, MsgSubType.TEXT_EDIT_POST, MsgSubType.TEXT_REPOST,
MsgSubType.TEXT_CHANNEL_META, MsgSubType.TEXT_CHANNEL_DELETE, MsgSubType.TEXT_ENTRYPOINT,
MsgSubType.TEXT_EXERCISE, MsgSubType.TEXT_SERVICE, MsgSubType.TEXT_COURSE -> true;
default -> false;
};
}
/** Проверяет соответствие линии, затем разбирает CONTENT без legacy-префикса. */
public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) {
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE");
boolean header = content.type() == 0 && content.subType() == MsgSubType.HEADER_COMPAT;
if (content.version() != 1)
throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
CoreRecord.Line line = core.line();
int expected = switch (content.type()) {
case 0 -> header ? -1 : CoreRecord.TECH;
case 1 -> isChannelText(content.subType()) ? -2 : -1;
case 3 -> CoreRecord.CONNECTION;
case 4 -> CoreRecord.PROFILE;
default -> -1;
};
boolean match = expected == -1 ? line == null : line != null &&
(expected == -2 ? LineIndex.isChannel(line.lineCode()) : line.lineCode() == expected);
if (!match) throw new IllegalArgumentException("CONTENT не соответствует линии CORE");
short s = (short) content.subType(), v = (short) content.version();
byte[] bytes = content.bodyBytes();
BodyRecord body = switch (content.type()) {
case 0 -> switch (s) {
case MsgSubType.HEADER_COMPAT -> new HeaderBody(s, v, bytes);
case MsgSubType.TECH_CREATE_CHANNEL -> new CreateChannelBody(s, v, bytes, line);
case MsgSubType.TECH_FORK -> new ForkBody(s, v, bytes, line);
default -> throw new IllegalArgumentException("Неизвестный TECH subtype");
};
case 1 -> {
if (isChannelText(content.subType())) yield new TextLineBody(s, v, bytes, line);
yield switch (s) {
case MsgSubType.TEXT_REPLY, MsgSubType.TEXT_EDIT_REPLY -> new TextReplyBody(s, v, bytes);
case MsgSubType.TEXT_RATING -> new TextRatingBody(s, v, bytes);
default -> throw new IllegalArgumentException("Неизвестный TEXT subtype");
};
}
case 2 -> new ReactionBody(s, v, bytes);
case 3 -> new ConnectionBody(s, v, bytes, line);
case 4 -> new UserParamBody(s, v, bytes, line);
case 5 -> new StatusActionBody(s, v, bytes);
default -> throw new IllegalArgumentException("Неизвестный CONTENT type");
};
return body.check();
}
/** Для нового события, в дополнение к проверкам БД и авторизации вызывающим кодом. */
public static BodyRecord parseForCreate(CoreRecord core, ContentRecord content) {
BodyRecord body = parseForCore(core, content);
if (body instanceof CreateChannelBody create) create.checkForCreate();
return body;
}
}
@@ -0,0 +1,36 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Objects;
/** Бинарный CONTENT v1. Неизвестные типы разбираются как raw envelope. */
public final class ContentRecord {
public static final int CONTENT_CODE = 1, HEADER_SIZE = 7;
// Верхняя граница payload; полный ANS-104 дополнительно ограничен собственным лимитом.
public static final int MAX_PAYLOAD_SIZE = Ans104DataItem.MAX_DATA_ITEM_BYTES - 117;
private final int type, subType, version;
private final byte[] body;
public ContentRecord(int type, int subType, int version, byte[] body) {
if ((type & ~0xffff) != 0 || (subType & ~0xffff) != 0 || (version & ~0xffff) != 0)
throw new IllegalArgumentException("Ожидается uint16");
Objects.requireNonNull(body);
if (body.length > MAX_PAYLOAD_SIZE - HEADER_SIZE) throw new IllegalArgumentException("CONTENT слишком большой");
this.type = type; this.subType = subType; this.version = version; this.body = body.clone();
}
public static ContentRecord parse(byte[] bytes) {
if (bytes == null || bytes.length < HEADER_SIZE || bytes.length > MAX_PAYLOAD_SIZE)
throw new IllegalArgumentException("Неверная длина CONTENT");
ByteBuffer b = ByteBuffer.wrap(bytes);
if (Byte.toUnsignedInt(b.get()) != CONTENT_CODE) throw new IllegalArgumentException("Неверный contentCode");
int t = Short.toUnsignedInt(b.getShort()), s = Short.toUnsignedInt(b.getShort()), v = Short.toUnsignedInt(b.getShort());
byte[] body = new byte[b.remaining()]; b.get(body);
return new ContentRecord(t, s, v, body);
}
public byte[] toBytes() { return ByteBuffer.allocate(HEADER_SIZE + body.length).put((byte) CONTENT_CODE)
.putShort((short) type).putShort((short) subType).putShort((short) version).put(body).array(); }
public int type() { return type; }
public int subType() { return subType; }
public int version() { return version; }
public byte[] bodyBytes() { return body.clone(); }
public byte[] contentHash32() { return ProtocolHash.sha256(toBytes()); }
}
@@ -0,0 +1,36 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Arrays;
/** Внутренний block_bytes: u32 BE размер CORE, затем два исходных ANS-104. Не DataItem. */
public final class CoreContentContainer {
private CoreContentContainer() {}
public static final int MAX_CORE_ITEM_BYTES = 65865;
public static final int MAX_CONTAINER_BYTES = 4 + MAX_CORE_ITEM_BYTES + Ans104DataItem.MAX_DATA_ITEM_BYTES;
private static final int MIN_ITEM_BYTES = 116;
public record Parts(Ans104DataItem core, Ans104DataItem content) {}
public static Parts unpack(byte[] bytes) {
if (bytes == null || bytes.length < 4 + 2 * MIN_ITEM_BYTES || bytes.length > MAX_CONTAINER_BYTES)
throw new IllegalArgumentException("Неверная длина контейнера CORE/CONTENT");
long n = Integer.toUnsignedLong(ByteBuffer.wrap(bytes).getInt());
long rest = bytes.length - 4L - n;
checkLengths(n, rest);
int end = 4 + (int) n;
return new Parts(new Ans104DataItem(Arrays.copyOfRange(bytes, 4, end)),
new Ans104DataItem(Arrays.copyOfRange(bytes, end, bytes.length)));
}
public static byte[] pack(Ans104DataItem core, Ans104DataItem content) {
byte[] c = core.rawBytes(), p = content.rawBytes();
checkLengths(c.length, p.length);
return ByteBuffer.allocate(4 + c.length + p.length).putInt(c.length).put(c).put(p).array();
}
private static void checkLengths(long core, long content) {
if (core < MIN_ITEM_BYTES || core > MAX_CORE_ITEM_BYTES || content < MIN_ITEM_BYTES || content > Ans104DataItem.MAX_DATA_ITEM_BYTES)
throw new IllegalArgumentException("Неверная длина CORE/CONTENT DataItem");
}
}
@@ -0,0 +1,73 @@
package blockchain;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import utils.crypto.Ed25519Util;
/** Новый транспорт; не переключает существующий runtime Frame v1. */
public final class CoreContentTransport {
private CoreContentTransport() {}
public static List<Ans104DataItem.Tag> coreTags(CoreRecord core) {
var tags = new ArrayList<Ans104DataItem.Tag>();
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE));
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_NUMBER_TAG_NAME, Integer.toString(core.blockNumber())));
if (core.line() != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_LINE_TAG_NAME, lineTag(core.line().lineCode())));
return List.copyOf(tags);
}
public static String lineTag(int code) {
return switch (code) {
case CoreRecord.PROFILE -> "P";
case CoreRecord.CONNECTION -> "C";
case CoreRecord.TECH -> "T";
default -> {
if (code < 0 || code > CoreRecord.MAX_BLOCK_NUMBER) throw new IllegalArgumentException("Неизвестный системный тег линии");
yield Integer.toString(code);
}
};
}
private static void require(boolean ok, String message) { if (!ok) throw new IllegalArgumentException(message); }
private static void verify(Ans104DataItem item, byte[] expectedOwner, byte[] expectedId) {
require(item.ownerEquals(ProtocolHash.copy32(expectedOwner)), "Неавторизованный owner");
require(Arrays.equals(item.id32(), ProtocolHash.copy32(expectedId)), "DataItem ID не совпадает");
require(item.verifySignature(), "Неверная подпись ANS-104");
}
public static CoreRecord verifyCore(Ans104DataItem item, byte[] authorizedOwner, byte[] expectedId, long nowSeconds) {
verify(item, authorizedOwner, expectedId);
CoreRecord core = CoreRecord.parse(item.data()); core.checkTimestamp(nowSeconds);
List<Ans104DataItem.Tag> expected = coreTags(core);
for (String name : List.of("App", "n", "l")) {
var actual = item.tags().stream().filter(t -> t.name().equals(name)).toList();
var wanted = expected.stream().filter(t -> t.name().equals(name)).toList();
require(actual.equals(wanted), "Некорректный тег CORE: " + name);
}
require(item.tags().stream().noneMatch(t -> t.name().equals("t") || t.name().equals("c")), "Legacy теги CORE запрещены");
return core;
}
/** Только соответствие payload подписанному CORE; это не проверка собственной подписи CONTENT. */
public static ContentRecord verifyPayload(CoreRecord core, byte[] payload) {
require(payload != null && payload.length <= ContentRecord.MAX_PAYLOAD_SIZE, "Неверная длина CONTENT");
byte[] snapshot = payload.clone();
require(Arrays.equals(core.contentHash32(), ProtocolHash.sha256(snapshot)), "CONTENT hash не совпадает");
return ContentRecord.parse(snapshot);
}
/** authorizedOwner должен быть owner уже проверенного CORE, а не произвольный ключ CONTENT. */
public static ContentRecord verifyContent(CoreRecord core, Ans104DataItem item, byte[] authorizedOwner) {
verify(item, authorizedOwner, core.contentDataItemId32());
require(item.tags().stream().noneMatch(t -> List.of("App", "n", "l", "t", "c").contains(t.name())), "CONTENT не должен иметь поисковые теги SHiNE");
return verifyPayload(core, item.data());
}
public record VerifiedPair(CoreRecord core, ContentRecord content) {}
/** Криптографическая проверка пары; семантика проверяется ContentBodyParser отдельно. */
public static VerifiedPair verifyPair(Ans104DataItem coreItem, byte[] expectedCoreId, Ans104DataItem contentItem,
byte[] authorizedOwner, long nowSeconds) {
CoreRecord core = verifyCore(coreItem, authorizedOwner, expectedCoreId, nowSeconds);
return new VerifiedPair(core, verifyContent(core, contentItem, coreItem.owner32()));
}
/** Для локального тестового издателя; production сервер не получает приватный ключ пользователя. */
public static Ans104DataItem sign(byte[] payload, List<Ans104DataItem.Tag> tags, byte[] seed) {
byte[] owner = Ed25519Util.derivePublicKey(seed);
byte[] sig = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, payload), seed);
return new Ans104DataItem(Ans104DataItem.serializeEd25519(sig, owner, tags, payload));
}
}
@@ -0,0 +1,75 @@
package blockchain;
import java.nio.ByteBuffer;
import java.util.Arrays;
/** Неизменяемый бинарный CORE v2; проверка ссылок на историю выполняется отдельно. */
public final class CoreRecord {
public static final int BASE_SIZE = 109, LINE_SIZE = 149, FRAME_CODE = 1;
public static final int MAX_BLOCK_NUMBER = Integer.MAX_VALUE - 1024;
public static final int PROFILE = Integer.MAX_VALUE - 2, CONNECTION = Integer.MAX_VALUE - 1, TECH = Integer.MAX_VALUE;
public static final long FUTURE_TOLERANCE_SECONDS = 60;
public record Line(int lineCode, int prevLineBlockNumber, byte[] prevLineCoreHash32) {
public Line {
if (lineCode < 0 || prevLineBlockNumber < 0 || prevLineBlockNumber > MAX_BLOCK_NUMBER)
throw new IllegalArgumentException("Неверный номер линии/предшественника");
prevLineCoreHash32 = ProtocolHash.copy32(prevLineCoreHash32);
}
@Override public byte[] prevLineCoreHash32() { return prevLineCoreHash32.clone(); }
@Override public boolean equals(Object other) {
return other instanceof Line l && lineCode == l.lineCode && prevLineBlockNumber == l.prevLineBlockNumber
&& Arrays.equals(prevLineCoreHash32, l.prevLineCoreHash32);
}
@Override public int hashCode() {
return 31 * (31 * lineCode + prevLineBlockNumber) + Arrays.hashCode(prevLineCoreHash32);
}
}
private final byte[] prevCoreHash32, contentHash32, contentDataItemId32;
private final int blockNumber;
private final long timestamp;
private final Line line;
public CoreRecord(byte[] prevCoreHash32, int blockNumber, long timestamp, byte[] contentHash32,
byte[] contentDataItemId32, Line line) {
this.prevCoreHash32 = ProtocolHash.copy32(prevCoreHash32);
this.contentHash32 = ProtocolHash.copy32(contentHash32);
this.contentDataItemId32 = ProtocolHash.copy32(contentDataItemId32);
this.blockNumber = blockNumber; this.timestamp = timestamp; this.line = line;
if (blockNumber < 0 || blockNumber > MAX_BLOCK_NUMBER || timestamp < 0)
throw new IllegalArgumentException("Неверный номер CORE или timestamp");
if (blockNumber == 0 && (line != null || !Arrays.equals(this.prevCoreHash32, new byte[32])))
throw new IllegalArgumentException("Неверный genesis CORE");
if (line != null && (line.prevLineBlockNumber() >= blockNumber ||
(line.lineCode() > 0 && line.lineCode() <= MAX_BLOCK_NUMBER &&
(line.lineCode() >= blockNumber || line.prevLineBlockNumber() < line.lineCode()))))
throw new IllegalArgumentException("Неверная ссылка линии");
}
public static CoreRecord parse(byte[] bytes) {
if (bytes == null || (bytes.length != BASE_SIZE && bytes.length != LINE_SIZE))
throw new IllegalArgumentException("CORE должен иметь 109 или 149 байт");
ByteBuffer b = ByteBuffer.wrap(bytes);
if (Byte.toUnsignedInt(b.get()) != FRAME_CODE) throw new IllegalArgumentException("Неверный frameCode");
byte[] prev = read32(b); int n = b.getInt(); long t = b.getLong();
byte[] content = read32(b), id = read32(b);
Line line = b.hasRemaining() ? new Line(b.getInt(), b.getInt(), read32(b)) : null;
return new CoreRecord(prev, n, t, content, id, line);
}
private static byte[] read32(ByteBuffer b) { byte[] v = new byte[32]; b.get(v); return v; }
public byte[] toBytes() {
ByteBuffer b = ByteBuffer.allocate(line == null ? BASE_SIZE : LINE_SIZE);
b.put((byte) FRAME_CODE).put(prevCoreHash32).putInt(blockNumber).putLong(timestamp).put(contentHash32).put(contentDataItemId32);
if (line != null) b.putInt(line.lineCode()).putInt(line.prevLineBlockNumber()).put(line.prevLineCoreHash32());
return b.array();
}
public void checkTimestamp(long nowSeconds) {
if (nowSeconds < 0 || (timestamp > nowSeconds && timestamp - nowSeconds > FUTURE_TOLERANCE_SECONDS))
throw new IllegalArgumentException("CORE timestamp в будущем");
}
public int blockNumber() { return blockNumber; }
public long timestamp() { return timestamp; }
public Line line() { return line; }
public byte[] prevCoreHash32() { return prevCoreHash32.clone(); }
public byte[] contentHash32() { return contentHash32.clone(); }
public byte[] contentDataItemId32() { return contentDataItemId32.clone(); }
public byte[] coreHash32() { return ProtocolHash.sha256(toBytes()); }
}
@@ -1,17 +1,12 @@
//package blockchain; package blockchain;
//
///** /** Канонические линии CORE v2; Frame v1 использует старую модель. */
// * LineIndex — канонические номера линий блокчейна. public final class LineIndex {
// * private LineIndex() {}
// * Линия = независимая последовательность блоков внутри одного блокчейна. public static final int DEFAULT_CHANNEL = 0;
// */ public static final int USER_PROFILE = CoreRecord.PROFILE;
//public final class LineIndex { public static final int CONNECTION = CoreRecord.CONNECTION;
// public static final int TECH = CoreRecord.TECH;
// private LineIndex() {} public static final int MAX_CHANNEL = CoreRecord.MAX_BLOCK_NUMBER;
// public static boolean isChannel(int code) { return code >= 0 && code <= MAX_CHANNEL; }
// public static final short HEADER = 0; // genesis / идентификация }
// public static final short TEXT = 1; // сообщения да надо
// public static final short REACTION = 2; // реакции не надо
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
//}
@@ -0,0 +1,26 @@
package blockchain;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HexFormat;
public final class ProtocolHash {
private ProtocolHash() {}
public static byte[] copy32(byte[] bytes) {
if (bytes == null || bytes.length != 32) throw new IllegalArgumentException("Ожидается 32 байта");
return bytes.clone();
}
public static byte[] sha256(byte[] bytes) {
try { return MessageDigest.getInstance("SHA-256").digest(bytes); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
public static String hex32(byte[] bytes) { return HexFormat.of().formatHex(copy32(bytes)); }
public static byte[] fromHex32(String value) { return copy32(HexFormat.of().parseHex(value)); }
public static String base64url32(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(copy32(bytes)); }
public static byte[] fromBase64url32(String value) {
byte[] result = copy32(Base64.getUrlDecoder().decode(value));
if (!base64url32(result).equals(value)) throw new IllegalArgumentException("Неканонический base64url");
return result;
}
}
@@ -9,6 +9,14 @@ package blockchain;
public final class ShineProtocolTags { public final class ShineProtocolTags {
private ShineProtocolTags() {} private ShineProtocolTags() {}
public static final String CORE_NAMESPACE = "test5599";
/** Новый регистрационный сертификат остаётся отдельным объектом; используется при переключении эпохи. */
public static final java.util.List<Ans104DataItem.Tag> CORE_REGISTRATION_TAGS = java.util.List.of(
new Ans104DataItem.Tag("App", CORE_NAMESPACE),
new Ans104DataItem.Tag("t", "reg"),
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
public static final String CORE_NUMBER_TAG_NAME = "n";
public static final String CORE_LINE_TAG_NAME = "l";
public static final String NAMESPACE = "test5592"; public static final String NAMESPACE = "test5592";
public static final String APP_TAG_NAME = "App"; public static final String APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE; public static final String APP_TAG_VALUE = NAMESPACE;
@@ -21,6 +21,9 @@ package blockchain.body;
*/ */
public interface BodyHasLine { public interface BodyHasLine {
/** CORE не подписывает ordinal; до проверки канонического хвоста значение отсутствует. */
int UNRESOLVED_SEQUENCE = -1;
int lineCode(); int lineCode();
int prevLineBlockGlobalNumber(); int prevLineBlockGlobalNumber();
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -16,6 +17,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public static final short VER = 1; public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
public final int prevConnectionBlockNumber; public final int prevConnectionBlockNumber;
@@ -27,16 +29,28 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public final byte[] toBlockHash32; public final byte[] toBlockHash32;
public ConnectionBody(short subType, short version, byte[] bodyBytes) { public ConnectionBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public ConnectionBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header"); if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short"); BodyTargetSupport.ensureMin(bb, (4 + 32 + 4 + 1 + 1 + 2 + 4 + 32) - (contentOnly ? 40 : 0), "ConnectionBody too short");
if (contentOnly) {
this.prevConnectionBlockNumber = line.prevLineBlockNumber();
this.prevConnectionBlockHash32 = line.prevLineCoreHash32();
this.connectionSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.prevConnectionBlockNumber = bb.getInt(); this.prevConnectionBlockNumber = bb.getInt();
this.prevConnectionBlockHash32 = new byte[32]; this.prevConnectionBlockHash32 = new byte[32];
bb.get(this.prevConnectionBlockHash32); bb.get(this.prevConnectionBlockHash32);
this.connectionSequence = bb.getInt(); this.connectionSequence = bb.getInt();
}
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0); BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login(); this.toLogin = t.login();
this.toForkNumber = t.forkNumber(); this.toForkNumber = t.forkNumber();
@@ -47,6 +61,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType, public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) { String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
this.contentOnly = false;
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields"); if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
this.prevConnectionBlockNumber = prevConnectionBlockNumber; this.prevConnectionBlockNumber = prevConnectionBlockNumber;
@@ -64,15 +79,15 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields"); if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0"); if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid"); if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1"); if (!contentOnly && connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return this; return this;
} }
@Override public byte[] toBytes() { @Override public byte[] toBytes() {
check(); check();
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 40) + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence); if (!contentOnly) bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION"); BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array(); return bb.array();
} }
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -42,6 +43,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
private static final int MAX_NAME_LENGTH = 32; private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048; public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -56,6 +58,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
public final short channelTypeVersion; public final short channelTypeVersion;
public CreateChannelBody(short subType, short version, byte[] bodyBytes) { public CreateChannelBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public CreateChannelBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
@@ -67,16 +75,23 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) { if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF)); throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
} }
if (bodyBytes.length < 4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) { if (bodyBytes.length < (4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) - (contentOnly ? 44 : 0)) {
throw new IllegalArgumentException("CreateChannelBody too short"); throw new IllegalArgumentException("CreateChannelBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.lineCode = 0;
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32); bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
int nameLen = Byte.toUnsignedInt(bb.get()); int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0"); if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
@@ -86,7 +101,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
byte[] nameBytes = new byte[nameLen]; byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes); bb.get(nameBytes);
this.channelName = new String(nameBytes, StandardCharsets.UTF_8); this.channelName = contentOnly ? BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName") : new String(nameBytes, StandardCharsets.UTF_8);
int descriptionLen = Short.toUnsignedInt(bb.getShort()); int descriptionLen = Short.toUnsignedInt(bb.getShort());
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) { if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
@@ -100,7 +115,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
} else { } else {
byte[] descriptionBytes = new byte[descriptionLen]; byte[] descriptionBytes = new byte[descriptionLen];
bb.get(descriptionBytes); bb.get(descriptionBytes);
this.channelDescription = normalizeDescription(new String(descriptionBytes, StandardCharsets.UTF_8)); this.channelDescription = normalizeDescription(contentOnly ? BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription") : new String(descriptionBytes, StandardCharsets.UTF_8));
} }
this.channelTypeCode = bb.getShort(); this.channelTypeCode = bb.getShort();
this.channelTypeVersion = bb.getShort(); this.channelTypeVersion = bb.getShort();
@@ -117,6 +132,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String channelDescription, String channelDescription,
short channelTypeCode, short channelTypeCode,
short channelTypeVersion) { short channelTypeVersion) {
this.contentOnly = false;
Objects.requireNonNull(channelName, "channelName == null"); Objects.requireNonNull(channelName, "channelName == null");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0"); if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
@@ -142,6 +158,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
String normalizedName = normalizeDisplayName(channelName); String normalizedName = normalizeDisplayName(channelName);
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank"); if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
int cpLen = normalizedName.codePointCount(0, normalizedName.length()); int cpLen = normalizedName.codePointCount(0, normalizedName.length());
if (contentOnly && normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32"); if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
String normalizedDescription = normalizeDescription(channelDescription); String normalizedDescription = normalizeDescription(channelDescription);
@@ -157,7 +174,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody"); if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody");
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid"); if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody"); if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
return this; return this;
} }
@@ -199,12 +216,14 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048"); throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
} }
int cap = 4 + (4 + 32 + 4) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4; int cap = (contentOnly ? 0 : 44) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(lineCode); bb.putInt(lineCode);
bb.putInt(prevLineNumber); bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32)); bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber); bb.putInt(thisLineNumber);
}
bb.put((byte) nameUtf8.length); bb.put((byte) nameUtf8.length);
bb.put(nameUtf8); bb.put(nameUtf8);
bb.putShort((short) (descriptionUtf8.length & 0xFFFF)); bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -49,6 +50,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2; private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN; private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -69,6 +71,12 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public final String comment; public final String comment;
public ForkBody(short subType, short version, byte[] bodyBytes) { public ForkBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public ForkBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
@@ -79,16 +87,23 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
if ((version & 0xFFFF) != (VER & 0xFFFF)) { if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody version must be 1"); throw new IllegalArgumentException("ForkBody version must be 1");
} }
if (bodyBytes.length < FIXED_LEN) { if (bodyBytes.length < FIXED_LEN - (contentOnly ? LINE_PREFIX_LEN : 0)) {
throw new IllegalArgumentException("ForkBody too short"); throw new IllegalArgumentException("ForkBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.lineCode = 0;
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32); bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
this.parentBlockchainKey32 = new byte[32]; this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32); bb.get(this.parentBlockchainKey32);
@@ -111,7 +126,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
} }
byte[] commentBytes = new byte[commentLen]; byte[] commentBytes = new byte[commentLen];
bb.get(commentBytes); bb.get(commentBytes);
this.comment = new String(commentBytes, StandardCharsets.UTF_8); this.comment = contentOnly ? BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment") : new String(commentBytes, StandardCharsets.UTF_8);
} }
public ForkBody(int lineCode, public ForkBody(int lineCode,
@@ -128,6 +143,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
int discardedBlocksCount, int discardedBlocksCount,
int reasonCode, int reasonCode,
String comment) { String comment) {
this.contentOnly = false;
this.subType = SUBTYPE; this.subType = SUBTYPE;
this.version = VER; this.version = VER;
this.lineCode = lineCode; this.lineCode = lineCode;
@@ -157,7 +173,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0"); if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0"); if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
require32(prevLineHash32, "prevLineHash32"); require32(prevLineHash32, "prevLineHash32");
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1"); if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
require32(parentBlockchainKey32, "parentBlockchainKey32"); require32(parentBlockchainKey32, "parentBlockchainKey32");
require32(forkPointBlockHash32, "forkPointBlockHash32"); require32(forkPointBlockHash32, "forkPointBlockHash32");
@@ -186,11 +202,13 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
public byte[] toBytes() { public byte[] toBytes() {
check(); check();
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8); byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? FIXED_PAYLOAD_LEN : FIXED_LEN) + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(lineCode); bb.putInt(lineCode);
bb.putInt(prevLineNumber); bb.putInt(prevLineNumber);
bb.put(prevLineHash32); bb.put(prevLineHash32);
bb.putInt(thisLineNumber); bb.putInt(thisLineNumber);
}
bb.put(parentBlockchainKey32); bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber); bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32); bb.put(forkPointBlockHash32);
@@ -6,25 +6,23 @@ import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects; import java.util.Objects;
/** /**
* HeaderBody — type=0, subType=0, version=1. * HEADER 1.0 — TECH type=0, subType=0, version=1.
* *
* bodyBytes (BigEndian): * bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII * [TAG_LEN] tag ASCII; [1] login length; [N] login UTF-8;
* [1] loginLength (uint8) * [1] accountType (0 alternative / 1 primary);
* [N] login UTF-8 * [2+N] previous accounts CSV for Primary only;
* [32] initialBlockchainKey32 * [1] license length; [M] arbitrary license UTF-8; [32] initial blockchain key.
*
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
* It is historical identity metadata and MUST remain byte-for-byte unchanged when a
* preserved prefix (including block #0) is republished into later forks.
*/ */
public final class HeaderBody implements BodyRecord { public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0; public static final short TYPE = 0;
public static final short VER = 1; public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int ALTERNATIVE = 0, PRIMARY = 1;
public static final short SUBTYPE_COMPAT = 0; public static final short SUBTYPE_COMPAT = 0;
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG; public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
@@ -36,57 +34,108 @@ public final class HeaderBody implements BodyRecord {
public final String tag; public final String tag;
public final String login; public final String login;
public final byte[] initialBlockchainKey32; public final byte[] initialBlockchainKey32;
public final int accountType;
public final List<String> previousAccounts;
public final String license;
public HeaderBody(short subType, short version, byte[] bodyBytes) { public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); if ((subType & 0xFFFF) != SUBTYPE_COMPAT) throw new IllegalArgumentException("HeaderBody subType must be 0");
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1"); if (version != VER) throw new IllegalArgumentException("HeaderBody version must be 1.0");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short"); if (bodyBytes.length < TAG_LEN + 1 + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
byte[] tagBytes = new byte[TAG_LEN]; byte[] tagBytes = new byte[TAG_LEN];
bb.get(tagBytes); bb.get(tagBytes);
String parsedTag = new String(tagBytes, StandardCharsets.US_ASCII); this.tag = new String(tagBytes, StandardCharsets.US_ASCII);
if (!TAG.equals(parsedTag)) throw new IllegalArgumentException("Bad tag: " + parsedTag); if (!TAG.equals(tag)) throw new IllegalArgumentException("Bad tag: " + tag);
this.tag = parsedTag;
int loginLen = Byte.toUnsignedInt(bb.get()); int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0 || bb.remaining() != loginLen + 32) throw new IllegalArgumentException("Bad HeaderBody login/key length"); if (loginLen == 0 || bb.remaining() < loginLen + 34) throw new IllegalArgumentException("Bad HEADER login length");
byte[] loginBytes = new byte[loginLen]; byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes); bb.get(loginBytes);
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login"); this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HEADER login");
this.accountType = Byte.toUnsignedInt(bb.get());
List<String> parsedPrevious;
if (accountType == PRIMARY) {
if (bb.remaining() < 35) throw new IllegalArgumentException("Truncated HEADER previous accounts");
int size = Short.toUnsignedInt(bb.getShort());
if (size > bb.remaining() - 33) throw new IllegalArgumentException("Bad HEADER previous accounts length");
byte[] previous = new byte[size];
bb.get(previous);
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
parsedPrevious = csv.isEmpty() ? List.of() : List.of(csv.split(",", -1));
} else if (accountType == ALTERNATIVE) {
parsedPrevious = List.of();
} else {
throw new IllegalArgumentException("Bad HEADER account type");
}
this.previousAccounts = parsedPrevious;
int licenseSize = Byte.toUnsignedInt(bb.get());
if (bb.remaining() != licenseSize + 32) throw new IllegalArgumentException("Bad HEADER license length");
byte[] licenseBytes = new byte[licenseSize];
bb.get(licenseBytes);
this.license = BodyTargetSupport.decodeStrictUtf8(licenseBytes, "HEADER license");
this.initialBlockchainKey32 = new byte[32]; this.initialBlockchainKey32 = new byte[32];
bb.get(this.initialBlockchainKey32); bb.get(initialBlockchainKey32);
requireNonZeroKey(this.initialBlockchainKey32);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail"); if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
check();
} }
/** Creates the canonical 1.0 HEADER for a Primary account. */
public HeaderBody(String login, byte[] initialBlockchainKey32) { public HeaderBody(String login, byte[] initialBlockchainKey32) {
Objects.requireNonNull(login, "login == null"); this(login, initialBlockchainKey32, "", PRIMARY, List.of());
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"); }
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
return new HeaderBody(login, initialBlockchainKey32);
}
public static HeaderBody identity(String login, byte[] initialBlockchainKey32, String license,
int accountType, List<String> previousAccounts) {
return new HeaderBody(login, initialBlockchainKey32, license, accountType, previousAccounts);
}
private HeaderBody(String login, byte[] initialBlockchainKey32, String license,
int accountType, List<String> previousAccounts) {
this.subType = SUBTYPE_COMPAT; this.subType = SUBTYPE_COMPAT;
this.version = VER; this.version = VER;
this.tag = TAG; this.tag = TAG;
this.login = login; this.login = Objects.requireNonNull(login, "login == null");
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length); this.initialBlockchainKey32 = Arrays.copyOf(Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"), initialBlockchainKey32.length);
this.license = Objects.requireNonNull(license, "license == null");
this.accountType = accountType;
this.previousAccounts = List.copyOf(Objects.requireNonNull(previousAccounts, "previousAccounts == null"));
check(); check();
} }
@Override @Override
public HeaderBody check() { public HeaderBody check() {
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0"); if ((subType & 0xFFFF) != SUBTYPE_COMPAT || version != VER) throw new IllegalArgumentException("Bad HeaderBody version");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank"); if (!StandardCharsets.UTF_8.newEncoder().canEncode(license) || license.getBytes(StandardCharsets.UTF_8).length > 255)
throw new IllegalArgumentException("HEADER license must be 0..255 UTF-8 bytes");
if (login.isBlank()) throw new IllegalArgumentException("Login is blank");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$"); boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$"); boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
if (!legacyLogin && !namespacedLogin) { if (!legacyLogin && !namespacedLogin) throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)"); if (loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
if (accountType != ALTERNATIVE && accountType != PRIMARY) throw new IllegalArgumentException("Bad HEADER account type");
if (previousAccounts.size() > 10 || (accountType == ALTERNATIVE && !previousAccounts.isEmpty()))
throw new IllegalArgumentException("Bad HEADER previous account count");
var seen = new java.util.HashSet<String>();
seen.add(login.toLowerCase(Locale.ROOT));
for (String prev : previousAccounts) {
if (!(prev.matches("^[A-Za-z0-9_]{1,255}$") || (prev.length() <= 30 && prev.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$")))
|| !seen.add(prev.toLowerCase(Locale.ROOT)))
throw new IllegalArgumentException("Bad, duplicate or self HEADER previous account");
} }
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255"); byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
if (previous.length > 0xFFFF) throw new IllegalArgumentException("HEADER previous accounts are too long");
requireNonZeroKey(initialBlockchainKey32); requireNonZeroKey(initialBlockchainKey32);
return this; return this;
} }
@@ -95,11 +144,13 @@ public final class HeaderBody implements BodyRecord {
public byte[] toBytes() { public byte[] toBytes() {
check(); check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8); byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).order(ByteOrder.BIG_ENDIAN); byte[] licenseUtf8 = license.getBytes(StandardCharsets.UTF_8);
bb.put(TAG_ASCII); byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
bb.put((byte) loginUtf8.length); int identitySize = 1 + (accountType == PRIMARY ? 2 + previous.length : 0);
bb.put(loginUtf8); ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + identitySize + 1 + licenseUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
bb.put(initialBlockchainKey32); bb.put(TAG_ASCII).put((byte) loginUtf8.length).put(loginUtf8).put((byte) accountType);
if (accountType == PRIMARY) bb.putShort((short) previous.length).put(previous);
bb.put((byte) licenseUtf8.length).put(licenseUtf8).put(initialBlockchainKey32);
return bb.array(); return bb.array();
} }
@@ -112,6 +163,6 @@ public final class HeaderBody implements BodyRecord {
@Override @Override
public String toString() { public String toString() {
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}"; return "HeaderBody{version=1.0, login='" + login + "', accountType=" + accountType + ", license=" + license + ", initialBlockchainKey32=<32 bytes>}";
} }
} }
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -27,6 +28,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
public static final short VER = 1; public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
public final int lineCode; public final int lineCode;
@@ -40,17 +42,30 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
public final String message; public final String message;
public TextLineBody(short subType, short version, byte[] bodyBytes) { public TextLineBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public TextLineBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
this.version = version; this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header"); if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 2, "TextLineBody too short"); BodyTargetSupport.ensureMin(bb, (4 + 4 + 32 + 4 + 2) - (contentOnly ? 44 : 0), "TextLineBody too short");
if (contentOnly) {
this.lineCode = line.lineCode();
this.prevLineNumber = line.prevLineBlockNumber();
this.prevLineHash32 = line.prevLineCoreHash32();
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.lineCode = bb.getInt(); this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt(); this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32); this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt(); this.thisLineNumber = bb.getInt();
}
int st = subType & 0xFFFF; int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) { if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
@@ -88,6 +103,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
Integer toBlockGlobalNumber, Integer toBlockGlobalNumber,
byte[] toBlockHash32, byte[] toBlockHash32,
String message) { String message) {
this.contentOnly = false;
Objects.requireNonNull(message, "message == null"); Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype"); if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0"); if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
@@ -144,8 +160,8 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32; if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin); else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 44) + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber); if (!contentOnly) bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) { if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber).put(toBlockHash32); bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) { } else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
@@ -1,6 +1,7 @@
package blockchain.body; package blockchain.body;
import blockchain.MsgSubType; import blockchain.MsgSubType;
import blockchain.CoreRecord;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.ByteOrder; import java.nio.ByteOrder;
@@ -35,6 +36,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF); public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
private final boolean contentOnly;
public final short subType; public final short subType;
public final short version; public final short version;
@@ -46,6 +48,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public final String paramValue; public final String paramValue;
public UserParamBody(short subType, short version, byte[] bodyBytes) { public UserParamBody(short subType, short version, byte[] bodyBytes) {
this(subType, version, bodyBytes, null);
}
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
public UserParamBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
this.contentOnly = line != null;
Objects.requireNonNull(bodyBytes, "bodyBytes == null"); Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType; this.subType = subType;
@@ -59,16 +67,22 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
} }
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1) // prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
if (bodyBytes.length < 4 + 32 + 4 + 2 + 1 + 2 + 1) { if (bodyBytes.length < (4 + 32 + 4 + 2 + 1 + 2 + 1) - (contentOnly ? 40 : 0)) {
throw new IllegalArgumentException("UserParamBody too short"); throw new IllegalArgumentException("UserParamBody too short");
} }
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (contentOnly) {
this.prevProfileBlockNumber = line.prevLineBlockNumber();
this.prevProfileBlockHash32 = line.prevLineCoreHash32();
this.profileSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
} else {
this.prevProfileBlockNumber = bb.getInt(); this.prevProfileBlockNumber = bb.getInt();
this.prevProfileBlockHash32 = new byte[32]; this.prevProfileBlockHash32 = new byte[32];
bb.get(this.prevProfileBlockHash32); bb.get(this.prevProfileBlockHash32);
this.profileSequence = bb.getInt(); this.profileSequence = bb.getInt();
}
int keyLen = Short.toUnsignedInt(bb.getShort()); int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0"); if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
@@ -98,6 +112,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
int profileSequence, int profileSequence,
String paramKey, String paramKey,
String paramValue) { String paramValue) {
this.contentOnly = false;
Objects.requireNonNull(paramKey, "paramKey == null"); Objects.requireNonNull(paramKey, "paramKey == null");
Objects.requireNonNull(paramValue, "paramValue == null"); Objects.requireNonNull(paramValue, "paramValue == null");
@@ -123,7 +138,7 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
} }
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0"); if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid"); if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
if (profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1"); if (!contentOnly && profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank"); if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank"); if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
@@ -140,14 +155,16 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535"); if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535"); if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
int cap = 4 + 32 + 4 int cap = (contentOnly ? 0 : 40)
+ 2 + keyUtf8.length + 2 + keyUtf8.length
+ 2 + valUtf8.length; + 2 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN); ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
if (!contentOnly) {
bb.putInt(prevProfileBlockNumber); bb.putInt(prevProfileBlockNumber);
bb.put(prevProfileBlockHash32); bb.put(prevProfileBlockHash32);
bb.putInt(profileSequence); bb.putInt(profileSequence);
}
bb.putShort((short) keyUtf8.length); bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8); bb.put(keyUtf8);
bb.putShort((short) valUtf8.length); bb.putShort((short) valUtf8.length);
@@ -55,7 +55,7 @@ final class Ans104DataItemTest {
); );
byte[] actual = Ans104DataItem.buildSigningMessage(owner, tags, data); byte[] actual = Ans104DataItem.buildSigningMessage(owner, tags, data);
byte[] expected = hex("1abe0371d12268b34be32ca5ebf3d3d2189f9d311d9004c142538ca8a4312faa329d1a4873df72dd01b632a2ecce6b87"); byte[] expected = hex("507e6879ff233333fb4116c9495fcf695f0cabbb2c2d956b3fb32b6dc1f894b67e4d23170444f0cecdb805eec3494234");
assertArrayEquals(expected, actual); assertArrayEquals(expected, actual);
} }
@@ -0,0 +1,332 @@
package blockchain;
import blockchain.body.*;
import utils.crypto.Ed25519Util;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import static blockchain.MsgSubType.*;
/** Запускается и из Gradle/JUnit, и автономно через javac --release 17. */
public final class StageAProtocolChecks {
private static int count;
private static final byte[] ZERO = new byte[32], HASH = ProtocolHash.sha256(new byte[]{1});
private static final long NOW = 1700001000L;
private static final byte[] SEED = new byte[32];
static { for (int i=0;i<32;i++) SEED[i]=(byte)i; }
private static final byte[] OWNER = Ed25519Util.derivePublicKey(SEED);
private static final HexFormat HEX = HexFormat.of();
private static void ok(boolean condition, String label) {
if (!condition) throw new AssertionError(label);
count++;
}
private static void eq(byte[] a, byte[] b, String label) { ok(Arrays.equals(a,b), label); }
private static void bad(Runnable r, String label) {
try { r.run(); } catch (IllegalArgumentException expected) { count++; return; }
throw new AssertionError("Ожидался отказ: " + label);
}
private static CoreRecord core(int number, CoreRecord.Line line, ContentRecord content, byte[] id) {
return new CoreRecord(number == 0 ? ZERO : HASH, number, NOW, content.contentHash32(), id, line);
}
private static CoreRecord.Line line(int code) { return new CoreRecord.Line(code,0,HASH); }
private static Ans104DataItem sign(CoreRecord c, List<Ans104DataItem.Tag> tags) {
return CoreContentTransport.sign(c.toBytes(), tags, SEED);
}
private static void rejectTags(CoreRecord c, List<Ans104DataItem.Tag> tags) {
var i = sign(c,tags); bad(() -> CoreContentTransport.verifyCore(i,OWNER,i.id32(),NOW), "signed bad tags " + tags);
}
private static Ans104DataItem.Tag tag(String name,String value) { return new Ans104DataItem.Tag(name,value); }
private static void checkBodies() throws Exception {
var header = HeaderBody.forCoreContent("Alice@shine", OWNER);
testBody(0,HEADER_COMPAT,header,null,0);
ok(header.license.isEmpty() && header.accountType == HeaderBody.PRIMARY,"canonical HEADER 1.0");
for (String license : new String[]{"", "CC0-1.0", "CC-BY-NC-4.0", "Лицензия 🌞", "x".repeat(255)}) {
var h = HeaderBody.identity("Alice@shine", OWNER, license, HeaderBody.PRIMARY, List.of());
var c = new ContentRecord(0,0,1,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(license.equals(parsed.license), "arbitrary license");
eq(h.toBytes(), parsed.toBytes(), "HEADER 1.0 roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(), h.toBytes(), "HEADER 1.0 create");
var contentItem = CoreContentTransport.sign(c.toBytes(), List.of(), SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var coreItem = sign(coreRecord,CoreContentTransport.coreTags(coreRecord));
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(coreItem, contentItem));
ok(license.equals(((HeaderBody)pair.body).license), "signed HEADER 1.0 pair");
eq(pair.getContentRecord().bodyBytes(), h.toBytes(), "signed HEADER 1.0 exact bytes");
bad(() -> parseSemantic(new ContentRecord(0,0,1,Arrays.copyOf(h.toBytes(),h.toBytes().length-1))), "truncated HEADER 1.0");
}
bad(() -> HeaderBody.identity("Alice",OWNER,"x".repeat(256),HeaderBody.PRIMARY,List.of()), "license too long");
byte[] invalidUtf8 = HeaderBody.identity("Alice",OWNER,"x",HeaderBody.PRIMARY,List.of()).toBytes();
invalidUtf8[15] = (byte)0xff;
bad(() -> parseSemantic(new ContentRecord(0,0,1,invalidUtf8)), "invalid license UTF8");
for (int type : new int[]{0,1}) {
for (List<String> prev : type == 0 ? List.of(List.<String>of()) : List.of(List.<String>of(), List.of("Bob@free", "Old@shine"), java.util.stream.IntStream.range(0,10).mapToObj(n -> "old"+n+"@free").toList())) {
var h = HeaderBody.identity("Alice@shine",OWNER,"Лицензия",type,prev);
var c = new ContentRecord(0,0,1,h.toBytes());
var parsed = (HeaderBody) parseSemantic(c);
ok(parsed.accountType == type && parsed.previousAccounts.equals(prev) && parsed.license.equals("Лицензия"), "HEADER 1.0 role and predecessors");
eq(parsed.toBytes(), h.toBytes(), "HEADER 1.0 byte roundtrip");
eq(ContentBodyParser.parseForCreate(core(0,null,c,HASH),c).toBytes(),h.toBytes(),"HEADER 1.0 create");
var contentItem = CoreContentTransport.sign(c.toBytes(),List.of(),SEED);
var coreRecord = core(0,null,c,contentItem.id32());
var pair = BchBlockEntry.fromCoreContent(CoreContentContainer.pack(sign(coreRecord,CoreContentTransport.coreTags(coreRecord)),contentItem));
ok(((HeaderBody)pair.body).previousAccounts.equals(prev),"signed HEADER 1.0 pair");
for(int n=0;n<h.toBytes().length;n++) {
byte[] cut=Arrays.copyOf(h.toBytes(),n);
bad(()->parseSemantic(new ContentRecord(0,0,1,cut)),"truncated HEADER 1.0");
}
}
}
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",2,List.of()),"unknown type");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",0,List.of("Bob@free")),"alternative predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("alice@shine")),"self predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob@free","bob@free")),"duplicate predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,List.of("Bob,old")),"comma in predecessor");
bad(()->HeaderBody.identity("Alice@shine",OWNER,"",1,java.util.stream.IntStream.range(0,11).mapToObj(n->"old"+n+"@free").toList()),"eleven predecessors");
byte[] invalidRole = HeaderBody.identity("Alice@shine",OWNER,"",0,List.of()).toBytes();
invalidRole[6+"Alice@shine".length()] = 2;
bad(()->parseSemantic(new ContentRecord(0,0,1,invalidRole)),"invalid parsed role");
var create=new CreateChannelContentBody("Новости","Описание",(short)1,(short)1);
testBody(0,TECH_CREATE_CHANNEL,create,line(CoreRecord.TECH),1);
eq(create.toBytes(),Arrays.copyOfRange(new CreateChannelBody(0,0,HASH,1,"Новости","Описание",(short)1,(short)1).toBytes(),44,
new CreateChannelBody(0,0,HASH,1,"Новости","Описание",(short)1,(short)1).toBytes().length),"CREATE_CHANNEL prefix removed");
var fork=new ForkContentBody(OWNER,0,HASH,123,1,HASH,234,1,1,"rotate");
testBody(0,TECH_FORK,fork,line(CoreRecord.TECH),2);
var oldFork=new ForkBody(0,0,HASH,1,OWNER,0,HASH,123,1,HASH,234,1,1,"rotate");
eq(fork.toBytes(),Arrays.copyOfRange(oldFork.toBytes(),44,oldFork.toBytes().length),"FORK prefix removed");
for(short s:new short[]{TEXT_POST,TEXT_EDIT_POST,TEXT_REPOST,TEXT_CHANNEL_META,TEXT_CHANNEL_DELETE,TEXT_ENTRYPOINT,TEXT_EXERCISE,TEXT_SERVICE,TEXT_COURSE}) {
boolean edit=s==TEXT_EDIT_POST, repost=s==TEXT_REPOST, target=edit||repost;
String msg=s==TEXT_CHANNEL_DELETE?"": "Тест 🌞";
var body=new TextLineContentBody(s,repost?"Bob":null,repost?1:null,target?0:null,target?HASH:null,msg);
testBody(1,s,body,line(0),2);
var legacy=new TextLineBody(0,0,HASH,1,s,repost?"Bob":null,repost?1:null,target?0:null,target?HASH:null,msg);
eq(body.toBytes(),Arrays.copyOfRange(legacy.toBytes(),44,legacy.toBytes().length),"TEXT prefix removed " + s);
bad(() -> parseSemantic(new ContentRecord(1,s,1,legacy.toBytes())),"old text prefix");
}
testBody(1,TEXT_REPLY,new TextReplyBody(TEXT_REPLY,"Bob",1,0,HASH,"ответ"),null,2);
testBody(1,TEXT_EDIT_REPLY,new TextReplyBody(TEXT_EDIT_REPLY,null,null,0,HASH,""),null,2);
testBody(1,TEXT_RATING,new TextRatingBody("Bob",1,0,HASH,"rating"),null,2);
for(short s: new short[]{REACTION_LIKE,REACTION_UNLIKE}) testBody(2,s,new ReactionBody(s,"Bob",1,0,HASH),null,2);
for(var field: MsgSubType.class.getFields()) {
if(field.getName().startsWith("CONNECTION_")) {
short s=field.getShort(null);
var body=new ConnectionContentBody(s,"Bob",1,0,HASH);
testBody(3,s,body,line(CoreRecord.CONNECTION),2);
var legacy=new ConnectionBody(0,HASH,1,s,"Bob",1,0,HASH);
eq(body.toBytes(),Arrays.copyOfRange(legacy.toBytes(),40,legacy.toBytes().length),"CONNECTION prefix removed " + s);
}
if(field.getName().startsWith("STATUS_")) {
short s=field.getShort(null);
testBody(5,s,new StatusActionBody(s,"Bob",1,0,HASH,""),null,2);
}
}
var profile=new UserParamContentBody("name","Алиса");
testBody(4,USER_PARAM_TEXT_TEXT,profile,line(CoreRecord.PROFILE),2);
var oldProfile=new UserParamBody(0,HASH,1,"name","Алиса");
eq(profile.toBytes(),Arrays.copyOfRange(oldProfile.toBytes(),40,oldProfile.toBytes().length),"PROFILE prefix removed");
bad(() -> parseSemantic(new ContentRecord(4,1,1,oldProfile.toBytes())),"old profile prefix");
bad(() -> parseSemantic(new ContentRecord(0,1,1,new byte[]{1,(byte)0xff,0,0,0,1,0,1})),"invalid channel UTF-8");
bad(() -> parseSemantic(new ContentRecord(1,TEXT_POST,1,new byte[]{0,1,(byte)0xff})),"invalid text UTF-8");
bad(() -> parseSemantic(new ContentRecord(65535,65535,1,new byte[0])),"unknown type");
bad(() -> parseSemantic(new ContentRecord(1,TEXT_POST,2,new byte[0])),"unknown version");
var shortName=new ContentRecord(0,1,1,new byte[]{1,'x',0,0,0,1,0,1});
var cc=core(1,line(CoreRecord.TECH),shortName,HASH);
ok(ContentBodyParser.parseForCore(cc,shortName) instanceof CreateChannelBody,"existing short name can be read");
bad(() -> ContentBodyParser.parseForCreate(cc,shortName),"new short name rejected");
}
// Для негативных тестов semantic parser строим корректный CORE вокруг испорченного тела.
private static BodyRecord parseSemantic(ContentRecord c) {
boolean header = c.type()==0 && c.subType()==HEADER_COMPAT;
CoreRecord.Line l = switch(c.type()) {
case 0 -> header ? null : line(CoreRecord.TECH);
case 1 -> ContentBodyParser.isChannelText(c.subType()) ? line(0) : null;
case 3 -> line(CoreRecord.CONNECTION);
case 4 -> line(CoreRecord.PROFILE);
default -> null;
};
return ContentBodyParser.parseForCore(core(header?0:2,l,c,HASH),c);
}
private static void testBody(int t, short s, BodyRecord body, CoreRecord.Line line, int n) {
byte[] raw=body.toBytes(); var content=new ContentRecord(t,s,1,raw); var c=core(n,line,content,HASH);
eq(ContentBodyParser.parseForCreate(c,content).toBytes(),raw,"roundtrip " + t + "/" + s);
for(int len=0;len<raw.length;len++) {
byte[] truncated=Arrays.copyOf(raw,len);
bad(() -> parseSemantic(new ContentRecord(t,s,1,truncated)),"truncated " + t + "/" + s + " len=" + len);
}
bad(() -> parseSemantic(new ContentRecord(t,s,1,Arrays.copyOf(raw,raw.length+1))),"body trailing bytes");
if(n==0) bad(() -> ContentBodyParser.parseForCore(core(1,null,content,HASH),content),"HEADER outside genesis");
else bad(() -> ContentBodyParser.parseForCore(core(n,line==null?line(0):null,content,HASH),content),"wrong line presence");
if(line!=null) {
int wrong=line.lineCode()==0?CoreRecord.PROFILE:0;
bad(() -> ContentBodyParser.parseForCore(core(n,line(wrong),content,HASH),content),"wrong line class");
}
}
private static void checkBinaryAndTransport() {
byte[] raw={0,5,'H','e','l','l','o'};
var content=new ContentRecord(1,TEXT_POST,1,raw);
raw[2]=0; ok(content.bodyBytes()[2]=='H',"immutable CONTENT input");
content.bodyBytes()[2]=0; ok(content.bodyBytes()[2]=='H',"immutable CONTENT output");
var item=CoreContentTransport.sign(content.toBytes(),List.of(),SEED);
var c=core(128,line(0),content,item.id32());
eq(c.toBytes(),CoreRecord.parse(c.toBytes()).toBytes(),"CORE roundtrip");
eq(content.toBytes(),ContentRecord.parse(content.toBytes()).toBytes(),"CONTENT roundtrip");
byte[] copy=c.prevCoreHash32(); copy[0]^=1; eq(c.prevCoreHash32(),HASH,"immutable CORE prev hash");
byte[] source=HASH.clone(); var l=new CoreRecord.Line(0,0,source); source[0]^=1; eq(l.prevLineCoreHash32(),HASH,"immutable Line input");
l.prevLineCoreHash32()[0]^=1; eq(l.prevLineCoreHash32(),HASH,"immutable Line output");
eq(ProtocolHash.fromHex32(ProtocolHash.hex32(HASH)),HASH,"hex");
eq(ProtocolHash.fromBase64url32(ProtocolHash.base64url32(HASH)),HASH,"base64url");
bad(() -> ProtocolHash.fromBase64url32(ProtocolHash.base64url32(HASH)+"="),"base64url padding");
for(int len:new int[]{0,108,110,148,150}) bad(() -> CoreRecord.parse(new byte[len]),"CORE length");
for(int len=0;len<7;len++) { int n=len; bad(() -> ContentRecord.parse(new byte[n]),"CONTENT length"); }
byte[] code=c.toBytes(); code[0]=2; bad(() -> CoreRecord.parse(code),"frameCode");
byte[] wrongContent=content.toBytes(); wrongContent[0]=2; bad(() -> ContentRecord.parse(wrongContent),"contentCode");
byte[] le=c.toBytes(); ByteBuffer.wrap(le).order(ByteOrder.LITTLE_ENDIAN).putInt(33,128); bad(() -> CoreRecord.parse(le),"wrong endian number");
bad(() -> core(-1,null,content,HASH),"negative global");
bad(() -> core(CoreRecord.MAX_BLOCK_NUMBER+1,null,content,HASH),"reserved global");
bad(() -> core(0,line(0),content,HASH),"genesis line");
bad(() -> new CoreRecord(HASH,0,NOW,HASH,HASH,null),"genesis nonzero prev");
bad(() -> core(1,new CoreRecord.Line(0,1,HASH),content,HASH),"line predecessor same number");
bad(() -> core(1,new CoreRecord.Line(1,0,HASH),content,HASH),"channel not created yet");
bad(() -> core(5,new CoreRecord.Line(3,2,HASH),content,HASH),"line pred before root");
new CoreRecord(HASH,1,NOW+60,HASH,HASH,null).checkTimestamp(NOW); count++;
bad(() -> new CoreRecord(HASH,1,NOW+61,HASH,HASH,null).checkTimestamp(NOW),"timestamp +61");
bad(() -> new CoreRecord(HASH,1,-1,HASH,HASH,null),"negative timestamp");
var signed=sign(c,CoreContentTransport.coreTags(c));
eq(CoreContentTransport.verifyPair(signed,signed.id32(),item,OWNER,NOW).content().toBytes(),content.toBytes(),"pair verify");
eq(CoreContentTransport.verifyCore(signed,OWNER,signed.id32(),NOW).toBytes(),c.toBytes(),"CORE only");
eq(CoreContentTransport.verifyPayload(c,item.data()).toBytes(),content.toBytes(),"payload only");
bad(() -> CoreContentTransport.verifyCore(signed,OWNER,HASH,NOW),"core ID mismatch");
byte[] altered=item.data(); altered[altered.length-1]^=1;
bad(() -> CoreContentTransport.verifyPayload(c,altered),"content hash mismatch");
byte[] signature=signed.rawBytes(); signature[2]^=1; var tampered=new Ans104DataItem(signature);
bad(() -> CoreContentTransport.verifyCore(tampered,OWNER,tampered.id32(),NOW),"bad signature with new ID");
byte[] secondSeed=SEED.clone(); secondSeed[0]^=1;
var other=CoreContentTransport.sign(content.toBytes(),List.of(),secondSeed);
var foreignCore=core(128,line(0),content,other.id32()); var foreign=sign(foreignCore,CoreContentTransport.coreTags(foreignCore));
bad(() -> CoreContentTransport.verifyPair(foreign,foreign.id32(),other,OWNER,NOW),"different owner with matching content ID");
bad(() -> CoreContentTransport.verifyContent(c,other,other.owner32()),"wrong content ID");
var tagged=CoreContentTransport.sign(content.toBytes(),List.of(tag("App","test5599"),tag("n","128")),SEED);
bad(() -> CoreContentTransport.verifyContent(core(128,line(0),content,tagged.id32()),tagged,OWNER),"tagged CONTENT");
rejectTags(c,List.of(tag("App","test5592"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","0128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","129"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","P")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128")));
rejectTags(c,List.of(tag("App","test5599"),tag("App","test5599"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("n","128"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("l","0")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("c","news")));
rejectTags(c,List.of(tag("App","test5599"),tag("n","128"),tag("l","0"),tag("t","tech")));
rejectTags(core(128,null,content,item.id32()),List.of(tag("App","test5599"),tag("n","128"),tag("l","0")));
rejectTags(core(128,line(CoreRecord.TECH),content,item.id32()),List.of(tag("App","test5599"),tag("n","128"),tag("l",Integer.toString(CoreRecord.TECH))));
ok(ShineProtocolTags.CORE_REGISTRATION_TAGS.equals(List.of(tag("App","test5599"), tag("t","reg"), tag("Protocol","SHiNE-Free-Registration-V1"))), "separate registration tags");
rejectTags(core(128,null,content,item.id32()),ShineProtocolTags.CORE_REGISTRATION_TAGS);
var oldFrame=new byte[109]; oldFrame[1]=1;
bad(() -> CoreRecord.parse(oldFrame),"old Frame v1");
var unsignedUnknown=new ContentRecord(65535,65535,65535,new byte[0]);
ok(ContentRecord.parse(unsignedUnknown.toBytes()).type()==65535,"raw unknown unsigned type");
bad(() -> new ContentRecord(65536,0,0,new byte[0]),"uint16 overflow");
}
// ANS-104 подписывает исходные Avro-байты, а не декодированный список тегов.
private static byte[] replaceRawTags(Ans104DataItem item, byte[] rawTags) {
// Тестовые оболочки без target/anchor: tags_size расположен по смещению 108.
byte[] old = item.rawBytes(), data = item.data();
byte[] result = Arrays.copyOf(old, 116 + rawTags.length + data.length);
ByteBuffer.wrap(result).order(ByteOrder.LITTLE_ENDIAN).putLong(108, rawTags.length);
System.arraycopy(rawTags,0,result,116,rawTags.length);
System.arraycopy(data,0,result,116+rawTags.length,data.length);
return result;
}
private static void checkRawTagSignatures() {
var original = CoreContentTransport.sign(new byte[]{7},List.of(tag("App","test5599")),SEED);
byte[] raw = original.rawTags();
// Эквивалентный Avro-массив с отрицательным count и явным размером блока.
byte[] alternative = new byte[raw.length+1];
alternative[0]=1; // zigzag(-1)
alternative[1]=(byte)((raw.length-2)*2);
System.arraycopy(raw,1,alternative,2,raw.length-1);
byte[] replaced=replaceRawTags(original,alternative);
var changed = new Ans104DataItem(replaced);
ok(changed.tags().equals(original.tags()),"same decoded tags");
ok(!changed.verifySignature(),"modified raw tags must invalidate original signature");
ok(!Arrays.equals(changed.signingMessage(),original.signingMessage()),"raw encoding is part of deep hash");
byte[] sig=Ed25519Util.sign(changed.signingMessage(),SEED);
System.arraycopy(sig,0,replaced,2,64);
ok(new Ans104DataItem(replaced).verifySignature(),"genuinely signed alternative Avro encoding");
byte[] wrongSize=alternative.clone(); wrongSize[1]-=2;
bad(() -> new Ans104DataItem(replaceRawTags(original,wrongSize)),"wrong Avro block size");
bad(() -> new Ans104DataItem(replaceRawTags(original,Arrays.copyOf(raw,raw.length-1))),"missing Avro terminator");
byte[] invalidUtf8=raw.clone(); invalidUtf8[2]=(byte)0xff;
bad(() -> new Ans104DataItem(replaceRawTags(original,invalidUtf8)),"invalid UTF-8 in tags");
var empty=CoreContentTransport.sign(new byte[]{7},List.of(),SEED);
byte[] emptyRaw=replaceRawTags(empty,new byte[0]);
var unsigned=new Ans104DataItem(emptyRaw);
ok(!unsigned.verifySignature(),"zero-length Avro differs from encoded empty array");
System.arraycopy(Ed25519Util.sign(unsigned.signingMessage(),SEED),0,emptyRaw,2,64);
ok(new Ans104DataItem(emptyRaw).verifySignature(),"signed zero-length tag section");
}
private static Path vectorsPath() {
for(Path p=Path.of("").toAbsolutePath();p!=null;p=p.getParent()) {
Path f=p.resolve("docs/Blockchain/vectors/core-content-v1.tsv"); if(Files.isRegularFile(f))return f;
}
throw new IllegalStateException("Не найдены golden vectors");
}
private static void checkVectors() throws Exception {
var rows=Files.readAllLines(vectorsPath()); var history=new ArrayList<CoreRecord>();
for(String row:rows.subList(1,rows.size())) {
String[] f=row.split("\t"); byte[] owner=HEX.parseHex(f[1]); byte[] c=HEX.parseHex(f[2]), h=HEX.parseHex(f[3]), p=HEX.parseHex(f[4]);
var ci=new Ans104DataItem(HEX.parseHex(f[6])); var pi=new Ans104DataItem(HEX.parseHex(f[8]));
var pair=CoreContentTransport.verifyPair(ci,HEX.parseHex(f[7]),pi,owner,NOW);
eq(pair.core().toBytes(),c,"golden CORE " + f[0]); eq(pair.core().coreHash32(),h,"golden CORE hash");
eq(pair.content().toBytes(),p,"golden CONTENT"); eq(pair.content().contentHash32(),HEX.parseHex(f[5]),"golden CONTENT hash");
eq(pi.id32(),HEX.parseHex(f[9]),"golden CONTENT ID");
eq(CoreContentTransport.sign(c,CoreContentTransport.coreTags(pair.core()),SEED).rawBytes(),ci.rawBytes(),"independent CORE signing");
eq(CoreContentTransport.sign(p,List.of(),SEED).rawBytes(),pi.rawBytes(),"independent CONTENT signing");
ContentBodyParser.parseForCreate(pair.core(),pair.content()); count++;
var core=pair.core(); eq(core.prevCoreHash32(),history.isEmpty()?ZERO:history.get(history.size()-1).coreHash32(),"global hash link");
if(core.line()!=null) eq(core.line().prevLineCoreHash32(),history.get(core.line().prevLineBlockNumber()).coreHash32(),"line hash link");
history.add(core);
}
}
private static void checkContainer() throws Exception {
var rows=Files.readAllLines(vectorsPath());
for (String row: rows.subList(1,rows.size())) {
String[] f=row.split("\t");
var ci=new Ans104DataItem(HEX.parseHex(f[6])); var pi=new Ans104DataItem(HEX.parseHex(f[8]));
byte[] raw=CoreContentContainer.pack(ci,pi);
var entry=BchBlockEntry.fromCoreContent(raw);
ok(entry.isCoreContent(),"pair entry");
eq(entry.toBytes(),raw,"container byte-identical");
eq(entry.getFrameBytes(),HEX.parseHex(f[2]),"CORE payload");
eq(entry.getHash32(),HEX.parseHex(f[3]),"CORE hash");
eq(entry.getDataItemId32(),HEX.parseHex(f[7]),"CORE ID");
eq(entry.getContentDataItem().rawBytes(),pi.rawBytes(),"signed CONTENT");
eq(entry.body.toBytes(),entry.getContentRecord().bodyBytes(),"concrete body roundtrip");
ok(entry.back32Hash32==null,"no back32");
ok(BchCryptoVerifier.verifyBlock(entry,OWNER),"pair authorized");
ok(!BchCryptoVerifier.verifyBlock(entry,new byte[32]),"wrong owner");
try { entry.getDataItem(); throw new AssertionError("legacy accessor must refuse pair"); }
catch (IllegalStateException expected) { count++; }
if(entry.body instanceof BodyHasLine l) {
int signed=entry.getCoreRecord().line().lineCode();
ok(l.lineCode()==(LineIndex.isChannel(signed)?signed:0),"internal line mapping");
ok(l.lineSeq()==BodyHasLine.UNRESOLVED_SEQUENCE,"no fabricated sequence");
eq(l.prevLineBlockHash32(),entry.getCoreRecord().line().prevLineCoreHash32(),"previous line hash");
}
byte[] badLen=raw.clone(); ByteBuffer.wrap(badLen).putInt(-1);
bad(()->BchBlockEntry.fromCoreContent(badLen),"unsigned length overflow");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,4+ci.rawBytes().length)),"missing CONTENT");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,raw.length-1)),"truncated CONTENT");
bad(()->BchBlockEntry.fromCoreContent(Arrays.copyOf(raw,raw.length+1)),"extra CONTENT byte");
byte[] changed=raw.clone(); changed[4+2]^=1;
bad(()->BchBlockEntry.fromCoreContent(changed),"CORE signature tamper");
byte[] changedContent=raw.clone(); changedContent[4+ci.rawBytes().length+2]^=1;
bad(()->BchBlockEntry.fromCoreContent(changedContent),"CONTENT signature tamper");
}
bad(()->BchBlockEntry.fromCoreContent(new byte[CoreContentContainer.MAX_CONTAINER_BYTES+1]),"oversize");
}
public static int runAll() throws Exception { count=0; checkContainer(); checkBinaryAndTransport(); checkRawTagSignatures(); checkBodies(); checkVectors(); return count; }
public static void main(String[] args) throws Exception { System.out.println("Stage A assertions passed: " + runAll()); }
}
@@ -0,0 +1,10 @@
package blockchain;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
class StageAProtocolTest {
@Test void coreContentProtocol() throws Exception {
assertTrue(StageAProtocolChecks.runAll() > 0);
}
}
@@ -84,10 +84,9 @@ final class TargetLoginFormatTest {
} }
@Test @Test
void forkZeroIsReservedButStillDecodableAsHistoricalUnknown() { void forkZeroIsRejectedByCurrentFormat() {
ReactionBody source = new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 0, 42, HASH); assertThrows(IllegalArgumentException.class,
ReactionBody parsed = new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, source.toBytes()).check(); () -> new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 0, 42, HASH));
assertEquals(0, parsed.toForkNumber());
} }
@Test @Test
@@ -108,6 +107,22 @@ final class TargetLoginFormatTest {
} }
} }
@Test
void headerV10CarriesIdentityAndArbitraryLicense() {
HeaderBody header = HeaderBody.identity("Alice@shine", INITIAL_KEY, "Лицензия 🌞", HeaderBody.PRIMARY, java.util.List.of("Bob@free"));
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, header.toBytes()).check();
assertEquals(1, parsed.version);
assertEquals("Лицензия 🌞", parsed.license);
assertEquals(HeaderBody.PRIMARY, parsed.accountType);
assertEquals(java.util.List.of("Bob@free"), parsed.previousAccounts);
assertArrayEquals(header.toBytes(), parsed.toBytes());
assertThrows(IllegalArgumentException.class,
() -> new HeaderBody(HeaderBody.SUBTYPE_COMPAT, (short) 2, header.toBytes()));
assertThrows(IllegalArgumentException.class,
() -> HeaderBody.identity("Alice@shine", INITIAL_KEY, "x".repeat(256), HeaderBody.PRIMARY, java.util.List.of()));
}
@Test @Test
void namespacedHeaderRejectsMalformedOrOversizedLogin() { void namespacedHeaderRejectsMalformedOrOversizedLogin() {
for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) { for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) {
@@ -0,0 +1,83 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class ConnectionContentBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 3;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public ConnectionContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 1 + 1 + 2 + 4 + 32, "ConnectionContentBody too short");
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected ConnectionContentBody tail");
}
public ConnectionContentBody(short subType,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
this.subType = subType;
this.version = VER;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
}
@Override public ConnectionContentBody check() {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return this;
}
@Override public byte[] toBytes() {
check();
ByteBuffer bb = ByteBuffer.allocate(BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array();
}
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static boolean isValidSubType(short st) {
int v = st & 0xFFFF;
return v == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCLOSE_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CONTACT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCONTACT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FOLLOW & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SPOUSE & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSPOUSE & 0xFFFF)
|| v == (MsgSubType.CONNECTION_PARENT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNPARENT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CHILD & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCHILD & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SIBLING & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSIBLING & 0xFFFF)
|| v == (MsgSubType.CONNECTION_KNOWN_PERSON & 0xFFFF) || v == (MsgSubType.CONNECTION_UNKNOWN_PERSON & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNCONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_SEEN & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNSEEN & 0xFFFF)
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
}
}
@@ -0,0 +1,176 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class CreateChannelContentBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final short SUBTYPE = MsgSubType.TECH_CREATE_CHANNEL;
public static final short CHANNEL_TYPE_STORIES = 0;
public static final short CHANNEL_TYPE_PUBLIC = 1;
public static final short CHANNEL_TYPE_PERSONAL = 100;
public static final short CHANNEL_TYPE_GROUP = 200;
public static final short CHANNEL_TYPE_VERSION_DEFAULT = 1;
// Минимум для создания нового канала; исторические блоки 1–3 символа читаются.
public static final int MIN_NAME_LENGTH_FOR_CREATE = 4;
private static final int MAX_NAME_LENGTH = 32;
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
public final short subType;
public final short version;
public final String channelName;
public final String channelDescription;
public final short channelTypeCode;
public final short channelTypeVersion;
public CreateChannelContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
int ver = this.version & 0xFFFF;
if (ver != (VER & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody version must be 1, got=" + ver);
}
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
}
if (bodyBytes.length < 1 + 1 + 2 + 4) {
throw new IllegalArgumentException("CreateChannelContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
if (bb.remaining() < nameLen + 2 + 4) {
throw new IllegalArgumentException("CreateChannelContentBody tail mismatch: remaining=" + bb.remaining() + " nameLen=" + nameLen);
}
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.channelName = BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName");
int descriptionLen = Short.toUnsignedInt(bb.getShort());
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
if (bb.remaining() != descriptionLen + 4) {
throw new IllegalArgumentException("CreateChannelContentBody tail mismatch: remaining=" + bb.remaining() + " descriptionLen=" + descriptionLen);
}
if (descriptionLen == 0) {
this.channelDescription = "";
} else {
byte[] descriptionBytes = new byte[descriptionLen];
bb.get(descriptionBytes);
this.channelDescription = normalizeDescription(BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription"));
}
this.channelTypeCode = bb.getShort();
this.channelTypeVersion = bb.getShort();
if (bb.remaining() != 0) {
throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
}
}
public CreateChannelContentBody(String channelName,
String channelDescription,
short channelTypeCode,
short channelTypeVersion) {
Objects.requireNonNull(channelName, "channelName == null");
this.subType = SUBTYPE;
this.version = VER;
this.channelName = channelName;
this.channelDescription = channelDescription == null ? "" : channelDescription;
this.channelTypeCode = channelTypeCode;
this.channelTypeVersion = channelTypeVersion;
}
@Override
public CreateChannelContentBody check() {
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("CreateChannelContentBody subType must be TECH_CREATE_CHANNEL(1)");
}
String normalizedName = normalizeDisplayName(channelName);
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
int cpLen = normalizedName.codePointCount(0, normalizedName.length());
if (normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
String normalizedDescription = normalizeDescription(channelDescription);
byte[] descUtf8 = normalizedDescription.getBytes(StandardCharsets.UTF_8);
if (descUtf8.length > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
int typeCode = Short.toUnsignedInt(channelTypeCode);
int typeVer = Short.toUnsignedInt(channelTypeVersion);
if (typeCode < 0 || typeCode > 0xFFFF) throw new IllegalArgumentException("channelTypeCode invalid");
if (typeVer < 0 || typeVer > 0xFFFF) throw new IllegalArgumentException("channelTypeVersion invalid");
return this;
}
/**
* Правило создания нового TECH_CREATE_CHANNEL (в отличие от чтения истории).
* check() намеренно принимает старые каналы с именами из 1–3 символов.
*/
public CreateChannelContentBody checkForCreate() {
check();
String normalizedName = normalizeDisplayName(channelName);
int length = normalizedName.codePointCount(0, normalizedName.length());
if (length < MIN_NAME_LENGTH_FOR_CREATE) {
throw new IllegalArgumentException("channelName length must be 4..32");
}
return this;
}
private static String normalizeDisplayName(String value) {
if (value == null) return "";
return value.trim().replaceAll("\\s+", " ");
}
private static String normalizeDescription(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
@Override
public byte[] toBytes() {
// Новые блоки кодируются только с именем от 4 символов.
// Исторические блоки при чтении разбираются без повторного кодирования.
checkForCreate();
byte[] nameUtf8 = normalizeDisplayName(channelName).getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("channelName utf8 len must be 1..255");
}
byte[] descriptionUtf8 = normalizeDescription(channelDescription).getBytes(StandardCharsets.UTF_8);
if (descriptionUtf8.length > MAX_DESCRIPTION_UTF8_LEN) {
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
}
int cap = 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
if (descriptionUtf8.length > 0) bb.put(descriptionUtf8);
bb.putShort(channelTypeCode);
bb.putShort(channelTypeVersion);
return bb.array();
}
}
@@ -0,0 +1,182 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class ForkContentBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
public static final short SUBTYPE = MsgSubType.TECH_FORK;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final int REASON_ROUTINE_ROTATION = 1;
public static final int REASON_POSSIBLE_COMPROMISE = 2;
public static final int REASON_CONFIRMED_COMPROMISE_ROLLBACK = 3;
public static final int REASON_RECOVERY = 4;
public static final int MAX_COMMENT_UTF8_LEN = 1024;
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
private static final int FIXED_LEN = FIXED_PAYLOAD_LEN;
public final short subType;
public final short version;
public final byte[] parentBlockchainKey32;
public final int forkPointBlockNumber;
public final byte[] forkPointBlockHash32;
public final long forkPointTimestampMs;
public final int parentTipBlockNumber;
public final byte[] parentTipBlockHash32;
public final long parentTipTimestampMs;
public final int discardedBlocksCount;
public final int reasonCode;
public final String comment;
public ForkContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody version must be 1");
}
if (bodyBytes.length < FIXED_LEN) {
throw new IllegalArgumentException("ForkContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32);
this.forkPointBlockNumber = bb.getInt();
this.forkPointBlockHash32 = new byte[32];
bb.get(this.forkPointBlockHash32);
this.forkPointTimestampMs = bb.getLong();
this.parentTipBlockNumber = bb.getInt();
this.parentTipBlockHash32 = new byte[32];
bb.get(this.parentTipBlockHash32);
this.parentTipTimestampMs = bb.getLong();
this.discardedBlocksCount = bb.getInt();
this.reasonCode = Byte.toUnsignedInt(bb.get());
int commentLen = Short.toUnsignedInt(bb.getShort());
if (commentLen > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkContentBody comment utf8 len must be <=1024");
}
if (bb.remaining() != commentLen) {
throw new IllegalArgumentException("ForkContentBody tail mismatch: remaining=" + bb.remaining() + " commentLen=" + commentLen);
}
byte[] commentBytes = new byte[commentLen];
bb.get(commentBytes);
this.comment = BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment");
}
public ForkContentBody(byte[] parentBlockchainKey32,
int forkPointBlockNumber,
byte[] forkPointBlockHash32,
long forkPointTimestampMs,
int parentTipBlockNumber,
byte[] parentTipBlockHash32,
long parentTipTimestampMs,
int discardedBlocksCount,
int reasonCode,
String comment) {
this.subType = SUBTYPE;
this.version = VER;
this.parentBlockchainKey32 = copy32(parentBlockchainKey32, "parentBlockchainKey32");
this.forkPointBlockNumber = forkPointBlockNumber;
this.forkPointBlockHash32 = copy32(forkPointBlockHash32, "forkPointBlockHash32");
this.forkPointTimestampMs = forkPointTimestampMs;
this.parentTipBlockNumber = parentTipBlockNumber;
this.parentTipBlockHash32 = copy32(parentTipBlockHash32, "parentTipBlockHash32");
this.parentTipTimestampMs = parentTipTimestampMs;
this.discardedBlocksCount = discardedBlocksCount;
this.reasonCode = reasonCode;
this.comment = normalizeComment(comment);
}
@Override
public ForkContentBody check() {
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkContentBody version must be 1");
}
require32(parentBlockchainKey32, "parentBlockchainKey32");
require32(forkPointBlockHash32, "forkPointBlockHash32");
require32(parentTipBlockHash32, "parentTipBlockHash32");
if (forkPointBlockNumber < 0) throw new IllegalArgumentException("forkPointBlockNumber < 0");
if (parentTipBlockNumber < forkPointBlockNumber) {
throw new IllegalArgumentException("parentTipBlockNumber < forkPointBlockNumber");
}
if (forkPointTimestampMs < 0) throw new IllegalArgumentException("forkPointTimestampMs < 0");
if (parentTipTimestampMs < 0) throw new IllegalArgumentException("parentTipTimestampMs < 0");
int expectedDiscarded = parentTipBlockNumber - forkPointBlockNumber;
if (discardedBlocksCount != expectedDiscarded) {
throw new IllegalArgumentException("discardedBlocksCount must equal parentTipBlockNumber - forkPointBlockNumber");
}
if (!isReasonSupported(reasonCode)) {
throw new IllegalArgumentException("Unsupported fork reasonCode=" + reasonCode);
}
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
if (commentUtf8.length > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkContentBody comment utf8 len must be <=1024");
}
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32);
bb.putLong(forkPointTimestampMs);
bb.putInt(parentTipBlockNumber);
bb.put(parentTipBlockHash32);
bb.putLong(parentTipTimestampMs);
bb.putInt(discardedBlocksCount);
bb.put((byte) reasonCode);
bb.putShort((short) commentUtf8.length);
bb.put(commentUtf8);
return bb.array();
}
public static boolean isReasonSupported(int code) {
return code == REASON_ROUTINE_ROTATION
|| code == REASON_POSSIBLE_COMPROMISE
|| code == REASON_CONFIRMED_COMPROMISE_ROLLBACK
|| code == REASON_RECOVERY;
}
private static byte[] copy32(byte[] value, String name) {
require32(value, name);
return Arrays.copyOf(value, 32);
}
private static void require32(byte[] value, String name) {
if (value == null || value.length != 32) {
throw new IllegalArgumentException(name + " must be 32 bytes");
}
}
private static String normalizeComment(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
}
@@ -0,0 +1,152 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class TextLineContentBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toLogin;
public final Integer toForkNumber;
public final Integer toBlockGlobalNumber;
public final byte[] toBlockHash32;
public final String message;
public TextLineContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.ensureMin(bb, 2, "TextLineContentBody too short");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
BodyTargetSupport.ensureMin(bb, 4 + 32 + 2, "EDIT_POST target missing");
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32]; bb.get(this.toBlockHash32);
BodyTargetSupport.validateCompact(this.toBlockGlobalNumber, this.toBlockHash32, "EDIT_POST");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "REPOST", 2);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
} else {
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
}
boolean allowEmpty = st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
this.message = readText(bb, allowEmpty);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextLineContentBody tail");
}
public TextLineContentBody(short subType,
String toLogin,
Integer toForkNumber,
Integer toBlockGlobalNumber,
byte[] toBlockHash32,
String message) {
Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody subtype");
this.subType = subType;
this.version = VER;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = toBlockHash32 == null ? null : blockchain.ProtocolHash.copy32(toBlockHash32);
this.message = message;
check();
}
@Override public TextLineContentBody check() {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineContentBody subtype");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (toLogin != null || toForkNumber != null) throw new IllegalArgumentException("EDIT_POST must not contain login/fork target");
BodyTargetSupport.validateCompact(toBlockGlobalNumber, toBlockHash32, "EDIT_POST");
if (message == null) throw new IllegalArgumentException("EDIT_POST message is null");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
if (message == null || message.isBlank()) throw new IllegalArgumentException("REPOST message is blank");
} else {
if (toLogin != null || toForkNumber != null || toBlockGlobalNumber != null || toBlockHash32 != null) {
throw new IllegalArgumentException("Non-target text body must not contain target fields");
}
if (st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
if (message == null) throw new IllegalArgumentException("CHANNEL_META message is null");
} else if (st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
if (message == null || !message.isEmpty()) throw new IllegalArgumentException("CHANNEL_DELETE message must be empty");
} else if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Text message is blank");
}
}
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
int st = subType & 0xFFFF;
int targetSize = 0;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
ByteBuffer bb = ByteBuffer.allocate(targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
}
bb.putShort((short) text.length).put(text);
return bb.array();
}
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32 == null ? null : Arrays.copyOf(toBlockHash32, 32); }
public boolean isEditPost() { return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_POST & 0xFFFF); }
private static boolean isSupportedSubType(short subType) {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF) || st == (MsgSubType.TEXT_COURSE & 0xFFFF);
}
private static String readText(ByteBuffer bb, boolean allowEmpty) {
if (bb.remaining() < 2) throw new IllegalArgumentException("Text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (len == 0) { if (allowEmpty) return ""; throw new IllegalArgumentException("Text is empty"); }
if (bb.remaining() < len) throw new IllegalArgumentException("Text payload too short");
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { String s = dec.decode(ByteBuffer.wrap(bytes)).toString(); if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException("Text blank"); return s; }
catch (CharacterCodingException e) { throw new IllegalArgumentException("Text invalid UTF-8", e); }
}
}
@@ -0,0 +1,133 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/** Смысловое тело CONTENT v1; структурные связи хранятся только в CORE. */
public final class UserParamContentBody implements BodyRecord {
public static final short TYPE = 4;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String paramKey;
public final String paramValue;
public UserParamContentBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("UserParamContentBody version must be 1, got=" + (this.version & 0xFFFF));
}
if ((this.subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
throw new IllegalArgumentException("Bad UserParam subType: " + (this.subType & 0xFFFF));
}
if (bodyBytes.length < 2 + 1 + 2 + 1) {
throw new IllegalArgumentException("UserParamContentBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
if (bb.remaining() < keyLen + 2) throw new IllegalArgumentException("UserParam key payload too short");
byte[] keyBytes = new byte[keyLen];
bb.get(keyBytes);
int valLen = Short.toUnsignedInt(bb.getShort());
if (valLen <= 0) throw new IllegalArgumentException("paramValueLen is 0");
if (bb.remaining() < valLen) throw new IllegalArgumentException("UserParam value payload too short");
byte[] valBytes = new byte[valLen];
bb.get(valBytes);
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
this.paramKey = strictUtf8(keyBytes, "paramKey");
this.paramValue = strictUtf8(valBytes, "paramValue");
if (this.paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (this.paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
}
public UserParamContentBody(String paramKey,
String paramValue) {
Objects.requireNonNull(paramKey, "paramKey == null");
Objects.requireNonNull(paramValue, "paramValue == null");
this.subType = MsgSubType.USER_PARAM_TEXT_TEXT;
this.version = VER;
if (paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
this.paramKey = paramKey;
this.paramValue = paramValue;
}
@Override
public UserParamContentBody check() {
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
throw new IllegalArgumentException("Bad UserParam subType: " + (subType & 0xFFFF));
}
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
if (paramKey.getBytes(StandardCharsets.UTF_8).length > 65535 || paramValue.getBytes(StandardCharsets.UTF_8).length > 65535)
throw new IllegalArgumentException("Profile key/value too long");
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] keyUtf8 = paramKey.getBytes(StandardCharsets.UTF_8);
byte[] valUtf8 = paramValue.getBytes(StandardCharsets.UTF_8);
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
int cap = 2 + keyUtf8.length
+ 2 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8);
bb.putShort((short) valUtf8.length);
bb.put(valUtf8);
return bb.array();
}
private static String strictUtf8(byte[] bytes, String fieldName) {
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return decoder.decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
}
@@ -29,17 +29,23 @@ public final class AppConfig {
} }
private void load() { private void load() {
boolean hasInternalConfig;
try (InputStream in = getClass().getClassLoader().getResourceAsStream("application.properties")) { try (InputStream in = getClass().getClassLoader().getResourceAsStream("application.properties")) {
if (in == null) { hasInternalConfig = in != null;
throw new RuntimeException("Config file application.properties not found"); if (hasInternalConfig) {
}
properties.load(in); properties.load(in);
}
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Failed to load application.properties", e); throw new RuntimeException("Failed to load application.properties", e);
} }
Path externalConfig = Paths.get("application.properties"); Path externalConfig = Paths.get("application.properties");
if (!Files.isRegularFile(externalConfig)) { if (!Files.isRegularFile(externalConfig)) {
if (!hasInternalConfig || Files.exists(externalConfig)) {
throw new IllegalStateException("External application.properties missing or not a regular file: "
+ externalConfig.toAbsolutePath()
+ "; copy application.properties.example to the server working directory");
}
return; return;
} }
@@ -31,6 +31,16 @@ public final class DatabaseInitializer {
public static final int SCHEMA_VERSION_38 = 38; public static final int SCHEMA_VERSION_38 = 38;
public static final int SCHEMA_VERSION_39 = 39; public static final int SCHEMA_VERSION_39 = 39;
public static final int SCHEMA_VERSION_40 = 40; public static final int SCHEMA_VERSION_40 = 40;
public static final int SCHEMA_VERSION_41 = 41;
public static final int SCHEMA_VERSION_42 = 42;
public static final int SCHEMA_VERSION_43 = 43;
public static final int SCHEMA_VERSION_44 = 44;
public static final int SCHEMA_VERSION_45 = 45;
public static final int SCHEMA_VERSION_46 = 46;
public static final int SCHEMA_VERSION_47 = 47;
public static final int SCHEMA_VERSION_48 = 48;
public static final int SCHEMA_VERSION_49 = 49;
public static final int SCHEMA_VERSION_50 = 50;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql"; public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql"; public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql"; public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
@@ -42,6 +52,16 @@ public final class DatabaseInitializer {
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.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_V39_RESOURCE = "postgres/migration_v39.sql";
public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql"; public static final String POSTGRES_MIGRATION_V40_RESOURCE = "postgres/migration_v40.sql";
public static final String POSTGRES_MIGRATION_V41_RESOURCE = "postgres/migration_v41.sql";
public static final String POSTGRES_MIGRATION_V42_RESOURCE = "postgres/migration_v42.sql";
public static final String POSTGRES_MIGRATION_V43_RESOURCE = "postgres/migration_v43.sql";
public static final String POSTGRES_MIGRATION_V44_RESOURCE = "postgres/migration_v44.sql";
public static final String POSTGRES_MIGRATION_V45_RESOURCE = "postgres/migration_v45.sql";
public static final String POSTGRES_MIGRATION_V46_RESOURCE = "postgres/migration_v46.sql";
public static final String POSTGRES_MIGRATION_V47_RESOURCE = "postgres/migration_v47.sql";
public static final String POSTGRES_MIGRATION_V49_RESOURCE = "postgres/migration_v49.sql";
public static final String POSTGRES_MIGRATION_V48_RESOURCE = "postgres/migration_v48.sql";
public static final String POSTGRES_MIGRATION_V50_RESOURCE = "postgres/migration_v50.sql";
private DatabaseInitializer() {} private DatabaseInitializer() {}
@@ -173,9 +193,49 @@ public final class DatabaseInitializer {
runSqlScript(conn, POSTGRES_MIGRATION_V40_RESOURCE); runSqlScript(conn, POSTGRES_MIGRATION_V40_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn); currentVersion = readCurrentSchemaVersion(conn);
} }
if (currentVersion != SCHEMA_VERSION_40) { if (currentVersion == SCHEMA_VERSION_40) {
runSqlScript(conn, POSTGRES_MIGRATION_V41_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_41) {
runSqlScript(conn, POSTGRES_MIGRATION_V42_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_42) {
runSqlScript(conn, POSTGRES_MIGRATION_V43_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_43) {
runSqlScript(conn, POSTGRES_MIGRATION_V44_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_44) {
runSqlScript(conn, POSTGRES_MIGRATION_V45_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_45) {
runSqlScript(conn, POSTGRES_MIGRATION_V46_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_46) {
runSqlScript(conn, POSTGRES_MIGRATION_V47_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_47) {
runSqlScript(conn, POSTGRES_MIGRATION_V48_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_48) {
runSqlScript(conn, POSTGRES_MIGRATION_V49_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion == SCHEMA_VERSION_49) {
runSqlScript(conn, POSTGRES_MIGRATION_V50_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion != SCHEMA_VERSION_50) {
throw new SQLException( throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 40, found " + currentVersion); "Unsupported SHiNE DB v2 schema version: expected 50, found " + currentVersion);
} }
normalizeBlockchainStateKeysToBase64(conn); normalizeBlockchainStateKeysToBase64(conn);
} }
@@ -0,0 +1,119 @@
package shine.db.dao;
import shine.db.DbController;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/** Состояние внешней публикации не влияет на уже принятую цепочку. */
public final class BlockPublicationsDAO {
private static final BlockPublicationsDAO INSTANCE = new BlockPublicationsDAO();
private final DbController db = DbController.getInstance();
private BlockPublicationsDAO() {}
public static BlockPublicationsDAO getInstance() { return INSTANCE; }
public record Row(String login, int fork, int number, String coreId, String contentId,
byte[] coreHash, byte[] contentHash, String status, boolean contentConfirmed,
boolean coreConfirmed, long receivedAt, int attempts, String lastError) {}
private static Row row(ResultSet rs) throws SQLException {
return new Row(rs.getString("login"), rs.getInt("fork_number"), rs.getInt("block_number"),
rs.getString("core_id"), rs.getString("content_id"), rs.getBytes("core_hash"),
rs.getBytes("content_hash"), rs.getString("status"),
rs.getObject("content_confirmed_at_ms") != null, rs.getObject("core_confirmed_at_ms") != null,
rs.getLong("first_received_at_ms"), rs.getInt("attempts"), rs.getString("last_error"));
}
public Row get(String login, int fork, int number) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE login=? AND fork_number=? AND block_number=?")) {
ps.setString(1, login); ps.setInt(2, fork); ps.setInt(3, number);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? row(rs) : null; }
}
}
public List<Row> pending(String login, int fork, int limit) throws SQLException {
List<Row> out = new ArrayList<>();
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE login=? AND fork_number=? AND status <> 'ARWEAVE_CONFIRMED' AND status <> 'TURBO_CONFIRMED' ORDER BY block_number LIMIT ?")) {
ps.setString(1, login); ps.setInt(2, fork); ps.setInt(3, limit);
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(row(rs)); }
}
return out;
}
public List<Row> due(int limit, long now) throws SQLException {
List<Row> out = new ArrayList<>();
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(
"SELECT * FROM block_publications WHERE status <> 'ARWEAVE_CONFIRMED' AND status <> 'TURBO_CONFIRMED' AND (next_retry_at_ms IS NULL OR next_retry_at_ms<=?) ORDER BY first_received_at_ms LIMIT ?")) {
ps.setLong(1, now); ps.setInt(2, limit);
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(row(rs)); }
}
return out;
}
public void attempted(Row r, String error, long now) throws SQLException {
try (Connection c = db.getConnection()) {
c.setAutoCommit(false);
try (PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET attempts=attempts+1,last_attempt_at_ms=?,last_error=?,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status NOT IN ('TURBO_CONFIRMED','ARWEAVE_CONFIRMED')
""")) {
ps.setLong(1, now); ps.setString(2, error); ps.setLong(3, now + 30_000L);
ps.setString(4, r.login()); ps.setInt(5, r.fork()); ps.setInt(6, r.number()); ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("INSERT INTO block_publication_attempts(login,fork_number,block_number,attempted_at_ms,outcome) VALUES(?,?,?,?,?)")) {
ps.setString(1, r.login()); ps.setInt(2, r.fork()); ps.setInt(3, r.number()); ps.setLong(4, now);
ps.setString(5, error == null ? "client_report" : error); ps.executeUpdate();
}
c.commit();
}
}
public void clientReported(Row r, String error, long now) throws SQLException {
String status = error == null || error.isBlank() ? "TURBO_SUBMITTED" : "FAILED_RETRYABLE";
try (Connection c = db.getConnection()) {
c.setAutoCommit(false);
try (PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET status=?,attempts=attempts+1,last_attempt_at_ms=?,last_error=?,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status NOT IN ('TURBO_CONFIRMED','ARWEAVE_CONFIRMED')
""")) {
ps.setString(1, status); ps.setLong(2, now); ps.setString(3, error);
ps.setLong(4, now); ps.setString(5, r.login()); ps.setInt(6, r.fork()); ps.setInt(7, r.number());
ps.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("INSERT INTO block_publication_attempts(login,fork_number,block_number,attempted_at_ms,outcome) VALUES(?,?,?,?,?)")) {
ps.setString(1, r.login()); ps.setInt(2, r.fork()); ps.setInt(3, r.number()); ps.setLong(4, now);
ps.setString(5, status + (error == null || error.isBlank() ? "" : ": " + error)); ps.executeUpdate();
}
c.commit();
}
}
public void verified(Row r, boolean content, boolean core, long now) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET
content_confirmed_at_ms=CASE WHEN ? THEN COALESCE(content_confirmed_at_ms,?) ELSE content_confirmed_at_ms END,
core_confirmed_at_ms=CASE WHEN ? THEN COALESCE(core_confirmed_at_ms,?) ELSE core_confirmed_at_ms END,
status=CASE WHEN (content_confirmed_at_ms IS NOT NULL OR ?) AND (core_confirmed_at_ms IS NOT NULL OR ?)
THEN 'TURBO_CONFIRMED' ELSE 'PENDING_TURBO' END,
last_error=NULL,next_retry_at_ms=?
WHERE login=? AND fork_number=? AND block_number=? AND status <> 'ARWEAVE_CONFIRMED'
""")) {
ps.setBoolean(1, content); ps.setLong(2, now); ps.setBoolean(3, core); ps.setLong(4, now);
ps.setBoolean(5, content); ps.setBoolean(6, core); ps.setLong(7, now + 30_000L);
ps.setString(8, r.login()); ps.setInt(9, r.fork()); ps.setInt(10, r.number()); ps.executeUpdate();
}
}
public void arweaveConfirmed(String login, int fork, int number, long now) throws SQLException {
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE block_publications SET status='ARWEAVE_CONFIRMED',arweave_confirmed_at_ms=?,
content_confirmed_at_ms=COALESCE(content_confirmed_at_ms,?),core_confirmed_at_ms=COALESCE(core_confirmed_at_ms,?)
WHERE login=? AND fork_number=? AND block_number=?
""")) {
ps.setLong(1, now); ps.setLong(2, now); ps.setLong(3, now);
ps.setString(4, login); ps.setInt(5, fork); ps.setInt(6, number); ps.executeUpdate();
}
}
}
@@ -87,6 +87,7 @@ public final class BlockchainResyncCleanupDAO {
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){ try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate(); ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
} }
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,ref.login());ps.execute();}
c.commit(); c.commit();
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState); return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); } }catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
@@ -214,6 +215,7 @@ public final class BlockchainResyncCleanupDAO {
) )
""")){ps.setString(1,login);ps.executeUpdate();} """)){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,login);ps.execute();}
// Recompute all message aggregates whose target belongs to this user. This also fixes // Recompute all message aggregates whose target belongs to this user. This also fixes
// external reactions/replies that intentionally survive this user's rebuild. // external reactions/replies that intentionally survive this user's rebuild.
try(PreparedStatement ps=c.prepareStatement(""" try(PreparedStatement ps=c.prepareStatement("""
@@ -187,10 +187,27 @@ public final class BlockchainStateDAO {
} }
} }
/** Change ONLY the quota projection; 0 means unbounded. */
public void updateSizeLimit(String blockchainName, long limit) throws SQLException {
if (limit < 0L) throw new IllegalArgumentException("limit must be nonnegative");
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement("""
UPDATE blockchain_state_store SET size_limit = ?, updated_at_ms = ?
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
""")) {
ChainRef r = chainRef(blockchainName);
ps.setLong(1, limit);
ps.setLong(2, System.currentTimeMillis());
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.executeUpdate();
}
}
/** /**
* Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit. * Атомарно увеличить file_size_bytes на deltaBytes, но только если НЕ превысим size_limit.
*/ */
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException { public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
if (deltaBytes < 0L) throw new IllegalArgumentException("deltaBytes must be nonnegative");
String sql = """ String sql = """
UPDATE blockchain_state_store UPDATE blockchain_state_store
SET SET
@@ -198,7 +215,8 @@ public final class BlockchainStateDAO {
updated_at_ms = ? updated_at_ms = ?
WHERE WHERE
LOWER(login) = LOWER(?) AND fork_number = ? LOWER(login) = LOWER(?) AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit AND file_size_bytes <= 9223372036854775807 - ?
AND (size_limit = 0 OR (file_size_bytes + ?) <= size_limit)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -208,6 +226,7 @@ public final class BlockchainStateDAO {
ps.setString(3, r.login()); ps.setString(3, r.login());
ps.setInt(4, r.fork()); ps.setInt(4, r.fork());
ps.setLong(5, deltaBytes); ps.setLong(5, deltaBytes);
ps.setLong(6, deltaBytes);
return ps.executeUpdate() > 0; return ps.executeUpdate() > 0;
} }
} }
@@ -9,7 +9,7 @@ import java.sql.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** DAO for SHiNE Frame v1 blocks. block_bytes contains the complete ANS-104 DataItem. */ /** DAO for SHiNE blocks. block_bytes contains the complete signed CORE/CONTENT container. */
public final class BlocksDAO { public final class BlocksDAO {
private static volatile BlocksDAO instance; private static volatile BlocksDAO instance;
private final DbController db = DbController.getInstance(); private final DbController db = DbController.getInstance();
@@ -22,14 +22,19 @@ public final class BlocksDAO {
} }
public void insert(Connection c, BlockEntry e) throws SQLException { public void insert(Connection c, BlockEntry e) throws SQLException {
insert(c, e, null, null);
}
public void insert(Connection c, BlockEntry e, Integer accountType, List<String> previousAccounts) throws SQLException {
String sql = """ String sql = """
INSERT INTO blocks_store ( INSERT INTO blocks_store (
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes, login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash, to_login,to_fork_number,to_block_number,to_block_hash,
block_hash,block_signature,data_item_id, block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms, arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number,
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) header_account_type,header_previous_accounts
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1; int i = 1;
@@ -53,12 +58,31 @@ public final class BlocksDAO {
setNullableInt(ps, i++, e.getPrevLineNumber()); setNullableInt(ps, i++, e.getPrevLineNumber());
setNullableBytes(ps, i++, e.getPrevLineHash()); setNullableBytes(ps, i++, e.getPrevLineHash());
setNullableInt(ps, i++, e.getThisLineNumber()); setNullableInt(ps, i++, e.getThisLineNumber());
if (accountType == null) {
ps.setNull(i++, Types.SMALLINT); ps.setNull(i, Types.ARRAY);
} else {
ps.setInt(i++, accountType);
ps.setArray(i, c.createArrayOf("text", previousAccounts.toArray(String[]::new)));
}
ps.executeUpdate(); ps.executeUpdate();
} }
} }
public void insert(BlockEntry e) throws SQLException { try (Connection c = db.getConnection()) { insert(c, e); } } public void insert(BlockEntry e) throws SQLException { try (Connection c = db.getConnection()) { insert(c, e); } }
public void insertPublication(Connection c, BlockEntry e, byte[] contentId, byte[] contentHash,
byte[] owner, byte[] prevCoreHash, long receivedAtMs) throws SQLException {
String sql = "INSERT INTO block_publications(login,fork_number,block_number,core_id,content_id,core_hash,content_hash,owner,prev_core_hash,first_received_at_ms) VALUES(?,?,?,?,?,?,?,?,?,?)";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, e.getLogin()); ps.setInt(2, e.getForkNumber()); ps.setInt(3, e.getBlockNumber());
ps.setString(4, java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(e.getDataItemId()));
ps.setString(5, java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(contentId));
ps.setBytes(6, e.getBlockHash()); ps.setBytes(7, contentHash);
ps.setBytes(8, owner); ps.setBytes(9, prevCoreHash); ps.setLong(10, receivedAtMs);
ps.executeUpdate();
}
}
public boolean existsByDataItemId(byte[] dataItemId) throws SQLException { public boolean existsByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return false; if (dataItemId == null || dataItemId.length != 32) return false;
try (Connection c = db.getConnection(); try (Connection c = db.getConnection();
@@ -68,6 +92,14 @@ public final class BlocksDAO {
} }
} }
public BlockEntry getByDataItemId(byte[] id) throws SQLException {
String sql = baseSelect() + " WHERE data_item_id=? LIMIT 1";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBytes(1, id);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? mapRow(rs) : null; }
}
}
/** Возвращает ещё не опубликованный пользовательский DataItem для быстрой Turbo-попытки. */ /** Возвращает ещё не опубликованный пользовательский DataItem для быстрой Turbo-попытки. */
public BlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException { public BlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return null; if (dataItemId == null || dataItemId.length != 32) return null;
@@ -67,12 +67,53 @@ public final class ChannelNameStateDAO {
channel_root_block_hash, channel_root_block_hash,
created_at_ms, created_at_ms,
ava_ar, ava_ar,
ava_sha256, ava_pr,
ava_size, ava_size,
meta_updated_at_ms meta_updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
bindInsert(ps, entry);
ps.executeUpdate();
}
}
/**
* Используется только при воспроизведении уже подписанной истории. В live AddBlock
* дубликат имени запрещён; при replay блок всё же нужно сохранить, иначе цепочка
* после него останется разорванной.
*/
public void insertOrReplaceWithNewerRoot(Connection c, ChannelNameStateEntry entry) throws SQLException {
String sql = """
INSERT INTO channel_names_state (
slug, display_name, channel_description, owner_login, owner_bch_name,
channel_type_code, channel_type_version, channel_root_block_number,
channel_root_block_hash, created_at_ms, ava_ar, ava_pr, ava_size, meta_updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (owner_bch_name, channel_type_code, slug) DO UPDATE SET
display_name = EXCLUDED.display_name,
channel_description = EXCLUDED.channel_description,
owner_login = EXCLUDED.owner_login,
channel_type_version = EXCLUDED.channel_type_version,
channel_root_block_number = EXCLUDED.channel_root_block_number,
channel_root_block_hash = EXCLUDED.channel_root_block_hash,
created_at_ms = EXCLUDED.created_at_ms,
ava_ar = EXCLUDED.ava_ar,
ava_pr = EXCLUDED.ava_pr,
ava_size = EXCLUDED.ava_size,
meta_updated_at_ms = EXCLUDED.meta_updated_at_ms,
is_deleted = FALSE,
deleted_at_ms = 0,
deleted_block_number = NULL
WHERE EXCLUDED.channel_root_block_number > channel_names_state.channel_root_block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
bindInsert(ps, entry);
ps.executeUpdate();
}
}
private static void bindInsert(PreparedStatement ps, ChannelNameStateEntry entry) throws SQLException {
ps.setString(1, entry.getSlug()); ps.setString(1, entry.getSlug());
ps.setString(2, entry.getDisplayName()); ps.setString(2, entry.getDisplayName());
ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription()); ps.setString(3, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
@@ -84,11 +125,9 @@ public final class ChannelNameStateDAO {
ps.setBytes(9, entry.getChannelRootBlockHash()); ps.setBytes(9, entry.getChannelRootBlockHash());
ps.setLong(10, entry.getCreatedAtMs()); ps.setLong(10, entry.getCreatedAtMs());
ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr()); ps.setString(11, entry.getAvaAr() == null ? "" : entry.getAvaAr());
ps.setString(12, entry.getAvaSha256() == null ? "" : entry.getAvaSha256()); ps.setString(12, entry.getAvaPr() == null ? "" : entry.getAvaPr());
ps.setLong(13, Math.max(0L, entry.getAvaSize())); ps.setLong(13, Math.max(0L, entry.getAvaSize()));
ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs())); ps.setLong(14, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.executeUpdate();
}
} }
public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException { public void updateMeta(Connection c, ChannelNameStateEntry entry) throws SQLException {
@@ -97,7 +136,7 @@ public final class ChannelNameStateDAO {
SET display_name = ?, SET display_name = ?,
channel_description = ?, channel_description = ?,
ava_ar = ?, ava_ar = ?,
ava_sha256 = ?, ava_pr = ?,
ava_size = ?, ava_size = ?,
meta_updated_at_ms = ? meta_updated_at_ms = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ? WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
@@ -106,7 +145,7 @@ public final class ChannelNameStateDAO {
ps.setString(1, entry.getDisplayName() == null ? "" : entry.getDisplayName()); ps.setString(1, entry.getDisplayName() == null ? "" : entry.getDisplayName());
ps.setString(2, entry.getChannelDescription() == null ? "" : entry.getChannelDescription()); ps.setString(2, entry.getChannelDescription() == null ? "" : entry.getChannelDescription());
ps.setString(3, entry.getAvaAr() == null ? "" : entry.getAvaAr()); ps.setString(3, entry.getAvaAr() == null ? "" : entry.getAvaAr());
ps.setString(4, entry.getAvaSha256() == null ? "" : entry.getAvaSha256()); ps.setString(4, entry.getAvaPr() == null ? "" : entry.getAvaPr());
ps.setLong(5, Math.max(0L, entry.getAvaSize())); ps.setLong(5, Math.max(0L, entry.getAvaSize()));
ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs())); ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.setString(7, entry.getOwnerLogin()); ps.setString(7, entry.getOwnerLogin());
@@ -21,6 +21,16 @@ public final class ChannelReadStateDAO {
private ChannelReadStateDAO() {} private ChannelReadStateDAO() {}
// Корневой канал существует виртуально даже до появления Header. Никаких записей CreateChannel.
private static final String PUBLIC_CHANNELS = """
public_channels AS (
SELECT owner_login, slug, channel_root_block_number, channel_root_block_hash, is_deleted
FROM channel_names_state WHERE channel_type_code=1 AND slug<>'stories'
UNION ALL
SELECT login, 'stories', 0, NULL::bytea, FALSE FROM user_identity_current
)
""";
public static ChannelReadStateDAO getInstance() { public static ChannelReadStateDAO getInstance() {
if (instance == null) { if (instance == null) {
synchronized (ChannelReadStateDAO.class) { synchronized (ChannelReadStateDAO.class) {
@@ -64,22 +74,21 @@ public final class ChannelReadStateDAO {
} }
public long sumUnreadCount(Connection c, String viewerLogin) throws SQLException { public long sumUnreadCount(Connection c, String viewerLogin) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT COALESCE(SUM(crs.unread_count),0) SELECT COALESCE(SUM(crs.unread_count),0)
FROM channel_read_state crs FROM channel_read_state crs
WHERE LOWER(crs.viewer_login)=LOWER(?) WHERE LOWER(crs.viewer_login)=LOWER(?)
AND EXISTS ( AND EXISTS (
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login) ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=30 AND cs.rel_type=30
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login) WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
AND NOT cns.is_deleted AND NOT cns.is_deleted
) )
"""; """;
@@ -96,18 +105,17 @@ public final class ChannelReadStateDAO {
*/ */
public boolean hasActiveSubscription(Connection c, String viewerLogin, String ownerBchName, String channelName, public boolean hasActiveSubscription(Connection c, String viewerLogin, String ownerBchName, String channelName,
int followRelType) throws SQLException { int followRelType) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(?) ON LOWER(cs.login)=LOWER(?)
AND cs.rel_type=? AND cs.rel_type=?
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(?) WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.slug=? AND cns.slug=?
AND cns.channel_type_code=1
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -122,10 +130,10 @@ public final class ChannelReadStateDAO {
} }
public String resolvePublicChannelNameByRoot(Connection c, String ownerBchName, int rootBlockNumber) throws SQLException { public String resolvePublicChannelNameByRoot(Connection c, String ownerBchName, int rootBlockNumber) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT slug SELECT slug
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -139,10 +147,10 @@ public final class ChannelReadStateDAO {
public Integer resolvePublicChannelRootByName(Connection c, String ownerBchName, String channelName) throws SQLException { public Integer resolvePublicChannelRootByName(Connection c, String ownerBchName, String channelName) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT channel_root_block_number SELECT channel_root_block_number
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND slug=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -155,10 +163,10 @@ public final class ChannelReadStateDAO {
} }
public String resolveOwnerLogin(Connection c, String ownerBchName, String channelName) throws SQLException { public String resolveOwnerLogin(Connection c, String ownerBchName, String channelName) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
SELECT owner_login SELECT owner_login
FROM channel_names_state FROM public_channels
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1 WHERE LOWER(owner_login)=LOWER(?) AND slug=?
LIMIT 1 LIMIT 1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -242,7 +250,7 @@ public final class ChannelReadStateDAO {
String channelName, String channelName,
int followRelType, int followRelType,
long nowMs) throws SQLException { long nowMs) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
UPDATE channel_read_state crs UPDATE channel_read_state crs
SET unread_count = crs.unread_count + 1, SET unread_count = crs.unread_count + 1,
updated_at_ms = ? updated_at_ms = ?
@@ -251,16 +259,15 @@ public final class ChannelReadStateDAO {
AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login) AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login)
AND EXISTS ( AND EXISTS (
SELECT 1 SELECT 1
FROM channel_names_state cns FROM public_channels cns
JOIN connections_state cs JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login) ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=? AND cs.rel_type=?
AND LOWER(cs.to_login)=LOWER(cns.owner_login) AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash AND (cns.channel_root_block_number=0 OR cs.to_block_hash=cns.channel_root_block_hash)
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login) WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
) )
RETURNING viewer_login RETURNING viewer_login
"""; """;
@@ -280,15 +287,14 @@ public final class ChannelReadStateDAO {
/** Delete the projection row when a channel FOLLOW is explicitly removed. */ /** Delete the projection row when a channel FOLLOW is explicitly removed. */
public boolean deleteForUnfollowTarget(Connection c, String viewerLogin, String ownerBchName, public boolean deleteForUnfollowTarget(Connection c, String viewerLogin, String ownerBchName,
int rootBlockNumber) throws SQLException { int rootBlockNumber) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + """
DELETE FROM channel_read_state crs DELETE FROM channel_read_state crs
USING channel_names_state cns USING public_channels cns
WHERE LOWER(crs.viewer_login)=LOWER(?) WHERE LOWER(crs.viewer_login)=LOWER(?)
AND LOWER(crs.owner_login)=LOWER(?) AND LOWER(crs.owner_login)=LOWER(?)
AND LOWER(cns.owner_login)=LOWER(crs.owner_login) AND LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name AND cns.slug=crs.channel_name
AND cns.channel_root_block_number=? AND cns.channel_root_block_number=?
AND cns.channel_type_code=1
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin); ps.setString(1, viewerLogin);
@@ -299,24 +305,27 @@ public final class ChannelReadStateDAO {
} }
/** /**
* Recomputes server-owned unread counters for all public channels owned by one logical login. * Recomputes server-owned unread counters for all public channels owned by one logical login.
* Signed read_count/read signature fields are preserved exactly. Safe to call repeatedly after replay. * Clamp the effective read_count to the rebuilt history; invalidate a signature
* when its stored count changes. Keep the last accepted timestamp to reject stale requests.
*/ */
public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException { public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException {
String sql = """ String sql = "WITH " + PUBLIC_CHANNELS + ", " + """
WITH counts AS ( counts AS (
SELECT cns.owner_login, cns.slug, COUNT(b.block_number)::BIGINT AS message_count SELECT cns.owner_login, cns.slug, COUNT(b.block_number)::BIGINT AS message_count
FROM channel_names_state cns FROM public_channels cns
LEFT JOIN blocks_store b LEFT JOIN blocks_store b
ON LOWER(b.login)=LOWER(cns.owner_login) ON LOWER(b.login)=LOWER(cns.owner_login)
AND b.line_code=cns.channel_root_block_number AND b.line_code=cns.channel_root_block_number
AND b.msg_type=1 AND b.msg_type=1
AND b.msg_sub_type IN (10,50,100,110,120,130) AND b.msg_sub_type IN (10,50,100,110,120,130)
AND b.fork_number=shine_active_fork(b.login,b.block_number)
WHERE LOWER(cns.owner_login)=LOWER(?) WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.channel_type_code=1
GROUP BY cns.owner_login,cns.slug GROUP BY cns.owner_login,cns.slug
) )
UPDATE channel_read_state crs UPDATE channel_read_state crs
SET unread_count=GREATEST(0, counts.message_count-crs.read_count), SET unread_count=GREATEST(0, counts.message_count-crs.read_count),
read_count=LEAST(crs.read_count, counts.message_count),
read_signature=CASE WHEN crs.read_count>counts.message_count THEN '' ELSE crs.read_signature END,
updated_at_ms=? updated_at_ms=?
FROM counts FROM counts
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login) WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
@@ -13,7 +13,7 @@ public final class ChannelSearchDAO {
private ChannelSearchDAO() {} private ChannelSearchDAO() {}
public record Match(String ownerLogin, String slug, String displayName, String description, public record Match(String ownerLogin, String slug, String displayName, String description,
String avatarAr, String avatarSha256, String ownerBlockchainName, String avatarAr, String avatarPr, String ownerBlockchainName,
int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {} int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {}
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально. // LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
@@ -45,7 +45,7 @@ public final class ChannelSearchDAO {
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%"; String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
String sql = """ String sql = """
SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description, SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description,
cn.ava_ar, cn.ava_sha256, cn.owner_bch_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash, cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash,
COALESCE(cs.subscribers_count, 0) AS subscribers_count COALESCE(cs.subscribers_count, 0) AS subscribers_count
FROM channel_names_state cn FROM channel_names_state cn
@@ -109,7 +109,7 @@ public final class ChannelSearchDAO {
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) matches.add(new Match( while (rs.next()) matches.add(new Match(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"),
rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_sha256"), rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_pr"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"),
rs.getString("root_hash"), rs.getInt("subscribers_count") rs.getString("root_hash"), rs.getInt("subscribers_count")
)); ));
@@ -73,10 +73,26 @@ public final class SolanaUserPdaCurrentDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName); ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) { if (rs.next()) return mapRow(rs);
return null;
} }
return mapRow(rs); }
// Old forks remain valid separate blockchains even after root rotation.
String forkSql = """
SELECT u.login,
u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0') AS blockchain_name,
f.value ->> 'blockchainKey' AS blockchain_key,
(f.value ->> 'paidLimitBytes')::bigint AS paid_limit_bytes
FROM solana_user_pda_current u
CROSS JOIN LATERAL jsonb_array_elements(
COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb
) AS f(value)
WHERE LOWER(u.login || '-' || LPAD(((f.value ->> 'forkIndex')::integer + 1)::text, 3, '0')) = LOWER(?)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(forkSql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
} }
} }
} }
@@ -1,104 +0,0 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.entities.SyncServerEntry;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* DAO локальной таблицы серверов-партнёров для будущей межсерверной синхронизации.
*/
public final class SyncServersDAO {
private static volatile SyncServersDAO instance;
private final DbController db = DbController.getInstance();
private SyncServersDAO() {}
public static SyncServersDAO getInstance() {
if (instance == null) {
synchronized (SyncServersDAO.class) {
if (instance == null) instance = new SyncServersDAO();
}
}
return instance;
}
public List<SyncServerEntry> listAll() throws SQLException {
try (Connection c = db.getConnection()) {
return listAll(c);
}
}
public List<SyncServerEntry> listAll(Connection c) throws SQLException {
String sql = """
SELECT login, server_address, updated_at_ms
FROM sync_servers
ORDER BY login
""";
List<SyncServerEntry> result = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
result.add(mapRow(rs));
}
}
return result;
}
/**
* Полностью заменяет список партнёров актуальным снимком из Solana PDA.
*/
public void replaceAll(List<SyncServerEntry> entries) throws SQLException {
try (Connection c = db.getConnection()) {
replaceAll(c, entries);
}
}
public void replaceAll(Connection c, List<SyncServerEntry> entries) throws SQLException {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try (Statement st = c.createStatement()) {
st.executeUpdate("DELETE FROM sync_servers");
String sql = """
INSERT INTO sync_servers (
login, server_address, updated_at_ms
) VALUES (?, ?, ?)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
for (SyncServerEntry entry : entries) {
ps.setString(1, entry.getLogin());
ps.setString(2, safe(entry.getServerAddress()));
ps.setLong(3, entry.getUpdatedAtMs());
ps.addBatch();
}
ps.executeBatch();
}
c.commit();
} catch (Exception e) {
try { c.rollback(); } catch (Exception ignored) {}
if (e instanceof SQLException sqlEx) throw sqlEx;
throw new SQLException("Не удалось обновить таблицу sync_servers", e);
} finally {
try { c.setAutoCommit(oldAutoCommit); } catch (Exception ignored) {}
}
}
private SyncServerEntry mapRow(ResultSet rs) throws SQLException {
SyncServerEntry entry = new SyncServerEntry();
entry.setLogin(rs.getString("login"));
entry.setServerAddress(rs.getString("server_address"));
entry.setUpdatedAtMs(rs.getLong("updated_at_ms"));
return entry;
}
private static String safe(String value) {
return value == null ? "" : value;
}
}
@@ -10,6 +10,7 @@ import java.sql.SQLException;
import java.sql.Types; import java.sql.Types;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Locale;
public final class UserNotificationsStateDAO { public final class UserNotificationsStateDAO {
private static volatile UserNotificationsStateDAO instance; private static volatile UserNotificationsStateDAO instance;
@@ -45,7 +46,7 @@ public final class UserNotificationsStateDAO {
"""; """;
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1; int i = 1;
ps.setString(i++, e.getOwnerLogin()); ps.setString(i++, normalizedLogin(e.getOwnerLogin()));
ps.setString(i++, e.getNotificationKind()); ps.setString(i++, e.getNotificationKind());
ps.setLong(i++, e.getCreatedAtMs()); ps.setLong(i++, e.getCreatedAtMs());
ps.setString(i++, e.getSourceLogin()); ps.setString(i++, e.getSourceLogin());
@@ -74,7 +75,7 @@ public final class UserNotificationsStateDAO {
"""; """;
List<UserNotificationEntry> out = new ArrayList<>(); List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(1, normalizedLogin(ownerLogin));
ps.setString(2, kind); ps.setString(2, kind);
ps.setInt(3, Math.max(1, limit)); ps.setInt(3, Math.max(1, limit));
try (ResultSet rs = ps.executeQuery()) { try (ResultSet rs = ps.executeQuery()) {
@@ -96,7 +97,7 @@ public final class UserNotificationsStateDAO {
"""; """;
List<UserNotificationEntry> out = new ArrayList<>(); List<UserNotificationEntry> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs)); ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
ps.setLong(4, Math.max(0, cutoffMs)); ps.setLong(4, Math.max(0, cutoffMs));
try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); } try (ResultSet rs = ps.executeQuery()) { while (rs.next()) out.add(mapRow(rs)); }
} }
@@ -106,7 +107,7 @@ public final class UserNotificationsStateDAO {
public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException { public long countUnseen(Connection c, String ownerLogin, String kind, long seenAtMs) throws SQLException {
String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?"; String sql = "SELECT COUNT(*) FROM user_notifications_state WHERE owner_login = ? AND notification_kind = ? AND created_at_ms > ?";
try (PreparedStatement ps = c.prepareStatement(sql)) { try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs)); ps.setString(1, normalizedLogin(ownerLogin)); ps.setString(2, kind); ps.setLong(3, Math.max(0, seenAtMs));
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; } try (ResultSet rs = ps.executeQuery()) { return rs.next() ? rs.getLong(1) : 0L; }
} }
} }
@@ -129,4 +130,12 @@ public final class UserNotificationsStateDAO {
e.setSourceText(rs.getString("source_text")); e.setSourceText(rs.getString("source_text"));
return e; return e;
} }
/**
* owner_login — технический FK на normalized_login. Исходный регистр остаётся
* в полях подписанного блока и в отображаемых source/target login.
*/
private static String normalizedLogin(String login) {
return login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
} }
@@ -37,6 +37,8 @@ public final class UserParamsDAO {
// -------------------- UPSERT (IF NEWER) -------------------- // -------------------- UPSERT (IF NEWER) --------------------
public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException { public int upsertIfNewer(Connection c, UserParamEntry e) throws SQLException {
if ("gender".equalsIgnoreCase(e.getParam())) return 0;
if ("account_role".equalsIgnoreCase(e.getParam()) && hasDeclaredIdentity(c, e.getLogin())) return 0;
String sql = """ String sql = """
INSERT INTO users_params ( INSERT INTO users_params (
login, login,
@@ -108,9 +110,17 @@ public final class UserParamsDAO {
} }
} }
public static boolean hasDeclaredIdentity(Connection c, String login) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT 1 FROM account_identity_state WHERE login=LOWER(?)")) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) { return rs.next(); }
}
}
// -------------------- SELECT -------------------- // -------------------- SELECT --------------------
public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException { public UserParamEntry getByLoginAndParam(Connection c, String login, String param) throws SQLException {
if ("gender".equalsIgnoreCase(param)) return null;
String sql = """ String sql = """
SELECT SELECT
login, login,
@@ -151,7 +161,7 @@ public final class UserParamsDAO {
client_key, client_key,
signature signature
FROM users_params FROM users_params
WHERE LOWER(login) = LOWER(?) WHERE LOWER(login) = LOWER(?) AND LOWER(param) <> 'gender'
ORDER BY time_ms DESC ORDER BY time_ms DESC
"""; """;
@@ -61,10 +61,10 @@ public final class UserProfileStateDAO {
String where = switch (String.valueOf(listType)) { String where = switch (String.valueOf(listType)) {
case "friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(cs.login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)"; case "friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=14 AND NOT EXISTS (SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(cs.login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)";
case "close_friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=10"; case "close_friends" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=10";
case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)"; case "primary_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(cs.to_login)"; case "primary_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,cs.to_login)";
case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)"; case "shine_received" -> "LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(cs.to_login)"; case "shine_given" -> "LOWER(cs.login)=LOWER(?) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,cs.to_login)";
default -> throw new IllegalArgumentException("Unsupported listType: " + listType); default -> throw new IllegalArgumentException("Unsupported listType: " + listType);
}; };
boolean received = "primary_received".equals(listType) || "shine_received".equals(listType); boolean received = "primary_received".equals(listType) || "shine_received".equals(listType);
@@ -77,9 +77,9 @@ public final class UserProfileStateDAO {
COALESCE(up.ava_ar,'') AS ava_ar, COALESCE(up.ava_ar,'') AS ava_ar,
up.account_role, up.shine_status, up.account_role, up.shine_status,
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=80 EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=80
AND shine_is_primary(x.login) AND shine_target_accepts_primary_confirmation(x.to_login)) AS primary_confirmed, AND shine_can_confirm_primary(x.login,x.to_login)) AS primary_confirmed,
EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=70 EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=70
AND shine_is_primary(x.login) AND shine_is_shining(x.login) AND shine_target_accepts_shine_confirmation(x.to_login)) AS shine_confirmed, AND shine_can_confirm_shine(x.login,x.to_login)) AS shine_confirmed,
CASE CASE
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=10) THEN 'close_friend' WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=10) THEN 'close_friend'
WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=14) THEN 'friend' WHEN EXISTS(SELECT 1 FROM connections_state x WHERE LOWER(x.login)=LOWER(?) AND LOWER(x.to_login)=LOWER(%s) AND x.rel_type=14) THEN 'friend'
@@ -113,27 +113,39 @@ public final class UserProfileStateDAO {
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException { public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException {
int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset); int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset);
String virtualChannels = """
WITH public_channels AS (
SELECT owner_login, slug, display_name, ava_ar, ava_pr, owner_bch_name,
channel_root_block_number, channel_root_block_hash, is_deleted, deleted_at_ms, deleted_block_number
FROM channel_names_state WHERE channel_type_code=1
UNION ALL
SELECT u.login, 'stories', COALESCE(NULLIF(TRIM(CONCAT_WS(' ', p.first_name, p.last_name)), ''), u.login),
COALESCE(p.ava_ar,''), '', u.blockchain_name, 0, NULL::bytea, FALSE, 0::bigint, NULL::integer
FROM user_identity_current u LEFT JOIN user_profile_state p ON LOWER(p.login)=LOWER(u.login)
)
""";
String sql; String sql;
if ("owned".equals(mode)) { if ("owned".equals(mode)) {
sql=""" sql=virtualChannels+"""
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, cn.owner_bch_name, SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM channel_names_state cn FROM public_channels cn
WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted) WHERE LOWER(cn.owner_login)=LOWER(?) AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ? ORDER BY CASE WHEN cn.channel_root_block_number=0 THEN 0 ELSE 1 END, cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else if ("following".equals(mode)) { } else if ("following".equals(mode)) {
sql=""" sql=virtualChannels+"""
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, cn.owner_bch_name, SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_pr, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM connections_state cs FROM public_channels cn
JOIN channel_names_state cn WHERE EXISTS (SELECT 1 FROM connections_state cs
ON LOWER(cn.owner_login)=LOWER(cs.to_login) WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30
AND cn.channel_root_block_number=cs.to_block_number AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cn.channel_root_block_hash=cs.to_block_hash AND cs.to_block_number=cn.channel_root_block_number
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30 AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted) AND (cn.channel_root_block_number=0 OR cs.to_block_hash=cn.channel_root_block_hash))
AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ? ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
"""; """;
} else throw new IllegalArgumentException("Unsupported channel mode: "+mode); } else throw new IllegalArgumentException("Unsupported channel mode: "+mode);
@@ -142,8 +154,8 @@ public final class UserProfileStateDAO {
ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset); ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset);
try(ResultSet rs=ps.executeQuery()){ try(ResultSet rs=ps.executeQuery()){
while(rs.next()) out.add(new ChannelCard( while(rs.next()) out.add(new ChannelCard(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_sha256"), rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_pr"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getString("root_hash"), rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getInt("channel_root_block_number") == 0 ? publicationsHash(c, rs.getString("owner_bch_name")) : rs.getString("root_hash"),
rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number") rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number")
)); ));
} }
@@ -151,8 +163,13 @@ public final class UserProfileStateDAO {
return out; return out;
} }
private static String publicationsHash(Connection c, String ownerBch) throws SQLException {
byte[] hash=CanonicalChainResolver.getInstance().getHash(c,ownerBch,0);
return java.util.HexFormat.of().formatHex(hash == null ? new byte[32] : hash);
}
private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));} private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));}
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){} public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){} public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String avatarSha256,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){} public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String avatarPr,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){}
} }
@@ -6,9 +6,9 @@ package shine.db.entities;
* Храним: * Храним:
* - login + fork_number (physical fork identity; bch_name is derived only for display/API) * - login + fork_number (physical fork identity; bch_name is derived only for display/API)
* - block_number (глобальный номер в этой цепочке) * - block_number (глобальный номер в этой цепочке)
* - block_bytes (полный блок: preimage + signature) * - block_bytes (контейнер двух оригинальных подписанных ANS-104)
* - block_hash (32 байта вычисленный SHA-256(preimage)) * - block_hash (32 байта вычисленный SHA-256(CORE payload))
* - block_signature (64 байта) * - block_signature (64 байта, подпись CORE)
* *
* Опционально: * Опционально:
* - line_code / prev_line_number / prev_line_hash / this_line_number * - line_code / prev_line_number / prev_line_hash / this_line_number
@@ -1,6 +1,7 @@
package shine.db.entities; package shine.db.entities;
import java.util.Base64; import java.util.Base64;
import java.util.Locale;
/** /**
* Агрегатная сущность текущего состояния блокчейна. * Агрегатная сущность текущего состояния блокчейна.
@@ -42,14 +43,18 @@ public final class BlockchainStateEntry {
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName); if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1)); int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
this.login=blockchainName.substring(0,dash); // Runtime-ключ цепочки всегда нормализован. Исходное написание
// зарегистрированного login хранится отдельно в user_identity_current.
this.login=blockchainName.substring(0,dash).trim().toLowerCase(Locale.ROOT);
this.forkNumber=parsedFork; this.forkNumber=parsedFork;
} }
public int getForkNumber() { return forkNumber; } public int getForkNumber() { return forkNumber; }
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; } public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
public String getLogin() { return login; } public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; } public void setLogin(String login) {
this.login = login == null ? null : login.trim().toLowerCase(Locale.ROOT);
}
public String getBlockchainKey() { return blockchainKey; } public String getBlockchainKey() { return blockchainKey; }
public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; } public void setBlockchainKey(String blockchainKey) { this.blockchainKey = blockchainKey; }
@@ -14,7 +14,7 @@ public class ChannelNameStateEntry {
private byte[] channelRootBlockHash; private byte[] channelRootBlockHash;
private long createdAtMs; private long createdAtMs;
private String avaAr; private String avaAr;
private String avaSha256; private String avaPr;
private long avaSize; private long avaSize;
private long metaUpdatedAtMs; private long metaUpdatedAtMs;
@@ -106,12 +106,12 @@ public class ChannelNameStateEntry {
this.avaAr = avaAr; this.avaAr = avaAr;
} }
public String getAvaSha256() { public String getAvaPr() {
return avaSha256; return avaPr;
} }
public void setAvaSha256(String avaSha256) { public void setAvaPr(String avaPr) {
this.avaSha256 = avaSha256; this.avaPr = avaPr;
} }
public long getAvaSize() { public long getAvaSize() {
@@ -1,43 +0,0 @@
package shine.db.entities;
/**
* Запись о сервере-партнёре, с которым текущий сервер должен синхронизироваться.
*/
public class SyncServerEntry {
private String login;
private String serverAddress;
private long updatedAtMs;
public SyncServerEntry() {}
public SyncServerEntry(String login, String serverAddress, long updatedAtMs) {
this.login = login;
this.serverAddress = serverAddress;
this.updatedAtMs = updatedAtMs;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getServerAddress() {
return serverAddress;
}
public void setServerAddress(String serverAddress) {
this.serverAddress = serverAddress;
}
public long getUpdatedAtMs() {
return updatedAtMs;
}
public void setUpdatedAtMs(long updatedAtMs) {
this.updatedAtMs = updatedAtMs;
}
}
@@ -0,0 +1,7 @@
-- SHiNE v41: public channel avatars now use BitTorrent v2 PR (Base58), no SHA256 legacy.
BEGIN;
ALTER TABLE channel_names_state RENAME COLUMN ava_sha256 TO ava_pr;
-- Old sha256 hex values cannot be used as Pieces Root; no automatic conversion exists.
UPDATE channel_names_state SET ava_pr = '', ava_ar = '', ava_size = 0 WHERE ava_pr <> '';
UPDATE db_schema_version SET schema_version = 41 WHERE id = 1;
COMMIT;
@@ -0,0 +1,27 @@
-- SHiNE v42: журнал выдачи разрешений R2 (не подтверждение успешного PUT).
-- В DM записываются только зашифрованные объекты (включая манифест), без имени и MIME.
BEGIN;
CREATE TABLE IF NOT EXISTS public_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS public_file_uploads_user_time_idx ON public_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS public_file_uploads_hash_idx ON public_file_uploads (file_hash);
CREATE TABLE IF NOT EXISTS dm_file_uploads (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_login TEXT NOT NULL,
file_hash TEXT NOT NULL,
file_size_bytes BIGINT NOT NULL CHECK (file_size_bytes > 0),
disposition TEXT NOT NULL CHECK (disposition IN ('upload_url_issued', 'already_exists')),
requested_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS dm_file_uploads_user_time_idx ON dm_file_uploads (user_login, requested_at DESC);
CREATE INDEX IF NOT EXISTS dm_file_uploads_hash_idx ON dm_file_uploads (file_hash);
UPDATE db_schema_version SET schema_version = 42, updated_at_ms = (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::BIGINT WHERE id = 1;
COMMIT;
@@ -0,0 +1,43 @@
-- v43: runtime-идентичность blockchain_state совпадает с normalized_login.
-- Исходный регистр зарегистрированного имени остаётся в user_identity_current.login
-- и никогда не переписывает подписанные сертификаты или блоки.
BEGIN;
-- blocks_store уже использует normalized_login. Временно снимаем составной FK,
-- чтобы привести родительские строки blockchain_state к тому же ключу.
ALTER TABLE blocks_store DROP CONSTRAINT IF EXISTS fk_blocks_physical_fork;
ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_login_fkey;
-- v36-совместимость подставляла display login, что несовместимо с blocks_store.
DROP TRIGGER IF EXISTS trg_canonical_identity_blockchain_state_store_login
ON blockchain_state_store;
UPDATE blockchain_state_store
SET login = LOWER(BTRIM(login))
WHERE login IS DISTINCT FROM LOWER(BTRIM(login));
ALTER TABLE blockchain_state_store
ADD CONSTRAINT blockchain_state_login_fkey
FOREIGN KEY (login) REFERENCES user_identity_current(normalized_login);
ALTER TABLE blocks_store
ADD CONSTRAINT fk_blocks_physical_fork
FOREIGN KEY (login, fork_number)
REFERENCES blockchain_state_store(login, fork_number);
CREATE OR REPLACE FUNCTION shine_normalize_blockchain_state_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.login := LOWER(BTRIM(NEW.login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_blockchain_state_login
BEFORE INSERT OR UPDATE OF login ON blockchain_state_store
FOR EACH ROW EXECUTE FUNCTION shine_normalize_blockchain_state_login();
UPDATE db_schema_version
SET schema_version = 43,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,29 @@
-- v44: owner_login уведомлений — технический ключ normalized_login.
-- Исходный регистр остаётся в содержимом подписанных блоков и полях source/target.
BEGIN;
UPDATE user_notifications_state
SET owner_login = LOWER(BTRIM(owner_login))
WHERE owner_login IS DISTINCT FROM LOWER(BTRIM(owner_login));
DROP TRIGGER IF EXISTS trg_canonical_identity_user_notifications_state_owner_login
ON user_notifications_state;
DROP TRIGGER IF EXISTS trg_normalize_user_notifications_state_owner_login
ON user_notifications_state;
CREATE OR REPLACE FUNCTION shine_normalize_user_notification_owner_login()
RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
NEW.owner_login := LOWER(BTRIM(NEW.owner_login));
RETURN NEW;
END $$;
CREATE TRIGGER trg_normalize_user_notifications_state_owner_login
BEFORE INSERT OR UPDATE OF owner_login ON user_notifications_state
FOR EACH ROW EXECUTE FUNCTION shine_normalize_user_notification_owner_login();
UPDATE db_schema_version
SET schema_version = 44,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,68 @@
-- v45: FREE_CERT — полноценная identity без фиктивной Solana PDA.
-- Обычные проекции и чтение blockchain выбирают ветку по user_identity_current;
-- Solana PDA остаётся источником только Solana-специфичных данных.
BEGIN;
CREATE OR REPLACE FUNCTION shine_identity_active_fork(p_login TEXT)
RETURNS INTEGER
LANGUAGE plpgsql
STABLE
AS $$
DECLARE
v_fork INTEGER;
BEGIN
SELECT substring(blockchain_name FROM '([0-9]{3})$')::INTEGER
INTO v_fork
FROM user_identity_current
WHERE LOWER(login) = LOWER(BTRIM(p_login))
LIMIT 1;
IF v_fork BETWEEN 1 AND 999 THEN
RETURN v_fork;
END IF;
SELECT fork_number
INTO v_fork
FROM blockchain_state_store
WHERE LOWER(login) = LOWER(BTRIM(p_login))
ORDER BY updated_at_ms DESC, fork_number DESC
LIMIT 1;
RETURN COALESCE(v_fork, 1);
END $$;
CREATE OR REPLACE FUNCTION shine_active_fork(p_login TEXT, p_block_number INTEGER)
RETURNS INTEGER
LANGUAGE sql
STABLE
AS $$
SELECT shine_canonical_fork(p_login, shine_identity_active_fork(p_login), p_block_number)
$$;
CREATE OR REPLACE FUNCTION shine_channel_names_state_refresh_owner_stats()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
PERFORM shine_refresh_user_stats(OLD.owner_login);
RETURN OLD;
END IF;
PERFORM shine_refresh_user_stats(NEW.owner_login);
RETURN NEW;
END $$;
DROP TRIGGER IF EXISTS trg_channel_names_state_refresh_owner_stats ON channel_names_state;
CREATE TRIGGER trg_channel_names_state_refresh_owner_stats
AFTER INSERT OR UPDATE OF owner_login, channel_type_code, is_deleted OR DELETE
ON channel_names_state
FOR EACH ROW EXECUTE FUNCTION shine_channel_names_state_refresh_owner_stats();
-- Исправить уже записанные FREE_CERT и paid identity одним пересчётом.
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
UPDATE db_schema_version
SET schema_version = 45,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,77 @@
-- HEADER V3: производные данные хранятся рядом с физическим блоком #0.
-- V1/V2: NULL, прежняя логика профиля. Указанные аккаунты не меняют никакие голоса.
BEGIN;
ALTER TABLE blocks_store ADD COLUMN header_account_type SMALLINT;
ALTER TABLE blocks_store ADD COLUMN header_previous_accounts TEXT[];
ALTER TABLE blocks_store ADD CONSTRAINT chk_header_identity CHECK (
(header_account_type IS NULL AND header_previous_accounts IS NULL) OR
(block_number=0 AND msg_type=0 AND msg_sub_type=0
AND header_account_type IS NOT NULL AND header_account_type IN (0,1)
AND header_previous_accounts IS NOT NULL AND cardinality(header_previous_accounts)<=10
AND (header_account_type=1 OR cardinality(header_previous_accounts)=0)));
CREATE VIEW account_identity_state AS
SELECT LOWER(b.login) AS login, b.header_account_type AS account_type,
3 AS header_version, b.block_hash AS header_hash, b.header_previous_accounts AS previous_accounts
FROM blocks_store b
WHERE b.block_number=0 AND b.header_account_type IS NOT NULL
AND b.fork_number=shine_active_fork(b.login,0);
CREATE VIEW account_predecessors AS
SELECT i.login, p.previous_login
FROM account_identity_state i CROSS JOIN LATERAL unnest(i.previous_accounts) AS p(previous_login);
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'account_role'),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
v_account_role := COALESCE(
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login = LOWER(p_login)),
LOWER(BTRIM(COALESCE(v_account_role, ''))));
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
-- Вызывать после записи HEADER и при завершении восстановления канонической цепи.
CREATE OR REPLACE FUNCTION shine_refresh_header_identity(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
BEGIN
PERFORM shine_refresh_user_profile(p_login);
PERFORM shine_refresh_related_user_stats(p_login);
PERFORM shine_refresh_message_qualified_likes_for_actor(p_login);
END $$;
UPDATE db_schema_version SET schema_version=46,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,82 @@
-- Official = signed canonical HEADER V3 / account_type=1. Legacy USER_PARAM is not proof.
BEGIN;
CREATE OR REPLACE FUNCTION shine_is_primary(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT EXISTS (SELECT 1 FROM account_identity_state
WHERE login=LOWER(p_login) AND account_type=1)
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'account_role'),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
v_account_role := COALESCE(
(SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login = LOWER(p_login)),
CASE WHEN LOWER(BTRIM(COALESCE(v_account_role, ''))) = 'non_voting'
THEN 'non_voting' ELSE NULL END);
IF v_account_role NOT IN ('primary', 'non_voting') THEN v_account_role := NULL; END IF;
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
-- Remove obsolete legacy Primary projections, leaving the original signed history intact.
-- The shared predicate also serves social graph confirmations; refresh affected projections.
DO $$
DECLARE r RECORD;
BEGIN
FOR r IN
UPDATE user_profile_state ups SET account_role=NULL
WHERE ups.account_role='primary' AND NOT shine_is_primary(ups.login)
RETURNING login
LOOP
PERFORM shine_refresh_related_user_stats(r.login);
END LOOP;
END $$;
-- Recalculate both qualified counters, not the all-accounts count.
-- The aggregate returns zeros even if no qualifying reaction exists.
UPDATE message_stats ms SET (primary_likes_count, shining_likes_count) = (
SELECT COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login))::INTEGER,
COUNT(*) FILTER (WHERE shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))::INTEGER
FROM reactions_state rs
WHERE rs.reaction_type=1 AND rs.last_sub_type=1
AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number
AND rs.to_block_hash=ms.to_block_hash
);
UPDATE db_schema_version SET schema_version=47,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,109 @@
-- Только канонический HEADER V3 определяет Primary. История не меняется.
BEGIN;
CREATE OR REPLACE FUNCTION shine_target_accepts_primary_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT shine_is_primary(p_login)
$$;
CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT shine_is_primary(p_login) AND NOT EXISTS (
SELECT 1 FROM user_profile_state WHERE LOWER(login)=LOWER(p_login) AND shine_status='not_interested')
$$;
CREATE OR REPLACE FUNCTION shine_can_confirm_primary(p_actor TEXT,p_target TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
AND shine_is_primary(p_actor) AND shine_target_accepts_primary_confirmation(p_target),FALSE)
$$;
CREATE OR REPLACE FUNCTION shine_can_confirm_shine(p_actor TEXT,p_target TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$
SELECT COALESCE(LOWER(p_actor)<>LOWER(p_target)
AND shine_is_primary(p_actor) AND shine_is_shining(p_actor)
AND shine_target_accepts_shine_confirmation(p_target),FALSE)
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_profile(p_login TEXT)
RETURNS VOID
LANGUAGE plpgsql
AS $$
DECLARE
v_first_name TEXT := '';
v_last_name TEXT := '';
v_ava_ar TEXT := '';
v_account_role TEXT := NULL;
v_shine TEXT := NULL;
v_updated BIGINT := 0;
BEGIN
IF p_login IS NULL OR btrim(p_login) = '' THEN RETURN; END IF;
SELECT COALESCE(MAX(value) FILTER (WHERE param = 'first_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'last_name'), ''),
COALESCE(MAX(value) FILTER (WHERE param = 'ava'), ''),
MAX(value) FILTER (WHERE param = 'shine'),
COALESCE(MAX(time_ms), 0)
INTO v_first_name, v_last_name, v_ava_ar, v_shine, v_updated
FROM users_params
WHERE LOWER(login) = LOWER(p_login);
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
INTO v_account_role FROM account_identity_state WHERE login = LOWER(p_login);
v_shine := LOWER(BTRIM(COALESCE(v_shine, '')));
IF v_shine = 'yes' THEN v_shine := 'shining'; END IF; -- legacy compatibility
IF v_shine NOT IN ('shining', 'unknown', 'not_interested') THEN v_shine := NULL; END IF;
INSERT INTO user_profile_state(login, first_name, last_name, ava_ar, account_role, shine_status, updated_at_ms)
VALUES (p_login, v_first_name, v_last_name, v_ava_ar, v_account_role, v_shine, v_updated)
ON CONFLICT (login) DO UPDATE SET
first_name = EXCLUDED.first_name,
last_name = EXCLUDED.last_name,
ava_ar = EXCLUDED.ava_ar,
account_role = EXCLUDED.account_role,
shine_status = EXCLUDED.shine_status,
updated_at_ms = EXCLUDED.updated_at_ms;
END;
$$;
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
-- Архивная связь может прийти до регистрации цели в локальном каталоге.
-- Не создавать строку статистики без владельца FK, но сохранить подписанную связь.
SELECT i.login INTO p_login FROM user_identity_current i WHERE i.normalized_login=LOWER(p_login);
IF p_login IS NULL THEN RETURN; END IF;
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(cs.login,p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_can_confirm_primary(p_login,cs.to_login)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(cs.login,p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_can_confirm_shine(p_login,cs.to_login)),v_now
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
-- Обновить роль в существующих карточках; не переписывать исходные параметры/блоки.
UPDATE user_profile_state ups SET account_role = (
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login=LOWER(ups.login))
WHERE account_role IS DISTINCT FROM (
SELECT CASE account_type WHEN 1 THEN 'primary' ELSE 'non_voting' END
FROM account_identity_state WHERE login=LOWER(ups.login));
-- У аккаунтов с HEADER, но без параметров, также должна существовать карточка.
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT login FROM account_identity_state i
WHERE NOT EXISTS (SELECT 1 FROM user_profile_state p WHERE LOWER(p.login)=i.login)
LOOP PERFORM shine_refresh_user_profile(r.login); END LOOP;
-- Все старые участники подтверждений, в том числе с устаревшими ненулевыми счётчиками.
FOR r IN SELECT login FROM user_stats_state
UNION SELECT login FROM connections_state WHERE rel_type IN (70,80)
UNION SELECT to_login FROM connections_state WHERE rel_type IN (70,80)
LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP;
END $$;
UPDATE db_schema_version SET schema_version=48,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,13 @@
-- Only self-declared shining accounts may receive shine confirmations.
BEGIN;
CREATE OR REPLACE FUNCTION shine_target_accepts_shine_confirmation(p_login TEXT)
RETURNS BOOLEAN LANGUAGE sql STABLE AS $$ SELECT shine_is_shining(p_login) $$;
-- Existing signed relations stay intact; qualification is evaluated dynamically.
DO $$ DECLARE r RECORD; BEGIN
FOR r IN SELECT login FROM user_stats_state
UNION SELECT login FROM connections_state WHERE rel_type=70
UNION SELECT to_login FROM connections_state WHERE rel_type=70
LOOP PERFORM shine_refresh_user_stats(r.login); END LOOP;
END $$;
UPDATE db_schema_version SET schema_version=49, updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
COMMIT;
@@ -0,0 +1,39 @@
CREATE TABLE IF NOT EXISTS block_publications (
login TEXT NOT NULL,
fork_number INTEGER NOT NULL,
block_number INTEGER NOT NULL,
core_id TEXT NOT NULL,
content_id TEXT NOT NULL,
core_hash BYTEA NOT NULL,
content_hash BYTEA NOT NULL,
owner BYTEA NOT NULL,
prev_core_hash BYTEA NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING_TURBO',
content_confirmed_at_ms BIGINT,
core_confirmed_at_ms BIGINT,
arweave_confirmed_at_ms BIGINT,
first_received_at_ms BIGINT NOT NULL,
last_attempt_at_ms BIGINT,
attempts INTEGER NOT NULL DEFAULT 0,
last_error TEXT,
next_retry_at_ms BIGINT,
PRIMARY KEY (login, fork_number, block_number),
FOREIGN KEY (login, fork_number, block_number)
REFERENCES blocks_store(login, fork_number, block_number) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_block_publications_pending
ON block_publications(status, next_retry_at_ms) WHERE status <> 'ARWEAVE_CONFIRMED';
CREATE TABLE IF NOT EXISTS block_publication_attempts (
id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
login TEXT NOT NULL,
fork_number INTEGER NOT NULL,
block_number INTEGER NOT NULL,
attempted_at_ms BIGINT NOT NULL,
outcome TEXT,
FOREIGN KEY (login, fork_number, block_number)
REFERENCES block_publications(login, fork_number, block_number) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_block_publication_attempts_block
ON block_publication_attempts(login, fork_number, block_number, attempted_at_ms);
UPDATE db_schema_version SET schema_version=50,
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
@@ -478,25 +478,6 @@ CREATE TABLE IF NOT EXISTS ip_geo_cache (
CREATE INDEX IF NOT EXISTS idx_ip_geo_cache_updated_at CREATE INDEX IF NOT EXISTS idx_ip_geo_cache_updated_at
ON ip_geo_cache(updated_at_ms); ON ip_geo_cache(updated_at_ms);
CREATE TABLE IF NOT EXISTS test_free_avatar_uploads (
login TEXT PRIMARY KEY REFERENCES solana_user_pda_current(login),
used_count INTEGER NOT NULL DEFAULT 0,
updated_at_ms BIGINT NOT NULL,
last_tx_id TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_test_free_avatar_uploads_updated
ON test_free_avatar_uploads(updated_at_ms);
CREATE TABLE IF NOT EXISTS sync_servers (
login TEXT PRIMARY KEY,
server_address TEXT NOT NULL DEFAULT '',
updated_at_ms BIGINT NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_sync_servers_updated
ON sync_servers(updated_at_ms);
CREATE TABLE IF NOT EXISTS blockchain_state ( CREATE TABLE IF NOT EXISTS blockchain_state (
blockchain_name TEXT PRIMARY KEY, blockchain_name TEXT PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login), login TEXT NOT NULL REFERENCES solana_user_pda_current(login),
@@ -0,0 +1,36 @@
-- Запускать psql -v ON_ERROR_STOP=1 -f <этот файл> на отдельной тестовой БД после миграции 48.
-- Фикстуры временные; проверяются действующие SQL-функции, изменения откатываются.
BEGIN;
SET LOCAL search_path TO pg_temp, public;
CREATE TEMP TABLE account_identity_state(login TEXT PRIMARY KEY,account_type SMALLINT);
CREATE TEMP TABLE user_profile_state (LIKE public.user_profile_state INCLUDING ALL);
CREATE TEMP TABLE user_stats_state (LIKE public.user_stats_state INCLUDING ALL);
CREATE TEMP TABLE user_identity_current(login TEXT PRIMARY KEY,normalized_login TEXT UNIQUE);
CREATE TEMP TABLE users_params(login TEXT,param TEXT,value TEXT,time_ms BIGINT);
CREATE TEMP TABLE connections_state(login TEXT,rel_type INTEGER,to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA);
CREATE TEMP TABLE channel_names_state(owner_login TEXT,channel_type_code INTEGER,is_deleted BOOLEAN,channel_root_block_number INTEGER,channel_root_block_hash BYTEA);
INSERT INTO account_identity_state VALUES ('alice@free',1),('bob@free',1),('alt@free',0),('optout@free',1);
INSERT INTO user_identity_current SELECT login,lower(login) FROM account_identity_state;
INSERT INTO user_identity_current VALUES ('legacy@free','legacy@free');
INSERT INTO users_params VALUES ('alice@free','shine','shining',1),('alt@free','shine','shining',1),('legacy@free','account_role','primary',1),('optout@free','shine','not_interested',1);
SELECT shine_refresh_user_profile(login) FROM user_identity_current;
DO $$ BEGIN
IF NOT shine_can_confirm_primary('ALICE@FREE','bob@free') OR NOT shine_can_confirm_shine('alice@free','bob@free') THEN RAISE EXCEPTION 'Primary pair rejected'; END IF;
IF shine_can_confirm_primary('alice@free','alt@free') OR shine_can_confirm_primary('alt@free','alice@free') OR shine_can_confirm_primary('legacy@free','alice@free') OR shine_can_confirm_primary('alice@free','legacy@free') OR shine_can_confirm_primary('alice@free','missing@free') OR shine_can_confirm_primary('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid primary pair accepted'; END IF;
IF shine_can_confirm_shine('alice@free','alt@free') OR shine_can_confirm_shine('alt@free','alice@free') OR shine_can_confirm_shine('bob@free','alice@free') OR shine_can_confirm_shine('alice@free','optout@free') OR shine_can_confirm_shine('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid shine pair accepted'; END IF;
IF (SELECT account_role FROM user_profile_state WHERE login='legacy@free') IS NOT NULL THEN RAISE EXCEPTION 'Legacy role leaked into profile'; END IF;
END $$;
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES
('alice@free',80,'bob@free',0,'\x00'),('alice@free',70,'bob@free',0,'\x00'),
('alice@free',80,'alt@free',0,'\x00'),('alice@free',70,'alt@free',0,'\x00'),
('alt@free',80,'bob@free',0,'\x00'),('alt@free',70,'bob@free',0,'\x00'),
('legacy@free',80,'bob@free',0,'\x00'),('alice@free',80,'alice@free',0,'\x00');
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
SELECT shine_refresh_user_stats('missing@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='bob@free' AND primary_confirmations_received_count=1 AND shine_confirmations_received_count=1) THEN RAISE EXCEPTION 'Wrong Bob counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND primary_confirmations_given_count=1 AND shine_confirmations_given_count=1 AND primary_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Alice counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alt@free' AND primary_confirmations_received_count=0 AND primary_confirmations_given_count=0 AND shine_confirmations_received_count=0 AND shine_confirmations_given_count=0) THEN RAISE EXCEPTION 'Alternative counters not zero'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
ROLLBACK;
@@ -0,0 +1,61 @@
-- Запускать psql -v ON_ERROR_STOP=1 -f <этот файл> на отдельной тестовой БД после миграции 49.
-- Фикстуры временные; проверяются действующие SQL-функции, изменения откатываются.
BEGIN;
SET LOCAL search_path TO pg_temp, public;
CREATE TEMP TABLE account_identity_state(login TEXT PRIMARY KEY,account_type SMALLINT);
CREATE TEMP TABLE user_profile_state (LIKE public.user_profile_state INCLUDING ALL);
CREATE TEMP TABLE user_stats_state (LIKE public.user_stats_state INCLUDING ALL);
CREATE TEMP TABLE user_identity_current(login TEXT PRIMARY KEY,normalized_login TEXT UNIQUE);
CREATE TEMP TABLE users_params(login TEXT,param TEXT,value TEXT,time_ms BIGINT);
CREATE TEMP TABLE connections_state(login TEXT,rel_type INTEGER,to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA);
CREATE TEMP TABLE channel_names_state(owner_login TEXT,channel_type_code INTEGER,is_deleted BOOLEAN,channel_root_block_number INTEGER,channel_root_block_hash BYTEA);
INSERT INTO account_identity_state VALUES ('alice@free',1),('bob@free',1),('alt@free',0),('optout@free',1);
INSERT INTO user_identity_current SELECT login,lower(login) FROM account_identity_state;
INSERT INTO user_identity_current VALUES ('legacy@free','legacy@free');
INSERT INTO users_params VALUES ('alice@free','shine','shining',1),('alt@free','shine','shining',1),('legacy@free','account_role','primary',1),('optout@free','shine','not_interested',1);
SELECT shine_refresh_user_profile(login) FROM user_identity_current;
DO $$ BEGIN
IF NOT shine_can_confirm_primary('ALICE@FREE','bob@free') OR shine_can_confirm_shine('alice@free','bob@free') THEN RAISE EXCEPTION 'Primary pair rejected'; END IF;
IF shine_can_confirm_primary('alice@free','alt@free') OR shine_can_confirm_primary('alt@free','alice@free') OR shine_can_confirm_primary('legacy@free','alice@free') OR shine_can_confirm_primary('alice@free','legacy@free') OR shine_can_confirm_primary('alice@free','missing@free') OR shine_can_confirm_primary('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid primary pair accepted'; END IF;
IF NOT shine_can_confirm_shine('alice@free','alt@free') OR shine_can_confirm_shine('alt@free','alice@free') OR shine_can_confirm_shine('bob@free','alice@free') OR shine_can_confirm_shine('alice@free','optout@free') OR shine_can_confirm_shine('alice@free','ALICE@FREE') THEN RAISE EXCEPTION 'Invalid shine pair accepted'; END IF;
IF (SELECT account_role FROM user_profile_state WHERE login='legacy@free') IS NOT NULL THEN RAISE EXCEPTION 'Legacy role leaked into profile'; END IF;
END $$;
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash) VALUES
('alice@free',80,'bob@free',0,'\x00'),('alice@free',70,'bob@free',0,'\x00'),
('alice@free',80,'alt@free',0,'\x00'),('alice@free',70,'alt@free',0,'\x00'),
('alt@free',80,'bob@free',0,'\x00'),('alt@free',70,'bob@free',0,'\x00'),
('legacy@free',80,'bob@free',0,'\x00'),('alice@free',80,'alice@free',0,'\x00');
SELECT shine_refresh_user_stats(login) FROM user_identity_current;
SELECT shine_refresh_user_stats('missing@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='bob@free' AND primary_confirmations_received_count=1 AND shine_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Bob counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND primary_confirmations_given_count=1 AND shine_confirmations_given_count=1 AND primary_confirmations_received_count=0) THEN RAISE EXCEPTION 'Wrong Alice counters'; END IF;
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alt@free' AND primary_confirmations_received_count=0 AND primary_confirmations_given_count=0 AND shine_confirmations_received_count=1 AND shine_confirmations_given_count=0) THEN RAISE EXCEPTION 'Alternative counters incorrect'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
-- Existing declarations must become inactive when either end stops shining,
-- and become effective again without writing a new connection block.
UPDATE user_profile_state SET shine_status='shining' WHERE login='bob@free';
SELECT shine_refresh_related_user_stats('bob@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=2) THEN RAISE EXCEPTION 'Bob opt-in did not activate old relation'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='unknown' WHERE login='alice@free';
SELECT shine_refresh_related_user_stats('alice@free');
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM user_stats_state WHERE login IN ('bob@free','alt@free') AND shine_confirmations_received_count<>0) THEN RAISE EXCEPTION 'Actor opt-out failed'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='shining' WHERE login='alice@free';
SELECT shine_refresh_related_user_stats('alice@free');
UPDATE user_profile_state SET shine_status='unknown' WHERE login='alt@free';
SELECT shine_refresh_related_user_stats('alt@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=1) THEN RAISE EXCEPTION 'Target opt-out failed'; END IF;
END $$;
UPDATE user_profile_state SET shine_status='shining' WHERE login='alt@free';
SELECT shine_refresh_related_user_stats('alt@free');
DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM user_stats_state WHERE login='alice@free' AND shine_confirmations_given_count=2) THEN RAISE EXCEPTION 'Target opt-in failed'; END IF;
IF (SELECT COUNT(*) FROM connections_state)<>8 THEN RAISE EXCEPTION 'Raw history changed'; END IF;
END $$;
ROLLBACK;
@@ -34,9 +34,14 @@ dependencies {
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
implementation project(':shine-server-geo') // модуль для определения геолокации по IP implementation project(':shine-server-geo') // модуль для определения геолокации по IP
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
} }
test {
useJUnitPlatform()
}
java { java {
sourceCompatibility = JavaVersion.VERSION_17 sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17
@@ -25,6 +25,7 @@ public class ConnectionContext {
// Статусы аутентификации // Статусы аутентификации
public static final int AUTH_STATUS_NONE = 0; // анонимный / не авторизован public static final int AUTH_STATUS_NONE = 0; // анонимный / не авторизован
public static final int AUTH_STATUS_AUTH_IN_PROGRESS = 1; // выполнен challenge (AuthChallenge или SessionChallenge) public static final int AUTH_STATUS_AUTH_IN_PROGRESS = 1; // выполнен challenge (AuthChallenge или SessionChallenge)
public static final int AUTH_STATUS_REGISTRAR = 3;
public static final int AUTH_STATUS_USER = 2; // авторизованный пользователь public static final int AUTH_STATUS_USER = 2; // авторизованный пользователь
// При успешной авторизации отдельно фиксируем отношение пользователя к этому серверу. // При успешной авторизации отдельно фиксируем отношение пользователя к этому серверу.
@@ -43,6 +43,8 @@ import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_StartEspPairing_
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_UpsertEspPairingSettings_Request; import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_UpsertEspPairingSettings_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_BlockPublication_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_BlockPublication_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetBlockchainBlock_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetBlockchainBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetMyBlockchain_Handler; import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetMyBlockchain_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request; import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
@@ -91,6 +93,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_GetChannelMessages_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetMessageThread_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_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_GetPersonalDiary_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handler; import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handler;
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler; import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
@@ -104,6 +109,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_GetGroupDialog_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageThread_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_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_GetPersonalDiary_Request;
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_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; import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
@@ -152,7 +160,6 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_UpsertPushToken_Reque
// --- NEW: Ping --- // --- NEW: Ping ---
import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_GetServerInfo_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_GetCallIceConfig_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_GetCallIceConfig_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_GetSyncUserProfile_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientErrorLog_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ClientErrorLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ClientDebugLog_Handler;
import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_Handler; import server.logic.ws_protocol.JSON.handlers.system.Net_ListBlockchainHeads_Handler;
@@ -164,7 +171,6 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientErrorLog
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetCallIceConfig_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetServerInfo_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetServerInfo_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_GetSyncUserProfile_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchainHeads_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchainHeads_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request; import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
@@ -225,6 +231,7 @@ public final class JsonHandlerRegistry {
// --- blockchain --- // --- blockchain ---
Map.entry("AddBlock", new Net_AddBlock_Handler()), Map.entry("AddBlock", new Net_AddBlock_Handler()),
Map.entry("BlockPublication", new Net_BlockPublication_Handler()),
Map.entry("GetBlockchainBlock", new Net_GetBlockchainBlock_Handler()), Map.entry("GetBlockchainBlock", new Net_GetBlockchainBlock_Handler()),
Map.entry("GetMyBlockchain", new Net_GetMyBlockchain_Handler()), Map.entry("GetMyBlockchain", new Net_GetMyBlockchain_Handler()),
@@ -254,6 +261,9 @@ public final class JsonHandlerRegistry {
Map.entry("GetPersonalDiary", new Net_GetPersonalDiary_Handler()), Map.entry("GetPersonalDiary", new Net_GetPersonalDiary_Handler()),
Map.entry("GetMessageThread", new Net_GetMessageThread_Handler()), Map.entry("GetMessageThread", new Net_GetMessageThread_Handler()),
Map.entry("GetMessageLikes", new Net_GetMessageLikes_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("GetGroupDialog", new Net_GetGroupDialog_Handler()),
Map.entry("ListGroupChats200", new Net_ListGroupChats200_Handler()), Map.entry("ListGroupChats200", new Net_ListGroupChats200_Handler()),
Map.entry("GetChannelsCounters", new Net_GetChannelsCounters_Handler()), Map.entry("GetChannelsCounters", new Net_GetChannelsCounters_Handler()),
@@ -286,7 +296,6 @@ public final class JsonHandlerRegistry {
Map.entry("Ping", new Net_Ping_Handler()), Map.entry("Ping", new Net_Ping_Handler()),
Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()), Map.entry("GetServerInfo", new Net_GetServerInfo_Handler()),
Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()), Map.entry("ListBlockchainHeads", new Net_ListBlockchainHeads_Handler()),
Map.entry("GetSyncUserProfile", new Net_GetSyncUserProfile_Handler()),
Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()), Map.entry("GetCallIceConfig", new Net_GetCallIceConfig_Handler()),
Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()), Map.entry("ClientErrorLog", new Net_ClientErrorLog_Handler()),
Map.entry("ClientDebugLog", new Net_ClientDebugLog_Handler()), Map.entry("ClientDebugLog", new Net_ClientDebugLog_Handler()),
@@ -338,6 +347,7 @@ public final class JsonHandlerRegistry {
// --- blockchain --- // --- blockchain ---
Map.entry("AddBlock", Net_AddBlock_Request.class), Map.entry("AddBlock", Net_AddBlock_Request.class),
Map.entry("BlockPublication", Net_BlockPublication_Request.class),
Map.entry("GetBlockchainBlock", Net_GetBlockchainBlock_Request.class), Map.entry("GetBlockchainBlock", Net_GetBlockchainBlock_Request.class),
Map.entry("GetMyBlockchain", Net_GetMyBlockchain_Request.class), Map.entry("GetMyBlockchain", Net_GetMyBlockchain_Request.class),
@@ -367,6 +377,9 @@ public final class JsonHandlerRegistry {
Map.entry("GetPersonalDiary", Net_GetPersonalDiary_Request.class), Map.entry("GetPersonalDiary", Net_GetPersonalDiary_Request.class),
Map.entry("GetMessageThread", Net_GetMessageThread_Request.class), Map.entry("GetMessageThread", Net_GetMessageThread_Request.class),
Map.entry("GetMessageLikes", Net_GetMessageLikes_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("GetGroupDialog", Net_GetGroupDialog_Request.class),
Map.entry("ListGroupChats200", Net_ListGroupChats200_Request.class), Map.entry("ListGroupChats200", Net_ListGroupChats200_Request.class),
Map.entry("GetChannelsCounters", Net_GetChannelsCounters_Request.class), Map.entry("GetChannelsCounters", Net_GetChannelsCounters_Request.class),
@@ -399,7 +412,6 @@ public final class JsonHandlerRegistry {
Map.entry("Ping", Net_Ping_Request.class), Map.entry("Ping", Net_Ping_Request.class),
Map.entry("GetServerInfo", Net_GetServerInfo_Request.class), Map.entry("GetServerInfo", Net_GetServerInfo_Request.class),
Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_Request.class), Map.entry("ListBlockchainHeads", Net_ListBlockchainHeads_Request.class),
Map.entry("GetSyncUserProfile", Net_GetSyncUserProfile_Request.class),
Map.entry("GetCallIceConfig", Net_GetCallIceConfig_Request.class), Map.entry("GetCallIceConfig", Net_GetCallIceConfig_Request.class),
Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class), Map.entry("ClientErrorLog", Net_ClientErrorLog_Request.class),
Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class), Map.entry("ClientDebugLog", Net_ClientDebugLog_Request.class),
@@ -91,6 +91,19 @@ public final class JsonInboundProcessor {
op = getTextOrNull(root, "op"); op = getTextOrNull(root, "op");
requestId = getTextOrNull(root, "requestId"); requestId = getTextOrNull(root, "requestId");
if (requestId == null || requestId.isBlank()) {
log.error("JSON request rejected: missing or blank requestId (op={}, login={}, sessionId={})",
safe(op), ctxLogin, ctxSessionId);
Net_Exception_Response err = NetExceptionResponseFactory.error(
op,
requestId,
WireCodes.Status.BAD_REQUEST,
"MISSING_REQUEST_ID",
"Поле 'requestId' обязательно и не должно быть пустым"
);
return writeResponse(err);
}
if (op == null || op.isEmpty()) { if (op == null || op.isEmpty()) {
Net_Exception_Response err = NetExceptionResponseFactory.error( Net_Exception_Response err = NetExceptionResponseFactory.error(
null, null,
@@ -59,7 +59,7 @@ public final class SolanaUserPdaImportService {
} }
/** /**
* Чтение server PDA 1.2 по логину сервера. В 1.2 разрешён ровно один endpoint. * Чтение server PDA 1.0 по логину сервера. В 1.0 разрешён ровно один endpoint.
*/ */
public static ParsedServerProfile fetchServerProfileByLogin(String loginRaw) throws Exception { public static ParsedServerProfile fetchServerProfileByLogin(String loginRaw) throws Exception {
String login = normalizeLogin(loginRaw); String login = normalizeLogin(loginRaw);
@@ -143,7 +143,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null; if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5); int major = u8(raw, 5);
int minor = u8(raw, 6); int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null; if (major != 1 || minor != 0) return null;
return parseUserPdaV12(raw); return parseUserPdaV12(raw);
} }
@@ -256,7 +256,7 @@ public final class SolanaUserPdaImportService {
if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null; if (!MAGIC.equals(new String(raw, 0, 5, StandardCharsets.UTF_8))) return null;
int major = u8(raw, 5); int major = u8(raw, 5);
int minor = u8(raw, 6); int minor = u8(raw, 6);
if (major != 1 || minor != 2) return null; if (major != 1 || minor != 0) return null;
return parseServerProfileV12(raw); return parseServerProfileV12(raw);
} }
@@ -0,0 +1,24 @@
package server.logic.ws_protocol.JSON.handlers.avatars;
import java.math.BigInteger;
import java.util.regex.Pattern;
/** Canonical 32-byte BitTorrent v2 pieces root encoded as Bitcoin Base58. */
public final class PiecesRootValidator {
private static final String ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
private static final Pattern B58 = Pattern.compile("^[1-9A-HJ-NP-Za-km-z]{32,44}$");
private PiecesRootValidator() {}
public static boolean valid(String root) {
if (root == null || !B58.matcher(root).matches()) return false;
int leadingZeros = 0;
while (leadingZeros < root.length() && root.charAt(leadingZeros) == '1') leadingZeros++;
BigInteger value = BigInteger.ZERO;
for (int i = leadingZeros; i < root.length(); i++) {
int digit = ALPHABET.indexOf(root.charAt(i));
if (digit < 0) return false;
value = value.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(digit));
}
int dataBytes = value.signum() == 0 ? 0 : (value.bitLength() + 7) / 8;
return leadingZeros + dataBytes == 32;
}
}

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