SHA256
Compare commits
469
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
6a43681bee | ||
|
|
a3d8211460 | ||
|
|
cfc679cbc8 | ||
|
|
bf170553f9 | ||
|
|
08969ecb13 | ||
|
|
eae8280062 | ||
|
|
c61cbf239c | ||
|
|
58e4bac3c8 | ||
|
|
34a9c88d91 | ||
|
|
61c33c8fec | ||
|
|
9dec8293cd | ||
|
|
0c85948556 | ||
|
|
ad4949d2ac | ||
|
|
d8ef68836d | ||
|
|
a9fa1cd2a2 | ||
|
|
7cf0170de7 | ||
|
|
fae8cdd2bf | ||
|
|
c5f640b2a9 | ||
|
|
af0beccb4a | ||
|
|
d05d9db8a2 | ||
|
|
dd461eaa16 | ||
|
|
5e61ca20cb | ||
|
|
d58af23ebb | ||
|
|
85b860a138 | ||
|
|
016aff7169 | ||
|
|
370cb79078 | ||
|
|
d9a9187506 | ||
|
|
a320c12bdd | ||
|
|
3fa1e681d9 | ||
|
|
c778ab8a39 | ||
|
|
e32d424eda | ||
|
|
1e52b4dd2a | ||
|
|
c175a54a01 | ||
|
|
3f3e93c87d | ||
|
|
1621537d77 | ||
|
|
10d9d0a45a | ||
|
|
e11c39e933 | ||
|
|
a1eae4c3a2 | ||
|
|
de0af29b6d | ||
|
|
8cf09e69af | ||
|
|
3e826e87cd | ||
|
|
920f0d7217 | ||
|
|
e7349c7bf4 | ||
|
|
1c59b82ff7 | ||
|
|
af5b5cc6b5 | ||
|
|
d120c6ecd7 | ||
|
|
09789fdf2f | ||
|
|
4d78e87447 | ||
|
|
55f2d11721 | ||
|
|
3309cdb6ba | ||
|
|
10fe1430fe | ||
|
|
83c607d995 | ||
|
|
faebecacb6 | ||
|
|
ebd5d37039 | ||
|
|
34e5fa1403 | ||
|
|
d1ca64d1c1 | ||
|
|
7d3f5db206 | ||
|
|
91a8bb9c3c | ||
|
|
ae430e84c7 | ||
|
|
f9e7c4ef94 | ||
|
|
d3a84dd451 | ||
|
|
653015b2e7 | ||
|
|
8ac8f04128 | ||
|
|
80c70ebcdc | ||
|
|
792f368175 | ||
|
|
859dbee1f1 | ||
|
|
8f3b81c368 | ||
|
|
0274183730 | ||
|
|
c9f54224bb | ||
|
|
02c705d41e | ||
|
|
76bbc9d023 | ||
|
|
780ca53931 | ||
|
|
fc86c6190e | ||
|
|
2dd0ed6d59 | ||
|
|
1f06629838 | ||
|
|
c477560632 | ||
|
|
548160f7f8 | ||
|
|
a86a380dc7 | ||
|
|
d9fdaf1930 | ||
|
|
102feccb2e | ||
|
|
1b86bca19a | ||
|
|
fed28527ae | ||
|
|
2aa770a07b | ||
|
|
4362c0a015 | ||
|
|
2983ac89e6 | ||
|
|
4a6e072946 | ||
|
|
ac6a2e5b3f | ||
|
|
e01da7ae87 | ||
|
|
70540ff041 | ||
|
|
3ecec25fce | ||
|
|
2f5736e67d | ||
|
|
97db033eb8 | ||
|
|
c972a975fd | ||
|
|
42a05a7a67 | ||
|
|
2a72842a7a | ||
|
|
c97df82538 | ||
|
|
6b120731a3 | ||
|
|
d39d2777d1 | ||
|
|
afece72444 | ||
|
|
6031d95fe8 | ||
|
|
84f2400bef | ||
|
|
e7f6e0580c | ||
|
|
689321da1a | ||
|
|
b220f2ac8b | ||
|
|
6489fb56ab | ||
|
|
003cc942d8 | ||
|
|
9c30b33b39 | ||
|
|
405b9a91a7 | ||
|
|
526941eb33 | ||
|
|
34f7faf0a8 | ||
|
|
4068465ee6 | ||
|
|
9405f28525 | ||
|
|
571f4cbc7d | ||
|
|
e8f68f8fc4 | ||
|
|
4591d171d6 | ||
|
|
3185ce8b5e | ||
|
|
e575512ebb | ||
|
|
4f8c2a72e9 | ||
|
|
3c6021a290 | ||
|
|
dafa377cbe | ||
|
|
7ed47f7b7e | ||
|
|
bd52a23bec | ||
|
|
e84ab41fe6 | ||
|
|
41d5e79f83 | ||
|
|
c13734cbc9 | ||
|
|
e78402c860 | ||
|
|
2ce80eeaef | ||
|
|
551bdc2d65 | ||
|
|
f507bdb343 | ||
|
|
395aa62bda | ||
|
|
d2b2876a79 | ||
|
|
8bb7d39c76 | ||
|
|
e296217f21 | ||
|
|
c0257f4be2 | ||
|
|
7b88b61b22 | ||
|
|
ab61787ee7 | ||
|
|
219a65ae27 | ||
|
|
94d4665185 | ||
|
|
ce97171d5a | ||
|
|
a22f590395 | ||
|
|
a520c5c5e1 | ||
|
|
cab26bbf41 | ||
|
|
6c8159c5f7 | ||
|
|
df0e9cef9b | ||
|
|
7a6ab3b35a | ||
|
|
aa5addb5d9 | ||
|
|
b67d06ce43 | ||
|
|
8d9a580f50 | ||
|
|
45eb77f431 | ||
|
|
2be6fe3ff9 | ||
|
|
a380900ec8 | ||
|
|
bca788c5e6 | ||
|
|
e77aaa3675 | ||
|
|
d25894149b | ||
|
|
68eec2b28b | ||
|
|
694aaf1f0e | ||
|
|
5caa4ce0ae | ||
|
|
af5b26c934 | ||
|
|
6997bc7600 | ||
|
|
9eedbf60a8 | ||
|
|
6294646922 | ||
|
|
42797b1a43 | ||
|
|
8c3751aba0 | ||
|
|
f40353725e | ||
|
|
3f0d71f788 | ||
|
|
f2ba7ce630 | ||
|
|
edc3d50136 | ||
|
|
a7a600035a | ||
|
|
3f05806563 | ||
|
|
2fb19ee66d | ||
|
|
d91ca5fbb3 | ||
|
|
7173f33d5f | ||
|
|
b3f9e1fe21 | ||
|
|
401ba918ad | ||
|
|
82d5a768f8 | ||
|
|
835109c81a | ||
|
|
d5f2c12fe7 | ||
|
|
11f169b080 | ||
|
|
96d23b16fc | ||
|
|
26db18e250 | ||
|
|
8fee7e1a9b | ||
|
|
e7cf98889b | ||
|
|
3fdff2a92b | ||
|
|
4d5a485933 | ||
|
|
b9cbbb857b | ||
|
|
56de0f2c74 | ||
|
|
68fe0532ce | ||
|
|
3edde418a2 | ||
|
|
923f281bf6 | ||
|
|
9ea276ba77 | ||
|
|
cfb0f9b734 | ||
|
|
993930eb82 | ||
|
|
17d6cb5be0 | ||
|
|
bb725ee451 | ||
|
|
b5ce7b0fa0 | ||
|
|
58de6a025d | ||
|
|
e6937cb49c | ||
|
|
7ac9e5a806 | ||
|
|
89630878af | ||
|
|
8b2012fad3 | ||
|
|
07ddaf5e4c | ||
|
|
4d10096ba2 | ||
|
|
5e9699613d | ||
|
|
b56a3a795f | ||
|
|
70fac068d0 | ||
|
|
d138bd9464 | ||
|
|
e14e3dfa21 | ||
|
|
30541ae4af | ||
|
|
74bace639c | ||
|
|
dda21a54ff | ||
|
|
d8f42c769c | ||
|
|
7b8e178723 | ||
|
|
b1c42efa82 | ||
|
|
acd5d4406d | ||
|
|
83548a859f | ||
|
|
79598fffa6 | ||
|
|
72e62127b3 | ||
|
|
67010a57f2 | ||
|
|
daa221a158 | ||
|
|
aca1e3054e | ||
|
|
6b5734d535 | ||
|
|
de8700f8e0 | ||
|
|
e101e5c5f4 | ||
|
|
8d22602761 | ||
|
|
f452ce1f1e | ||
|
|
3281da7f5c | ||
|
|
08c7fd7676 | ||
|
|
2e62616b46 | ||
|
|
9be4c4d3a5 | ||
|
|
f5698771e4 | ||
|
|
151a2c1754 | ||
|
|
13693a0a53 | ||
|
|
451280edd2 | ||
|
|
c997057a37 | ||
|
|
f8900e531a | ||
|
|
6e5b57fd7c | ||
|
|
408e474130 | ||
|
|
ef707ec217 | ||
|
|
8b12760dde | ||
|
|
cae64639bd | ||
|
|
be696d116b | ||
|
|
23969121e5 | ||
|
|
4da2d7129a | ||
|
|
2be5ad0b7d | ||
|
|
f44ab75c64 | ||
|
|
7aa05dc609 | ||
|
|
7b81d140ec | ||
|
|
1be1d56599 | ||
|
|
2df0a78eb2 | ||
|
|
c3253dceac | ||
|
|
ef068eca81 | ||
|
|
f9ae811702 | ||
|
|
ea0098d705 | ||
|
|
4991a146d5 | ||
|
|
849250bfa8 | ||
|
|
d83f1d4cce | ||
|
|
4c7e71f21f | ||
|
|
107f85b818 | ||
|
|
3a466b4c38 | ||
|
|
08663fa339 | ||
|
|
8e86872aa7 | ||
|
|
2d059e9ff5 | ||
|
|
9f77c54955 | ||
|
|
f827c3e493 | ||
|
|
ae2f2fac41 | ||
|
|
1f70d36e74 | ||
|
|
7d27bfdcaf | ||
|
|
023d61a1e9 | ||
|
|
85d90a7f95 | ||
|
|
e0295eebde | ||
|
|
ebc9143593 | ||
|
|
e7c8fd748c | ||
|
|
aff601f61a | ||
|
|
0c5089fa79 | ||
|
|
e5556f3706 | ||
|
|
09c7f8541e | ||
|
|
8eb2ef438c | ||
|
|
34abe14151 | ||
|
|
90e37c198f | ||
|
|
1373283947 | ||
|
|
065616a18b | ||
|
|
53cd55a2a0 | ||
|
|
079be37fff | ||
|
|
806a8c57d4 | ||
|
|
797e769cc3 | ||
|
|
822a72e246 | ||
|
|
58b564b385 | ||
|
|
7aa9e2f6a4 | ||
|
|
f645686d87 | ||
|
|
6fcaa5d3d4 | ||
|
|
5d19e17a0b | ||
|
|
52a9f1ac1d | ||
|
|
3dec5e3225 | ||
|
|
90ded1612a | ||
|
|
7ab9fb7c28 | ||
|
|
6f499c68e2 | ||
|
|
19beba8fd7 | ||
|
|
f7e33802c8 | ||
|
|
c03d94105c | ||
|
|
632d56737b | ||
|
|
8801b93973 | ||
|
|
390a2b988e | ||
|
|
a66d7a64e6 | ||
|
|
a8596d3350 | ||
|
|
8a5dabee95 | ||
|
|
da859468d3 | ||
|
|
3e4583bbe9 | ||
|
|
b47440dd72 | ||
|
|
357a05f7ec | ||
|
|
f2fdb8195c | ||
|
|
8a0275d962 | ||
|
|
ef1fd9f579 | ||
|
|
f6b95d94bc | ||
|
|
2a65e6d359 | ||
|
|
83f87ba22c | ||
|
|
01321f5200 | ||
|
|
3a5851939e | ||
|
|
7d929e626e | ||
|
|
d8e0c77951 | ||
|
|
78ddb8ffb6 | ||
|
|
db37f35d09 | ||
|
|
d8f5fe4fd0 | ||
|
|
015fade4c0 | ||
|
|
da14b51e80 | ||
|
|
7a5ac01d1c | ||
|
|
5e6d64e965 | ||
|
|
c425fa41aa | ||
|
|
781157299f | ||
|
|
0f30317bb4 | ||
|
|
1f1bc0a7b9 | ||
|
|
60c8a6608a | ||
|
|
86adaf8c6b | ||
|
|
731688d16e | ||
|
|
63b66c48d8 | ||
|
|
ea19e511c0 | ||
|
|
f5e401cff8 | ||
|
|
bc8c7f318b | ||
|
|
585750007d | ||
|
|
6e80ac976a | ||
|
|
c70f18fcf4 | ||
|
|
d3e6aa2be2 | ||
|
|
b7a869c514 | ||
|
|
19362b950a | ||
|
|
0a4c31fb36 | ||
|
|
fef7694b48 | ||
|
|
60206e21df | ||
|
|
b9b77c66ce | ||
|
|
745a0e39d7 | ||
|
|
23bdadab56 | ||
|
|
47a4844ce8 | ||
|
|
8741be6cba | ||
|
|
4656a03ea9 | ||
|
|
5763eb828e | ||
|
|
6a5c20a165 | ||
|
|
fac166f186 | ||
|
|
091291bfa2 | ||
|
|
288fde67e8 | ||
|
|
ce30b77328 | ||
|
|
8c4e404f23 | ||
|
|
e8a4713f6e | ||
|
|
b4b23afc10 | ||
|
|
8f32e82d14 | ||
|
|
cf391bdd80 | ||
|
|
7120d6a9db | ||
|
|
4d80ab639e | ||
|
|
95bbd2852e | ||
|
|
4b0a934e51 | ||
|
|
ee5d86003b | ||
|
|
bc11b60147 | ||
|
|
801a4697ea | ||
|
|
628a970e6f | ||
|
|
566ea942dc | ||
|
|
e047c2d54e | ||
|
|
3fdd3d22e2 | ||
|
|
08e0fa9206 | ||
|
|
ed9e6ce676 | ||
|
|
a7bf07130e | ||
|
|
7c31662698 | ||
|
|
15df06a0bc | ||
|
|
47b5f8db7b | ||
|
|
0e763987aa | ||
|
|
37e8ea27d0 | ||
|
|
67d63256c2 | ||
|
|
ee185cf20a | ||
|
|
3552e05e4c | ||
|
|
735bb55b78 | ||
|
|
60f8a50a97 | ||
|
|
ffd01814b0 | ||
|
|
c511910b8f | ||
|
|
5c38f8f0d8 | ||
|
|
d512442325 | ||
|
|
43f54c90d2 | ||
|
|
57a99b478a | ||
|
|
3f402fbde7 | ||
|
|
98140c1f71 | ||
|
|
f00de85e38 | ||
|
|
b686b12c6a | ||
|
|
e4b903b13c | ||
|
|
72f576a70e | ||
|
|
c4f2c7be63 | ||
|
|
75b75fd223 | ||
|
|
391b18a5ac | ||
|
|
8de0f8e87c | ||
|
|
adb0b76559 | ||
|
|
b6df25c02c | ||
|
|
620186db1c | ||
|
|
21fac8046e | ||
|
|
de7c35f587 | ||
|
|
a23c979045 | ||
|
|
13da7287b1 | ||
|
|
e8398df9fc | ||
|
|
8303682bd7 | ||
|
|
8125d1a124 | ||
|
|
110ff5e12e | ||
|
|
24afcba20a | ||
|
|
d5f41d12e8 | ||
|
|
d640dd66e2 | ||
|
|
05bd9f57d6 | ||
|
|
60ab476ec7 | ||
|
|
bcae285ab3 | ||
|
|
cd67176b41 | ||
|
|
98eba54621 | ||
|
|
c530627078 | ||
|
|
f961947e1e | ||
|
|
e9e6628b21 | ||
|
|
c7684d6fe1 | ||
|
|
7d475ab403 | ||
|
|
143adcbbe4 | ||
|
|
ca8b6a33ba | ||
|
|
2f73cdb0f9 | ||
|
|
d1e06d9ef1 | ||
|
|
0ed78e2202 | ||
|
|
64818c586b | ||
|
|
578f5cad4a | ||
|
|
d2ff277b16 | ||
|
|
df4f9b3f8e | ||
|
|
be7f53a9ae | ||
|
|
6ed91a105e | ||
|
|
0db3c3af5a | ||
|
|
23748504e6 | ||
|
|
f74fecddd8 | ||
|
|
618a30c2ab | ||
|
|
b5116474c7 | ||
|
|
91e7239866 | ||
|
|
1dddb5fb3c | ||
|
|
8ddf592ffc | ||
|
|
59a1117ed3 | ||
|
|
3bb6fa1e59 | ||
|
|
5af98ac911 | ||
|
|
f197196c21 | ||
|
|
ce5595bc16 | ||
|
|
1406111f22 | ||
|
|
bfdada6792 | ||
|
|
5326ad85d8 | ||
|
|
f9dd245481 | ||
|
|
20677a9090 | ||
|
|
d54cb7507a | ||
|
|
d6b313b582 | ||
|
|
f31cdb413b | ||
|
|
69faf55b2b | ||
|
|
4d9e42205f | ||
|
|
5df69d73c7 | ||
|
|
4704f8485b | ||
|
|
809c216a5c | ||
|
|
415a40e436 | ||
|
|
d233f1d73f | ||
|
|
9a7019a2ce | ||
|
|
07b1623c5e | ||
|
|
681437acb1 |
+35
@@ -78,6 +78,8 @@ shine-solana/shine/scripts/**/TEMP_*.md
|
||||
|
||||
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
||||
ESP32/esp32-config-tool/
|
||||
ESP32/local-sketches/
|
||||
ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/
|
||||
ESP32/**/.git/
|
||||
ESP32/**/.idea/
|
||||
ESP32-wallet/.idea/
|
||||
@@ -105,6 +107,7 @@ ESP32/**/*.a
|
||||
# Полные серверные бэкапы (тяжёлые архивы, не коммитим)
|
||||
deploy/backup/archive/**
|
||||
!deploy/backup/archive/.gitkeep
|
||||
SHiNE-bundle-*.zip
|
||||
|
||||
# Локальная дев-обвязка AI-агентов (сессии, планы, настройки) — не коммитим
|
||||
.agents/
|
||||
@@ -113,3 +116,35 @@ deploy/backup/archive/**
|
||||
# Рабочие бэкапы/превью-ассеты UI — не для репозитория
|
||||
*.bak.png
|
||||
shine-UI/assets/navbar_preview.png
|
||||
|
||||
# Private local configuration: keep on disk, never push to GitHub
|
||||
/SHiNE-server/src/main/resources/application.properties
|
||||
/application.properties
|
||||
/deploy/backup/scheme/
|
||||
/shine-solana/shine/create-SHiNE-DAO/dao.config.mainnet.env
|
||||
**/.env
|
||||
**/.env.*
|
||||
!**/.env.example
|
||||
!**/.env.sample
|
||||
|
||||
# Private key files and local credential stores (never commit)
|
||||
*.key
|
||||
*.pem
|
||||
*.p12
|
||||
*.pfx
|
||||
*.jwk
|
||||
*.jks
|
||||
*.keystore
|
||||
*keypair*.json
|
||||
|
||||
# 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/
|
||||
|
||||
@@ -1,147 +1,33 @@
|
||||
# AGENTS
|
||||
# Актуальная архитектура SHiNE
|
||||
|
||||
## Язык проекта
|
||||
- По умолчанию использовать русский язык во всех пользовательских текстах и технических пояснениях.
|
||||
- Пояснения к коммитам, PR и merge-запросам писать на русском языке.
|
||||
- Комментарии в коде, встроенные справки, документацию и инструкции писать по возможности на русском языке.
|
||||
Начинать с [Blockchain](docs/Blockchain/README.md) и [общей архитектуры](docs/ARCHITECTURE.md). Активный runtime CORE/CONTENT, App=test5599. Прямая межсерверная репликация блоков не используется. Не менять протокол или независимые подсистемы без согласования. Интеграционную приёмку и production deploy выполнять отдельно с разрешения пользователя.
|
||||
|
||||
## Примечание
|
||||
- Если внешний инструмент/интеграция требует английский формат, допускается английский, но рядом желательно дать краткое пояснение на русском.
|
||||
---
|
||||
|
||||
## Структура проекта (кратко)
|
||||
- Серверный код SHiNE находится в папке `SHiNE-server/`.
|
||||
- Код клиентского UI SHiNE находится в папке `shine-UI/`.
|
||||
- Веб-панель администратора сервера (управление Solana PDA сервера) находится в `shine-UI/`:
|
||||
- точка входа `shine-UI/server-ui.html`;
|
||||
- остальные файлы серверного UI — в `shine-UI/server-ui/`.
|
||||
- Локальный Telegram-бот агента-кодера живёт рядом с репозиторием продукта, обычно в `../SHiNE-agent-bot-coder/`, и не входит в публичный код основного приложения.
|
||||
- Solana/Anchor-модуль находится в папке `shine-solana/shine/` и ведётся отдельно от основного server/UI деплоя.
|
||||
# Инструкции для агентов SHiNE
|
||||
|
||||
## Сервис агента-кодера
|
||||
- Локальный Telegram-бот-сервис агента-кодера находится вне этого git-репозитория, обычно в `../SHiNE-agent-bot-coder/`.
|
||||
- Сервис принимает сообщения из Telegram, ведёт историю диалога, ставит задачи в очередь и вызывает Codex CLI для обработки запросов по проекту.
|
||||
- Рабочая папка Codex для сервиса должна указывать на этот продуктовый репозиторий: `CODEX_WORKDIR=/home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-product`.
|
||||
- Автоматически читаемые инструкции для Codex внутри сервиса держать в `../SHiNE-agent-bot-coder/AGENTS.md`.
|
||||
- Подробные служебные правила Telegram-обработчика, его очередь, история, systemd-запуск и особенности ответов описывать в `../SHiNE-agent-bot-coder/AGENT.md`.
|
||||
- Если в сообщениях пользователя встречается «агент MD» или похожая формулировка про файл инструкций Codex, считать, что имеется в виду автоматически читаемый `AGENTS.md`.
|
||||
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
|
||||
|
||||
## ESP32 UI homeserver
|
||||
- Для UI-скетча устройства `ESP32-S3-Touch-AMOLED-2.16` документ-спецификация и Arduino-скетч должны всегда оставаться синхронными.
|
||||
- Актуальный документ по экранной логике, состояниям, кнопкам, полям, статусам и ограничениям UI считать источником истины для скетча.
|
||||
- При изменении документа обязательно в том же наборе изменений приводить в соответствие скетч.
|
||||
- При изменении скетча обязательно в том же наборе изменений обновлять документ, если поменялись экраны, тексты, переходы, статусы, кнопки, поля или поведение.
|
||||
- Для нового ESP32 UI-прототипа homeserver использовать русский язык как основной и отдельно следить, чтобы текст реально отображался на устройстве, а не только логически присутствовал в коде.
|
||||
## Сначала определить область работы
|
||||
|
||||
## Solana-модуль
|
||||
- В проекте есть отдельный Solana/Anchor-модуль в папке `shine-solana/shine/`.
|
||||
- Модуль логически связан с SHiNE, но не должен автоматически подключаться к сборке или деплою основного сервера без отдельного решения.
|
||||
- В Solana-модуле действуют локальные инструкции `shine-solana/shine/AGENTS.md`; при изменениях внутри модуля сначала читать их.
|
||||
- В git добавлять исходники, lock-файлы, настройки проекта и документацию Solana-модуля, но не добавлять локальные ключи, `.git`, `.idea`, `.gradle`, `target`, `node_modules`, `test-ledger`, логи, временные run-отчёты и `.env`-конфиги.
|
||||
- Для Solana deploy/push использовать правила из локального `shine-solana/shine/AGENTS.md`; не смешивать deploy Solana-модуля со скриптами основного server/UI deploy из `deploy/scripts/`.
|
||||
- Для регистрации пользователей в Solana (программа `shine_users`) единая актуальная инструкция по деплою/инициализации, адресам программ, и куда их прописывать в UI/сервере находится в:
|
||||
- `docs/Инициализация_Solana_регистрации/README.md`
|
||||
- Этот файл считать основной справкой (single source of truth) по деплою и первичной инициализации Solana-регистрации в текущем проекте.
|
||||
- Актуальная архитектурная справка по устройству Solana-программ, PDA-счетам, ролям DAO и движению средств находится в:
|
||||
- `docs/Solana_Architecture/README.md`
|
||||
- Документ формата пользовательской PDA-записи `shine_users` находится в:
|
||||
- `shine-solana/shine/doc/formats/shine-user-pda-format-v.1.0.md`
|
||||
| Область | Код | Правила и документация |
|
||||
| --- | --- | --- |
|
||||
| Сервер, WebSocket/API, PostgreSQL | `SHiNE-server/` | `SHiNE-server/AGENTS.md`, `docs/API/` |
|
||||
| Блокчейн, Arweave | `SHiNE-server/shine-server-blockchain/` | `docs/Blockchain/README.md` |
|
||||
| Личные сообщения | сервер и `shine-UI/` | `docs/Personal_Messages/README.md`, локальный `AGENTS.md` |
|
||||
| Браузерный UI | `shine-UI/` | `shine-UI/AGENTS.md`, `docs/UI-Design/README.md` |
|
||||
| Solana/Anchor | `shine-solana/shine/` | локальный `AGENTS.md`, `docs/Solana_Architecture/README.md` |
|
||||
| ESP32 | `ESP32/` | `ESP32/AGENTS.md`, инструкции конкретного устройства |
|
||||
| Деплой и резервные копии | `deploy/` | `deploy/AGENTS.md`, `deploy/backup/AGENTS.md` |
|
||||
| Тестовый издатель | `tools/test-publisher/` | локальный `AGENTS.md` |
|
||||
|
||||
## Документация блокчейна
|
||||
- Актуальная документация по форматам блокчейна находится в `docs/Blockchain/README.md`.
|
||||
- Это точка входа (оглавление), рядом расположены детальные файлы по форматам, типам каналов и командным сообщениям.
|
||||
- При любом изменении кода, связанного с блокчейном (формат блока, типы каналов, правила чтения/записи, команды), обязательно обновлять соответствующие документы в `docs/Blockchain/`.
|
||||
- Дополнительно обязательно вести `docs/Blockchain/CHANGELOG.md`: дописывать изменения построчно с указанием даты/времени и хэша коммита, после которого внесено изменение.
|
||||
- Перед любым изменением формата блокчейна обязательно заранее предупреждать пользователя, что формат будет изменён.
|
||||
- Изменять формат блокчейна можно только после явного подтверждения пользователя (без подтверждения формат не менять).
|
||||
- Добавление любых данных в блокчейн выполнять только через операцию `AddBlock`.
|
||||
- Перед каждым `AddBlock` обязательно проверять/актуализировать текущее состояние вершины блокчейна (`last global number/hash`) и использовать его при формировании блока.
|
||||
Общий каталог — `docs/README.md`; карта компонентов и потоков данных — `docs/ARCHITECTURE.md`. Правила сопровождения документов — `docs/CONTRIBUTING_DOCS.md`; после правки документации запускать `python3 scripts/check_docs.py`. Планы в `TODO/` не считать описанием действующего поведения или разрешением на реализацию.
|
||||
|
||||
## Документация личных сообщений (DM)
|
||||
- Актуальная документация по логике личных сообщений находится в `docs/Personal_Messages/Протокол_DM_v1.md`.
|
||||
- Точный байтовый формат DM находится в `docs/Personal_Messages/Формат_DM_v1.md`.
|
||||
- При любом изменении кода, связанного с личными сообщениями (формат подписанного DM-блока, типы DM-сообщений, правила доставки/ACK/read-receipt, роутинг по сессиям, UI-логика чатов), обязательно обновлять оба документа:
|
||||
- `docs/Personal_Messages/Протокол_DM_v1.md`
|
||||
- `docs/Personal_Messages/Формат_DM_v1.md`
|
||||
- Логика личных сообщений в коде должна всегда соответствовать этим документам.
|
||||
- Документ по личным сообщениям обязан поддерживаться в актуальном состоянии.
|
||||
## Постоянные правила
|
||||
|
||||
## Документация API сервера
|
||||
- Актуальная документация по публичному JSON/WebSocket API сервера находится в `docs/API/`.
|
||||
- При любом изменении серверного API/эндпоинтов/операций `op` обязательно обновлять соответствующие документы в `docs/API/`.
|
||||
- Перед изменением самого серверного API обязательно явно предупредить пользователя, какие операции, поля запросов/ответов или коды ошибок будут изменены, и запросить отдельное подтверждение.
|
||||
- Без явного подтверждения пользователя формат серверного API не менять; допускается только приведение документации в соответствие уже существующему коду.
|
||||
- Если добавляется новая операция `op`, нужно обновить общий список операций в `docs/API/09_Operations_Index.md` или создать его, если файла ещё нет.
|
||||
|
||||
## Документация Figma
|
||||
- Актуальная документация по переносу экранов SHiNE в Figma и обратному переносу из Figma в код находится в `docs/Figma/`.
|
||||
- Точка входа: `docs/Figma/README.md`.
|
||||
- Подробный рабочий регламент: `docs/Figma/TRANSFER_UI_SCREENS.md`.
|
||||
- Для экранов регистрации, входа и других чувствительных UI-flow по умолчанию переносить экраны в Figma по одному, а не пачкой, если пользователь отдельно не подтвердил иной способ.
|
||||
|
||||
## Версионирование
|
||||
- Единый файл версий проекта: `VERSION.properties` (в корне репозитория).
|
||||
- Перед каждым новым коммитом обязательно увеличивать версии в `VERSION.properties`:
|
||||
- `client.version` — версия клиентского UI.
|
||||
- `server.version` — версия серверной части.
|
||||
- Базовое правило инкремента: `+1` по последнему числовому сегменту (patch), если не оговорено иное.
|
||||
- Обычные коммиты делать стандартным `git commit`; переменная `$GITEA_TOKEN` для коммитов не нужна и не используется.
|
||||
|
||||
## Deploy
|
||||
- Все документы, инструкции, backup-правила и скрипты деплоя хранить в папке `deploy/`.
|
||||
- Подробные правила для агента по деплою находятся в `deploy/AGENTS.md`; перед любым deploy читать этот файл.
|
||||
- Production-серверы SHiNE: `shineup.me` и `server2.shineup.me`.
|
||||
- Тестовые/devnet серверы SHiNE: `t1.shineup.me`, `t2.shineup.me`, `t3.shineup.me`, `t4.shineup.me`.
|
||||
- В deploy-документах и скриптах использовать домены, а не IP.
|
||||
- По возможности все справки, комментарии и примечания в конфигах/документах писать на русском языке.
|
||||
- Для операций `git push` при необходимости использовать токен из переменной окружения `$GITEA_TOKEN`.
|
||||
- Любые изменения и любой деплой на production (`shineup.me` и `server2.shineup.me`) выполнять только после отдельного явного подтверждения пользователя.
|
||||
- Перед production deploy обязательно проверить/обновить бэкап в `deploy/backup/archive/`.
|
||||
- Если пользователь пишет просто `задеплой` без уточнения production/test, уточнить целевой контур; не выбирать production автоматически.
|
||||
- Deploy выполнять shell-скриптами из `deploy/scripts/`; Gradle deploy-задачи не использовать.
|
||||
- Для локального запуска использовать `./gradlew startLocal` (или `startLocalWithBuild`).
|
||||
- Сначала предлагать локальную проверку, а деплой на сервер выполнять по запросу пользователя.
|
||||
- Для временной бесплатной загрузки аватаров в Arweave секретный JWK нельзя хранить в git и нельзя прописывать в репозиторный `application.properties`.
|
||||
- Для продовой настройки тестового Arweave-кошелька JWK-файл нужно хранить только на сервере, например: `/home/player/SHiNE/secrets/test-free-avatar-wallet.json`.
|
||||
- Для этой временной фичи на проде должны быть заданы параметры `test.freeAvatar.walletJwkPath` и `test.freeAvatar.walletAddress` через серверный override-конфиг/секреты на хосте.
|
||||
- После изменения продовых значений `test.freeAvatar.*` нужно заново выполнить серверный деплой или перезапуск сервера, чтобы настройки были перечитаны приложением.
|
||||
- При таких изменениях в git допускается коммитить только документацию и код чтения настроек, но не сам JWK, не содержимое секрета и не реальные приватные ключи.
|
||||
|
||||
## Логи звонков (установка соединения)
|
||||
- Специальный поток диагностики установки звонков идёт через `CallDeliveryReport` (клиент → сервер).
|
||||
- На проде специальный файл для звонков:
|
||||
- `/home/player/SHiNE/shine-server/logs/call-delivery-events.log`
|
||||
- Общий серверный лог (и ротации) на проде:
|
||||
- `/home/player/SHiNE/shine-server/logs/app.log`
|
||||
- `/home/player/SHiNE/shine-server/logs/app.YYYY-MM-DD.log`
|
||||
- Для анализа причин недозвона в первую очередь фильтровать записи по ключам:
|
||||
- `CallDeliveryReport`
|
||||
- `call_connected`
|
||||
- `outgoing_failed`
|
||||
- `incoming_failed`
|
||||
- `call_busy`
|
||||
- `call_declined`
|
||||
- `unknown_error`
|
||||
- В этих записях искать поля `reason`, `failureStage`, `pcConnectionState`, `pcIceConnectionState`, `routeLabel`, `configuredTurnHosts*`, `reachableTurnHosts*`.
|
||||
|
||||
## Будущие фичи / TODO
|
||||
- Папка для задач, сознательно отложенных на будущее: `TODO/`.
|
||||
- Точка входа по планам: `TODO/README.md`.
|
||||
- Внутри планы разделены по горизонтам: `near/`, `medium/`, `far/` и тематическим подпапкам.
|
||||
- Если пользователь спрашивает, какие есть планы или что можно продолжить, сначала читать `TODO/README.md`, затем при необходимости конкретные файлы из подпапок.
|
||||
- Файлы из этой папки не считать активными задачами и не начинать реализацию без явной просьбы пользователя.
|
||||
- Старую папку `docs/Future_Features/` считать выведенной из использования и больше не использовать для новых записей.
|
||||
- Если часть кода временно отключена или закомментирована, либо удалена как временная заглушка, в TODO-файле подробно описывать:
|
||||
- какие файлы и участки отключены;
|
||||
- что осталось в коде как заготовка;
|
||||
- какие документы нужно обновить при возврате;
|
||||
- с какого сценария продолжать разработку;
|
||||
- из какого коммита брать последнюю полную реализацию.
|
||||
|
||||
## Коммуникация по новым задачам (обязательно)
|
||||
- При получении нового задания сначала кратко пересказать задачу своими словами.
|
||||
- До начала реализации задать недостающие уточняющие вопросы (если они есть).
|
||||
- Если есть уместные идеи/улучшения — кратко предложить их; если полезных идей нет, ничего дополнительно не предлагать.
|
||||
- Добавлять краткую оценку фичи (насколько это полезно/удачно по мнению исполнителя).
|
||||
- После этого обязательно запросить подтверждение от пользователя, что задача понята верно, и только после подтверждения переходить к реализации.
|
||||
- Если вопросов нет, явно написать в формате: «Я всё понял, начинаю делать?» и ждать подтверждения.
|
||||
- Без подтверждения пользователя реализацию не начинать.
|
||||
- Прежде чем править подсистему, прочитать её локальный `AGENTS.md` и действующую документацию через `docs/README.md`. Архивные отчёты и старые планы не использовать как текущий контракт. При расхождении документа с кодом проверить реализацию и исправить документ либо явно отметить неопределённость.
|
||||
- Изменение поведения, формата, API, конфигурации или пользовательского сценария сопровождать обновлением соответствующего документа в том же наборе изменений. Не выдавать план, черновик или тестовое состояние за действующую функцию.
|
||||
- Формат блокчейна и контракт серверного API изменять только после отдельного явного согласия пользователя; документировать изменения в `docs/Blockchain/` и `docs/API/`. Для добавления блока использовать `AddBlock` с актуальной вершиной цепочки.
|
||||
- Любые изменения и деплой production (`shineup.me`, `server2.shineup.me`) — только после отдельного явного согласия пользователя. Перед деплоем прочитать `deploy/AGENTS.md` и проверить резервную копию. Для деплоя использовать скрипты `deploy/scripts/`.
|
||||
- Секреты, приватные ключи, локальные конфиги, сборочные артефакты и логи не добавлять в git.
|
||||
- Коммиты, версии и merge выполнять по `COMMIT_AND_VERSION_RULES.md`. Не делать коммит или push без необходимости для задачи.
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Правила коммитов, merge и версионирования
|
||||
|
||||
Этот файл является единым источником правил для:
|
||||
- коммитов;
|
||||
- merge в `main`;
|
||||
- изменения версий в `VERSION.properties`;
|
||||
- `git push` из этого репозитория.
|
||||
|
||||
## Язык
|
||||
|
||||
- Пояснения к коммитам, PR и merge-запросам писать на русском языке.
|
||||
|
||||
## Где хранится версия
|
||||
|
||||
- Единый файл версий проекта: `VERSION.properties` в корне репозитория.
|
||||
- Основные поля:
|
||||
- `client.version` — версия клиентского UI.
|
||||
- `server.version` — версия серверной части.
|
||||
|
||||
## Базовое правило для обычных коммитов
|
||||
|
||||
- Версии обновляются только вместе с изменениями соответствующего продукта: UI — `client.version`, сервер — `server.version`.
|
||||
- Если менялся только UI, увеличивать только `client.version`.
|
||||
- Если менялся только сервер, увеличивать только `server.version`.
|
||||
- Если менялись и UI, и сервер, увеличивать обе версии.
|
||||
- Для обычных коммитов вне `main` использовать стандартный patch-инкремент: `+1` к последнему числовому сегменту.
|
||||
- Пример: `1.2.346` → `1.2.347`.
|
||||
|
||||
- Коммиты только с документацией, настройками процесса или служебными файлами не требуют изменения `VERSION.properties`.
|
||||
|
||||
## Правило для `main`
|
||||
|
||||
- Ветка `main` предназначена только для стабильных версий.
|
||||
- По умолчанию в `main` нужно не коммитить напрямую, а мержить готовые изменения из рабочей ветки.
|
||||
- Если пользователь просит сделать прямой коммит в `main`, нужно отдельно и явно предупредить, что это обход обычного стабильного процесса, и обязательно переспросить подтверждение.
|
||||
- При merge рабочей ветки в `main` не нужно дополнительно изменять `VERSION.properties` и создавать отдельный коммит только ради версии.
|
||||
- Версия в `main` приходит из уже подготовленного коммита рабочей ветки; после merge достаточно проверить, что она соответствует слитым изменениям.
|
||||
|
||||
## Правила для git commit и git push
|
||||
|
||||
- Обычные коммиты делать стандартным `git commit`; токен для локального коммита не нужен и не используется.
|
||||
- Для операций `git push` при необходимости использовать токен из переменной окружения `$GITEA_TOKEN`.
|
||||
+2
-2
@@ -8,12 +8,12 @@
|
||||
|
||||
## Синхронизация со спецификацией
|
||||
|
||||
- При изменении экранов, кнопок, переходов, статусов или текстов обязательно обновлять соответствующую спецификацию в `ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/reference/`.
|
||||
- При изменении экранов, кнопок, переходов, статусов или текстов обновлять соответствующую спецификацию в `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/`.
|
||||
|
||||
## Сборка ESP32
|
||||
|
||||
- Основной способ проверки и прошивки скетчей для `ESP32-S3-Touch-AMOLED-2.16` - `main-device/burn.sh`.
|
||||
- Не собирать эти скетчи напрямую через `arduino-cli compile` без `burn.sh`, потому что скрипт добавляет нужные локальные библиотеки и конфиги из `official-demo/examples/Arduino-v3.3.5/libraries`.
|
||||
- Не собирать эти скетчи напрямую через `arduino-cli compile` без `burn.sh`, потому что скрипт добавляет нужные библиотеки и конфиги из `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5/libraries`.
|
||||
- Если сборка падает по `lv_conf.h` или `TouchDrvCSTXXX.hpp`, сначала проверять именно `burn.sh` и его `--library` пути, а не считать, что файл пропал из репозитория.
|
||||
|
||||
## Диагностика ESP32
|
||||
|
||||
@@ -32,27 +32,24 @@ ls -l /dev/ttyACM0
|
||||
|
||||
## 3) Структура подпроекта (эталон)
|
||||
|
||||
- `official-demo/` — официальный repo Waveshare (примеры+библиотеки)
|
||||
- `original-firmware/` — backup/restore заводской прошивки
|
||||
- `main-device/` — прошивки и `burn.sh`
|
||||
- `reference/` — заметки и ссылки
|
||||
- `main-device/` — актуальная прошивка регистрации и `burn.sh`
|
||||
- `old_version/` — старые версии homeserver
|
||||
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/` — официальный repo Waveshare (примеры+библиотеки)
|
||||
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/` — заметки и спецификации
|
||||
|
||||
## 4) Бэкап перед любыми экспериментами
|
||||
|
||||
```bash
|
||||
cd ESP32-S3-Touch-AMOLED-2.16/original-firmware
|
||||
./backup_factory.sh
|
||||
cd ESP32-S3-Touch-AMOLED-2.16/main-device
|
||||
./burn.sh registration-signer
|
||||
```
|
||||
|
||||
Ожидаемый результат:
|
||||
- `factory-full-16mb.bin`
|
||||
- `factory-full-16mb.bin.sha256`
|
||||
- резервная копия заводской прошивки хранится отдельно от Git-проектов
|
||||
|
||||
Восстановление:
|
||||
|
||||
```bash
|
||||
./restore_factory_backup.sh
|
||||
```
|
||||
Восстановление выполняется из локального каталога backup конкретной платы.
|
||||
|
||||
## 5) Деплой (прошивка) — стандарт
|
||||
|
||||
@@ -67,7 +64,7 @@ cd ESP32-S3-Touch-AMOLED-2.16/main-device
|
||||
- `hello` — базовый экран
|
||||
- `widgets` — экран+touch+IMU (официальный пример)
|
||||
- `audio` — тест аудио тракта
|
||||
- `simple` — кастомный интеграционный тест (экран, touch, запись/воспроизведение, VU, tilt)
|
||||
- `registration-signer` — актуальный скетч регистрации SHiNE
|
||||
|
||||
## 6) Как писать код под эту плату (важно)
|
||||
|
||||
|
||||
@@ -1,28 +1,26 @@
|
||||
# ESP32-S3-Touch-AMOLED-2.16
|
||||
|
||||
Подпроект для Waveshare `ESP32-S3-Touch-AMOLED-2.16`.
|
||||
Подпроект SHiNE для платы Waveshare `ESP32-S3-Touch-AMOLED-2.16`.
|
||||
|
||||
Структура:
|
||||
В основном проекте оставлен только актуальный рабочий скетч регистрации:
|
||||
|
||||
- `official-demo/` — официальный репозиторий примеров Waveshare
|
||||
- `original-firmware/` — резервная копия заводской прошивки
|
||||
- `main-device/` — скрипты быстрой проверки устройства и основной скетч `shine_homeserver_main/`
|
||||
- `reference/` — локальные заметки по документации и железу
|
||||
- `main-device/shine_homeserver_main/` — основной рабочий скетч ESP32-проекта `SHiNE`
|
||||
- `main-device/shine_registration_signer/shine_registration_signer.ino`
|
||||
- `main-device/burn.sh` — сборка и прошивка
|
||||
- `old_version/` — две старые версии homeserver, сохранённые только для истории
|
||||
|
||||
Примечание по git:
|
||||
Примеры Waveshare, библиотеки и справочные документы находятся в отдельном репозитории `SKETCH`:
|
||||
|
||||
- `official-demo/` держать как локальный внешний checkout из `https://github.com/waveshareteam/ESP32-S3-Touch-AMOLED-2.16`, в основной git его не добавлять.
|
||||
- `original-firmware/*.bin` — локальный дамп конкретной платы, в git не добавлять.
|
||||
- `.arduino-build/` и готовые `.bin/.elf/.map` — сборочные артефакты, в git не добавлять.
|
||||
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`
|
||||
- `SKETCH/ESP32-S3-Touch-AMOLED-2.16/reference/`
|
||||
|
||||
Локальные сборочные артефакты (`.arduino-build/`, `.bin`, `.elf`, `.map`) в Git не добавляются.
|
||||
|
||||
Быстрый старт:
|
||||
|
||||
1. Сделать backup текущей прошивки:
|
||||
- `cd original-firmware && ./backup_factory.sh`
|
||||
2. Залить тест экрана/тача:
|
||||
- `cd ../main-device && ./burn.sh widgets`
|
||||
3. Залить тест динамика:
|
||||
- `cd ../main-device && ./burn.sh audio`
|
||||
4. Залить основной UI:
|
||||
- `cd ../main-device && ./burn.sh shine-homeserver-main`
|
||||
1. Убедиться, что рядом с `SHiNE-product` существует `SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`.
|
||||
2. Перейти в `main-device`.
|
||||
3. Собрать и прошить актуальный скетч:
|
||||
|
||||
`./burn.sh registration-signer`
|
||||
|
||||
Для тестового режима регистратора можно использовать `REGISTRAR_DEV_UNENCRYPTED=1`, но такой вариант нельзя использовать на рабочем устройстве.
|
||||
|
||||
@@ -1,52 +1,14 @@
|
||||
# Main Device
|
||||
|
||||
Основной скетч homeserver и старые тестовые скетчи для быстрой проверки платы.
|
||||
`burn.sh` теперь:
|
||||
- сам пытается найти USB-порт ESP32;
|
||||
- сначала делает быструю инкрементальную сборку;
|
||||
- если быстрая сборка не удалась, автоматически повторяет полную `clean`-сборку.
|
||||
В этой папке оставлен только актуальный скетч `shine_registration_signer`.
|
||||
|
||||
Для режимов `widgets`, `audio` и `hello` рядом должен лежать локальный checkout `official-demo/` из официального репозитория Waveshare. В основной git он не добавляется, потому что это большой внешний набор примеров, библиотек, прошивок и артефактов.
|
||||
`burn.sh` поддерживает режимы:
|
||||
|
||||
Режимы:
|
||||
- `widgets` — экран + touch + IMU (пример `05_LVGL_Widgets`)
|
||||
- `audio` — динамик/аудио-кодек (пример `07_ES8311`)
|
||||
- `hello` — базовый тест экрана (пример `01_HelloWorld`)
|
||||
- `simple` — простой кастомный тест: экран + touch + запись/проигрывание + наклон (IMU)
|
||||
- `argon2` — генерация masterSecret через Argon2id с SD-картой как памятью (тест скорости)
|
||||
- `homeserver-ui` — совместимый алиас, указывает на `shine_homeserver_main/`
|
||||
- `shine-homeserver-main` — основной скетч проекта `SHiNE` для ESP32, текущая рабочая версия UI
|
||||
- `shine-homeserver-ui-main` — старое имя основного скетча, оставлено как совместимый алиас
|
||||
- `legacy-homeserver-ui` — старый UI-прототип `shine_homeserver_ui/`, оставлен как тестовый и не является основным
|
||||
- `text-test` — диагностический экран рендера текста: default font, U8g2 ASCII, U8g2 кириллица, кнопки с подписями
|
||||
- `gfx-text-test` — тот же тест рендера текста, но уже внутри новой папки `test_sketches/`
|
||||
- `gfx-layout-test` — тест геометрии и нижних рядов кнопок
|
||||
- `lvgl-basic-test` — минимальный экран на `LVGL` с текстом и кнопками
|
||||
- `lvgl-interaction-test` — экран на `LVGL` с большим числом кнопок и сообщением о нажатой кнопке
|
||||
- `lvgl-touch-debug-test` — точечная диагностика touch: сырые координаты, маркер точки и большая тест-кнопка `LVGL`
|
||||
- `lvgl-official-based-test` — наш минимальный экран, но на максимально близкой к официальному `LVGL_Widgets` инициализации
|
||||
- `lvgl-subserver-touch-test` — старый гибридный тест: `LVGL`-интерфейс, но display/touch init и raw touch-read взяты из старого `shine_homeserver_ui`; подтверждено на устройстве, touch работает, зелёных линий по краям нет
|
||||
- `lvgl-russian-font-test` — тест кастомного `LVGL`-шрифта с кириллицей: русские кнопки, длинные подписи и статусы
|
||||
- `lvgl-nav-minimal-test` — старое имя основного скетча, теперь ведёт на `shine_homeserver_main/` для совместимости
|
||||
- `registration-signer` — рабочий скетч регистрации SHiNE;
|
||||
- `hello`, `widgets`, `audio` — официальные тесты Waveshare из репозитория `SKETCH`.
|
||||
|
||||
Запуск:
|
||||
Официальные библиотеки должны находиться в соседнем репозитории:
|
||||
|
||||
- `./burn.sh widgets`
|
||||
- `./burn.sh audio`
|
||||
- `./burn.sh hello`
|
||||
- `./burn.sh simple`
|
||||
- `./burn.sh homeserver-ui`
|
||||
- `./burn.sh shine-homeserver-main`
|
||||
- `./burn.sh shine-homeserver-ui-main`
|
||||
- `./burn.sh legacy-homeserver-ui`
|
||||
- `./burn.sh text-test`
|
||||
- `./burn.sh gfx-text-test`
|
||||
- `./burn.sh gfx-layout-test`
|
||||
- `./burn.sh lvgl-basic-test`
|
||||
- `./burn.sh lvgl-interaction-test`
|
||||
- `./burn.sh lvgl-touch-debug-test`
|
||||
- `./burn.sh lvgl-official-based-test`
|
||||
- `./burn.sh lvgl-subserver-touch-test`
|
||||
- `./burn.sh lvgl-russian-font-test`
|
||||
- `./burn.sh lvgl-nav-minimal-test`
|
||||
- `./flash_shine_homeserver_main.sh` - автоматически находит USB-порт и заливает `shine_homeserver_main`
|
||||
`SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/`
|
||||
|
||||
Если репозитории расположены иначе, перед запуском укажите путь через переменную `DEMO_BASE`.
|
||||
|
||||
@@ -3,7 +3,7 @@ set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
BOARD_DIR="$(cd "${ROOT_DIR}/.." && pwd)"
|
||||
DEMO_BASE="${BOARD_DIR}/official-demo/examples/Arduino-v3.3.5"
|
||||
DEMO_BASE="${DEMO_BASE:-${BOARD_DIR}/../../../../SKETCH/ESP32-S3-Touch-AMOLED-2.16/official-demo/examples/Arduino-v3.3.5}"
|
||||
MODE="${1:-widgets}"
|
||||
PORT="${PORT:-}"
|
||||
FQBN="${FQBN:-esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi}"
|
||||
@@ -32,39 +32,16 @@ case "${MODE}" in
|
||||
hello) SKETCH_DIR="${DEMO_BASE}/examples/01_HelloWorld" ;;
|
||||
widgets) SKETCH_DIR="${DEMO_BASE}/examples/05_LVGL_Widgets" ;;
|
||||
audio) SKETCH_DIR="${DEMO_BASE}/examples/07_ES8311" ;;
|
||||
simple) SKETCH_DIR="${ROOT_DIR}/simple_av_test" ;;
|
||||
argon2) SKETCH_DIR="${ROOT_DIR}/argon2_sd_test" ;;
|
||||
homeserver-ui) 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" ;;
|
||||
legacy-homeserver-ui) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_ui" ;;
|
||||
text-test) SKETCH_DIR="${ROOT_DIR}/text_render_test" ;;
|
||||
gfx-text-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/gfx_text_render_test" ;;
|
||||
gfx-layout-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/gfx_button_layout_test" ;;
|
||||
lvgl-basic-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_basic_test" ;;
|
||||
lvgl-interaction-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_interaction_test" ;;
|
||||
lvgl-touch-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_touch_debug_test" ;;
|
||||
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
|
||||
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
|
||||
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
|
||||
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
||||
registration-signer) SKETCH_DIR="${ROOT_DIR}/shine_registration_signer" ;;
|
||||
*)
|
||||
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" >&2
|
||||
echo "Use one of: registration-signer, hello, widgets, audio" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z "${PORT}" ]]; then
|
||||
if ! PORT="$(detect_port)"; then
|
||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||
exit 3
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "== Mode: ${MODE}"
|
||||
echo "== Sketch: ${SKETCH_DIR}"
|
||||
echo "== Port: ${PORT}"
|
||||
echo "== FQBN: ${FQBN}"
|
||||
|
||||
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
||||
@@ -81,12 +58,31 @@ compile_args=(
|
||||
"${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"
|
||||
if ! arduino-cli compile "${compile_args[@]}"; then
|
||||
echo "== Compile: fast build failed, retrying clean build"
|
||||
arduino-cli compile --clean "${compile_args[@]}"
|
||||
fi
|
||||
|
||||
if [[ "${NO_UPLOAD:-0}" == "1" ]]; then
|
||||
echo "== Done: compiled without upload (NO_UPLOAD=1)."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [[ -z "${PORT}" ]]; then
|
||||
if ! PORT="$(detect_port)"; then
|
||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||
exit 3
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "== Port: ${PORT}"
|
||||
|
||||
arduino-cli upload \
|
||||
-p "${PORT}" \
|
||||
--fqbn "${FQBN}" \
|
||||
|
||||
+39
@@ -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/проверку реального устройства.
|
||||
+54
@@ -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
|
||||
+29
@@ -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;}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
02003830de5c252e8d4da7dab6de28fdc2f8693dc709f4688895c2e92e2092113f4172cd21a1c7e9842c4cac6fd0cb0537c958d8ad22a00f0297082275df4edf730e03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b800000300000000000000390000000000000006064170701074657374353539390274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d56310001000c4578616d706c654066726565202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f779d957dfe14d4d4097cfcb567944a1a3b4ee04024b71c189d95cfe15ed1bba8a5cf7b7a314e264437a0361f7422c287da24e70d785a0e7c2b1f8cc7073e6d05808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f
|
||||
+4
@@ -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("");}
|
||||
Executable
+10
@@ -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'
|
||||
+35
@@ -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";
|
||||
+377
@@ -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);}
|
||||
-784
@@ -1,784 +0,0 @@
|
||||
/**
|
||||
* @file lv_conf.h
|
||||
* Configuration file for v8.4.0
|
||||
*/
|
||||
|
||||
/*
|
||||
* Copy this file as `lv_conf.h`
|
||||
* 1. simply next to the `lvgl` folder
|
||||
* 2. or any other places and
|
||||
* - define `LV_CONF_INCLUDE_SIMPLE`
|
||||
* - add the path as include path
|
||||
*/
|
||||
|
||||
/* clang-format off */
|
||||
#if 1 /*Set it to "1" to enable content*/
|
||||
|
||||
#ifndef LV_CONF_H
|
||||
#define LV_CONF_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/*====================
|
||||
COLOR SETTINGS
|
||||
*====================*/
|
||||
|
||||
/*Color depth: 1 (1 byte per pixel), 8 (RGB332), 16 (RGB565), 32 (ARGB8888)*/
|
||||
#define LV_COLOR_DEPTH 16
|
||||
|
||||
/*Swap the 2 bytes of RGB565 color. Useful if the display has an 8-bit interface (e.g. SPI)*/
|
||||
#define LV_COLOR_16_SWAP 0
|
||||
|
||||
/*Enable features to draw on transparent background.
|
||||
*It's required if opa, and transform_* style properties are used.
|
||||
*Can be also used if the UI is above another layer, e.g. an OSD menu or video player.*/
|
||||
#define LV_COLOR_SCREEN_TRANSP 0
|
||||
|
||||
/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
|
||||
* 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
|
||||
#define LV_COLOR_MIX_ROUND_OFS 0
|
||||
|
||||
/*Images pixels with this color will not be drawn if they are chroma keyed)*/
|
||||
#define LV_COLOR_CHROMA_KEY lv_color_hex(0x00ff00) /*pure green*/
|
||||
|
||||
/*=========================
|
||||
MEMORY SETTINGS
|
||||
*=========================*/
|
||||
|
||||
/*1: use custom malloc/free, 0: use the built-in `lv_mem_alloc()` and `lv_mem_free()`*/
|
||||
#define LV_MEM_CUSTOM 0
|
||||
#if LV_MEM_CUSTOM == 0
|
||||
/*Size of the memory available for `lv_mem_alloc()` in bytes (>= 2kB)*/
|
||||
#define LV_MEM_SIZE (48U * 1024U) /*[bytes]*/
|
||||
|
||||
/*Set an address for the memory pool instead of allocating it as a normal array. Can be in external SRAM too.*/
|
||||
#define LV_MEM_ADR 0 /*0: unused*/
|
||||
/*Instead of an address give a memory allocator that will be called to get a memory pool for LVGL. E.g. my_malloc*/
|
||||
#if LV_MEM_ADR == 0
|
||||
#undef LV_MEM_POOL_INCLUDE
|
||||
#undef LV_MEM_POOL_ALLOC
|
||||
#endif
|
||||
|
||||
#else /*LV_MEM_CUSTOM*/
|
||||
#define LV_MEM_CUSTOM_INCLUDE <stdlib.h> /*Header for the dynamic memory function*/
|
||||
#define LV_MEM_CUSTOM_ALLOC malloc
|
||||
#define LV_MEM_CUSTOM_FREE free
|
||||
#define LV_MEM_CUSTOM_REALLOC realloc
|
||||
#endif /*LV_MEM_CUSTOM*/
|
||||
|
||||
/*Number of the intermediate memory buffer used during rendering and other internal processing mechanisms.
|
||||
*You will see an error log message if there wasn't enough buffers. */
|
||||
#define LV_MEM_BUF_MAX_NUM 16
|
||||
|
||||
/*Use the standard `memcpy` and `memset` instead of LVGL's own functions. (Might or might not be faster).*/
|
||||
#define LV_MEMCPY_MEMSET_STD 0
|
||||
|
||||
/*====================
|
||||
HAL SETTINGS
|
||||
*====================*/
|
||||
|
||||
/*Default display refresh period. LVG will redraw changed areas with this period time*/
|
||||
#define LV_DISP_DEF_REFR_PERIOD 10 /*[ms]*/
|
||||
|
||||
/*Input device read period in milliseconds*/
|
||||
#define LV_INDEV_DEF_READ_PERIOD 10 /*[ms]*/
|
||||
|
||||
/*Use a custom tick source that tells the elapsed time in milliseconds.
|
||||
*It removes the need to manually update the tick with `lv_tick_inc()`)*/
|
||||
#define LV_TICK_CUSTOM 0
|
||||
#if LV_TICK_CUSTOM
|
||||
#define LV_TICK_CUSTOM_INCLUDE "Arduino.h" /*Header for the system time function*/
|
||||
#define LV_TICK_CUSTOM_SYS_TIME_EXPR (millis()) /*Expression evaluating to current system time in ms*/
|
||||
/*If using lvgl as ESP32 component*/
|
||||
// #define LV_TICK_CUSTOM_INCLUDE "esp_timer.h"
|
||||
// #define LV_TICK_CUSTOM_SYS_TIME_EXPR ((esp_timer_get_time() / 1000LL))
|
||||
#endif /*LV_TICK_CUSTOM*/
|
||||
|
||||
/*Default Dot Per Inch. Used to initialize default sizes such as widgets sized, style paddings.
|
||||
*(Not so important, you can adjust it to modify default sizes and spaces)*/
|
||||
#define LV_DPI_DEF 130 /*[px/inch]*/
|
||||
|
||||
/*=======================
|
||||
* FEATURE CONFIGURATION
|
||||
*=======================*/
|
||||
|
||||
/*-------------
|
||||
* Drawing
|
||||
*-----------*/
|
||||
|
||||
/*Enable complex draw engine.
|
||||
*Required to draw shadow, gradient, rounded corners, circles, arc, skew lines, image transformations or any masks*/
|
||||
#define LV_DRAW_COMPLEX 1
|
||||
#if LV_DRAW_COMPLEX != 0
|
||||
|
||||
/*Allow buffering some shadow calculation.
|
||||
*LV_SHADOW_CACHE_SIZE is the max. shadow size to buffer, where shadow size is `shadow_width + radius`
|
||||
*Caching has LV_SHADOW_CACHE_SIZE^2 RAM cost*/
|
||||
#define LV_SHADOW_CACHE_SIZE 0
|
||||
|
||||
/* Set number of maximally cached circle data.
|
||||
* The circumference of 1/4 circle are saved for anti-aliasing
|
||||
* radius * 4 bytes are used per circle (the most often used radiuses are saved)
|
||||
* 0: to disable caching */
|
||||
#define LV_CIRCLE_CACHE_SIZE 4
|
||||
#endif /*LV_DRAW_COMPLEX*/
|
||||
|
||||
/**
|
||||
* "Simple layers" are used when a widget has `style_opa < 255` to buffer the widget into a layer
|
||||
* and blend it as an image with the given opacity.
|
||||
* Note that `bg_opa`, `text_opa` etc don't require buffering into layer)
|
||||
* The widget can be buffered in smaller chunks to avoid using large buffers.
|
||||
*
|
||||
* - LV_LAYER_SIMPLE_BUF_SIZE: [bytes] the optimal target buffer size. LVGL will try to allocate it
|
||||
* - LV_LAYER_SIMPLE_FALLBACK_BUF_SIZE: [bytes] used if `LV_LAYER_SIMPLE_BUF_SIZE` couldn't be allocated.
|
||||
*
|
||||
* Both buffer sizes are in bytes.
|
||||
* "Transformed layers" (where transform_angle/zoom properties are used) use larger buffers
|
||||
* and can't be drawn in chunks. So these settings affects only widgets with opacity.
|
||||
*/
|
||||
#define LV_LAYER_SIMPLE_BUF_SIZE (24 * 1024)
|
||||
#define LV_LAYER_SIMPLE_FALLBACK_BUF_SIZE (3 * 1024)
|
||||
|
||||
/*Default image cache size. Image caching keeps the images opened.
|
||||
*If only the built-in image formats are used there is no real advantage of caching. (I.e. if no new image decoder is added)
|
||||
*With complex image decoders (e.g. PNG or JPG) caching can save the continuous open/decode of images.
|
||||
*However the opened images might consume additional RAM.
|
||||
*0: to disable caching*/
|
||||
#define LV_IMG_CACHE_DEF_SIZE 0
|
||||
|
||||
/*Number of stops allowed per gradient. Increase this to allow more stops.
|
||||
*This adds (sizeof(lv_color_t) + 1) bytes per additional stop*/
|
||||
#define LV_GRADIENT_MAX_STOPS 2
|
||||
|
||||
/*Default gradient buffer size.
|
||||
*When LVGL calculates the gradient "maps" it can save them into a cache to avoid calculating them again.
|
||||
*LV_GRAD_CACHE_DEF_SIZE sets the size of this cache in bytes.
|
||||
*If the cache is too small the map will be allocated only while it's required for the drawing.
|
||||
*0 mean no caching.*/
|
||||
#define LV_GRAD_CACHE_DEF_SIZE 0
|
||||
|
||||
/*Allow dithering the gradients (to achieve visual smooth color gradients on limited color depth display)
|
||||
*LV_DITHER_GRADIENT implies allocating one or two more lines of the object's rendering surface
|
||||
*The increase in memory consumption is (32 bits * object width) plus 24 bits * object width if using error diffusion */
|
||||
#define LV_DITHER_GRADIENT 0
|
||||
#if LV_DITHER_GRADIENT
|
||||
/*Add support for error diffusion dithering.
|
||||
*Error diffusion dithering gets a much better visual result, but implies more CPU consumption and memory when drawing.
|
||||
*The increase in memory consumption is (24 bits * object's width)*/
|
||||
#define LV_DITHER_ERROR_DIFFUSION 0
|
||||
#endif
|
||||
|
||||
/*Maximum buffer size to allocate for rotation.
|
||||
*Only used if software rotation is enabled in the display driver.*/
|
||||
#define LV_DISP_ROT_MAX_BUF (10*1024)
|
||||
|
||||
/*-------------
|
||||
* GPU
|
||||
*-----------*/
|
||||
|
||||
/*Use Arm's 2D acceleration library Arm-2D */
|
||||
#define LV_USE_GPU_ARM2D 0
|
||||
|
||||
/*Use STM32's DMA2D (aka Chrom Art) GPU*/
|
||||
#define LV_USE_GPU_STM32_DMA2D 0
|
||||
#if LV_USE_GPU_STM32_DMA2D
|
||||
/*Must be defined to include path of CMSIS header of target processor
|
||||
e.g. "stm32f7xx.h" or "stm32f4xx.h"*/
|
||||
#define LV_GPU_DMA2D_CMSIS_INCLUDE
|
||||
#endif
|
||||
|
||||
/*Enable RA6M3 G2D GPU*/
|
||||
#define LV_USE_GPU_RA6M3_G2D 0
|
||||
#if LV_USE_GPU_RA6M3_G2D
|
||||
/*include path of target processor
|
||||
e.g. "hal_data.h"*/
|
||||
#define LV_GPU_RA6M3_G2D_INCLUDE "hal_data.h"
|
||||
#endif
|
||||
|
||||
/*Use SWM341's DMA2D GPU*/
|
||||
#define LV_USE_GPU_SWM341_DMA2D 0
|
||||
#if LV_USE_GPU_SWM341_DMA2D
|
||||
#define LV_GPU_SWM341_DMA2D_INCLUDE "SWM341.h"
|
||||
#endif
|
||||
|
||||
/*Use NXP's PXP GPU iMX RTxxx platforms*/
|
||||
#define LV_USE_GPU_NXP_PXP 0
|
||||
#if LV_USE_GPU_NXP_PXP
|
||||
/*1: Add default bare metal and FreeRTOS interrupt handling routines for PXP (lv_gpu_nxp_pxp_osa.c)
|
||||
* and call lv_gpu_nxp_pxp_init() automatically during lv_init(). Note that symbol SDK_OS_FREE_RTOS
|
||||
* has to be defined in order to use FreeRTOS OSA, otherwise bare-metal implementation is selected.
|
||||
*0: lv_gpu_nxp_pxp_init() has to be called manually before lv_init()
|
||||
*/
|
||||
#define LV_USE_GPU_NXP_PXP_AUTO_INIT 0
|
||||
#endif
|
||||
|
||||
/*Use NXP's VG-Lite GPU iMX RTxxx platforms*/
|
||||
#define LV_USE_GPU_NXP_VG_LITE 0
|
||||
|
||||
/*Use SDL renderer API*/
|
||||
#define LV_USE_GPU_SDL 0
|
||||
#if LV_USE_GPU_SDL
|
||||
#define LV_GPU_SDL_INCLUDE_PATH <SDL2/SDL.h>
|
||||
/*Texture cache size, 8MB by default*/
|
||||
#define LV_GPU_SDL_LRU_SIZE (1024 * 1024 * 8)
|
||||
/*Custom blend mode for mask drawing, disable if you need to link with older SDL2 lib*/
|
||||
#define LV_GPU_SDL_CUSTOM_BLEND_MODE (SDL_VERSION_ATLEAST(2, 0, 6))
|
||||
#endif
|
||||
|
||||
/*-------------
|
||||
* Logging
|
||||
*-----------*/
|
||||
|
||||
/*Enable the log module*/
|
||||
#define LV_USE_LOG 0
|
||||
#if LV_USE_LOG
|
||||
|
||||
/*How important log should be added:
|
||||
*LV_LOG_LEVEL_TRACE A lot of logs to give detailed information
|
||||
*LV_LOG_LEVEL_INFO Log important events
|
||||
*LV_LOG_LEVEL_WARN Log if something unwanted happened but didn't cause a problem
|
||||
*LV_LOG_LEVEL_ERROR Only critical issue, when the system may fail
|
||||
*LV_LOG_LEVEL_USER Only logs added by the user
|
||||
*LV_LOG_LEVEL_NONE Do not log anything*/
|
||||
#define LV_LOG_LEVEL LV_LOG_LEVEL_WARN
|
||||
|
||||
/*1: Print the log with 'printf';
|
||||
*0: User need to register a callback with `lv_log_register_print_cb()`*/
|
||||
#define LV_LOG_PRINTF 0
|
||||
|
||||
/*Enable/disable LV_LOG_TRACE in modules that produces a huge number of logs*/
|
||||
#define LV_LOG_TRACE_MEM 1
|
||||
#define LV_LOG_TRACE_TIMER 1
|
||||
#define LV_LOG_TRACE_INDEV 1
|
||||
#define LV_LOG_TRACE_DISP_REFR 1
|
||||
#define LV_LOG_TRACE_EVENT 1
|
||||
#define LV_LOG_TRACE_OBJ_CREATE 1
|
||||
#define LV_LOG_TRACE_LAYOUT 1
|
||||
#define LV_LOG_TRACE_ANIM 1
|
||||
|
||||
#endif /*LV_USE_LOG*/
|
||||
|
||||
/*-------------
|
||||
* Asserts
|
||||
*-----------*/
|
||||
|
||||
/*Enable asserts if an operation is failed or an invalid data is found.
|
||||
*If LV_USE_LOG is enabled an error message will be printed on failure*/
|
||||
#define LV_USE_ASSERT_NULL 1 /*Check if the parameter is NULL. (Very fast, recommended)*/
|
||||
#define LV_USE_ASSERT_MALLOC 1 /*Checks is the memory is successfully allocated or no. (Very fast, recommended)*/
|
||||
#define LV_USE_ASSERT_STYLE 0 /*Check if the styles are properly initialized. (Very fast, recommended)*/
|
||||
#define LV_USE_ASSERT_MEM_INTEGRITY 0 /*Check the integrity of `lv_mem` after critical operations. (Slow)*/
|
||||
#define LV_USE_ASSERT_OBJ 0 /*Check the object's type and existence (e.g. not deleted). (Slow)*/
|
||||
|
||||
/*Add a custom handler when assert happens e.g. to restart the MCU*/
|
||||
#define LV_ASSERT_HANDLER_INCLUDE <stdint.h>
|
||||
#define LV_ASSERT_HANDLER while(1); /*Halt by default*/
|
||||
|
||||
/*-------------
|
||||
* Others
|
||||
*-----------*/
|
||||
|
||||
/*1: Show CPU usage and FPS count*/
|
||||
#define LV_USE_PERF_MONITOR 0
|
||||
#if LV_USE_PERF_MONITOR
|
||||
#define LV_USE_PERF_MONITOR_POS LV_ALIGN_BOTTOM_RIGHT
|
||||
#endif
|
||||
|
||||
/*1: Show the used memory and the memory fragmentation
|
||||
* Requires LV_MEM_CUSTOM = 0*/
|
||||
#define LV_USE_MEM_MONITOR 0
|
||||
#if LV_USE_MEM_MONITOR
|
||||
#define LV_USE_MEM_MONITOR_POS LV_ALIGN_BOTTOM_LEFT
|
||||
#endif
|
||||
|
||||
/*1: Draw random colored rectangles over the redrawn areas*/
|
||||
#define LV_USE_REFR_DEBUG 0
|
||||
|
||||
/*Change the built in (v)snprintf functions*/
|
||||
#define LV_SPRINTF_CUSTOM 0
|
||||
#if LV_SPRINTF_CUSTOM
|
||||
#define LV_SPRINTF_INCLUDE <stdio.h>
|
||||
#define lv_snprintf snprintf
|
||||
#define lv_vsnprintf vsnprintf
|
||||
#else /*LV_SPRINTF_CUSTOM*/
|
||||
#define LV_SPRINTF_USE_FLOAT 0
|
||||
#endif /*LV_SPRINTF_CUSTOM*/
|
||||
|
||||
#define LV_USE_USER_DATA 1
|
||||
|
||||
/*Garbage Collector settings
|
||||
*Used if lvgl is bound to higher level language and the memory is managed by that language*/
|
||||
#define LV_ENABLE_GC 0
|
||||
#if LV_ENABLE_GC != 0
|
||||
#define LV_GC_INCLUDE "gc.h" /*Include Garbage Collector related things*/
|
||||
#endif /*LV_ENABLE_GC*/
|
||||
|
||||
/*=====================
|
||||
* COMPILER SETTINGS
|
||||
*====================*/
|
||||
|
||||
/*For big endian systems set to 1*/
|
||||
#define LV_BIG_ENDIAN_SYSTEM 0
|
||||
|
||||
/*Define a custom attribute to `lv_tick_inc` function*/
|
||||
#define LV_ATTRIBUTE_TICK_INC
|
||||
|
||||
/*Define a custom attribute to `lv_timer_handler` function*/
|
||||
#define LV_ATTRIBUTE_TIMER_HANDLER
|
||||
|
||||
/*Define a custom attribute to `lv_disp_flush_ready` function*/
|
||||
#define LV_ATTRIBUTE_FLUSH_READY
|
||||
|
||||
/*Required alignment size for buffers*/
|
||||
#define LV_ATTRIBUTE_MEM_ALIGN_SIZE 1
|
||||
|
||||
/*Will be added where memories needs to be aligned (with -Os data might not be aligned to boundary by default).
|
||||
* E.g. __attribute__((aligned(4)))*/
|
||||
#define LV_ATTRIBUTE_MEM_ALIGN
|
||||
|
||||
/*Attribute to mark large constant arrays for example font's bitmaps*/
|
||||
#define LV_ATTRIBUTE_LARGE_CONST
|
||||
|
||||
/*Compiler prefix for a big array declaration in RAM*/
|
||||
#define LV_ATTRIBUTE_LARGE_RAM_ARRAY
|
||||
|
||||
/*Place performance critical functions into a faster memory (e.g RAM)*/
|
||||
#define LV_ATTRIBUTE_FAST_MEM
|
||||
|
||||
/*Prefix variables that are used in GPU accelerated operations, often these need to be placed in RAM sections that are DMA accessible*/
|
||||
#define LV_ATTRIBUTE_DMA
|
||||
|
||||
/*Export integer constant to binding. This macro is used with constants in the form of LV_<CONST> that
|
||||
*should also appear on LVGL binding API such as Micropython.*/
|
||||
#define LV_EXPORT_CONST_INT(int_value) struct _silence_gcc_warning /*The default value just prevents GCC warning*/
|
||||
|
||||
/*Extend the default -32k..32k coordinate range to -4M..4M by using int32_t for coordinates instead of int16_t*/
|
||||
#define LV_USE_LARGE_COORD 0
|
||||
|
||||
/*==================
|
||||
* FONT USAGE
|
||||
*===================*/
|
||||
|
||||
/*Montserrat fonts with ASCII range and some symbols using bpp = 4
|
||||
*https://fonts.google.com/specimen/Montserrat*/
|
||||
#define LV_FONT_MONTSERRAT_8 1
|
||||
#define LV_FONT_MONTSERRAT_10 1
|
||||
#define LV_FONT_MONTSERRAT_12 1
|
||||
#define LV_FONT_MONTSERRAT_14 1
|
||||
#define LV_FONT_MONTSERRAT_16 1
|
||||
#define LV_FONT_MONTSERRAT_18 1
|
||||
#define LV_FONT_MONTSERRAT_20 1
|
||||
#define LV_FONT_MONTSERRAT_22 1
|
||||
#define LV_FONT_MONTSERRAT_24 1
|
||||
#define LV_FONT_MONTSERRAT_26 1
|
||||
#define LV_FONT_MONTSERRAT_28 1
|
||||
#define LV_FONT_MONTSERRAT_30 1
|
||||
#define LV_FONT_MONTSERRAT_32 1
|
||||
#define LV_FONT_MONTSERRAT_34 1
|
||||
#define LV_FONT_MONTSERRAT_36 1
|
||||
#define LV_FONT_MONTSERRAT_38 1
|
||||
#define LV_FONT_MONTSERRAT_40 1
|
||||
#define LV_FONT_MONTSERRAT_42 1
|
||||
#define LV_FONT_MONTSERRAT_44 1
|
||||
#define LV_FONT_MONTSERRAT_46 1
|
||||
#define LV_FONT_MONTSERRAT_48 1
|
||||
|
||||
/*Demonstrate special features*/
|
||||
#define LV_FONT_MONTSERRAT_12_SUBPX 0
|
||||
#define LV_FONT_MONTSERRAT_28_COMPRESSED 0 /*bpp = 3*/
|
||||
#define LV_FONT_DEJAVU_16_PERSIAN_HEBREW 0 /*Hebrew, Arabic, Persian letters and all their forms*/
|
||||
#define LV_FONT_SIMSUN_16_CJK 0 /*1000 most common CJK radicals*/
|
||||
|
||||
/*Pixel perfect monospace fonts*/
|
||||
#define LV_FONT_UNSCII_8 0
|
||||
#define LV_FONT_UNSCII_16 0
|
||||
|
||||
/*Optionally declare custom fonts here.
|
||||
*You can use these fonts as default font too and they will be available globally.
|
||||
*E.g. #define LV_FONT_CUSTOM_DECLARE LV_FONT_DECLARE(my_font_1) LV_FONT_DECLARE(my_font_2)*/
|
||||
#define LV_FONT_CUSTOM_DECLARE
|
||||
|
||||
/*Always set a default font*/
|
||||
#define LV_FONT_DEFAULT &lv_font_montserrat_14
|
||||
|
||||
/*Enable handling large font and/or fonts with a lot of characters.
|
||||
*The limit depends on the font size, font face and bpp.
|
||||
*Compiler error will be triggered if a font needs it.*/
|
||||
#define LV_FONT_FMT_TXT_LARGE 0
|
||||
|
||||
/*Enables/disables support for compressed fonts.*/
|
||||
#define LV_USE_FONT_COMPRESSED 0
|
||||
|
||||
/*Enable subpixel rendering*/
|
||||
#define LV_USE_FONT_SUBPX 0
|
||||
#if LV_USE_FONT_SUBPX
|
||||
/*Set the pixel order of the display. Physical order of RGB channels. Doesn't matter with "normal" fonts.*/
|
||||
#define LV_FONT_SUBPX_BGR 0 /*0: RGB; 1:BGR order*/
|
||||
#endif
|
||||
|
||||
/*Enable drawing placeholders when glyph dsc is not found*/
|
||||
#define LV_USE_FONT_PLACEHOLDER 1
|
||||
|
||||
/*=================
|
||||
* TEXT SETTINGS
|
||||
*=================*/
|
||||
|
||||
/**
|
||||
* Select a character encoding for strings.
|
||||
* Your IDE or editor should have the same character encoding
|
||||
* - LV_TXT_ENC_UTF8
|
||||
* - LV_TXT_ENC_ASCII
|
||||
*/
|
||||
#define LV_TXT_ENC LV_TXT_ENC_UTF8
|
||||
|
||||
/*Can break (wrap) texts on these chars*/
|
||||
#define LV_TXT_BREAK_CHARS " ,.;:-_"
|
||||
|
||||
/*If a word is at least this long, will break wherever "prettiest"
|
||||
*To disable, set to a value <= 0*/
|
||||
#define LV_TXT_LINE_BREAK_LONG_LEN 0
|
||||
|
||||
/*Minimum number of characters in a long word to put on a line before a break.
|
||||
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
|
||||
#define LV_TXT_LINE_BREAK_LONG_PRE_MIN_LEN 3
|
||||
|
||||
/*Minimum number of characters in a long word to put on a line after a break.
|
||||
*Depends on LV_TXT_LINE_BREAK_LONG_LEN.*/
|
||||
#define LV_TXT_LINE_BREAK_LONG_POST_MIN_LEN 3
|
||||
|
||||
/*The control character to use for signalling text recoloring.*/
|
||||
#define LV_TXT_COLOR_CMD "#"
|
||||
|
||||
/*Support bidirectional texts. Allows mixing Left-to-Right and Right-to-Left texts.
|
||||
*The direction will be processed according to the Unicode Bidirectional Algorithm:
|
||||
*https://www.w3.org/International/articles/inline-bidi-markup/uba-basics*/
|
||||
#define LV_USE_BIDI 0
|
||||
#if LV_USE_BIDI
|
||||
/*Set the default direction. Supported values:
|
||||
*`LV_BASE_DIR_LTR` Left-to-Right
|
||||
*`LV_BASE_DIR_RTL` Right-to-Left
|
||||
*`LV_BASE_DIR_AUTO` detect texts base direction*/
|
||||
#define LV_BIDI_BASE_DIR_DEF LV_BASE_DIR_AUTO
|
||||
#endif
|
||||
|
||||
/*Enable Arabic/Persian processing
|
||||
*In these languages characters should be replaced with an other form based on their position in the text*/
|
||||
#define LV_USE_ARABIC_PERSIAN_CHARS 0
|
||||
|
||||
/*==================
|
||||
* WIDGET USAGE
|
||||
*================*/
|
||||
|
||||
/*Documentation of the widgets: https://docs.lvgl.io/latest/en/html/widgets/index.html*/
|
||||
|
||||
#define LV_USE_ARC 1
|
||||
|
||||
#define LV_USE_BAR 1
|
||||
|
||||
#define LV_USE_BTN 1
|
||||
|
||||
#define LV_USE_BTNMATRIX 1
|
||||
|
||||
#define LV_USE_CANVAS 1
|
||||
|
||||
#define LV_USE_CHECKBOX 1
|
||||
|
||||
#define LV_USE_DROPDOWN 1 /*Requires: lv_label*/
|
||||
|
||||
#define LV_USE_IMG 1 /*Requires: lv_label*/
|
||||
|
||||
#define LV_USE_LABEL 1
|
||||
#if LV_USE_LABEL
|
||||
#define LV_LABEL_TEXT_SELECTION 1 /*Enable selecting text of the label*/
|
||||
#define LV_LABEL_LONG_TXT_HINT 1 /*Store some extra info in labels to speed up drawing of very long texts*/
|
||||
#endif
|
||||
|
||||
#define LV_USE_LINE 1
|
||||
|
||||
#define LV_USE_ROLLER 1 /*Requires: lv_label*/
|
||||
#if LV_USE_ROLLER
|
||||
#define LV_ROLLER_INF_PAGES 7 /*Number of extra "pages" when the roller is infinite*/
|
||||
#endif
|
||||
|
||||
#define LV_USE_SLIDER 1 /*Requires: lv_bar*/
|
||||
|
||||
#define LV_USE_SWITCH 1
|
||||
|
||||
#define LV_USE_TEXTAREA 1 /*Requires: lv_label*/
|
||||
#if LV_USE_TEXTAREA != 0
|
||||
#define LV_TEXTAREA_DEF_PWD_SHOW_TIME 1500 /*ms*/
|
||||
#endif
|
||||
|
||||
#define LV_USE_TABLE 1
|
||||
|
||||
/*==================
|
||||
* EXTRA COMPONENTS
|
||||
*==================*/
|
||||
|
||||
/*-----------
|
||||
* Widgets
|
||||
*----------*/
|
||||
#define LV_USE_ANIMIMG 1
|
||||
|
||||
#define LV_USE_CALENDAR 1
|
||||
#if LV_USE_CALENDAR
|
||||
#define LV_CALENDAR_WEEK_STARTS_MONDAY 0
|
||||
#if LV_CALENDAR_WEEK_STARTS_MONDAY
|
||||
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"}
|
||||
#else
|
||||
#define LV_CALENDAR_DEFAULT_DAY_NAMES {"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}
|
||||
#endif
|
||||
|
||||
#define LV_CALENDAR_DEFAULT_MONTH_NAMES {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
|
||||
#define LV_USE_CALENDAR_HEADER_ARROW 1
|
||||
#define LV_USE_CALENDAR_HEADER_DROPDOWN 1
|
||||
#endif /*LV_USE_CALENDAR*/
|
||||
|
||||
#define LV_USE_CHART 1
|
||||
|
||||
#define LV_USE_COLORWHEEL 1
|
||||
|
||||
#define LV_USE_IMGBTN 1
|
||||
|
||||
#define LV_USE_KEYBOARD 1
|
||||
|
||||
#define LV_USE_LED 1
|
||||
|
||||
#define LV_USE_LIST 1
|
||||
|
||||
#define LV_USE_MENU 1
|
||||
|
||||
#define LV_USE_METER 1
|
||||
|
||||
#define LV_USE_MSGBOX 1
|
||||
|
||||
#define LV_USE_SPAN 1
|
||||
#if LV_USE_SPAN
|
||||
/*A line text can contain maximum num of span descriptor */
|
||||
#define LV_SPAN_SNIPPET_STACK_SIZE 64
|
||||
#endif
|
||||
|
||||
#define LV_USE_SPINBOX 1
|
||||
|
||||
#define LV_USE_SPINNER 1
|
||||
|
||||
#define LV_USE_TABVIEW 1
|
||||
|
||||
#define LV_USE_TILEVIEW 1
|
||||
|
||||
#define LV_USE_WIN 1
|
||||
|
||||
/*-----------
|
||||
* Themes
|
||||
*----------*/
|
||||
|
||||
/*A simple, impressive and very complete theme*/
|
||||
#define LV_USE_THEME_DEFAULT 1
|
||||
#if LV_USE_THEME_DEFAULT
|
||||
|
||||
/*0: Light mode; 1: Dark mode*/
|
||||
#define LV_THEME_DEFAULT_DARK 0
|
||||
|
||||
/*1: Enable grow on press*/
|
||||
#define LV_THEME_DEFAULT_GROW 1
|
||||
|
||||
/*Default transition time in [ms]*/
|
||||
#define LV_THEME_DEFAULT_TRANSITION_TIME 80
|
||||
#endif /*LV_USE_THEME_DEFAULT*/
|
||||
|
||||
/*A very simple theme that is a good starting point for a custom theme*/
|
||||
#define LV_USE_THEME_BASIC 1
|
||||
|
||||
/*A theme designed for monochrome displays*/
|
||||
#define LV_USE_THEME_MONO 1
|
||||
|
||||
/*-----------
|
||||
* Layouts
|
||||
*----------*/
|
||||
|
||||
/*A layout similar to Flexbox in CSS.*/
|
||||
#define LV_USE_FLEX 1
|
||||
|
||||
/*A layout similar to Grid in CSS.*/
|
||||
#define LV_USE_GRID 1
|
||||
|
||||
/*---------------------
|
||||
* 3rd party libraries
|
||||
*--------------------*/
|
||||
|
||||
/*File system interfaces for common APIs */
|
||||
|
||||
/*API for fopen, fread, etc*/
|
||||
#define LV_USE_FS_STDIO 0
|
||||
#if LV_USE_FS_STDIO
|
||||
#define LV_FS_STDIO_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define LV_FS_STDIO_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
||||
#define LV_FS_STDIO_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
/*API for open, read, etc*/
|
||||
#define LV_USE_FS_POSIX 0
|
||||
#if LV_USE_FS_POSIX
|
||||
#define LV_FS_POSIX_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define LV_FS_POSIX_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
||||
#define LV_FS_POSIX_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
/*API for CreateFile, ReadFile, etc*/
|
||||
#define LV_USE_FS_WIN32 0
|
||||
#if LV_USE_FS_WIN32
|
||||
#define LV_FS_WIN32_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define LV_FS_WIN32_PATH "" /*Set the working directory. File/directory paths will be appended to it.*/
|
||||
#define LV_FS_WIN32_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
/*API for FATFS (needs to be added separately). Uses f_open, f_read, etc*/
|
||||
#define LV_USE_FS_FATFS 0
|
||||
#if LV_USE_FS_FATFS
|
||||
#define LV_FS_FATFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define LV_FS_FATFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
/*API for LittleFS (library needs to be added separately). Uses lfs_file_open, lfs_file_read, etc*/
|
||||
#define LV_USE_FS_LITTLEFS 0
|
||||
#if LV_USE_FS_LITTLEFS
|
||||
#define LV_FS_LITTLEFS_LETTER '\0' /*Set an upper cased letter on which the drive will accessible (e.g. 'A')*/
|
||||
#define LV_FS_LITTLEFS_CACHE_SIZE 0 /*>0 to cache this number of bytes in lv_fs_read()*/
|
||||
#endif
|
||||
|
||||
/*PNG decoder library*/
|
||||
#define LV_USE_PNG 0
|
||||
|
||||
/*BMP decoder library*/
|
||||
#define LV_USE_BMP 0
|
||||
|
||||
/* JPG + split JPG decoder library.
|
||||
* Split JPG is a custom format optimized for embedded systems. */
|
||||
#define LV_USE_SJPG 0
|
||||
|
||||
/*GIF decoder library*/
|
||||
#define LV_USE_GIF 0
|
||||
|
||||
/*QR code library*/
|
||||
#define LV_USE_QRCODE 1
|
||||
|
||||
/*FreeType library*/
|
||||
#define LV_USE_FREETYPE 0
|
||||
#if LV_USE_FREETYPE
|
||||
/*Memory used by FreeType to cache characters [bytes] (-1: no caching)*/
|
||||
#define LV_FREETYPE_CACHE_SIZE (16 * 1024)
|
||||
#if LV_FREETYPE_CACHE_SIZE >= 0
|
||||
/* 1: bitmap cache use the sbit cache, 0:bitmap cache use the image cache. */
|
||||
/* sbit cache:it is much more memory efficient for small bitmaps(font size < 256) */
|
||||
/* if font size >= 256, must be configured as image cache */
|
||||
#define LV_FREETYPE_SBIT_CACHE 0
|
||||
/* Maximum number of opened FT_Face/FT_Size objects managed by this cache instance. */
|
||||
/* (0:use system defaults) */
|
||||
#define LV_FREETYPE_CACHE_FT_FACES 0
|
||||
#define LV_FREETYPE_CACHE_FT_SIZES 0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/*Tiny TTF library*/
|
||||
#define LV_USE_TINY_TTF 0
|
||||
#if LV_USE_TINY_TTF
|
||||
/*Load TTF data from files*/
|
||||
#define LV_TINY_TTF_FILE_SUPPORT 0
|
||||
#endif
|
||||
|
||||
/*Rlottie library*/
|
||||
#define LV_USE_RLOTTIE 0
|
||||
|
||||
/*FFmpeg library for image decoding and playing videos
|
||||
*Supports all major image formats so do not enable other image decoder with it*/
|
||||
#define LV_USE_FFMPEG 0
|
||||
#if LV_USE_FFMPEG
|
||||
/*Dump input information to stderr*/
|
||||
#define LV_FFMPEG_DUMP_FORMAT 0
|
||||
#endif
|
||||
|
||||
/*-----------
|
||||
* Others
|
||||
*----------*/
|
||||
|
||||
/*1: Enable API to take snapshot for object*/
|
||||
#define LV_USE_SNAPSHOT 0
|
||||
|
||||
/*1: Enable Monkey test*/
|
||||
#define LV_USE_MONKEY 0
|
||||
|
||||
/*1: Enable grid navigation*/
|
||||
#define LV_USE_GRIDNAV 0
|
||||
|
||||
/*1: Enable lv_obj fragment*/
|
||||
#define LV_USE_FRAGMENT 0
|
||||
|
||||
/*1: Support using images as font in label or span widgets */
|
||||
#define LV_USE_IMGFONT 0
|
||||
|
||||
/*1: Enable a published subscriber based messaging system */
|
||||
#define LV_USE_MSG 0
|
||||
|
||||
/*1: Enable Pinyin input method*/
|
||||
/*Requires: lv_keyboard*/
|
||||
#define LV_USE_IME_PINYIN 0
|
||||
#if LV_USE_IME_PINYIN
|
||||
/*1: Use default thesaurus*/
|
||||
/*If you do not use the default thesaurus, be sure to use `lv_ime_pinyin` after setting the thesauruss*/
|
||||
#define LV_IME_PINYIN_USE_DEFAULT_DICT 1
|
||||
/*Set the maximum number of candidate panels that can be displayed*/
|
||||
/*This needs to be adjusted according to the size of the screen*/
|
||||
#define LV_IME_PINYIN_CAND_TEXT_NUM 6
|
||||
|
||||
/*Use 9 key input(k9)*/
|
||||
#define LV_IME_PINYIN_USE_K9_MODE 1
|
||||
#if LV_IME_PINYIN_USE_K9_MODE == 1
|
||||
#define LV_IME_PINYIN_K9_CAND_TEXT_NUM 3
|
||||
#endif // LV_IME_PINYIN_USE_K9_MODE
|
||||
#endif
|
||||
|
||||
/*==================
|
||||
* EXAMPLES
|
||||
*==================*/
|
||||
|
||||
/*Enable the examples to be built with the library*/
|
||||
#define LV_BUILD_EXAMPLES 1
|
||||
|
||||
/*===================
|
||||
* DEMO USAGE
|
||||
====================*/
|
||||
|
||||
/*Show some widget. It might be required to increase `LV_MEM_SIZE` */
|
||||
#define LV_USE_DEMO_WIDGETS 1
|
||||
#if LV_USE_DEMO_WIDGETS
|
||||
#define LV_DEMO_WIDGETS_SLIDESHOW 1
|
||||
#endif
|
||||
|
||||
/*Demonstrate the usage of encoder and keyboard*/
|
||||
#define LV_USE_DEMO_KEYPAD_AND_ENCODER 0
|
||||
|
||||
/*Benchmark your system*/
|
||||
#define LV_USE_DEMO_BENCHMARK 1
|
||||
#if LV_USE_DEMO_BENCHMARK
|
||||
/*Use RGB565A8 images with 16 bit color depth instead of ARGB8565*/
|
||||
#define LV_DEMO_BENCHMARK_RGB565A8 0
|
||||
#endif
|
||||
|
||||
/*Stress test for LVGL*/
|
||||
#define LV_USE_DEMO_STRESS 1
|
||||
|
||||
/*Music player demo*/
|
||||
#define LV_USE_DEMO_MUSIC 1
|
||||
#if LV_USE_DEMO_MUSIC
|
||||
#define LV_DEMO_MUSIC_SQUARE 0
|
||||
#define LV_DEMO_MUSIC_LANDSCAPE 0
|
||||
#define LV_DEMO_MUSIC_ROUND 0
|
||||
#define LV_DEMO_MUSIC_LARGE 0
|
||||
#define LV_DEMO_MUSIC_AUTO_PLAY 0
|
||||
#endif
|
||||
|
||||
/*--END OF LV_CONF_H--*/
|
||||
|
||||
#endif /*LV_CONF_H*/
|
||||
|
||||
#endif /*End of "Content enable"*/
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <algorithm>
|
||||
|
||||
// Remote AddBlock body is the existing type/subtype/version + semantic body.
|
||||
// This helper has no network/state dependencies; hashes and Ed25519 are supplied
|
||||
// by the existing firmware crypto libraries (or the offline vector test).
|
||||
namespace shine_core {
|
||||
using Bytes = std::vector<uint8_t>;
|
||||
using Hash = bool (*)(const uint8_t*, size_t, uint8_t*);
|
||||
using Sign = bool (*)(const Bytes&, const uint8_t*, uint8_t*);
|
||||
inline void putBE(Bytes& out, uint64_t n, unsigned count) {
|
||||
for (unsigned i=count; i>0; --i) out.push_back(uint8_t(n >> ((i-1)*8)));
|
||||
}
|
||||
inline void putLE(Bytes& out, uint64_t n, unsigned count) {
|
||||
for (unsigned i=0; i<count; ++i) out.push_back(uint8_t(n >> (i*8)));
|
||||
}
|
||||
inline uint32_t getBE(const uint8_t* p) {
|
||||
return (uint32_t(p[0])<<24)|(uint32_t(p[1])<<16)|(uint32_t(p[2])<<8)|p[3];
|
||||
}
|
||||
inline Bytes text(const std::string& s) { return Bytes(s.begin(),s.end()); }
|
||||
inline void avroLong(Bytes& out, size_t n) {
|
||||
uint64_t x=uint64_t(n)*2;
|
||||
while (x>=128) { out.push_back(uint8_t(x)|0x80); x>>=7; }
|
||||
out.push_back(uint8_t(x));
|
||||
}
|
||||
inline void avroString(Bytes& out,const std::string& s) {
|
||||
avroLong(out,s.size());out.insert(out.end(),s.begin(),s.end());
|
||||
}
|
||||
inline bool deepBlob(const Bytes& data,Hash sha384,uint8_t* out) {
|
||||
Bytes tag=text("blob"+std::to_string(data.size()));uint8_t pair[96];
|
||||
return sha384(tag.data(),tag.size(),pair)&&sha384(data.data(),data.size(),pair+48)&&sha384(pair,96,out);
|
||||
}
|
||||
inline bool makeItem(const Bytes& data,const Bytes& tags,size_t count,const uint8_t* owner,const uint8_t* secret,
|
||||
Hash sha384,Sign sign,Bytes& out) {
|
||||
const Bytes children[]={text("dataitem"),text("1"),text("2"),Bytes(owner,owner+32),Bytes(),Bytes(),tags,data};
|
||||
const Bytes list=text("list8");uint8_t acc[48],pair[96],sig[64];
|
||||
if(!sha384(list.data(),list.size(),acc))return false;
|
||||
for(const Bytes& child:children){
|
||||
std::copy(acc,acc+48,pair);
|
||||
if(!deepBlob(child,sha384,pair+48)||!sha384(pair,96,acc))return false;
|
||||
}
|
||||
if(!sign(Bytes(acc,acc+48),secret,sig))return false;
|
||||
out.clear();putLE(out,2,2);out.insert(out.end(),sig,sig+64);out.insert(out.end(),owner,owner+32);
|
||||
out.push_back(0);out.push_back(0);putLE(out,count,8);putLE(out,tags.size(),8);
|
||||
out.insert(out.end(),tags.begin(),tags.end());out.insert(out.end(),data.begin(),data.end());return true;
|
||||
}
|
||||
inline bool buildPair(uint16_t type,uint16_t subtype,uint16_t version,const Bytes& body,
|
||||
uint32_t number,uint64_t timestamp,const uint8_t* prev,const uint8_t* owner,const uint8_t* secret,
|
||||
const std::string& app,Hash sha256,Hash sha384,Sign sign,Bytes& out) {
|
||||
constexpr uint32_t MAX_NUMBER=2147482623,PROFILE=2147483645,CONNECTION=2147483646,TECH=2147483647;
|
||||
const bool header=type==0&&subtype==0,tech=type==0&&subtype==1,fixed=type==3||type==4;
|
||||
const bool channel=type==1&&(subtype==10||subtype==11||subtype==50||subtype==90||subtype==92||subtype==100||subtype==110||subtype==120||subtype==130);
|
||||
if((version!=1&&!(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
|
||||
+48
-23
@@ -9,6 +9,8 @@
|
||||
#include <TouchDrvCSTXXX.hpp>
|
||||
#include <mbedtls/gcm.h>
|
||||
#include <mbedtls/sha256.h>
|
||||
#include <mbedtls/sha512.h>
|
||||
#include "shine_core_content.h"
|
||||
#include <mbedtls/base64.h>
|
||||
#include <Ed25519.h>
|
||||
#include <sodium.h>
|
||||
@@ -4581,19 +4583,6 @@ static void processPendingRemoteAddBlockRequests() {
|
||||
continue;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> preimage;
|
||||
preimage.reserve(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
||||
appendUint16BE(preimage, 0);
|
||||
preimage.insert(preimage.end(), prevHash32, prevHash32 + 32);
|
||||
int32_t blockSize = (int32_t)(2 + 32 + 4 + 4 + 8 + 2 + 2 + 2 + bodyBytes.size());
|
||||
appendInt32BE(preimage, blockSize);
|
||||
appendInt32BE(preimage, nextBlockNumber);
|
||||
appendInt64BE(preimage, (int64_t)(shineNowMs() / 1000ULL));
|
||||
appendUint16BE(preimage, msgType);
|
||||
appendUint16BE(preimage, msgSubType);
|
||||
appendUint16BE(preimage, msgVersion);
|
||||
preimage.insert(preimage.end(), bodyBytes.begin(), bodyBytes.end());
|
||||
|
||||
uint8_t blockchainSeed[32] = {};
|
||||
uint8_t blockchainPub[32] = {};
|
||||
uint8_t blockchainSec[64] = {};
|
||||
@@ -4604,26 +4593,41 @@ static void processPendingRemoteAddBlockRequests() {
|
||||
continue;
|
||||
}
|
||||
|
||||
uint8_t hash32[32] = {};
|
||||
sha256calc(preimage.data(), preimage.size(), hash32);
|
||||
uint8_t signature[64] = {};
|
||||
if (!signMessageEd25519(std::vector<uint8_t>(hash32, hash32 + 32), blockchainSec, signature)) {
|
||||
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign AddBlock hash\",\"requestId\":\"")
|
||||
std::vector<uint8_t> fullBlock;
|
||||
const auto hash256 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||
return mbedtls_sha256(data, len, out, 0) == 0;
|
||||
};
|
||||
const auto hash384 = +[](const uint8_t* data, size_t len, uint8_t* out) -> bool {
|
||||
uint8_t buffer[64] = {};
|
||||
if (mbedtls_sha512(data, len, buffer, 1) != 0) return false;
|
||||
memcpy(out, buffer, 48);
|
||||
return true;
|
||||
};
|
||||
const auto sign = +[](const std::vector<uint8_t>& data, const uint8_t* key, uint8_t* sig) -> bool {
|
||||
return signMessageEd25519(data, key, sig);
|
||||
};
|
||||
// Same semantic remote body and signal contract; only the signed wire bytes change.
|
||||
if (resolvedBlockchainName != blockchainName || nextBlockNumber < 0 ||
|
||||
!shine_core::buildPair(msgType, msgSubType, msgVersion, bodyBytes, (uint32_t)nextBlockNumber,
|
||||
shineNowMs()/1000ULL, prevHash32, blockchainPub, blockchainSec,
|
||||
"test5599", hash256, hash384, sign, fullBlock)) {
|
||||
responseData = String("{\"ok\":false,\"error\":\"sign_failed\",\"errorMessage\":\"Failed to sign CORE/CONTENT pair\",\"requestId\":\"")
|
||||
+ jsonEscape(item.signalRequestId) + "\"}";
|
||||
sendSignalResponse(item.fromLogin, item.fromSessionId, "remote_addblock_result", item.signalRequestId, responseData);
|
||||
continue;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> fullBlock = preimage;
|
||||
fullBlock.push_back(0x01);
|
||||
fullBlock.push_back(0x00);
|
||||
fullBlock.insert(fullBlock.end(), signature, signature + 64);
|
||||
String addBlockReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber)
|
||||
+ ",\"prevBlockHash\":\"" + jsonEscape(cleanPrevHash)
|
||||
+ "\",\"blockBytesB64\":\"" + jsonEscape(bytesToBase64String(fullBlock.data(), fullBlock.size())) + "\"}";
|
||||
String addBlockResp;
|
||||
bool addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||
const bool uncertain = !addBlockOk;
|
||||
if (uncertain) {
|
||||
// Retry the identical container, not the semantic request or a new timestamp.
|
||||
addBlockResp = "";
|
||||
addBlockOk = shineWsRequest(gShineWs, "AddBlock", addBlockReq, addBlockResp, SHINE_RPC_TIMEOUT_MS);
|
||||
}
|
||||
uint64_t statusCode = 0;
|
||||
jsonInt64Field(addBlockResp, "status", statusCode);
|
||||
String serverLastHash;
|
||||
@@ -4635,6 +4639,27 @@ static void processPendingRemoteAddBlockRequests() {
|
||||
jsonStringField(addBlockResp, "message", errorMessage);
|
||||
jsonInt64Field(addBlockResp, "serverLastGlobalNumber", serverLastNumber);
|
||||
|
||||
if (uncertain && (!addBlockOk || statusCode != 200)) {
|
||||
const String readReq = String("{\"blockchainName\":\"") + jsonEscape(resolvedBlockchainName)
|
||||
+ "\",\"blockNumber\":" + String((long long)nextBlockNumber) + "}";
|
||||
String readResp, readBytes;
|
||||
uint64_t readStatus = 0;
|
||||
if (shineWsRequest(gShineWs, "GetBlockchainBlock", readReq, readResp, SHINE_RPC_TIMEOUT_MS)) {
|
||||
jsonInt64Field(readResp, "status", readStatus);
|
||||
jsonStringField(readResp, "blockBytesB64", readBytes);
|
||||
if (readStatus == 200 && readBytes == bytesToBase64String(fullBlock.data(), fullBlock.size())) {
|
||||
jsonStringField(readResp, "blockHash", serverLastHash);
|
||||
serverLastNumber = (uint64_t)nextBlockNumber;
|
||||
addBlockOk = true;
|
||||
statusCode = 200;
|
||||
}
|
||||
}
|
||||
if (!addBlockOk || statusCode != 200) {
|
||||
errorCode = "addblock_outcome_unknown";
|
||||
errorMessage = "AddBlock outcome unknown; refresh history before retrying";
|
||||
}
|
||||
}
|
||||
|
||||
if (!addBlockOk || statusCode != 200) {
|
||||
if (errorCode.isEmpty()) {
|
||||
errorCode = addBlockOk ? "addblock_rejected" : "addblock_request_failed";
|
||||
@@ -1,17 +0,0 @@
|
||||
# Reference Notes
|
||||
|
||||
Модель: Waveshare `ESP32-S3-Touch-AMOLED-2.16` (SKU 33969/33970)
|
||||
|
||||
Полезные страницы:
|
||||
- Product: https://www.waveshare.com/product/arduino/boards-kits/esp32-s3/esp32-s3-touch-amoled-2.16.htm
|
||||
- Docs home: https://docs.waveshare.com/ESP32-S3-Touch-AMOLED-2.16
|
||||
- Arduino setup: https://docs.waveshare.com/ESP32-S3-Touch-AMOLED-2.16/Development-Environment-Setup-Arduino
|
||||
- Official examples: https://github.com/waveshareteam/ESP32-S3-Touch-AMOLED-2.16
|
||||
|
||||
Ключевое по железу (по документации):
|
||||
- ESP32-S3R8, 16MB flash, 8MB PSRAM
|
||||
- AMOLED 2.16" 480x480
|
||||
- Capacitive touch (CST9220)
|
||||
- IMU QMI8658
|
||||
- Audio codec ES8311 (playback) и ES7210 (microphones)
|
||||
- TF slot (SD), сейчас без карты
|
||||
-353
@@ -1,353 +0,0 @@
|
||||
# SHiNE ESP32 Homeserver UI Nav Minimal Spec
|
||||
|
||||
Легаси-спецификация старого навигационного теста для `Waveshare ESP32-S3-Touch-AMOLED-2.16`.
|
||||
Актуальный основной скетч теперь находится в `../main-device/shine_homeserver_main/`; этот документ оставлен только как историческая справка по старому тестовому UI.
|
||||
|
||||
## Цель
|
||||
|
||||
Этот прототип проверяет базовую механику экранов, крупных кнопок, свайпов, первичную настройку Wi-Fi и настройку серверных адресов через общий экран редактирования текста.
|
||||
|
||||
На этом этапе отсутствуют:
|
||||
- логин/пароль учётной записи SHiNE;
|
||||
- PIN;
|
||||
- кошелёк;
|
||||
- QR;
|
||||
- регистрация;
|
||||
- PDA update/create транзакции;
|
||||
- входящие запросы.
|
||||
|
||||
## Экраны
|
||||
|
||||
Прототип содержит 10 экранов:
|
||||
- `HOME`
|
||||
- `SETTINGS_MENU`
|
||||
- `WIFI_SCREEN`
|
||||
- `SERVER_SCREEN`
|
||||
- `ACCOUNT_SCREEN`
|
||||
- `ACCOUNT_HOMESERVER_SCREEN`
|
||||
- `ACCOUNT_SECRET_SCREEN`
|
||||
- `SECRET_SHOW_SCREEN`
|
||||
- `SECRET_GENERATE_*`
|
||||
- `TEXT_EDIT_SCREEN`
|
||||
- `REGISTER_ACCOUNT_PLACEHOLDER`
|
||||
|
||||
## HOME
|
||||
|
||||
Показывает:
|
||||
- сверху слева значение homeserver или `homeserver not set`;
|
||||
- ниже значение логина или `login not set`;
|
||||
- справа от строки логина индикатор статуса Solana-аккаунта:
|
||||
- зелёный — все ключи совпадают;
|
||||
- красный — есть mismatch;
|
||||
- белый контур — пользователь не найден в Solana PDA;
|
||||
- рядом с индикатором краткий текст ошибки, если статус не зелёный;
|
||||
- третьей строкой `secret not set`, если секрет ещё не помечен как установленный;
|
||||
- сверху справа один ряд индикаторов:
|
||||
- процент батареи;
|
||||
- иконка батареи;
|
||||
- индикатор Wi-Fi уровня сигнала;
|
||||
- по центру крупный текст `STATUS`;
|
||||
- одна строка Wi-Fi вида `Wi-Fi (<ssid>) connected/disconnected`;
|
||||
- кнопка баланса вида `Balance: <value SOL>` или `Balance: failed to load`, по нажатию выполняет повторный запрос;
|
||||
- строка `SHiNE: <server> connected/account not configured/unavailable`;
|
||||
- при отсутствии пользователя в Solana PDA слева снизу появляется кнопка `REGISTER ACCOUNT`;
|
||||
- снизу кнопку `SETTINGS`, уменьшенную примерно до половины ширины экрана и сдвинутую к правому краю.
|
||||
- внизу на тёмной полосе подпись `SHiNE homeserver (v.0.18)`.
|
||||
|
||||
Строка Wi-Fi на `HOME`:
|
||||
- `Wi-Fi (not configured) not configured`
|
||||
- `Wi-Fi (<saved_ssid>) disconnected`
|
||||
- `Wi-Fi (<current_ssid>) connected`
|
||||
|
||||
Переходы:
|
||||
- кнопка `REGISTER ACCOUNT` -> `REGISTER_ACCOUNT_PLACEHOLDER`, только если пользователь не найден;
|
||||
- кнопка `SETTINGS` -> `SETTINGS_MENU`;
|
||||
- свайп влево -> `SETTINGS_MENU`.
|
||||
|
||||
Примечание:
|
||||
- поведение `REGISTER ACCOUNT -> REGISTER_ACCOUNT_PLACEHOLDER` относится к старой тестовой версии и не является актуальным для основного скетча.
|
||||
|
||||
Фоновая логика:
|
||||
- пока открыт `HOME`, экран сам обновляется примерно раз в секунду;
|
||||
- при наличии `login + secret + homeserver` и Wi-Fi устройство читает Solana `user_pda` напрямую через RPC;
|
||||
- сравниваются `root key`, `blockchain key`, `client key` и `homeserver` session-запись типа `100`;
|
||||
- для строки `SHiNE:` устройство держит отдельную WebSocket-сессию с сервером SHiNE:
|
||||
- авторизация через `AuthChallenge/CreateAuthSession` или `SessionChallenge/SessionLogin`;
|
||||
- session key = публичный `homeserver key`;
|
||||
- подтверждение создания сессии подписывается `client key`;
|
||||
- heartbeat выполняется `Ping` раз в минуту.
|
||||
|
||||
## SETTINGS_MENU
|
||||
|
||||
Показывает вертикальное меню из 3 пунктов:
|
||||
- `Wi-Fi`
|
||||
- `Server`
|
||||
- `Account`
|
||||
|
||||
Одновременно видны только 2 пункта.
|
||||
|
||||
Начальное состояние:
|
||||
- `Wi-Fi`
|
||||
- `Server`
|
||||
|
||||
После свайпа вверх:
|
||||
- `Server`
|
||||
- `Account`
|
||||
|
||||
После свайпа вниз:
|
||||
- `Wi-Fi`
|
||||
- `Server`
|
||||
|
||||
Обе видимые карточки меню имеют одинаковый цвет.
|
||||
|
||||
Переходы:
|
||||
- нажатие `Wi-Fi` -> `WIFI_SCREEN`;
|
||||
- нажатие `Server` -> `SERVER_SCREEN`;
|
||||
- нажатие `Account` -> `ACCOUNT_SCREEN`;
|
||||
- свайп вправо -> `HOME`.
|
||||
|
||||
## WIFI_SCREEN
|
||||
|
||||
Экран содержит 2 внутренних режима.
|
||||
|
||||
### 1. Overview
|
||||
|
||||
Показывает:
|
||||
- текущий Wi-Fi статус;
|
||||
- сохранённый SSID и число известных сетей;
|
||||
- статусное сообщение;
|
||||
- кнопку `SELECT NETWORK`;
|
||||
- кнопку `CLEAR SAVED WI-FI`;
|
||||
- кнопку `BACK`.
|
||||
|
||||
### 2. Scan Results
|
||||
|
||||
После `SELECT NETWORK` выполняется скан доступных Wi-Fi сетей.
|
||||
|
||||
Показывает:
|
||||
- заголовок `SELECT NETWORK`;
|
||||
- количество или результат сканирования;
|
||||
- список найденных SSID как крупные кнопки;
|
||||
- кнопку `SCAN AGAIN`;
|
||||
- кнопку `BACK`.
|
||||
|
||||
Нажатие на SSID открывает `TEXT_EDIT_SCREEN` для ввода пароля.
|
||||
|
||||
Поведение:
|
||||
- если для выбранного SSID пароль уже был сохранён раньше, он сразу подставляется в поле ввода;
|
||||
- если пароль меняют для другого SSID, старые сохранённые пароли других сетей не теряются;
|
||||
- после успешного подключения выбранная сеть становится текущей `wifi_ssid/wifi_pass`;
|
||||
- одновременно хранится до `8` известных сетей `SSID -> password`;
|
||||
- `CLEAR SAVED WI-FI` очищает все сохранённые сети и текущую сеть.
|
||||
|
||||
Переходы:
|
||||
- свайп вправо из любого режима `WIFI_SCREEN` -> `SETTINGS_MENU`
|
||||
- кнопка `BACK` -> `SETTINGS_MENU`
|
||||
|
||||
## SERVER_SCREEN
|
||||
|
||||
Показывает:
|
||||
- статусное сообщение;
|
||||
- текущий `Solana RPC` адрес;
|
||||
- кнопку `SOLANA RPC`;
|
||||
- текущий `SHiNE server login` или уже резолвленный адрес;
|
||||
- кнопку `SHiNE SERVER LOGIN`, если обычный `user PDA` ещё не зарегистрирован.
|
||||
|
||||
Значения по умолчанию:
|
||||
- Solana RPC: `https://api.mainnet-beta.solana.com`
|
||||
- SHiNE server login: `shineupme`
|
||||
|
||||
Нажатие на любую из двух кнопок открывает `TEXT_EDIT_SCREEN`.
|
||||
|
||||
Переходы:
|
||||
- свайп вправо -> `SETTINGS_MENU`
|
||||
|
||||
## ACCOUNT_SCREEN
|
||||
|
||||
Показывает:
|
||||
- заголовок `ACCOUNT`;
|
||||
- статусное сообщение;
|
||||
- кнопку `Login (<value|not set>)`;
|
||||
- кнопку `Homeserver (<value|not set>)`;
|
||||
- кнопку `Secret (<*****|not set>)`.
|
||||
|
||||
Переходы:
|
||||
- свайп вправо -> `SETTINGS_MENU`
|
||||
- `Login` -> `TEXT_EDIT_SCREEN`
|
||||
- `Homeserver` -> `ACCOUNT_HOMESERVER_SCREEN`
|
||||
- `Secret` -> `ACCOUNT_SECRET_SCREEN`
|
||||
|
||||
## ACCOUNT_HOMESERVER_SCREEN
|
||||
|
||||
Показывает:
|
||||
- текущий `homeserver`;
|
||||
- рекомендацию оставить `homeserver1`, если устройство одно;
|
||||
- кнопку `USE HOMESERVER1`;
|
||||
- кнопку `EDIT MANUALLY`;
|
||||
- кнопку `BACK`.
|
||||
|
||||
Переходы:
|
||||
- `USE HOMESERVER1` -> сохраняет `homeserver1` и возвращает в `ACCOUNT_SCREEN`
|
||||
- `EDIT MANUALLY` -> `TEXT_EDIT_SCREEN`
|
||||
- свайп вправо -> `ACCOUNT_SCREEN`
|
||||
|
||||
## ACCOUNT_SECRET_SCREEN
|
||||
|
||||
Показывает:
|
||||
- кнопку `SHOW SECRET` или серую `SECRET NOT SET`, если секрета ещё нет;
|
||||
- кнопку `ENTER SECRET MANUALLY (NOT RECOMMENDED)`;
|
||||
- кнопку `GENERATE SECRET`.
|
||||
|
||||
Переходы:
|
||||
- свайп вправо -> `ACCOUNT_SCREEN`
|
||||
- `SHOW SECRET` -> экран просмотра секрета
|
||||
- `ENTER SECRET MANUALLY (NOT RECOMMENDED)` -> `TEXT_EDIT_SCREEN`
|
||||
- `GENERATE SECRET` -> экран подтверждения генерации
|
||||
|
||||
## SECRET_SHOW_SCREEN
|
||||
|
||||
Показывает:
|
||||
- заголовок `SECRET`;
|
||||
- вертикально прокручиваемый список ключей;
|
||||
- `Secret (base58)`;
|
||||
- `Root key (base58)`;
|
||||
- `Root key priv (base58)`;
|
||||
- `Blockchain key (base58)`;
|
||||
- `Blockchain key priv (base58)`;
|
||||
- `Client key (base58)`;
|
||||
- `Client key priv (base58)`;
|
||||
- `Homeserver key (base58)`;
|
||||
- `Homeserver key priv (base58)`;
|
||||
- для каждого поля показывается формула derivation;
|
||||
- значения ключей показываются полными строками увеличенным шрифтом;
|
||||
- кнопку `BACK`.
|
||||
|
||||
## TEXT_EDIT_SCREEN
|
||||
|
||||
Общий экран редактирования строковых значений.
|
||||
|
||||
Используется для:
|
||||
- пароля Wi-Fi;
|
||||
- Solana RPC;
|
||||
- SHiNE server login.
|
||||
|
||||
Показывает:
|
||||
- заголовок;
|
||||
- поле ввода, уже заполненное старым значением;
|
||||
- новые символы всегда добавляются только в конец текста;
|
||||
- визуальный курсор не показывается;
|
||||
- пароль Wi-Fi показывается открыто, без маскировки точками;
|
||||
- кнопки `SAVE`, `CANCEL`, `DEL`, `CLR`;
|
||||
- большую экранную клавиатуру.
|
||||
|
||||
## REGISTER_ACCOUNT_PLACEHOLDER
|
||||
|
||||
Временный экран-заглушка регистрации.
|
||||
|
||||
Показывает:
|
||||
- заголовок `REGISTER ACCOUNT`;
|
||||
- сообщение, что регистрационный flow пока не реализован;
|
||||
- кнопку `BACK`.
|
||||
|
||||
## Клавиатура
|
||||
|
||||
Клавиатура единая для всех текстовых вводов.
|
||||
|
||||
Особенности:
|
||||
- занимает нижнюю часть экрана;
|
||||
- разбита на 2 страницы;
|
||||
- переключение страниц выполняется свайпом влево/вправо внутри `TEXT_EDIT_SCREEN`;
|
||||
- страница 1 содержит в основном буквы и базовые URL-символы;
|
||||
- страница 2 содержит цифры и дополнительные URL/символьные кнопки;
|
||||
- на символьных страницах должны быть доступны как минимум `!` и отдельная кнопка `SPACE`;
|
||||
- переключение `ABC/123` и `SHIFT` не должно очищать уже введённый текст;
|
||||
- переключение страниц клавиатуры свайпом тоже не должно очищать уже введённый текст, включая цифры, символы и уже набранные заглавные буквы;
|
||||
- есть специальные действия `DEL` и `CLR`.
|
||||
|
||||
## Хранение Wi-Fi
|
||||
|
||||
Используется `Preferences` (NVS памяти ESP32):
|
||||
- `wifi_ssid`
|
||||
- `wifi_pass`
|
||||
- `wifi_known_good`
|
||||
- до `8` сохранённых пар `SSID -> password`
|
||||
|
||||
При старте устройства, если сохранён SSID, выполняется попытка подключения к текущей сохранённой сети.
|
||||
|
||||
Если пользователь уже вводил пароль для сети раньше:
|
||||
- при повторном выборе этого SSID старый пароль сразу подставляется в editor screen;
|
||||
- сохранение пароля для другой сети не удаляет уже сохранённые пароли остальных сетей.
|
||||
|
||||
Если сеть раньше уже была успешно подключена и помечена как валидная:
|
||||
- после потери связи устройство автоматически пытается переподключиться;
|
||||
- первые повторные попытки идут раз в `10` секунд;
|
||||
- если связи нет долго, интервал увеличивается до `30` секунд.
|
||||
- пока открыт `HOME`, экран сам обновляется примерно раз в секунду и подтягивает актуальные:
|
||||
- статус Wi-Fi;
|
||||
- SSID;
|
||||
- уровень сигнала;
|
||||
- процент батареи.
|
||||
|
||||
## Хранение серверов
|
||||
|
||||
Используется `Preferences` (NVS памяти ESP32):
|
||||
- `solana_rpc`
|
||||
- `shine_server_login`
|
||||
|
||||
## Хранение аккаунта
|
||||
|
||||
Используется `Preferences` (NVS памяти ESP32):
|
||||
- `login`
|
||||
- `homeserver`
|
||||
- `secret_set`
|
||||
|
||||
## Детали клавиатуры
|
||||
|
||||
- клавиатура занимает примерно `2/3`-`3/4` высоты экрана;
|
||||
- сверху остаются только заголовок и поле ввода;
|
||||
- буквы занимают 3 ряда;
|
||||
- половина букв находится на левой странице, половина на правой;
|
||||
- на правой странице кнопки тоже стоят в ровных колонках, без сдвига рядов вправо;
|
||||
- отдельный режим `symbols` тоже разделён на 2 страницы;
|
||||
- в режиме `symbols` на правой странице есть отдельная кнопка `SPACE` и отдельная кнопка `!`;
|
||||
- 3 основных ряда клавиш и нижний служебный ряд увеличены по высоте;
|
||||
- клавиши дополнительно увеличены по высоте по сравнению с предыдущим промежуточным вариантом;
|
||||
- четвёртый ряд содержит:
|
||||
- переключение `ABC/123`
|
||||
- `SHIFT`
|
||||
- `DEL`
|
||||
- `SAVE`
|
||||
- `CANCEL`
|
||||
- ниже рамки клавиатурного блока остаётся отдельная тёмная полоса с версией `SHiNE homeserver (v.0.18)`.
|
||||
|
||||
## Жесты
|
||||
|
||||
Поддерживаются направления:
|
||||
- `SWIPE_LEFT`
|
||||
- `SWIPE_RIGHT`
|
||||
- `SWIPE_UP`
|
||||
- `SWIPE_DOWN`
|
||||
|
||||
Маршруты:
|
||||
- `HOME`: свайп влево -> `SETTINGS_MENU`
|
||||
- `SETTINGS_MENU`: свайп вправо -> `HOME`
|
||||
- `SETTINGS_MENU`: свайп вверх/вниз -> прокрутка списка
|
||||
- `WIFI_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
||||
- `SERVER_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
||||
- `ACCOUNT_SCREEN`: свайп вправо -> `SETTINGS_MENU`
|
||||
- `ACCOUNT_HOMESERVER_SCREEN`: свайп вправо -> `ACCOUNT_SCREEN`
|
||||
- `ACCOUNT_SECRET_SCREEN`: свайп вправо -> `ACCOUNT_SCREEN`
|
||||
- `TEXT_EDIT_SCREEN`: свайп влево/вправо -> переключение страниц клавиатуры
|
||||
- переключение страниц клавиатуры срабатывает только если свайп начался в зоне самой клавиатуры, а не по всему экрану редактора
|
||||
|
||||
## Особенность обработки жестов
|
||||
|
||||
- если палец ушёл из зоны обычного тапа и жест определяется как свайп, случайное попадание на кнопку по пути не должно превращать свайп в нажатие;
|
||||
- приоритет у свайпа, а не у `click`.
|
||||
- одно непрерывное касание может вызвать не более одного действия кнопки;
|
||||
- скольжение пальцем по экранной клавиатуре не должно вызывать цепочку из нескольких нажатий;
|
||||
- периодический refresh на `HOME` не должен срабатывать во время активного касания.
|
||||
|
||||
## Язык
|
||||
|
||||
Пока интерфейс отображается в ASCII/English, чтобы использовать подтверждённый рабочий шрифтовой путь на устройстве.
|
||||
@@ -1,681 +0,0 @@
|
||||
# SHiNE ESP32 Homeserver UI Spec
|
||||
|
||||
## Назначение
|
||||
|
||||
Этот документ описывает актуальный UI-прототип homeserver `SHiNE` для платы `Waveshare ESP32-S3-Touch-AMOLED-2.16`.
|
||||
Актуальный основной Arduino-скетч лежит в `../main-device/shine_homeserver_main/`.
|
||||
|
||||
Документ является источником истины для Arduino-скетча:
|
||||
|
||||
- если меняется этот документ, должен меняться и скетч;
|
||||
- если меняется скетч, должен обновляться и этот документ;
|
||||
- экраны, кнопки, поля, статусы, переходы и тексты не должны расходиться.
|
||||
|
||||
## Текущий объём реализации
|
||||
|
||||
Текущая реализация является интерактивным прототипом экрана устройства, пригодным для ручной проверки на железе.
|
||||
|
||||
Что уже входит в прототип:
|
||||
|
||||
- локальный UI на тач-экране;
|
||||
- хранение настроек и секретов во внутренней памяти `ESP32` через `NVS`;
|
||||
- экранный UI устройства работает на английском языке, потому что кириллица на этом шрифтовом пути пока не поддерживается стабильно;
|
||||
- экран пополнения с реальным `solana:` URI и рисованием QR-кода через `LVGL`;
|
||||
- реальное подключение к `Wi-Fi` по сохранённым `SSID/паролю`;
|
||||
- реальная проверка доступности `API`, `RPC` и `WS`-адресов;
|
||||
- реальное чтение баланса кошелька из `Solana RPC`;
|
||||
- проверка обязательных условий перед регистрацией;
|
||||
- живая on-chain регистрация серверного `user_pda` в `shine_users` по нажатию кнопки на главном экране;
|
||||
- живой экран заявок на подключение новых устройств через доверенную homeserver-сессию;
|
||||
- PIN-блокировка (в текущей временной сборке вход по PIN отключён, устройство открывает `HOME` сразу после старта);
|
||||
- базовые настройки, статус и главный экран;
|
||||
- сохранение `PDA` и `tx signature` после успешной регистрации.
|
||||
- создание и возобновление серверной сессии `SHiNE` через WebSocket с `sessionType = 100` и `clientPlatform = "ESP32"`.
|
||||
|
||||
Что пока считается именно прототипом, а не финальной интеграцией:
|
||||
|
||||
- пока реализован только сценарий заявок на подключение устройств через доверенную сессию;
|
||||
- другие типы входящих запросов на подпись и произвольные approval-flow на этом устройстве ещё не подключены.
|
||||
|
||||
## Основная идея устройства
|
||||
|
||||
Устройство работает как отдельный homeserver:
|
||||
|
||||
- хранит секрет на самом устройстве;
|
||||
- позволяет ввести логин, секрет и имя homeserver;
|
||||
- показывает адрес кошелька устройства;
|
||||
- позволяет пополнить баланс перед регистрацией;
|
||||
- после выполнения условий даёт зарегистрировать устройство как homeserver;
|
||||
- после авторизации в SHiNE может подтверждать заявки на подключение новых устройств пользователя.
|
||||
|
||||
`SD`-карта не нужна для постоянного хранения секрета в этом прототипе.
|
||||
Основное сохранение идёт во внутреннюю flash-память через `NVS`.
|
||||
|
||||
## Данные, которые хранятся на устройстве
|
||||
|
||||
Прототип хранит:
|
||||
|
||||
- `PIN`;
|
||||
- `Wi-Fi SSID`;
|
||||
- `Wi-Fi password`;
|
||||
- `login`;
|
||||
- `session/homeserver name`;
|
||||
- `master secret`;
|
||||
- `wallet address`;
|
||||
- `user pda address`;
|
||||
- `registration signature`;
|
||||
- `balance`;
|
||||
- `server login` для первичной привязки;
|
||||
- `resolved server api url` / `rpc url` / `ws url` после чтения PDA сервера;
|
||||
- флаги:
|
||||
`wifiReady`, `serversReady`, `secretReady`, `registered`, `online`.
|
||||
|
||||
Для первой регистрации обычного `user PDA` устройство берёт `createdAtMs` из NTP прямо перед отправкой транзакции в Solana. При последующих обновлениях `user PDA` устройство так же берёт актуальный `updatedAtMs` из NTP перед отправкой update-транзакции. Дальше в `user PDA` сохраняется `accessServers`, где по умолчанию лежит `shineupme`.
|
||||
|
||||
## Правило серверной сессии SHiNE
|
||||
|
||||
При подключении к серверу `SHiNE` устройство должно авторизовываться как homeserver-сеанс:
|
||||
|
||||
- `sessionType = 100`
|
||||
- `clientPlatform = "ESP32"`
|
||||
- `clientInfo = "ESP32 homeserver:<homeserverName>"`
|
||||
|
||||
Это относится и к `CreateAuthSession`, и к `SessionLogin`.
|
||||
|
||||
## Правила готовности к регистрации
|
||||
|
||||
Кнопка регистрации доступна только если одновременно выполнены условия:
|
||||
|
||||
1. настроен и подтверждён `Wi-Fi`;
|
||||
2. задан и подтверждён `SHiNE server login`;
|
||||
3. задан логин;
|
||||
4. сгенерирован или введён секрет;
|
||||
5. баланс кошелька не меньше `0.20 SOL`;
|
||||
6. устройство ещё не зарегистрировано.
|
||||
|
||||
Если хотя бы одно условие не выполнено, главный экран показывает, чего именно не хватает.
|
||||
|
||||
## Экранная модель
|
||||
|
||||
В прототипе используются следующие экраны:
|
||||
|
||||
1. `LOCK`
|
||||
2. `HOME`
|
||||
3. `STATUS`
|
||||
4. `CONNECTION`
|
||||
5. `WIFI_EDIT`
|
||||
6. `SERVERS`
|
||||
7. `ACCOUNT`
|
||||
8. `WALLET`
|
||||
9. `WALLET_QR`
|
||||
10. `WALLET_SIGN_REQUEST`
|
||||
11. `REQUESTS`
|
||||
12. `REQUEST_DETAIL`
|
||||
13. `SETTINGS`
|
||||
14. `PIN_EDIT`
|
||||
15. `TEXT_INPUT`
|
||||
16. `CONFIRM`
|
||||
17. `REGISTER_ACCOUNT_CONFIRM`
|
||||
18. `REGISTER_ACCOUNT_RESULT`
|
||||
|
||||
## Общие правила интерфейса
|
||||
|
||||
- Верхняя строка всегда показывает краткий статус устройства:
|
||||
`PIN`, `Wi-Fi`, `сервер`, `регистрация`.
|
||||
- В правом верхнем углу рядом с батареей:
|
||||
- сначала процент заряда;
|
||||
- затем, если устройство реально заряжается, маленькая иконка молнии;
|
||||
- затем контур батареи;
|
||||
- затем индикатор `Wi-Fi`.
|
||||
- Основной язык прототипа: английский.
|
||||
- Для вывода текста в текущей временной сборке используется стандартный шрифт `Arduino_GFX`.
|
||||
- Русские строки в UI устройства пока не использовать.
|
||||
- Кнопки крупные, с тач-ориентированным размером.
|
||||
- Опасные действия подтверждаются отдельным диалогом.
|
||||
- После изменения данных конфигурация сразу сохраняется в `NVS`.
|
||||
|
||||
## Экран LOCK
|
||||
|
||||
Назначение:
|
||||
|
||||
- экран блокировки предусмотрен в UI, но в текущей временной сборке после запуска пропускается;
|
||||
- вход по PIN временно отключён для отладки остальных экранов.
|
||||
|
||||
Отображается:
|
||||
|
||||
- заголовок `SHiNE Device`;
|
||||
- статус `Устройство заблокировано`;
|
||||
- поле ввода PIN в виде маски;
|
||||
- кнопки цифровой клавиатуры;
|
||||
- кнопки `Стереть` и `Открыть`.
|
||||
|
||||
Поведение:
|
||||
|
||||
- если PIN введён верно, открывается `HOME`;
|
||||
- если PIN неверный, показывается ошибка `Неверный PIN`;
|
||||
- в текущей временной сборке этот экран не показывается автоматически при старте.
|
||||
|
||||
## Экран HOME
|
||||
|
||||
Это основной экран устройства.
|
||||
|
||||
Показывает:
|
||||
|
||||
- крупный статус регистрации;
|
||||
- имя логина;
|
||||
- имя homeserver;
|
||||
- строку `Wi-Fi: <SSID> connected|disconnected`;
|
||||
- строку `SHiNE: <server address> connected|unavailable`;
|
||||
- короткий статус баланса.
|
||||
|
||||
Особенности верхнего блока:
|
||||
|
||||
- зелёный/контурный статусный кружок аккаунта расположен слева от строки логина;
|
||||
- блок `STATUS` поднят выше относительно предыдущей версии;
|
||||
- если состояние хорошее, слово `connected` в строках `Wi-Fi` и `SHiNE` показывается зелёным.
|
||||
|
||||
В зоне кошелька:
|
||||
|
||||
- вместо старых двух кнопок `баланс` и `QR` показывается одна широкая кнопка;
|
||||
- текст кнопки: `Wallet: <selected wallet name>`;
|
||||
- доступные имена:
|
||||
- `ClientKey`
|
||||
- `RootKey`
|
||||
- либо сохранённое имя `custom`-кошелька;
|
||||
- после старта устройства баланс активного выбранного кошелька пытается загрузиться автоматически, если уже есть секрет и `Wi-Fi`;
|
||||
- нажатие на эту кнопку открывает экран `WALLET`.
|
||||
|
||||
Нижние кнопки:
|
||||
|
||||
- `Статус`
|
||||
- `Подключение`
|
||||
- `Аккаунт`
|
||||
- `Wallet`
|
||||
- `Запросы`
|
||||
- `Настройки`
|
||||
|
||||
Дополнительная большая кнопка:
|
||||
|
||||
- `REGISTER ACCOUNT`
|
||||
- либо жёлтая `ADD HOMESERVER`
|
||||
- либо жёлтая `FIX HOMESERVER PASSWORD`
|
||||
|
||||
Если регистрация уже сделана:
|
||||
|
||||
- если пользователь создан, но в `PDA` ещё нет сессии текущего homeserver, показывается жёлтая кнопка `ADD HOMESERVER`;
|
||||
- если в `PDA` есть homeserver с тем же именем, но с другим ключом, показывается жёлтая кнопка `FIX HOMESERVER PASSWORD`;
|
||||
- если и пользователь, и homeserver-сессия уже корректны, вместо призыва к регистрации показывается статус `Homeserver активен`.
|
||||
- две нижние кнопки внизу экрана не прилегают вплотную друг к другу, между ними есть небольшой зазор.
|
||||
|
||||
## Экран REGISTER_ACCOUNT_CONFIRM
|
||||
|
||||
Показывает предварительную проверку перед отправкой транзакции регистрации.
|
||||
|
||||
Отображается:
|
||||
|
||||
- повторный `login`;
|
||||
- сообщение о том, что логин свободен или уже занят;
|
||||
- баланс кошелька с проверкой порога `0.020 SOL`;
|
||||
- имя homeserver;
|
||||
- пометка, если используется стандартное значение `homeserver1`;
|
||||
- отдельное предупреждение, если `Wi-Fi` не подключён.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `ЗАРЕГИСТРИРОВАТЬ В СИЯНИИ`
|
||||
- `BACK`
|
||||
|
||||
Поведение:
|
||||
|
||||
- если `Wi-Fi` не подключён, на экране прямо показывается уведомление об этом и кнопка регистрации недоступна;
|
||||
- если `login` уже занят в `shine_users`, регистрация недоступна;
|
||||
- если баланс меньше `0.020 SOL`, на экране показывается соответствующая ошибка;
|
||||
- если все проверки пройдены, кнопка регистрации активна и запускает on-chain регистрацию.
|
||||
|
||||
## Экран REGISTER_ACCOUNT_RESULT
|
||||
|
||||
Показывает результат отправки регистрации.
|
||||
|
||||
Отображается:
|
||||
|
||||
- текст успеха или ошибки;
|
||||
- подробное сообщение;
|
||||
- при успехе краткий `user_pda`;
|
||||
- при успехе краткий `tx signature`.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `BACK HOME`
|
||||
- `ACCOUNT`
|
||||
|
||||
Поведение:
|
||||
|
||||
- после успешной регистрации данные `user_pda` и `tx signature` сохраняются в `NVS`;
|
||||
- при ошибке на экране показывается причина отказа;
|
||||
- если ошибку вернул `sendTransaction`, экран старается показать не только общий текст, но и детали `RPC`/preflight/simulate-логов.
|
||||
|
||||
## Экран HOMESERVER_PDA_CONFIRM
|
||||
|
||||
Показывает, что именно не так с homeserver-секцией уже существующей пользовательской `PDA`.
|
||||
|
||||
Отображается:
|
||||
|
||||
- причина (`homeserver` отсутствует в `PDA` или ключ не совпадает с локальным секретом);
|
||||
- `login`;
|
||||
- имя `homeserver`;
|
||||
- короткое пояснение, что именно будет сделано.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `ADD HOMESERVER` или `FIX HOMESERVER PASSWORD`
|
||||
- `BACK`
|
||||
|
||||
Поведение:
|
||||
|
||||
- если `Wi-Fi` не подключён, действие недоступно;
|
||||
- экран не создаёт нового пользователя, а запускает `update_user_pda`;
|
||||
- при `ADD HOMESERVER` в блок `sessions` добавляется запись `session_type=100`;
|
||||
- при `FIX HOMESERVER PASSWORD` обновляется публичный ключ уже существующей записи `homeserver`.
|
||||
|
||||
## Экран HOMESERVER_PDA_RESULT
|
||||
|
||||
Показывает результат обновления `sessions` в пользовательской `PDA`.
|
||||
|
||||
Отображается:
|
||||
|
||||
- успех или ошибка;
|
||||
- короткое сообщение;
|
||||
- при успехе краткий `tx signature`.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `BACK HOME`
|
||||
- `ACCOUNT`
|
||||
|
||||
Поведение:
|
||||
|
||||
- при ошибке текст ошибки сохраняется в ту же USB/NVS-диагностику, что и регистрация;
|
||||
- после успешного обновления выполняется повторная проверка `PDA`, и основной экран должен перейти в состояние `ok`.
|
||||
|
||||
## Экран STATUS
|
||||
|
||||
Показывает сводку:
|
||||
|
||||
- логин;
|
||||
- homeserver;
|
||||
- есть ли секрет;
|
||||
- зарегистрировано ли устройство;
|
||||
- подключён ли Wi-Fi;
|
||||
- доступны ли серверы;
|
||||
- хватает ли баланса;
|
||||
- находится ли устройство онлайн;
|
||||
- краткий отпечаток `PDA` или `tx`.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Назад`
|
||||
- `Обновить статус`
|
||||
|
||||
`Обновить статус` в прототипе не делает сеть, а просто перерисовывает текущие вычисленные состояния.
|
||||
|
||||
## Экран CONNECTION
|
||||
|
||||
Показывает:
|
||||
|
||||
- `Wi-Fi`: готов / не готов;
|
||||
- `Серверы`: готовы / не готовы;
|
||||
- `Онлайн`: да / нет.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Wi-Fi`
|
||||
- `Серверы`
|
||||
- `Подключить`
|
||||
- `Отключить`
|
||||
- `Назад`
|
||||
|
||||
Поведение:
|
||||
|
||||
- `Подключить` переводит устройство в `online=true`, если `Wi-Fi` реально подключён и серверы реально проверены;
|
||||
- `Отключить` переводит устройство в `online=false`.
|
||||
|
||||
## Экран WIFI_EDIT
|
||||
|
||||
Поля:
|
||||
|
||||
- `SSID`
|
||||
- `Пароль`
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Изменить SSID`
|
||||
- `Изменить пароль`
|
||||
- `Проверить`
|
||||
- `Сбросить`
|
||||
- `Назад`
|
||||
|
||||
Поведение:
|
||||
|
||||
- `Проверить` делает реальную попытку подключения к `Wi-Fi`;
|
||||
- `Сбросить` очищает обе строки и ставит `wifiReady=false`.
|
||||
|
||||
## Экран SERVERS
|
||||
|
||||
Поля:
|
||||
|
||||
- `API URL`
|
||||
- `RPC URL`
|
||||
- `WS URL`
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Изменить API`
|
||||
- `Изменить RPC`
|
||||
- `Изменить WS`
|
||||
- `Проверить`
|
||||
- `Тестовые`
|
||||
- `Назад`
|
||||
|
||||
Поведение:
|
||||
|
||||
- `Тестовые` подставляет дефолтные тестовые значения;
|
||||
- `Проверить` делает реальные сетевые проверки:
|
||||
- `API URL` должен отвечать по `HTTP/HTTPS`;
|
||||
- `RPC URL` должен отвечать на `Solana JSON-RPC`;
|
||||
- `WS URL` должен принимать `TCP/TLS`-соединение.
|
||||
|
||||
## Экран ACCOUNT
|
||||
|
||||
Показывает:
|
||||
|
||||
- логин;
|
||||
- имя homeserver;
|
||||
- статус секрета;
|
||||
- короткий отпечаток секрета;
|
||||
- статус регистрации;
|
||||
- короткий отпечаток `PDA` или `tx`.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Изменить логин`
|
||||
- `Секрет`
|
||||
- `Имя homeserver`
|
||||
- `Сгенерировать`
|
||||
- `Очистить`
|
||||
- `Назад`
|
||||
|
||||
Поведение:
|
||||
|
||||
- `Сгенерировать` создаёт новый `master secret` и пересчитывает из него `device`-кошелёк;
|
||||
- `Очистить` удаляет секрет, адрес кошелька, `PDA`, `tx`, регистрацию и онлайн-статус;
|
||||
- логин приводится к нижнему регистру и trim.
|
||||
- после успешной регистрации на экране сохраняются и отображаются краткие отпечатки `PDA` и `TX`.
|
||||
|
||||
## Экран WALLET
|
||||
|
||||
Показывает:
|
||||
|
||||
- кнопку `Wallet: <selected wallet name>`;
|
||||
- строку текущего статуса/баланса активного кошелька;
|
||||
- сокращённый публичный ключ активного кошелька.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Wallet: <selected wallet name>`
|
||||
- `SHOW BALANCE`
|
||||
- `SHOW WALLET QR`
|
||||
|
||||
Поведение:
|
||||
|
||||
- верхняя кнопка открывает экран выбора кошелька `WALLET_SELECT`;
|
||||
- `Показать баланс кошелька` читает реальный баланс именно активного выбранного кошелька из `Solana RPC`;
|
||||
- `Показать QR-код кошелька` открывает экран `WALLET_QR`;
|
||||
- этот экран не меняет логику Solana-регистрации пользователя: on-chain регистрация и проверки `PDA` по-прежнему завязаны на `client key`.
|
||||
|
||||
## Экран WALLET_SELECT
|
||||
|
||||
Показывает:
|
||||
|
||||
- строку `Current: <selected wallet name>`;
|
||||
- три кнопки выбора:
|
||||
- `ClientKey`
|
||||
- `RootKey`
|
||||
- `Custom` или `Custom: <имя>`;
|
||||
- у текущего выбора видна галочка.
|
||||
|
||||
Поведение:
|
||||
|
||||
- `ClientKey` активирует кошелёк, выведенный из suffix `client.key`;
|
||||
- `RootKey` активирует кошелёк, выведенный из suffix `root.key`;
|
||||
- `Custom` использует derivation:
|
||||
`sha256(base64(secret32) + "|wallet." + customName)`;
|
||||
- если имя `custom`-кошелька ещё не задано, нажатие `Custom` открывает экран текстового ввода;
|
||||
- если `custom` уже выбран, повторное нажатие на него открывает экран редактирования имени;
|
||||
- после выбора кошелька устройство возвращается на экран `WALLET`.
|
||||
|
||||
## Экран WALLET_QR
|
||||
|
||||
Экран показывает:
|
||||
|
||||
- крупный реальный `QR` для строки `solana:<wallet_address>`;
|
||||
- снизу крупный текст самого адреса кошелька.
|
||||
|
||||
Поведение:
|
||||
|
||||
- отдельная текстовая подсказка возврата не показывается;
|
||||
- возврат на главный экран выполняется обычным тапом по экрану.
|
||||
|
||||
Показывает:
|
||||
|
||||
- QR-код для строки вида:
|
||||
`solana:<wallet>`;
|
||||
- мелкую подпись с полным адресом кошелька под QR.
|
||||
|
||||
Поведение:
|
||||
|
||||
- QR должен быть сканируемым, а не декоративным;
|
||||
- адрес кошелька берётся из текущего активного выбранного кошелька;
|
||||
- нажатие в любую точку экрана возвращает пользователя на `WALLET`.
|
||||
|
||||
## Экран WALLET_SIGN_REQUEST
|
||||
|
||||
Экран показывается, когда браузерное wallet-расширение присылает на ESP32 запрос `sign_transaction`.
|
||||
|
||||
Показывает:
|
||||
|
||||
- заголовок `SIGN REQUEST`;
|
||||
- вопрос о подписи транзакции текущим активным кошельком;
|
||||
- сокращённый публичный ключ кошелька;
|
||||
- комментарий, присланный полем `comment`;
|
||||
- две кнопки:
|
||||
- `REJECT`
|
||||
- `APPROVE`
|
||||
|
||||
Поведение:
|
||||
|
||||
- если пользователь нажимает `APPROVE`, ESP32 подписывает транзакцию текущим активным кошельком и отправляет ответ в расширение;
|
||||
- если пользователь нажимает `REJECT`, ESP32 отправляет отказ `rejected_by_user`;
|
||||
- пока запрос активен, свайпом этот экран не закрывается;
|
||||
- после ответа расширению устройство возвращается на предыдущий экран.
|
||||
|
||||
## Экран REQUESTS
|
||||
|
||||
Экран доступен только если homeserver уже авторизован в SHiNE.
|
||||
|
||||
Показывает:
|
||||
|
||||
- слева сверху кнопку `REFRESH`;
|
||||
- заголовок `REQUESTS:` немного правее стандартного левого положения;
|
||||
- справа сверху только большую цифру числа активных заявок;
|
||||
- ниже прокручиваемый список активных pairing-заявок;
|
||||
- на экране одновременно видны примерно две плитки.
|
||||
|
||||
Каждая плитка показывает:
|
||||
|
||||
- код подключения из `10` цифр в виде `5` пар: `XX XX XX XX XX`;
|
||||
- строку `Session: <platform/name>`;
|
||||
- строку `Kind: Client session` или `Kind: Wallet session`.
|
||||
|
||||
Поведение:
|
||||
|
||||
- список берётся из живой операции `ListTrustedDeviceLoginRequests`;
|
||||
- если заявок нет, экран показывает `No active requests`;
|
||||
- отдельная строка вида `Active requests: N` на этом экране не показывается;
|
||||
- вертикальный скролл позволяет просматривать все активные заявки;
|
||||
- нажатие по плитке открывает `REQUEST_DETAIL`;
|
||||
- свайп вправо возвращает в `SETTINGS`.
|
||||
|
||||
## Экран REQUEST_DETAIL
|
||||
|
||||
Показывает детали выбранной pairing-заявки:
|
||||
|
||||
- вопрос `Connect session ...?`;
|
||||
- код подключения `XX XX XX XX XX`;
|
||||
- строку `Session: <platform/name>`;
|
||||
- строку `Kind: Client session` или `Kind: Wallet session`;
|
||||
- пояснение:
|
||||
- для client session: `Only client key will be transferred. No additional keys will be sent.`
|
||||
- для wallet session: `No keys will be transferred.`
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `YES`
|
||||
- `NO`
|
||||
|
||||
Поведение:
|
||||
|
||||
- `YES` подтверждает заявку:
|
||||
- для client session устройство передаёт только `client key`;
|
||||
- для wallet session устройство выпускает отдельную `wallet-session` без передачи ключей;
|
||||
- `NO` отклоняет заявку;
|
||||
- после любого решения устройство возвращается в список `REQUESTS` и обновляет его;
|
||||
- свайп вправо возвращает в `REQUESTS`.
|
||||
|
||||
## Экран SETTINGS
|
||||
|
||||
Показывает вертикальное меню крупных пунктов.
|
||||
|
||||
Если homeserver ещё не авторизован в SHiNE:
|
||||
|
||||
- `1. Wi-Fi`
|
||||
- `2. Server`
|
||||
- `3. Account`
|
||||
|
||||
Если homeserver уже авторизован:
|
||||
|
||||
- `1. Device requests`
|
||||
- `2. Wi-Fi`
|
||||
- `3. Server`
|
||||
- `4. Account`
|
||||
|
||||
Поведение:
|
||||
|
||||
- одновременно видны только две карточки;
|
||||
- список листается свайпом вверх/вниз;
|
||||
- свайп вправо возвращает на `HOME`;
|
||||
- пункт `Device requests` должен быть первым и появляется только для авторизованного homeserver.
|
||||
|
||||
## Экран PIN_EDIT
|
||||
|
||||
Используется для ввода нового PIN.
|
||||
|
||||
Правила:
|
||||
|
||||
- допустимы только цифры;
|
||||
- длина PIN: 4..8 символов;
|
||||
- после сохранения новый PIN немедленно пишется в `NVS`.
|
||||
|
||||
## Экран TEXT_INPUT
|
||||
|
||||
Это общий экран редактирования текстовых полей.
|
||||
|
||||
Используется для:
|
||||
|
||||
- `SSID`
|
||||
- `Пароль Wi-Fi`
|
||||
- `Логин`
|
||||
- `Имя homeserver`
|
||||
- `API URL`
|
||||
- `RPC URL`
|
||||
- `WS URL`
|
||||
|
||||
Состав экрана:
|
||||
|
||||
- заголовок поля;
|
||||
- текущее значение;
|
||||
- программная клавиатура;
|
||||
- кнопки `Стереть`, `OK`, `Отмена`.
|
||||
|
||||
## Экран CONFIRM
|
||||
|
||||
Это модальный экран подтверждения.
|
||||
|
||||
Используется для:
|
||||
|
||||
- регистрации;
|
||||
- очистки секрета;
|
||||
- полного сброса.
|
||||
|
||||
Кнопки:
|
||||
|
||||
- `Подтвердить`
|
||||
- `Отмена`
|
||||
|
||||
## Сценарий первой настройки
|
||||
|
||||
Ожидаемый путь пользователя:
|
||||
|
||||
1. открыть устройство сразу после старта; экран PIN временно не требуется;
|
||||
2. открыть `Подключение -> Wi-Fi`;
|
||||
3. ввести `SSID` и пароль, нажать `Проверить`;
|
||||
4. открыть `Подключение -> Серверы`;
|
||||
5. проверить или задать `SHiNE server login` (по умолчанию `shineupme`);
|
||||
6. открыть `Аккаунт`;
|
||||
7. ввести логин;
|
||||
8. задать имя homeserver;
|
||||
9. сгенерировать секрет;
|
||||
10. открыть `Кошелёк`;
|
||||
11. при необходимости пополнить баланс;
|
||||
12. вернуться на `HOME`;
|
||||
13. нажать `REGISTER ACCOUNT`;
|
||||
14. на экране проверки ещё раз увидеть `login`, статус свободного `PDA`, баланс, `homeserver1`, серверный login и при необходимости сообщение о неподключённом `Wi-Fi`;
|
||||
15. нажать `ЗАРЕГИСТРИРОВАТЬ В СИЯНИИ`;
|
||||
16. после завершения увидеть либо экран успеха с `user_pda` и `tx signature`, либо подробную ошибку;
|
||||
17. после успешной регистрации увидеть статус `Homeserver активен`.
|
||||
|
||||
Примечание:
|
||||
|
||||
- устройство реально отправляет `create_user_pda` в `shine_users`, а после подтверждения сохраняет `PDA` и `tx signature`;
|
||||
- при первой регистрации для обычного `user PDA` не заполняется `serverAddress`, а `accessServers` получает `shineupme` или другой выбранный `SHiNE server login`.
|
||||
|
||||
## Сценарий входящего запроса
|
||||
|
||||
1. открыть `Запросы`;
|
||||
2. выбрать один из запросов;
|
||||
3. прочитать детали;
|
||||
4. нажать `Разрешить` или `Отклонить`;
|
||||
5. убедиться, что статус запроса изменился.
|
||||
|
||||
## Временный режим текста
|
||||
|
||||
В текущей диагностической версии:
|
||||
|
||||
- строковые литералы экранного UI должны оставаться английскими ASCII-совместимыми;
|
||||
- возвращение кириллицы допустимо только после отдельной доработки шрифтов и реальной проверки на устройстве;
|
||||
- рендер выполняется стандартным шрифтом `Arduino_GFX`;
|
||||
- это обходной режим, пока `U8g2`-шрифты на устройстве не начнут рисоваться стабильно.
|
||||
|
||||
## Критерии ручной проверки
|
||||
|
||||
Минимально нужно проверить:
|
||||
|
||||
1. устройство загружается и сразу открывает `HOME`; экран блокировки временно отключён;
|
||||
2. весь экранный текст отображается читаемо на английском без замены символов;
|
||||
3. ввод по экранной клавиатуре работает;
|
||||
4. после перезагрузки сохранённые поля остаются в памяти;
|
||||
5. секрет и адрес кошелька сохраняются на устройстве;
|
||||
6. экран `QR и URI` рисует читаемый QR-код;
|
||||
7. регистрация блокируется, пока условия не выполнены;
|
||||
8. после выполнения условий регистрация становится доступной;
|
||||
9. список запросов и экран подтверждения работают;
|
||||
10. полный сброс действительно очищает сохранённое состояние.
|
||||
+6
@@ -15,6 +15,9 @@
|
||||
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
|
||||
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
|
||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
||||
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
||||
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
||||
- `usb_contact_resistance_test/` - тест измерения сопротивления между USB D-/D+ через ADC на GPIO20; рассчитан на внешний известный резистор 10 kΩ с D+ на GND
|
||||
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
||||
|
||||
## Запуск
|
||||
@@ -29,3 +32,6 @@
|
||||
- `./burn.sh lvgl-official-based-test`
|
||||
- `./burn.sh lvgl-subserver-touch-test`
|
||||
- `./burn.sh lvgl-russian-font-test`
|
||||
- `./burn.sh usb-contact-test`
|
||||
- `./burn.sh usb-contact-debug-test`
|
||||
- `./burn.sh usb-contact-resistance-test`
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <lvgl.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include "pin_config.h"
|
||||
#include "TouchDrvCSTXXX.hpp"
|
||||
|
||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
||||
|
||||
// ESP32-S3 native USB data pins.
|
||||
static constexpr int kUsbDmPin = 19; // USB D-
|
||||
static constexpr int kUsbDpPin = 20; // USB D+, ADC input in resistance mode.
|
||||
static constexpr uint32_t kUiRefreshMs = 120;
|
||||
static constexpr uint32_t kAdcSamples = 32;
|
||||
|
||||
// For a stable ohm reading connect a known resistor from D+ / GPIO20 to GND.
|
||||
// The measured resistance must be connected between D- / GPIO19 and D+ / GPIO20.
|
||||
static constexpr float kKnownPulldownOhms = 10000.0f;
|
||||
static constexpr float kSourceMillivolts = 3300.0f;
|
||||
static constexpr float kOpenThresholdMillivolts = 25.0f;
|
||||
|
||||
static lv_disp_draw_buf_t gDrawBuf;
|
||||
static lv_color_t *gBuf1 = nullptr;
|
||||
static lv_color_t *gBuf2 = nullptr;
|
||||
static lv_obj_t *gModeLabel = nullptr;
|
||||
static lv_obj_t *gResistanceLabel = nullptr;
|
||||
static lv_obj_t *gRawLabel = nullptr;
|
||||
static lv_obj_t *gHintLabel = nullptr;
|
||||
static lv_obj_t *gActionButton = nullptr;
|
||||
static lv_obj_t *gActionButtonLabel = nullptr;
|
||||
|
||||
static TouchDrvCST92xx gTouch;
|
||||
static int16_t gTouchX[5];
|
||||
static int16_t gTouchY[5];
|
||||
|
||||
static bool gSensorMode = false;
|
||||
static uint32_t gLastUiRefreshMs = 0;
|
||||
|
||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
||||
|
||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
||||
uint32_t w = area->x2 - area->x1 + 1;
|
||||
uint32_t h = area->y2 - area->y1 + 1;
|
||||
#if (LV_COLOR_16_SWAP != 0)
|
||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#else
|
||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#endif
|
||||
lv_disp_flush_ready(disp);
|
||||
}
|
||||
|
||||
static void lvglTick(void *arg) {
|
||||
LV_UNUSED(arg);
|
||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
||||
LV_UNUSED(indevDrv);
|
||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
||||
if (touched > 0) {
|
||||
data->state = LV_INDEV_STATE_PR;
|
||||
data->point.x = gTouchX[0];
|
||||
data->point.y = gTouchY[0];
|
||||
return;
|
||||
}
|
||||
data->state = LV_INDEV_STATE_REL;
|
||||
}
|
||||
|
||||
static uint32_t readAverageRaw() {
|
||||
uint32_t sum = 0;
|
||||
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||
sum += analogRead(kUsbDpPin);
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
return sum / kAdcSamples;
|
||||
}
|
||||
|
||||
static uint32_t readAverageMillivolts() {
|
||||
uint32_t sum = 0;
|
||||
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||
sum += analogReadMilliVolts(kUsbDpPin);
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
return sum / kAdcSamples;
|
||||
}
|
||||
|
||||
static void setResistanceText(float ohms) {
|
||||
if (ohms >= 1000000.0f) {
|
||||
String text = String(ohms / 1000000.0f, 2) + " Mohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
} else if (ohms >= 1000.0f) {
|
||||
String text = String(ohms / 1000.0f, 2) + " kohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
} else {
|
||||
String text = String(ohms, 0) + " ohm";
|
||||
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
static void updateResistanceUi() {
|
||||
if (!gSensorMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint32_t now = millis();
|
||||
if (now - gLastUiRefreshMs < kUiRefreshMs) {
|
||||
return;
|
||||
}
|
||||
gLastUiRefreshMs = now;
|
||||
|
||||
uint32_t raw = readAverageRaw();
|
||||
uint32_t millivolts = readAverageMillivolts();
|
||||
|
||||
if (millivolts <= kOpenThresholdMillivolts) {
|
||||
lv_label_set_text(gResistanceLabel, "OPEN");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0xFFD166), 0);
|
||||
} else if (millivolts >= (uint32_t)(kSourceMillivolts - 80.0f)) {
|
||||
lv_label_set_text(gResistanceLabel, "SHORT / LOW");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
} else {
|
||||
float rx = kKnownPulldownOhms * ((kSourceMillivolts / (float)millivolts) - 1.0f);
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
setResistanceText(rx);
|
||||
}
|
||||
|
||||
String rawText = "ADC raw: " + String(raw);
|
||||
rawText += "\nD+ voltage: " + String(millivolts) + " mV";
|
||||
rawText += "\nKnown pulldown: 10 kohm to GND";
|
||||
lv_label_set_text(gRawLabel, rawText.c_str());
|
||||
}
|
||||
|
||||
static void enterSensorMode() {
|
||||
Serial.flush();
|
||||
delay(30);
|
||||
|
||||
pinMode(kUsbDmPin, OUTPUT);
|
||||
digitalWrite(kUsbDmPin, HIGH);
|
||||
|
||||
pinMode(kUsbDpPin, INPUT);
|
||||
analogReadResolution(12);
|
||||
analogSetPinAttenuation(kUsbDpPin, ADC_11db);
|
||||
|
||||
gSensorMode = true;
|
||||
gLastUiRefreshMs = 0;
|
||||
|
||||
lv_label_set_text(gModeLabel, "Resistance mode");
|
||||
lv_label_set_text(gHintLabel, "D- is 3.3V source. D+ is ADC input.\nUse 10 kohm from D+ to GND for accurate readings.");
|
||||
lv_label_set_text(gActionButtonLabel, "Restart to USB");
|
||||
updateResistanceUi();
|
||||
}
|
||||
|
||||
static void actionButtonEventCb(lv_event_t *event) {
|
||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!gSensorMode) {
|
||||
enterSensorMode();
|
||||
return;
|
||||
}
|
||||
|
||||
lv_label_set_text(gModeLabel, "Restarting...");
|
||||
lv_label_set_text(gHintLabel, "USB mode will return after reboot.");
|
||||
lv_timer_handler();
|
||||
delay(150);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void createUi() {
|
||||
lv_obj_t *screen = lv_scr_act();
|
||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||
|
||||
lv_obj_t *title = lv_label_create(screen);
|
||||
lv_label_set_text(title, "USB RESISTANCE TEST");
|
||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 24);
|
||||
|
||||
gModeLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gModeLabel, "USB mode");
|
||||
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0xB8C8DC), 0);
|
||||
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
|
||||
lv_obj_align(gModeLabel, LV_ALIGN_TOP_MID, 0, 68);
|
||||
|
||||
gResistanceLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gResistanceLabel, "READY");
|
||||
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_obj_set_style_text_font(gResistanceLabel, &lv_font_montserrat_40, 0);
|
||||
lv_obj_align(gResistanceLabel, LV_ALIGN_CENTER, 0, -72);
|
||||
|
||||
gRawLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gRawLabel, "ADC raw: -\nD+ voltage: -\nKnown pulldown: 10 kohm to GND");
|
||||
lv_obj_set_width(gRawLabel, 420);
|
||||
lv_label_set_long_mode(gRawLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gRawLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0xD5DCE5), 0);
|
||||
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_16, 0);
|
||||
lv_obj_align(gRawLabel, LV_ALIGN_CENTER, 0, -8);
|
||||
|
||||
gHintLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gHintLabel, "USB is normal now.\nTap Start to measure resistance between D- and D+.");
|
||||
lv_obj_set_width(gHintLabel, 420);
|
||||
lv_label_set_long_mode(gHintLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gHintLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_color(gHintLabel, lv_color_hex(0xAAB7C6), 0);
|
||||
lv_obj_set_style_text_font(gHintLabel, &lv_font_montserrat_14, 0);
|
||||
lv_obj_align(gHintLabel, LV_ALIGN_CENTER, 0, 72);
|
||||
|
||||
gActionButton = lv_btn_create(screen);
|
||||
lv_obj_set_size(gActionButton, 260, 72);
|
||||
lv_obj_align(gActionButton, LV_ALIGN_BOTTOM_MID, 0, -42);
|
||||
lv_obj_set_style_radius(gActionButton, 18, 0);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), 0);
|
||||
lv_obj_set_style_border_width(gActionButton, 0, 0);
|
||||
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_CLICKED, nullptr);
|
||||
|
||||
gActionButtonLabel = lv_label_create(gActionButton);
|
||||
lv_label_set_text(gActionButtonLabel, "Start");
|
||||
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_22, 0);
|
||||
lv_obj_center(gActionButtonLabel);
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
Wire.begin(IIC_SDA, IIC_SCL);
|
||||
|
||||
pinMode(TP_RST, OUTPUT);
|
||||
pinMode(TP_INT, INPUT);
|
||||
digitalWrite(TP_RST, LOW);
|
||||
delay(30);
|
||||
digitalWrite(TP_RST, HIGH);
|
||||
delay(50);
|
||||
delay(1000);
|
||||
|
||||
gTouch.setPins(TP_RST, TP_INT);
|
||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
||||
if (!touchOk) {
|
||||
Serial.println("Touch init failed");
|
||||
} else {
|
||||
gTouch.sleep();
|
||||
gTouch.reset();
|
||||
gTouch.setMaxCoordinates(480, 480);
|
||||
gTouch.setSwapXY(true);
|
||||
gTouch.setMirrorXY(true, false);
|
||||
}
|
||||
|
||||
gfx->begin();
|
||||
gBus->writeC8D8(0x36, 0xA0);
|
||||
gfx->setBrightness(220);
|
||||
gfx->fillScreen(0x0000);
|
||||
|
||||
lv_init();
|
||||
|
||||
uint32_t screenWidth = gfx->width();
|
||||
uint32_t screenHeight = gfx->height();
|
||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
||||
|
||||
static lv_disp_drv_t dispDrv;
|
||||
lv_disp_drv_init(&dispDrv);
|
||||
dispDrv.hor_res = screenWidth;
|
||||
dispDrv.ver_res = screenHeight;
|
||||
dispDrv.flush_cb = lvglFlushCb;
|
||||
dispDrv.draw_buf = &gDrawBuf;
|
||||
lv_disp_drv_register(&dispDrv);
|
||||
|
||||
static lv_indev_drv_t indevDrv;
|
||||
lv_indev_drv_init(&indevDrv);
|
||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
||||
indevDrv.read_cb = lvglTouchRead;
|
||||
lv_indev_drv_register(&indevDrv);
|
||||
|
||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
||||
.callback = &lvglTick,
|
||||
.name = "lvgl_tick"};
|
||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
||||
|
||||
createUi();
|
||||
Serial.println("USB resistance test ready; native USB remains active until Start is tapped.");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
updateResistanceUi();
|
||||
lv_timer_handler();
|
||||
delay(5);
|
||||
}
|
||||
+600
@@ -0,0 +1,600 @@
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <math.h>
|
||||
#include <Preferences.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include <TouchDrvCSTXXX.hpp>
|
||||
#include "ESP_I2S.h"
|
||||
#include "es8311.h"
|
||||
|
||||
#define PIN_LCD_CS 12
|
||||
#define PIN_LCD_SCLK 38
|
||||
#define PIN_LCD_D0 4
|
||||
#define PIN_LCD_D1 5
|
||||
#define PIN_LCD_D2 6
|
||||
#define PIN_LCD_D3 7
|
||||
#define PIN_LCD_RST 2
|
||||
#define PIN_I2C_SDA 15
|
||||
#define PIN_I2C_SCL 14
|
||||
#define PIN_TP_INT 11
|
||||
#define PIN_USER_BTN 0
|
||||
#define PIN_PA 46
|
||||
#define PIN_I2S_BCLK 9
|
||||
#define PIN_I2S_LRCK 45
|
||||
#define PIN_I2S_DOUT 8
|
||||
#define PIN_I2S_DIN 10
|
||||
#define PIN_I2S_MCLK 42
|
||||
|
||||
#define DISP_W 480
|
||||
#define DISP_H 480
|
||||
|
||||
static constexpr int kUsbDmPin = 19;
|
||||
static constexpr int kUsbDpPin = 20;
|
||||
static constexpr uint32_t kContactDebounceMs = 80;
|
||||
static constexpr uint32_t kButtonDebounceMs = 45;
|
||||
static constexpr uint32_t kUiPeriodMs = 200;
|
||||
static constexpr uint32_t kSampleRate = 16000;
|
||||
static constexpr uint32_t kMinCycleMs = 1500;
|
||||
static constexpr uint32_t kPauseAfterMs = 60000;
|
||||
|
||||
#define C_BG 0x0841u
|
||||
#define C_PANEL 0x1082u
|
||||
#define C_CARD 0x18C3u
|
||||
#define C_BORDER 0x39C7u
|
||||
#define C_TEXT 0xFFFFu
|
||||
#define C_MUTE 0xBDF7u
|
||||
#define C_ACCENT 0x5D5Fu
|
||||
#define C_OK 0x3666u
|
||||
#define C_BAD 0xD145u
|
||||
#define C_BUTTON 0x2145u
|
||||
|
||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
|
||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
|
||||
|
||||
TouchDrvCST92xx gTouch;
|
||||
I2SClass gI2s;
|
||||
Preferences gPrefs;
|
||||
|
||||
struct Rect {
|
||||
int16_t x;
|
||||
int16_t y;
|
||||
int16_t w;
|
||||
int16_t h;
|
||||
};
|
||||
|
||||
static const Rect kStartButton = {96, 348, 288, 78};
|
||||
static const Rect kLimitSlider = {42, 132, 396, 44};
|
||||
static const Rect kTickSlider = {42, 246, 396, 44};
|
||||
static const Rect kAlertSlider = {42, 360, 396, 44};
|
||||
static const uint16_t kLimitsSec[] = {5, 7, 10, 15, 20};
|
||||
static const int16_t kTickAmpByVolume[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600};
|
||||
static const int16_t kAlertAmpByVolume[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000};
|
||||
|
||||
static bool gStarted = false;
|
||||
static bool gSettingsOpen = false;
|
||||
static bool gAudioReady = false;
|
||||
static bool gStableClosed = false;
|
||||
static bool gLastRawClosed = false;
|
||||
static bool gStaticDrawn = false;
|
||||
static bool gNeedRedraw = true;
|
||||
static bool gNeedStaticRedraw = true;
|
||||
static bool gLastDrawnClosed = false;
|
||||
static bool gLastDrawnPaused = false;
|
||||
static bool gTouchDown = false;
|
||||
static bool gUserButtonDown = false;
|
||||
static int16_t gTouchStartX = 0;
|
||||
static int16_t gTouchStartY = 0;
|
||||
static int16_t gTouchLastX = 0;
|
||||
static int16_t gTouchLastY = 0;
|
||||
static uint32_t gLastRawChangeMs = 0;
|
||||
static uint32_t gStartedMs = 0;
|
||||
static uint32_t gLastCycleStartMs = 0;
|
||||
static uint32_t gLastUiMs = 0;
|
||||
static uint32_t gUserButtonChangeMs = 0;
|
||||
static uint32_t gCycleMs[5] = {};
|
||||
static uint8_t gCycleCount = 0;
|
||||
static uint8_t gCycleNext = 0;
|
||||
static uint8_t gLimitIndex = 2;
|
||||
static uint8_t gTickVolume = 3;
|
||||
static uint8_t gAlertVolume = 10;
|
||||
static uint8_t gShortStreak = 0;
|
||||
static char gLastTopLine[48] = "";
|
||||
static char gLastStreakLine[48] = "";
|
||||
|
||||
static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
|
||||
gfx->fillRoundRect(x, y, w, h, radius, fill);
|
||||
gfx->drawRoundRect(x, y, w, h, radius, border);
|
||||
}
|
||||
|
||||
static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) {
|
||||
gfx->setFont();
|
||||
gfx->setTextSize(size);
|
||||
gfx->setTextColor(color);
|
||||
gfx->setCursor(x, y);
|
||||
gfx->print(text);
|
||||
}
|
||||
|
||||
static void drawCenteredText(int x, int y, int w, const char *text, uint16_t color, uint8_t size = 2) {
|
||||
int textW = strlen(text) * 6 * size;
|
||||
int textX = x + (w - textW) / 2;
|
||||
if (textX < x + 8) {
|
||||
textX = x + 8;
|
||||
}
|
||||
drawText(textX, y, text, color, size);
|
||||
}
|
||||
|
||||
static void drawButton(const Rect &rect, const char *label, uint8_t size = 2) {
|
||||
drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12);
|
||||
drawCenteredText(rect.x, rect.y + 18, rect.w, label, C_TEXT, size);
|
||||
}
|
||||
|
||||
static bool contains(const Rect &rect, int16_t x, int16_t y) {
|
||||
return x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h;
|
||||
}
|
||||
|
||||
static void clearArea(int x, int y, int w, int h, uint16_t fill) {
|
||||
gfx->fillRect(x, y, w, h, fill);
|
||||
}
|
||||
|
||||
static void formatSec(char *out, size_t outSize, uint32_t ms) {
|
||||
snprintf(out, outSize, "%lu.%01lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100));
|
||||
}
|
||||
|
||||
static void formatClock(char *out, size_t outSize, uint32_t ms) {
|
||||
uint32_t sec = ms / 1000;
|
||||
snprintf(out, outSize, "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60));
|
||||
}
|
||||
|
||||
static uint32_t averageCycleMs() {
|
||||
if (gCycleCount == 0) {
|
||||
return 0;
|
||||
}
|
||||
uint32_t sum = 0;
|
||||
for (uint8_t i = 0; i < gCycleCount; i++) {
|
||||
sum += gCycleMs[i];
|
||||
}
|
||||
return sum / gCycleCount;
|
||||
}
|
||||
|
||||
static void resetCachedUiText() {
|
||||
gLastTopLine[0] = '\0';
|
||||
gLastStreakLine[0] = '\0';
|
||||
}
|
||||
|
||||
static void loadSettings() {
|
||||
gPrefs.begin("breath-mon", false);
|
||||
gLimitIndex = gPrefs.getUChar("limit", gLimitIndex);
|
||||
gTickVolume = gPrefs.getUChar("tick", gTickVolume);
|
||||
gAlertVolume = gPrefs.getUChar("alert", gAlertVolume);
|
||||
if (gLimitIndex > 4) {
|
||||
gLimitIndex = 2;
|
||||
}
|
||||
if (gTickVolume > 10) {
|
||||
gTickVolume = 3;
|
||||
}
|
||||
if (gAlertVolume > 10) {
|
||||
gAlertVolume = 10;
|
||||
}
|
||||
}
|
||||
|
||||
static void saveSettings() {
|
||||
gPrefs.putUChar("limit", gLimitIndex);
|
||||
gPrefs.putUChar("tick", gTickVolume);
|
||||
gPrefs.putUChar("alert", gAlertVolume);
|
||||
}
|
||||
|
||||
static bool isAutoPaused() {
|
||||
return gStarted && gLastCycleStartMs != 0 && (millis() - gLastCycleStartMs) > kPauseAfterMs;
|
||||
}
|
||||
|
||||
static esp_err_t codecInit() {
|
||||
es8311_handle_t esHandle = es8311_create(0, ES8311_ADDRRES_0);
|
||||
if (!esHandle) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
const es8311_clock_config_t clk = {
|
||||
.mclk_inverted = false,
|
||||
.sclk_inverted = false,
|
||||
.mclk_from_mclk_pin = true,
|
||||
.mclk_frequency = (int)kSampleRate * 256,
|
||||
.sample_frequency = (int)kSampleRate,
|
||||
};
|
||||
if (es8311_init(esHandle, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16) != ESP_OK) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
es8311_voice_volume_set(esHandle, 100, nullptr);
|
||||
es8311_voice_mute(esHandle, false);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void initAudio() {
|
||||
pinMode(PIN_PA, OUTPUT);
|
||||
digitalWrite(PIN_PA, HIGH);
|
||||
gI2s.setPins(PIN_I2S_BCLK, PIN_I2S_LRCK, PIN_I2S_DOUT, PIN_I2S_DIN, PIN_I2S_MCLK);
|
||||
if (!gI2s.begin(I2S_MODE_STD, kSampleRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO, I2S_STD_SLOT_BOTH)) {
|
||||
Serial.println("I2S init failed");
|
||||
return;
|
||||
}
|
||||
gAudioReady = (codecInit() == ESP_OK);
|
||||
Serial.println(gAudioReady ? "Audio init OK" : "Audio codec init failed");
|
||||
}
|
||||
|
||||
static void playBeep(uint16_t freq, uint16_t samples, int16_t amp) {
|
||||
if (!gAudioReady || amp <= 0) {
|
||||
return;
|
||||
}
|
||||
static int16_t toneBuf[1600 * 2];
|
||||
if (samples > 1600) {
|
||||
samples = 1600;
|
||||
}
|
||||
for (int i = 0; i < samples; i++) {
|
||||
float s = sinf(2.0f * 3.1415926f * (float)freq * ((float)i / (float)kSampleRate));
|
||||
int16_t v = (int16_t)(s * amp);
|
||||
toneBuf[i * 2] = v;
|
||||
toneBuf[i * 2 + 1] = v;
|
||||
}
|
||||
gI2s.write((uint8_t *)toneBuf, samples * 2 * sizeof(int16_t));
|
||||
}
|
||||
|
||||
static void playCycleTick() {
|
||||
playBeep(880, 480, kTickAmpByVolume[gTickVolume]);
|
||||
}
|
||||
|
||||
static void playAlertBeep() {
|
||||
playBeep(1200, 1600, kAlertAmpByVolume[gAlertVolume]);
|
||||
}
|
||||
|
||||
static void alertIfNeeded() {
|
||||
if (gShortStreak == 0) {
|
||||
return;
|
||||
}
|
||||
uint8_t count = min<uint8_t>(gShortStreak, 5);
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
playAlertBeep();
|
||||
delay(80);
|
||||
}
|
||||
}
|
||||
|
||||
static void addCycle(uint32_t cycleMs) {
|
||||
gCycleMs[gCycleNext] = cycleMs;
|
||||
gCycleNext = (gCycleNext + 1) % 5;
|
||||
if (gCycleCount < 5) {
|
||||
gCycleCount++;
|
||||
}
|
||||
|
||||
uint32_t avgMs = averageCycleMs();
|
||||
if (avgMs > 0 && avgMs < (uint32_t)kLimitsSec[gLimitIndex] * 1000UL) {
|
||||
if (gShortStreak < 5) {
|
||||
gShortStreak++;
|
||||
}
|
||||
} else {
|
||||
gShortStreak = 0;
|
||||
}
|
||||
}
|
||||
|
||||
static void drawReadyScreen() {
|
||||
gfx->fillScreen(C_BG);
|
||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
||||
drawText(28, 42, "BREATH MONITOR", C_TEXT, 3);
|
||||
drawText(28, 78, "USB contact sensor", C_MUTE, 2);
|
||||
drawPanel(34, 132, 412, 160, C_CARD, C_BORDER, 14);
|
||||
drawCenteredText(34, 166, 412, "READY", C_ACCENT, 4);
|
||||
drawCenteredText(34, 222, 412, "Closed = exhale", C_TEXT, 2);
|
||||
drawCenteredText(34, 252, 412, "Open = inhale", C_MUTE, 2);
|
||||
drawButton(kStartButton, "START", 3);
|
||||
}
|
||||
|
||||
static void drawSlider(const Rect &rect, const char *title, const char *value, uint8_t pos, uint8_t maxPos) {
|
||||
drawText(rect.x, rect.y - 28, title, C_TEXT, 2);
|
||||
drawText(rect.x + 278, rect.y - 28, value, C_ACCENT, 2);
|
||||
drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12);
|
||||
int trackX = rect.x + 22;
|
||||
int trackW = rect.w - 44;
|
||||
int trackY = rect.y + rect.h / 2 - 3;
|
||||
gfx->fillRect(trackX, trackY, trackW, 6, C_BORDER);
|
||||
int knobX = trackX + (trackW * pos) / max<uint8_t>(1, maxPos);
|
||||
gfx->fillRoundRect(knobX - 10, rect.y + 8, 20, rect.h - 16, 8, C_ACCENT);
|
||||
}
|
||||
|
||||
static void drawSettingsScreen() {
|
||||
char value[24];
|
||||
gfx->fillScreen(C_BG);
|
||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
||||
drawText(28, 36, "SETTINGS", C_TEXT, 3);
|
||||
drawText(28, 72, "Press top button to close", C_MUTE, 2);
|
||||
|
||||
snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]);
|
||||
drawSlider(kLimitSlider, "Limit", value, gLimitIndex, 4);
|
||||
snprintf(value, sizeof(value), "%u/10", gTickVolume);
|
||||
drawSlider(kTickSlider, "Cycle tick volume", value, gTickVolume, 10);
|
||||
snprintf(value, sizeof(value), "%u/10", gAlertVolume);
|
||||
drawSlider(kAlertSlider, "Alert volume", value, gAlertVolume, 10);
|
||||
|
||||
gStaticDrawn = false;
|
||||
gNeedStaticRedraw = true;
|
||||
}
|
||||
|
||||
static void drawMonitorStatic() {
|
||||
gfx->fillScreen(C_BG);
|
||||
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
|
||||
drawText(28, 32, "BREATH MONITOR", C_TEXT, 2);
|
||||
drawPanel(28, 96, 424, 104, C_CARD, C_BORDER, 14);
|
||||
drawPanel(28, 216, 200, 72, C_CARD, C_BORDER, 10);
|
||||
drawText(42, 236, "Current", C_MUTE, 1);
|
||||
drawPanel(252, 216, 200, 72, C_CARD, C_BORDER, 10);
|
||||
drawText(266, 236, "Average 5", C_MUTE, 1);
|
||||
drawPanel(28, 304, 200, 64, C_CARD, C_BORDER, 10);
|
||||
drawText(42, 322, "From start", C_MUTE, 1);
|
||||
drawPanel(252, 304, 200, 64, C_CARD, C_BORDER, 10);
|
||||
drawText(266, 322, "Limit", C_MUTE, 1);
|
||||
gStaticDrawn = true;
|
||||
gLastDrawnClosed = !gStableClosed;
|
||||
gLastDrawnPaused = !isAutoPaused();
|
||||
resetCachedUiText();
|
||||
}
|
||||
|
||||
static void updateMonitorValues(bool force) {
|
||||
char line[48];
|
||||
char value[16];
|
||||
uint32_t now = millis();
|
||||
uint32_t runMs = now - gStartedMs;
|
||||
uint32_t currentMs = (gLastCycleStartMs == 0) ? 0 : now - gLastCycleStartMs;
|
||||
bool paused = isAutoPaused();
|
||||
if (paused) {
|
||||
currentMs = now - gLastCycleStartMs - kPauseAfterMs;
|
||||
}
|
||||
uint32_t avgMs = averageCycleMs();
|
||||
|
||||
if (force || gLastDrawnClosed != gStableClosed || gLastDrawnPaused != paused) {
|
||||
clearArea(42, 118, 396, 68, C_CARD);
|
||||
if (paused) {
|
||||
drawCenteredText(28, 122, 424, "PAUSE", C_BAD, 4);
|
||||
drawCenteredText(28, 172, 424, "no cycle for 60s", C_MUTE, 2);
|
||||
} else {
|
||||
drawCenteredText(28, 122, 424, gStableClosed ? "EXHALE" : "INHALE",
|
||||
gStableClosed ? C_OK : C_ACCENT, 4);
|
||||
drawCenteredText(28, 172, 424, gStableClosed ? "contact closed" : "contact open", C_MUTE, 2);
|
||||
}
|
||||
gLastDrawnClosed = gStableClosed;
|
||||
gLastDrawnPaused = paused;
|
||||
}
|
||||
|
||||
snprintf(line, sizeof(line), "Limit: %us top button: settings", kLimitsSec[gLimitIndex]);
|
||||
if (strcmp(line, gLastTopLine) != 0) {
|
||||
clearArea(28, 58, 424, 28, C_PANEL);
|
||||
drawText(28, 60, line, C_MUTE, 2);
|
||||
strncpy(gLastTopLine, line, sizeof(gLastTopLine) - 1);
|
||||
gLastTopLine[sizeof(gLastTopLine) - 1] = '\0';
|
||||
}
|
||||
|
||||
clearArea(42, 254, 160, 28, C_CARD);
|
||||
formatSec(value, sizeof(value), currentMs);
|
||||
drawText(42, 256, value, C_TEXT, 3);
|
||||
|
||||
clearArea(266, 254, 160, 28, C_CARD);
|
||||
if (avgMs > 0) {
|
||||
formatSec(value, sizeof(value), avgMs);
|
||||
} else {
|
||||
snprintf(value, sizeof(value), "--");
|
||||
}
|
||||
drawText(266, 256, value, C_TEXT, 3);
|
||||
|
||||
clearArea(42, 340, 160, 24, C_CARD);
|
||||
formatClock(value, sizeof(value), runMs);
|
||||
drawText(42, 342, value, C_TEXT, 2);
|
||||
|
||||
clearArea(266, 340, 160, 24, C_CARD);
|
||||
snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]);
|
||||
drawText(266, 342, value, C_TEXT, 2);
|
||||
|
||||
snprintf(line, sizeof(line), "Short avg streak: %u", gShortStreak);
|
||||
if (strcmp(line, gLastStreakLine) != 0) {
|
||||
clearArea(28, 398, 280, 28, C_PANEL);
|
||||
drawText(32, 402, line, gShortStreak > 0 ? C_BAD : C_MUTE, 2);
|
||||
strncpy(gLastStreakLine, line, sizeof(gLastStreakLine) - 1);
|
||||
gLastStreakLine[sizeof(gLastStreakLine) - 1] = '\0';
|
||||
}
|
||||
}
|
||||
|
||||
static void redrawScreen() {
|
||||
if (gSettingsOpen) {
|
||||
drawSettingsScreen();
|
||||
} else if (gStarted) {
|
||||
if (gNeedStaticRedraw || !gStaticDrawn) {
|
||||
drawMonitorStatic();
|
||||
gNeedStaticRedraw = false;
|
||||
}
|
||||
updateMonitorValues(true);
|
||||
} else {
|
||||
drawReadyScreen();
|
||||
}
|
||||
gNeedRedraw = false;
|
||||
gLastUiMs = millis();
|
||||
}
|
||||
|
||||
static void enterSensorMode() {
|
||||
Serial.flush();
|
||||
delay(30);
|
||||
pinMode(kUsbDmPin, OUTPUT);
|
||||
digitalWrite(kUsbDmPin, LOW);
|
||||
pinMode(kUsbDpPin, INPUT_PULLUP);
|
||||
|
||||
uint32_t now = millis();
|
||||
gStarted = true;
|
||||
gStartedMs = now;
|
||||
gLastCycleStartMs = 0;
|
||||
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
gStableClosed = gLastRawClosed;
|
||||
gLastRawChangeMs = now;
|
||||
if (gStableClosed) {
|
||||
gLastCycleStartMs = now;
|
||||
playCycleTick();
|
||||
}
|
||||
gNeedStaticRedraw = true;
|
||||
gNeedRedraw = true;
|
||||
}
|
||||
|
||||
static void toggleSettings() {
|
||||
gSettingsOpen = !gSettingsOpen;
|
||||
gNeedStaticRedraw = true;
|
||||
gNeedRedraw = true;
|
||||
resetCachedUiText();
|
||||
}
|
||||
|
||||
static void handleStableContact(bool closed) {
|
||||
uint32_t now = millis();
|
||||
gStableClosed = closed;
|
||||
if (closed) {
|
||||
if (gLastCycleStartMs != 0) {
|
||||
uint32_t cycleMs = now - gLastCycleStartMs;
|
||||
if (cycleMs >= kPauseAfterMs) {
|
||||
gShortStreak = 0;
|
||||
gLastCycleStartMs = now;
|
||||
playCycleTick();
|
||||
} else if (cycleMs >= kMinCycleMs) {
|
||||
addCycle(cycleMs);
|
||||
gLastCycleStartMs = now;
|
||||
playCycleTick();
|
||||
alertIfNeeded();
|
||||
}
|
||||
} else {
|
||||
gLastCycleStartMs = now;
|
||||
playCycleTick();
|
||||
}
|
||||
}
|
||||
gNeedRedraw = !gSettingsOpen;
|
||||
}
|
||||
|
||||
static void pollContact() {
|
||||
if (!gStarted) {
|
||||
return;
|
||||
}
|
||||
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
uint32_t now = millis();
|
||||
if (rawClosed != gLastRawClosed) {
|
||||
gLastRawClosed = rawClosed;
|
||||
gLastRawChangeMs = now;
|
||||
}
|
||||
if ((now - gLastRawChangeMs) >= kContactDebounceMs && gStableClosed != gLastRawClosed) {
|
||||
handleStableContact(gLastRawClosed);
|
||||
}
|
||||
}
|
||||
|
||||
static void pollUserButton() {
|
||||
bool down = digitalRead(PIN_USER_BTN) == LOW;
|
||||
uint32_t now = millis();
|
||||
if (down != gUserButtonDown && (now - gUserButtonChangeMs) >= kButtonDebounceMs) {
|
||||
gUserButtonDown = down;
|
||||
gUserButtonChangeMs = now;
|
||||
if (down) {
|
||||
toggleSettings();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static uint8_t sliderValueFromX(const Rect &rect, int16_t x, uint8_t maxValue) {
|
||||
int16_t left = rect.x + 22;
|
||||
int16_t right = rect.x + rect.w - 22;
|
||||
if (x < left) x = left;
|
||||
if (x > right) x = right;
|
||||
return (uint8_t)(((uint32_t)(x - left) * maxValue + (right - left) / 2) / (right - left));
|
||||
}
|
||||
|
||||
static void handleSettingsTouch(int16_t x, int16_t y) {
|
||||
if (contains(kLimitSlider, x, y)) {
|
||||
uint8_t next = sliderValueFromX(kLimitSlider, x, 4);
|
||||
if (next == gLimitIndex) {
|
||||
return;
|
||||
}
|
||||
gLimitIndex = next;
|
||||
} else if (contains(kTickSlider, x, y)) {
|
||||
uint8_t next = sliderValueFromX(kTickSlider, x, 10);
|
||||
if (next == gTickVolume) {
|
||||
return;
|
||||
}
|
||||
gTickVolume = next;
|
||||
playCycleTick();
|
||||
} else if (contains(kAlertSlider, x, y)) {
|
||||
uint8_t next = sliderValueFromX(kAlertSlider, x, 10);
|
||||
if (next == gAlertVolume) {
|
||||
return;
|
||||
}
|
||||
gAlertVolume = next;
|
||||
playAlertBeep();
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
saveSettings();
|
||||
gNeedRedraw = true;
|
||||
}
|
||||
|
||||
static void pollTouch() {
|
||||
int16_t x = 0;
|
||||
int16_t y = 0;
|
||||
bool touching = gTouch.getPoint(&x, &y, 1) > 0;
|
||||
if (touching && !gTouchDown) {
|
||||
gTouchDown = true;
|
||||
gTouchStartX = x;
|
||||
gTouchStartY = y;
|
||||
gTouchLastX = x;
|
||||
gTouchLastY = y;
|
||||
return;
|
||||
}
|
||||
if (touching && gTouchDown) {
|
||||
gTouchLastX = x;
|
||||
gTouchLastY = y;
|
||||
return;
|
||||
}
|
||||
if (!touching && gTouchDown) {
|
||||
gTouchDown = false;
|
||||
int dx = abs(gTouchLastX - gTouchStartX);
|
||||
int dy = abs(gTouchLastY - gTouchStartY);
|
||||
if (dx >= 14 || dy >= 14) {
|
||||
return;
|
||||
}
|
||||
if (gSettingsOpen) {
|
||||
handleSettingsTouch(gTouchLastX, gTouchLastY);
|
||||
} else if (!gStarted && contains(kStartButton, gTouchLastX, gTouchLastY)) {
|
||||
enterSensorMode();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
|
||||
pinMode(PIN_USER_BTN, INPUT_PULLUP);
|
||||
loadSettings();
|
||||
initAudio();
|
||||
|
||||
gfx->begin();
|
||||
gBus->writeC8D8(0x36, 0xA0);
|
||||
gfx->setBrightness(220);
|
||||
gfx->fillScreen(C_BG);
|
||||
|
||||
gTouch.setPins(PIN_TP_INT, -1);
|
||||
bool touchOk = gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
|
||||
gTouch.setMaxCoordinates(DISP_W, DISP_H);
|
||||
gTouch.setSwapXY(true);
|
||||
gTouch.setMirrorXY(true, false);
|
||||
|
||||
Serial.println("Breath monitor ready.");
|
||||
Serial.println(touchOk ? "Touch init OK" : "Touch init failed");
|
||||
gNeedRedraw = true;
|
||||
}
|
||||
|
||||
void loop() {
|
||||
pollUserButton();
|
||||
pollTouch();
|
||||
pollContact();
|
||||
if (gStarted && !gSettingsOpen && millis() - gLastUiMs >= kUiPeriodMs) {
|
||||
updateMonitorValues(false);
|
||||
gLastUiMs = millis();
|
||||
}
|
||||
if (gNeedRedraw) {
|
||||
redrawScreen();
|
||||
}
|
||||
delay(10);
|
||||
}
|
||||
+407
@@ -0,0 +1,407 @@
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <lvgl.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include "pin_config.h"
|
||||
#include "TouchDrvCSTXXX.hpp"
|
||||
|
||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
||||
|
||||
// ESP32-S3 native USB data pins.
|
||||
static constexpr int kUsbDmPin = 19; // USB D-
|
||||
static constexpr int kUsbDpPin = 20; // USB D+
|
||||
static constexpr int kUserButtonPin = 0; // BOOT/user button, active LOW.
|
||||
static constexpr uint32_t kDebounceMs = 20;
|
||||
static constexpr uint32_t kEnterDelayMs = 250;
|
||||
static constexpr uint32_t kButtonDebounceMs = 35;
|
||||
|
||||
static lv_disp_draw_buf_t gDrawBuf;
|
||||
static lv_color_t *gBuf1 = nullptr;
|
||||
static lv_color_t *gBuf2 = nullptr;
|
||||
|
||||
static lv_obj_t *gRawLabel = nullptr;
|
||||
static lv_obj_t *gEventLabel = nullptr;
|
||||
static lv_obj_t *gModeLabel = nullptr;
|
||||
static lv_obj_t *gStateLabel = nullptr;
|
||||
static lv_obj_t *gActionButton = nullptr;
|
||||
static lv_obj_t *gActionButtonLabel = nullptr;
|
||||
static lv_obj_t *gMarker = nullptr;
|
||||
|
||||
static TouchDrvCST92xx gTouch;
|
||||
static int16_t gTouchX[5];
|
||||
static int16_t gTouchY[5];
|
||||
|
||||
static volatile bool gTouchPressed = false;
|
||||
static volatile int16_t gLastTouchX = -1;
|
||||
static volatile int16_t gLastTouchY = -1;
|
||||
static volatile uint32_t gRawTouchCount = 0;
|
||||
static uint32_t gButtonPressCount = 0;
|
||||
static uint32_t gButtonClickCount = 0;
|
||||
static bool gLastButtonRawPressed = false;
|
||||
static bool gButtonStablePressed = false;
|
||||
static uint32_t gLastButtonRawChangeMs = 0;
|
||||
|
||||
static bool gSensorMode = false;
|
||||
static bool gEnterPending = false;
|
||||
static uint32_t gEnterAtMs = 0;
|
||||
static bool gStableClosed = false;
|
||||
static bool gLastRawClosed = false;
|
||||
static uint32_t gLastRawChangeMs = 0;
|
||||
static uint32_t gLastUiRefreshMs = 0;
|
||||
|
||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
||||
|
||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
||||
uint32_t w = area->x2 - area->x1 + 1;
|
||||
uint32_t h = area->y2 - area->y1 + 1;
|
||||
#if (LV_COLOR_16_SWAP != 0)
|
||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#else
|
||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#endif
|
||||
lv_disp_flush_ready(disp);
|
||||
}
|
||||
|
||||
static void lvglTick(void *arg) {
|
||||
LV_UNUSED(arg);
|
||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
||||
LV_UNUSED(indevDrv);
|
||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
||||
|
||||
if (touched > 0) {
|
||||
gTouchPressed = true;
|
||||
gLastTouchX = gTouchX[0];
|
||||
gLastTouchY = gTouchY[0];
|
||||
gRawTouchCount++;
|
||||
|
||||
data->state = LV_INDEV_STATE_PR;
|
||||
data->point.x = gTouchX[0];
|
||||
data->point.y = gTouchY[0];
|
||||
return;
|
||||
}
|
||||
|
||||
gTouchPressed = false;
|
||||
data->state = LV_INDEV_STATE_REL;
|
||||
}
|
||||
|
||||
static void setStateUi(bool closed) {
|
||||
if (closed) {
|
||||
lv_label_set_text(gStateLabel, "CLOSED");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x6DFF8B), 0);
|
||||
} else {
|
||||
lv_label_set_text(gStateLabel, "OPEN");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFD166), 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void updateTouchDiagnostics() {
|
||||
uint32_t now = millis();
|
||||
if (now - gLastUiRefreshMs < 40) return;
|
||||
gLastUiRefreshMs = now;
|
||||
|
||||
String raw = gTouchPressed ? "RAW: PRESSED" : "RAW: released";
|
||||
raw += "\nx=" + String((int)gLastTouchX) + " y=" + String((int)gLastTouchY);
|
||||
raw += " n=" + String((uint32_t)gRawTouchCount);
|
||||
lv_label_set_text(gRawLabel, raw.c_str());
|
||||
|
||||
if (gTouchPressed && gLastTouchX >= 0 && gLastTouchY >= 0) {
|
||||
int markerX = gLastTouchX - 8;
|
||||
int markerY = gLastTouchY - 8;
|
||||
if (markerX < 0) markerX = 0;
|
||||
if (markerY < 0) markerY = 0;
|
||||
lv_obj_set_pos(gMarker, markerX, markerY);
|
||||
lv_obj_clear_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
||||
} else {
|
||||
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
}
|
||||
|
||||
static void actuallyEnterSensorMode() {
|
||||
gEnterPending = false;
|
||||
|
||||
// Make the visual transition happen BEFORE the USB data pins are repurposed.
|
||||
lv_label_set_text(gModeLabel, "SENSOR MODE");
|
||||
lv_label_set_text(gActionButtonLabel, "Restart to USB");
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0xA33D4F), LV_PART_MAIN | LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0xC94F65), LV_PART_MAIN | LV_STATE_PRESSED);
|
||||
lv_label_set_text(gEventLabel, "GPIO19=D- LOW GPIO20=D+ INPUT_PULLUP");
|
||||
lv_label_set_text(gStateLabel, "SWITCHING...");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_refr_now(nullptr);
|
||||
delay(60);
|
||||
|
||||
// Intentionally repurpose only USB D-/D+. These are not LCD or touch pins.
|
||||
// Do NOT call Serial.flush() here: USB CDC may already be disappearing.
|
||||
pinMode(kUsbDmPin, OUTPUT);
|
||||
digitalWrite(kUsbDmPin, LOW);
|
||||
pinMode(kUsbDpPin, INPUT_PULLUP);
|
||||
|
||||
gSensorMode = true;
|
||||
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
gStableClosed = gLastRawClosed;
|
||||
gLastRawChangeMs = millis();
|
||||
setStateUi(gStableClosed);
|
||||
}
|
||||
|
||||
static void actionButtonEventCb(lv_event_t *event) {
|
||||
lv_event_code_t code = lv_event_get_code(event);
|
||||
|
||||
if (code == LV_EVENT_PRESSED) {
|
||||
gButtonPressCount++;
|
||||
String text = "BUTTON PRESSED #" + String(gButtonPressCount);
|
||||
lv_label_set_text(gEventLabel, text.c_str());
|
||||
|
||||
if (!gSensorMode && !gEnterPending) {
|
||||
lv_label_set_text(gActionButtonLabel, "Starting...");
|
||||
lv_label_set_text(gStateLabel, "TOUCH OK");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (code != LV_EVENT_CLICKED) return;
|
||||
|
||||
gButtonClickCount++;
|
||||
|
||||
if (!gSensorMode) {
|
||||
lv_label_set_text(gModeLabel, "USB MODE");
|
||||
lv_label_set_text(gActionButtonLabel, "TOUCH OK");
|
||||
lv_label_set_text(gStateLabel, "PRESS BOOT");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFD166), 0);
|
||||
String text = "TOUCH CLICK OK #" + String(gButtonClickCount) + " use BOOT button";
|
||||
lv_label_set_text(gEventLabel, text.c_str());
|
||||
lv_refr_now(nullptr);
|
||||
return;
|
||||
}
|
||||
|
||||
lv_label_set_text(gModeLabel, "RESTARTING TO USB...");
|
||||
lv_label_set_text(gActionButtonLabel, "Restarting...");
|
||||
lv_label_set_text(gStateLabel, "USB NEXT BOOT");
|
||||
lv_refr_now(nullptr);
|
||||
delay(180);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void requestEnterSensorMode(const char *source) {
|
||||
if (gSensorMode || gEnterPending) {
|
||||
return;
|
||||
}
|
||||
|
||||
gEnterPending = true;
|
||||
gEnterAtMs = millis() + kEnterDelayMs;
|
||||
lv_label_set_text(gModeLabel, "START RECEIVED");
|
||||
lv_label_set_text(gActionButtonLabel, "Starting sensor...");
|
||||
String text = String(source) + " OK waiting 250 ms";
|
||||
lv_label_set_text(gEventLabel, text.c_str());
|
||||
lv_label_set_text(gStateLabel, "STARTING...");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
lv_refr_now(nullptr);
|
||||
}
|
||||
|
||||
static void pollUserButton() {
|
||||
bool rawPressed = (digitalRead(kUserButtonPin) == LOW);
|
||||
uint32_t now = millis();
|
||||
|
||||
if (rawPressed != gLastButtonRawPressed) {
|
||||
gLastButtonRawPressed = rawPressed;
|
||||
gLastButtonRawChangeMs = now;
|
||||
}
|
||||
|
||||
if ((now - gLastButtonRawChangeMs) < kButtonDebounceMs || rawPressed == gButtonStablePressed) {
|
||||
return;
|
||||
}
|
||||
|
||||
gButtonStablePressed = rawPressed;
|
||||
if (!gButtonStablePressed) {
|
||||
return;
|
||||
}
|
||||
|
||||
gButtonClickCount++;
|
||||
if (!gSensorMode) {
|
||||
requestEnterSensorMode("BOOT BUTTON");
|
||||
return;
|
||||
}
|
||||
|
||||
lv_label_set_text(gModeLabel, "RESTARTING TO USB...");
|
||||
lv_label_set_text(gActionButtonLabel, "Restarting...");
|
||||
lv_label_set_text(gStateLabel, "USB NEXT BOOT");
|
||||
lv_refr_now(nullptr);
|
||||
delay(180);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void createUi() {
|
||||
lv_obj_t *screen = lv_scr_act();
|
||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x000000), 0);
|
||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||
|
||||
lv_obj_t *title = lv_label_create(screen);
|
||||
lv_label_set_text(title, "USB CONTACT DEBUG");
|
||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
|
||||
|
||||
gRawLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gRawLabel, "RAW: released\nx=-1 y=-1 n=0");
|
||||
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_16, 0);
|
||||
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0x9EE493), 0);
|
||||
lv_obj_align(gRawLabel, LV_ALIGN_TOP_LEFT, 14, 48);
|
||||
|
||||
gModeLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gModeLabel, "USB MODE");
|
||||
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
|
||||
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_obj_align(gModeLabel, LV_ALIGN_TOP_RIGHT, -14, 50);
|
||||
|
||||
gEventLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gEventLabel, "Button events: waiting");
|
||||
lv_obj_set_width(gEventLabel, 440);
|
||||
lv_label_set_long_mode(gEventLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gEventLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_font(gEventLabel, &lv_font_montserrat_16, 0);
|
||||
lv_obj_set_style_text_color(gEventLabel, lv_color_hex(0xFFD166), 0);
|
||||
lv_obj_align(gEventLabel, LV_ALIGN_TOP_MID, 0, 102);
|
||||
|
||||
gStateLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gStateLabel, "READY");
|
||||
lv_obj_set_style_text_font(gStateLabel, &lv_font_montserrat_40, 0);
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_obj_align(gStateLabel, LV_ALIGN_CENTER, 0, -52);
|
||||
|
||||
// Put the button in almost the same position/size as the known-working touch debug sketch.
|
||||
gActionButton = lv_btn_create(screen);
|
||||
lv_obj_set_size(gActionButton, 360, 110);
|
||||
lv_obj_align(gActionButton, LV_ALIGN_CENTER, 0, 52);
|
||||
lv_obj_set_style_radius(gActionButton, 18, 0);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), LV_PART_MAIN | LV_STATE_DEFAULT);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x47C7B6), LV_PART_MAIN | LV_STATE_PRESSED);
|
||||
lv_obj_set_style_border_width(gActionButton, 3, 0);
|
||||
lv_obj_set_style_border_color(gActionButton, lv_color_hex(0xBDE0FE), 0);
|
||||
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_ALL, nullptr);
|
||||
|
||||
gActionButtonLabel = lv_label_create(gActionButton);
|
||||
lv_label_set_text(gActionButtonLabel, "START");
|
||||
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_28, 0);
|
||||
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_center(gActionButtonLabel);
|
||||
|
||||
lv_obj_t *hint = lv_label_create(screen);
|
||||
lv_label_set_text(hint, "Press BOOT button to START. Touch button only checks touch UI.");
|
||||
lv_obj_set_width(hint, 440);
|
||||
lv_label_set_long_mode(hint, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(hint, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
|
||||
lv_obj_set_style_text_color(hint, lv_color_hex(0xD9D9D9), 0);
|
||||
lv_obj_align(hint, LV_ALIGN_BOTTOM_MID, 0, -18);
|
||||
|
||||
gMarker = lv_obj_create(screen);
|
||||
lv_obj_set_size(gMarker, 16, 16);
|
||||
lv_obj_set_style_radius(gMarker, LV_RADIUS_CIRCLE, 0);
|
||||
lv_obj_set_style_bg_color(gMarker, lv_color_hex(0xFF4D6D), 0);
|
||||
lv_obj_set_style_border_width(gMarker, 2, 0);
|
||||
lv_obj_set_style_border_color(gMarker, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
|
||||
}
|
||||
|
||||
static void pollContact() {
|
||||
if (!gSensorMode) return;
|
||||
|
||||
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
uint32_t now = millis();
|
||||
|
||||
if (rawClosed != gLastRawClosed) {
|
||||
gLastRawClosed = rawClosed;
|
||||
gLastRawChangeMs = now;
|
||||
}
|
||||
|
||||
if ((now - gLastRawChangeMs) >= kDebounceMs && gStableClosed != gLastRawClosed) {
|
||||
gStableClosed = gLastRawClosed;
|
||||
setStateUi(gStableClosed);
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
|
||||
pinMode(kUserButtonPin, INPUT_PULLUP);
|
||||
|
||||
Wire.begin(IIC_SDA, IIC_SCL);
|
||||
|
||||
pinMode(TP_RST, OUTPUT);
|
||||
pinMode(TP_INT, INPUT);
|
||||
digitalWrite(TP_RST, LOW);
|
||||
delay(30);
|
||||
digitalWrite(TP_RST, HIGH);
|
||||
delay(50);
|
||||
delay(1000);
|
||||
|
||||
gTouch.setPins(TP_RST, TP_INT);
|
||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
||||
if (!touchOk) {
|
||||
Serial.println("Touch init failed");
|
||||
} else {
|
||||
Serial.print("Touch model: ");
|
||||
Serial.println(gTouch.getModelName());
|
||||
gTouch.sleep();
|
||||
gTouch.reset();
|
||||
gTouch.setMaxCoordinates(480, 480);
|
||||
gTouch.setSwapXY(true);
|
||||
gTouch.setMirrorXY(true, false);
|
||||
}
|
||||
|
||||
gfx->begin();
|
||||
gBus->writeC8D8(0x36, 0xA0);
|
||||
gfx->setBrightness(220);
|
||||
gfx->fillScreen(0x0000);
|
||||
|
||||
lv_init();
|
||||
|
||||
uint32_t screenWidth = gfx->width();
|
||||
uint32_t screenHeight = gfx->height();
|
||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
||||
|
||||
static lv_disp_drv_t dispDrv;
|
||||
lv_disp_drv_init(&dispDrv);
|
||||
dispDrv.hor_res = screenWidth;
|
||||
dispDrv.ver_res = screenHeight;
|
||||
dispDrv.flush_cb = lvglFlushCb;
|
||||
dispDrv.draw_buf = &gDrawBuf;
|
||||
lv_disp_drv_register(&dispDrv);
|
||||
|
||||
static lv_indev_drv_t indevDrv;
|
||||
lv_indev_drv_init(&indevDrv);
|
||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
||||
indevDrv.read_cb = lvglTouchRead;
|
||||
lv_indev_drv_register(&indevDrv);
|
||||
|
||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
||||
.callback = &lvglTick,
|
||||
.name = "lvgl_tick"};
|
||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
||||
|
||||
createUi();
|
||||
Serial.println("USB contact sensor DEBUG ready. USB pins remain untouched until START click.");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
updateTouchDiagnostics();
|
||||
pollUserButton();
|
||||
pollContact();
|
||||
|
||||
if (gEnterPending && (int32_t)(millis() - gEnterAtMs) >= 0) {
|
||||
actuallyEnterSensorMode();
|
||||
}
|
||||
|
||||
lv_timer_handler();
|
||||
delay(5);
|
||||
}
|
||||
+250
@@ -0,0 +1,250 @@
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <lvgl.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include "pin_config.h"
|
||||
#include "TouchDrvCSTXXX.hpp"
|
||||
|
||||
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
||||
|
||||
// ESP32-S3 native USB pins.
|
||||
static constexpr int kUsbDmPin = 19; // USB D-
|
||||
static constexpr int kUsbDpPin = 20; // USB D+
|
||||
static constexpr uint32_t kDebounceMs = 20;
|
||||
|
||||
static lv_disp_draw_buf_t gDrawBuf;
|
||||
static lv_color_t *gBuf1 = nullptr;
|
||||
static lv_color_t *gBuf2 = nullptr;
|
||||
static lv_obj_t *gModeLabel = nullptr;
|
||||
static lv_obj_t *gStateLabel = nullptr;
|
||||
static lv_obj_t *gHintLabel = nullptr;
|
||||
static lv_obj_t *gActionButton = nullptr;
|
||||
static lv_obj_t *gActionButtonLabel = nullptr;
|
||||
|
||||
static TouchDrvCST92xx gTouch;
|
||||
static int16_t gTouchX[5];
|
||||
static int16_t gTouchY[5];
|
||||
|
||||
static bool gSensorMode = false;
|
||||
static bool gStableClosed = false;
|
||||
static bool gLastRawClosed = false;
|
||||
static uint32_t gLastRawChangeMs = 0;
|
||||
|
||||
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
||||
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
||||
|
||||
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
||||
uint32_t w = area->x2 - area->x1 + 1;
|
||||
uint32_t h = area->y2 - area->y1 + 1;
|
||||
#if (LV_COLOR_16_SWAP != 0)
|
||||
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#else
|
||||
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||
#endif
|
||||
lv_disp_flush_ready(disp);
|
||||
}
|
||||
|
||||
static void lvglTick(void *arg) {
|
||||
LV_UNUSED(arg);
|
||||
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
||||
LV_UNUSED(indevDrv);
|
||||
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
||||
if (touched > 0) {
|
||||
data->state = LV_INDEV_STATE_PR;
|
||||
data->point.x = gTouchX[0];
|
||||
data->point.y = gTouchY[0];
|
||||
return;
|
||||
}
|
||||
data->state = LV_INDEV_STATE_REL;
|
||||
}
|
||||
|
||||
static void setStateUi(bool closed) {
|
||||
if (closed) {
|
||||
lv_label_set_text(gStateLabel, "CLOSED");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
|
||||
} else {
|
||||
lv_label_set_text(gStateLabel, "OPEN");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFCC66), 0);
|
||||
}
|
||||
}
|
||||
|
||||
static void enterSensorMode() {
|
||||
// From this moment the native USB data pair is no longer USB.
|
||||
// D- is held LOW, D+ is read with the ESP32-S3 internal pull-up.
|
||||
// A passive switch between D- and D+ therefore reads LOW when closed.
|
||||
Serial.flush();
|
||||
delay(30);
|
||||
|
||||
pinMode(kUsbDmPin, OUTPUT);
|
||||
digitalWrite(kUsbDmPin, LOW);
|
||||
pinMode(kUsbDpPin, INPUT_PULLUP);
|
||||
|
||||
gSensorMode = true;
|
||||
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
gStableClosed = gLastRawClosed;
|
||||
gLastRawChangeMs = millis();
|
||||
|
||||
lv_label_set_text(gModeLabel, "Sensor mode");
|
||||
lv_label_set_text(gHintLabel, "USB D- / D+ are now the contact input.\nDo not connect this port to a computer.");
|
||||
lv_label_set_text(gActionButtonLabel, "Restart to USB");
|
||||
setStateUi(gStableClosed);
|
||||
}
|
||||
|
||||
static void actionButtonEventCb(lv_event_t *event) {
|
||||
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!gSensorMode) {
|
||||
enterSensorMode();
|
||||
return;
|
||||
}
|
||||
|
||||
lv_label_set_text(gModeLabel, "Restarting...");
|
||||
lv_label_set_text(gHintLabel, "USB mode will return after reboot.");
|
||||
lv_timer_handler();
|
||||
delay(150);
|
||||
ESP.restart();
|
||||
}
|
||||
|
||||
static void createUi() {
|
||||
lv_obj_t *screen = lv_scr_act();
|
||||
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
||||
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||
|
||||
lv_obj_t *title = lv_label_create(screen);
|
||||
lv_label_set_text(title, "USB CONTACT TEST");
|
||||
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
||||
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 26);
|
||||
|
||||
gModeLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gModeLabel, "USB mode");
|
||||
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0xB8C8DC), 0);
|
||||
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
|
||||
lv_obj_align(gModeLabel, LV_ALIGN_TOP_MID, 0, 72);
|
||||
|
||||
gStateLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gStateLabel, "READY");
|
||||
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
|
||||
lv_obj_set_style_text_font(gStateLabel, &lv_font_montserrat_40, 0);
|
||||
lv_obj_align(gStateLabel, LV_ALIGN_CENTER, 0, -56);
|
||||
|
||||
gHintLabel = lv_label_create(screen);
|
||||
lv_label_set_text(gHintLabel, "USB is normal now.\nTap Start to use D- / D+ as a contact sensor.");
|
||||
lv_obj_set_width(gHintLabel, 390);
|
||||
lv_label_set_long_mode(gHintLabel, LV_LABEL_LONG_WRAP);
|
||||
lv_obj_set_style_text_align(gHintLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||
lv_obj_set_style_text_color(gHintLabel, lv_color_hex(0xD5DCE5), 0);
|
||||
lv_obj_set_style_text_font(gHintLabel, &lv_font_montserrat_16, 0);
|
||||
lv_obj_align(gHintLabel, LV_ALIGN_CENTER, 0, 18);
|
||||
|
||||
gActionButton = lv_btn_create(screen);
|
||||
lv_obj_set_size(gActionButton, 260, 72);
|
||||
lv_obj_align(gActionButton, LV_ALIGN_BOTTOM_MID, 0, -48);
|
||||
lv_obj_set_style_radius(gActionButton, 18, 0);
|
||||
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), 0);
|
||||
lv_obj_set_style_border_width(gActionButton, 0, 0);
|
||||
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_CLICKED, nullptr);
|
||||
|
||||
gActionButtonLabel = lv_label_create(gActionButton);
|
||||
lv_label_set_text(gActionButtonLabel, "Start");
|
||||
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
|
||||
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_22, 0);
|
||||
lv_obj_center(gActionButtonLabel);
|
||||
}
|
||||
|
||||
static void pollContact() {
|
||||
if (!gSensorMode) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
|
||||
uint32_t now = millis();
|
||||
|
||||
if (rawClosed != gLastRawClosed) {
|
||||
gLastRawClosed = rawClosed;
|
||||
gLastRawChangeMs = now;
|
||||
}
|
||||
|
||||
if ((now - gLastRawChangeMs) >= kDebounceMs && gStableClosed != gLastRawClosed) {
|
||||
gStableClosed = gLastRawClosed;
|
||||
setStateUi(gStableClosed);
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
// With the project's FQBN this is the normal ESP32-S3 native USB serial mode.
|
||||
// No sensor mode is persisted: every reset starts here with normal USB again.
|
||||
Serial.begin(115200);
|
||||
|
||||
Wire.begin(IIC_SDA, IIC_SCL);
|
||||
|
||||
pinMode(TP_RST, OUTPUT);
|
||||
pinMode(TP_INT, INPUT);
|
||||
digitalWrite(TP_RST, LOW);
|
||||
delay(30);
|
||||
digitalWrite(TP_RST, HIGH);
|
||||
delay(50);
|
||||
delay(1000);
|
||||
|
||||
gTouch.setPins(TP_RST, TP_INT);
|
||||
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
||||
if (!touchOk) {
|
||||
Serial.println("Touch init failed");
|
||||
} else {
|
||||
gTouch.sleep();
|
||||
gTouch.reset();
|
||||
gTouch.setMaxCoordinates(480, 480);
|
||||
gTouch.setSwapXY(true);
|
||||
gTouch.setMirrorXY(true, false);
|
||||
}
|
||||
|
||||
gfx->begin();
|
||||
gBus->writeC8D8(0x36, 0xA0);
|
||||
gfx->setBrightness(220);
|
||||
gfx->fillScreen(0x0000);
|
||||
|
||||
lv_init();
|
||||
|
||||
uint32_t screenWidth = gfx->width();
|
||||
uint32_t screenHeight = gfx->height();
|
||||
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
||||
|
||||
static lv_disp_drv_t dispDrv;
|
||||
lv_disp_drv_init(&dispDrv);
|
||||
dispDrv.hor_res = screenWidth;
|
||||
dispDrv.ver_res = screenHeight;
|
||||
dispDrv.flush_cb = lvglFlushCb;
|
||||
dispDrv.draw_buf = &gDrawBuf;
|
||||
lv_disp_drv_register(&dispDrv);
|
||||
|
||||
static lv_indev_drv_t indevDrv;
|
||||
lv_indev_drv_init(&indevDrv);
|
||||
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
||||
indevDrv.read_cb = lvglTouchRead;
|
||||
lv_indev_drv_register(&indevDrv);
|
||||
|
||||
const esp_timer_create_args_t lvglTickTimerArgs = {
|
||||
.callback = &lvglTick,
|
||||
.name = "lvgl_tick"};
|
||||
esp_timer_handle_t lvglTickTimer = nullptr;
|
||||
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
||||
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
||||
|
||||
createUi();
|
||||
Serial.println("USB contact sensor test ready; native USB remains active until Start is tapped.");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
pollContact();
|
||||
lv_timer_handler();
|
||||
delay(5);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
# Инструкция по commit и push в Git
|
||||
|
||||
## Репозиторий
|
||||
|
||||
Работать с Git нужно из корня репозитория `SHiNE-product/`:
|
||||
|
||||
```bash
|
||||
cd /home/ai/work/SHiNE/SHiNE-server-sha256/SHiNE-product
|
||||
```
|
||||
|
||||
## Канонический Gitea
|
||||
|
||||
Всегда использовать этот Git-сервер и этот remote:
|
||||
|
||||
```text
|
||||
https://git.shineup.me/Aidar/SHiNE-server.git
|
||||
```
|
||||
|
||||
Проверка и исправление `origin`:
|
||||
|
||||
```bash
|
||||
git remote set-url origin https://git.shineup.me/Aidar/SHiNE-server.git
|
||||
git remote -v
|
||||
```
|
||||
|
||||
Старый адрес `git2.shineup.me` не использовать.
|
||||
|
||||
Секреты, токены, приватные ключи, `.env`, логи и сборочные артефакты в Git не добавлять.
|
||||
|
||||
## Перед коммитом
|
||||
|
||||
```bash
|
||||
git status --short --branch
|
||||
git diff --check
|
||||
git diff
|
||||
```
|
||||
|
||||
Перед обычным коммитом обновить `VERSION.properties`:
|
||||
|
||||
- только UI — увеличить `client.version`;
|
||||
- только сервер — увеличить `server.version`;
|
||||
- UI и сервер — увеличить обе версии;
|
||||
- в рабочей ветке использовать patch-инкремент: `1.2.346` → `1.2.347`.
|
||||
|
||||
Сообщения коммитов писать на русском языке.
|
||||
|
||||
## Commit
|
||||
|
||||
```bash
|
||||
git add <нужные-файлы>
|
||||
git commit -m "Краткое описание изменения"
|
||||
```
|
||||
|
||||
Для локального `git commit` токен не нужен. Не использовать `git add .`, если в рабочем дереве есть непроверенные локальные файлы.
|
||||
|
||||
## Push
|
||||
|
||||
Сначала проверить ветку и remote:
|
||||
|
||||
```bash
|
||||
git branch --show-current
|
||||
git remote -v
|
||||
```
|
||||
|
||||
Для push использовать токен из переменной окружения `GITEA_TOKEN`; сам токен в команду, файл или историю shell не записывать. При HTTPS Git обычно запросит имя пользователя и пароль токена:
|
||||
|
||||
```bash
|
||||
export GITEA_TOKEN='токен задаётся локально и не коммитится'
|
||||
git push origin HEAD
|
||||
unset GITEA_TOKEN
|
||||
```
|
||||
|
||||
Если credential helper не умеет автоматически подставлять `GITEA_TOKEN`, использовать настроенный локально способ авторизации Gitea; не вставлять токен в URL remote.
|
||||
|
||||
После push проверить результат:
|
||||
|
||||
```bash
|
||||
git status --short --branch
|
||||
git log -1 --oneline
|
||||
```
|
||||
|
||||
## Ветка `main`
|
||||
|
||||
`main` предназначена для стабильных версий. По умолчанию изменения сначала коммитить в рабочей ветке, затем вливать в `main`. Для merge в `main` увеличивать вторую цифру версии и обнулять третью: `1.2.346` → `1.3.0`.
|
||||
|
||||
Перед push в `main` отдельно проверить diff, версию и отсутствие секретов.
|
||||
@@ -1,7 +1,29 @@
|
||||
# SHiNE
|
||||
|
||||
## План запуска DAO
|
||||
SHiNE — проект децентрализованного общения: браузерный клиент, сервер, пользовательские блокчейны, личные сообщения и интеграция с Solana и Arweave. Репозиторий содержит также экспериментальные компоненты для ESP32 и браузерное расширение кошелька.
|
||||
|
||||
План запуска DAO зафиксирован в [DAO_запуск/README.md](DAO_запуск/README.md).
|
||||
> **Статус:** активная разработка и подготовка к публичному запуску. Исходный код доступен для изучения; самостоятельный запуск возможен, но инструкции по установке ещё дорабатываются. Не все описанные в планах возможности реализованы.
|
||||
|
||||
Это рабочий список задач по `этап1` и `этап2`. Дальше ведём его как основной чек-лист запуска DAO и отмечаем в нём выполненные пункты по мере готовности.
|
||||
## Как устроен проект
|
||||
|
||||
| Компонент | Назначение |
|
||||
| --- | --- |
|
||||
| [`shine-UI/`](shine-UI/) | Браузерный клиент и панель администратора сервера |
|
||||
| [`SHiNE-server/`](SHiNE-server/) | WebSocket/HTTP сервер, PostgreSQL, блокчейн, доставка сообщений |
|
||||
| [`shine-solana/shine/`](shine-solana/shine/) | Anchor-программы и инструменты Solana |
|
||||
| [`SHiNE-browser-plugin-wallet/`](SHiNE-browser-plugin-wallet/) | Браузерное расширение кошелька |
|
||||
| [`ESP32/`](ESP32/) | Прошивки и прототипы устройств |
|
||||
| [`deploy/`](deploy/) | Скрипты и инструкции по развёртыванию |
|
||||
|
||||
Архитектура и границы компонентов описаны в [общей схеме](docs/ARCHITECTURE.md). Пользовательские блоки проектируются для публикации в Arweave; подробности и текущие ограничения тестового контура приведены в [документации блокчейна](docs/Blockchain/README.md).
|
||||
|
||||
## Самостоятельный запуск
|
||||
|
||||
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Для `./gradlew startLocal` скопируйте `application.properties.example` в `SHiNE-server/application.properties` и заполните параметры своей среды. При `java -jar` внешний `application.properties` ищется в текущем рабочем каталоге. Встроенный файл необязателен. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
|
||||
|
||||
## Документация
|
||||
|
||||
- [Каталог документации](docs/README.md) — действующие спецификации, инструкции и планы.
|
||||
- [Общая архитектура](docs/ARCHITECTURE.md) — компоненты и потоки данных.
|
||||
- [API](docs/API/09_Operations_Index.md), [формат блокчейна](docs/Blockchain/README.md), [личные сообщения](docs/Personal_Messages/README.md), [Solana](docs/Solana_Architecture/README.md).
|
||||
- [Правила обновления документации](docs/CONTRIBUTING_DOCS.md).
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# SHiNE Browser Plugin Wallet
|
||||
|
||||
> Статус: старая версия. Плагин находится в разработке и пока не работает.
|
||||
|
||||
Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.
|
||||
|
||||
## Что уже умеет
|
||||
|
||||
@@ -52,113 +52,84 @@ function readStrU8(bytes, cursorRef) {
|
||||
|
||||
function parseServerFieldsFromUserPda(dataBytes) {
|
||||
const bytes = dataBytes instanceof Uint8Array ? dataBytes : new Uint8Array(dataBytes || []);
|
||||
if (bytes.length < 5) throw new Error('Некорректный формат PDA');
|
||||
if (bytes.length < 9) throw new Error('Некорректный формат PDA');
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const cursorRef = { value: 0 };
|
||||
const readU16 = () => { if (cursorRef.value + 2 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getUint16(cursorRef.value, true); cursorRef.value += 2; return v; };
|
||||
const readU32 = () => { if (cursorRef.value + 4 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getUint32(cursorRef.value, true); cursorRef.value += 4; return v; };
|
||||
const readU64 = () => { if (cursorRef.value + 8 > bytes.length) throw new Error('Повреждённый формат PDA'); const v = view.getBigUint64(cursorRef.value, true); cursorRef.value += 8; return v; };
|
||||
const magic = new TextDecoder().decode(readBytes(bytes, cursorRef, 5));
|
||||
if (magic !== 'SHiNE') throw new Error('Некорректный формат PDA');
|
||||
cursorRef.value += 1; // format_major
|
||||
cursorRef.value += 1; // format_minor
|
||||
cursorRef.value += 2; // record_len
|
||||
const formatMajor = readU8(bytes, cursorRef);
|
||||
const formatMinor = readU8(bytes, cursorRef);
|
||||
if (formatMajor !== 1 || formatMinor !== 2) throw new Error(`Неподдерживаемый формат PDA ${formatMajor}.${formatMinor}`);
|
||||
const recordLen = readU16();
|
||||
if (recordLen < 73 || recordLen > bytes.length) throw new Error('Некорректный record_len PDA');
|
||||
cursorRef.value += 8; // created_at_ms
|
||||
cursorRef.value += 8; // updated_at_ms
|
||||
cursorRef.value += 4; // record_number
|
||||
cursorRef.value += 32; // prev_record_hash
|
||||
readStrU8(bytes, cursorRef); // login
|
||||
const login = readStrU8(bytes, cursorRef);
|
||||
const blocksCount = readU8(bytes, cursorRef);
|
||||
|
||||
let isServer = false;
|
||||
let serverAddress = '';
|
||||
let accessServers = [];
|
||||
let recoveryKey32 = null;
|
||||
let rootKey32 = null;
|
||||
let clientKey32 = null;
|
||||
let blockchainKey32 = null;
|
||||
let blockchainName = '';
|
||||
let homeserverSessions = [];
|
||||
let forkCount = 0;
|
||||
|
||||
for (let i = 0; i < blocksCount; i += 1) {
|
||||
const blockType = readU8(bytes, cursorRef);
|
||||
cursorRef.value += 1; // block_version
|
||||
|
||||
if (blockType === 0 || blockType === 1 || blockType === 2) {
|
||||
const blockVersion = readU8(bytes, cursorRef);
|
||||
if (blockVersion !== 0) throw new Error('Неподдерживаемая версия блока PDA');
|
||||
if (blockType === 1 || blockType === 2) {
|
||||
const key32 = readBytes(bytes, cursorRef, 32);
|
||||
if (blockType === 0) recoveryKey32 = key32;
|
||||
if (blockType === 1) rootKey32 = key32;
|
||||
if (blockType === 2) clientKey32 = key32;
|
||||
else clientKey32 = key32;
|
||||
continue;
|
||||
}
|
||||
|
||||
const payloadLen = readU16();
|
||||
const payloadEnd = cursorRef.value + payloadLen;
|
||||
if (payloadEnd > recordLen - 64) throw new Error('Повреждённый variable block PDA');
|
||||
|
||||
if (blockType === 3) {
|
||||
const count = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < count; j += 1) {
|
||||
cursorRef.value += 1;
|
||||
const currentBlockchainName = readStrU8(bytes, cursorRef);
|
||||
const currentBlockchainKey32 = readBytes(bytes, cursorRef, 32);
|
||||
if (!blockchainKey32) {
|
||||
blockchainKey32 = currentBlockchainKey32;
|
||||
blockchainName = currentBlockchainName;
|
||||
forkCount = readU16();
|
||||
if (forkCount < 1) throw new Error('BlockchainRegistry пуст');
|
||||
for (let j = 0; j < forkCount; j += 1) {
|
||||
blockchainKey32 = readBytes(bytes, cursorRef, 32);
|
||||
readU64(); // created_at_ms fork
|
||||
readU32(); // paid_limit_bytes
|
||||
}
|
||||
cursorRef.value += 8 + 8 + 4 + 32 + 64;
|
||||
const arPresent = readU8(bytes, cursorRef);
|
||||
if (arPresent === 1) readStrU8(bytes, cursorRef);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 30) {
|
||||
isServer = readU8(bytes, cursorRef) === 1;
|
||||
if (isServer) {
|
||||
cursorRef.value += 1; // address_format_type
|
||||
cursorRef.value += 1; // address_format_version
|
||||
} else if (blockType === 30) {
|
||||
const addressCount = readU8(bytes, cursorRef);
|
||||
if (addressCount !== 1) throw new Error('PDA 1.2 допускает ровно один адрес сервера');
|
||||
readU8(bytes, cursorRef); // address_format_type
|
||||
readU8(bytes, cursorRef); // address_format_version
|
||||
serverAddress = readStrU8(bytes, cursorRef);
|
||||
const syncCount = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < syncCount; j += 1) readStrU8(bytes, cursorRef);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 40) {
|
||||
} else if (blockType === 40) {
|
||||
const accessCount = readU8(bytes, cursorRef);
|
||||
if (accessCount > 1) throw new Error('PDA 1.2 допускает максимум один access server');
|
||||
accessServers = [];
|
||||
for (let j = 0; j < accessCount; j += 1) accessServers.push(readStrU8(bytes, cursorRef));
|
||||
continue;
|
||||
}
|
||||
if (blockType === 50) {
|
||||
cursorRef.value += 1;
|
||||
const sessionsCount = readU8(bytes, cursorRef);
|
||||
for (let j = 0; j < sessionsCount; j += 1) {
|
||||
const sessionType = readU8(bytes, cursorRef);
|
||||
const sessionVersion = readU8(bytes, cursorRef);
|
||||
const sessionName = readStrU8(bytes, cursorRef);
|
||||
const sessionPubKey32 = readBytes(bytes, cursorRef, 32);
|
||||
if (sessionType === 100) {
|
||||
homeserverSessions.push({
|
||||
sessionType,
|
||||
sessionVersion,
|
||||
sessionName,
|
||||
sessionPubKeyBase58: new PublicKey(sessionPubKey32).toBase58(),
|
||||
sessionPubKeyB64: `ed25519/${btoa(String.fromCharCode(...sessionPubKey32))}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (blockType === 70) {
|
||||
cursorRef.value += 1;
|
||||
continue;
|
||||
}
|
||||
throw new Error(`Неизвестный блок PDA: ${blockType}`);
|
||||
cursorRef.value = payloadEnd;
|
||||
}
|
||||
|
||||
if (!rootKey32 || !clientKey32 || !blockchainKey32) throw new Error('PDA 1.2 не содержит обязательные ключи');
|
||||
return {
|
||||
isServer,
|
||||
isServer: Boolean(serverAddress),
|
||||
serverAddress: normalizeHostLike(serverAddress),
|
||||
accessServers: accessServers.map((value) => normalizeServerLogin(value)).filter(Boolean),
|
||||
publicKeys: {
|
||||
recoveryKeyBase58: recoveryKey32 ? new PublicKey(recoveryKey32).toBase58() : '',
|
||||
rootKeyBase58: rootKey32 ? new PublicKey(rootKey32).toBase58() : '',
|
||||
clientKeyBase58: clientKey32 ? new PublicKey(clientKey32).toBase58() : '',
|
||||
blockchainKeyBase58: blockchainKey32 ? new PublicKey(blockchainKey32).toBase58() : '',
|
||||
blockchainName,
|
||||
recoveryKeyBase58: '',
|
||||
rootKeyBase58: new PublicKey(rootKey32).toBase58(),
|
||||
clientKeyBase58: new PublicKey(clientKey32).toBase58(),
|
||||
blockchainKeyBase58: new PublicKey(blockchainKey32).toBase58(),
|
||||
blockchainName: `${normalizeServerLogin(login)}-${String(forkCount).padStart(3, '0')}`,
|
||||
},
|
||||
homeserverSessions,
|
||||
homeserverSessions: [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
"": {
|
||||
"name": "shine-browser-plugin-wallet",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.5.0",
|
||||
"@solana/web3.js": "^1.98.4"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"name": "shine-browser-plugin-wallet",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.",
|
||||
"main": "popup.js",
|
||||
"scripts": {
|
||||
@@ -8,7 +9,7 @@
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^1.5.0",
|
||||
"@solana/web3.js": "^1.98.4"
|
||||
|
||||
+19
-14
@@ -9,24 +9,31 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
|
||||
|
||||
- `shine-server-net-server/` — точка входа, запуск HTTP/WS сервера
|
||||
- `shine-server-net-protocol/` — обработчики операций (RPC и события WS)
|
||||
- `shine-server-db/` — DAO, SQL-схема, SQLite
|
||||
- `shine-server-db/` — DAO, SQL-схема, PostgreSQL runtime
|
||||
- `shine-server-blockchain/` — логика хранения и проверки блоков блокчейна
|
||||
- `shine-server-crypto/` — криптографические утилиты
|
||||
- `shine-server-config/` — конфигурация сервера
|
||||
- `shine-server-log/` — логирование
|
||||
- `shine-server-geo/` — геолокация IP
|
||||
- `shine-server-solana-users-sync/` — синхронизация PDA Solana в серверные данные
|
||||
- `shine-server-archive/` — публикация/импорт Arweave и workflow бесплатной регистрации
|
||||
|
||||
## Документация при изменении кода
|
||||
|
||||
- Новая или изменённая WS-операция: обновить профильный документ `../docs/API/` и `../docs/API/09_Operations_Index.md`; список зарегистрированных операций сверять с `JsonHandlerRegistry.java`.
|
||||
- Формат блока, правила проверки или публикации: обновить `../docs/Blockchain/` и журнал изменений этого раздела.
|
||||
- Доставка или формат DM: обновить затронутые документы из `../docs/Personal_Messages/README.md`.
|
||||
- Синхронизация Solana users: обновить `../docs/Solana/SOLANA_USERS_SYNC_MODULE_DESIGN.md` и `../deploy/SOLANA_USERS_SYNC_SERVER_SETUP.md`.
|
||||
- Регистрация с email, namespace или Arweave-сертификатами: обновить действующие документы в `../docs/registration-v2/`, а исторические планы явно оставлять помеченными как история.
|
||||
- Изменение локального запуска или конфигурации: обновить корневой `../README.md`, `../docs/ARCHITECTURE.md` либо `../deploy/README.md` по затронутой теме.
|
||||
|
||||
## Настройка сервера в Solana (Solana PDA)
|
||||
|
||||
Серверный аккаунт SHiNE регистрируется в Solana в виде `user_pda` с флагом `is_server=true`.
|
||||
В PDA хранятся:
|
||||
Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.0 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint.
|
||||
|
||||
- **адрес сервера** (URL WebSocket/HTTPS, например `https://shineup.me/ws`);
|
||||
- **список серверов синхронизации** (`sync_servers`) — логины SHiNE-аккаунтов серверов-партнёров,
|
||||
с которыми синхронизируются блоки и DM;
|
||||
- **корневой ключ** сервера (`root_key`).
|
||||
PDA 1.0 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave.
|
||||
|
||||
Клиенты читают PDA напрямую из Solana, чтобы узнать адрес сервера и при необходимости подключиться.
|
||||
Клиенты читают server PDA из Solana, получают опубликованный endpoint и подключаются к нему. Межсерверная доставка DM через access-server routing остаётся отдельным механизмом.
|
||||
|
||||
**Управление серверной PDA выполняется через Web-панель администратора:**
|
||||
|
||||
@@ -36,10 +43,9 @@ shine-UI/server-ui.html
|
||||
|
||||
Страницы:
|
||||
- `shine-UI/server-ui/create-server-pda.html` — первичная регистрация серверного аккаунта;
|
||||
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса или списка sync_servers.
|
||||
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса сервера.
|
||||
|
||||
Для регистрации нужен полный keyBundle (root + device + blockchain).
|
||||
Для обновления — только root + device (blockchain-ключ не нужен).
|
||||
PDA 1.0 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root.
|
||||
|
||||
Актуальные адреса программ Solana (devnet):
|
||||
- `shine_users`: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6`
|
||||
@@ -47,10 +53,9 @@ shine-UI/server-ui.html
|
||||
|
||||
Подробнее: `docs/Инициализация_Solana_регистрации/README.md`
|
||||
|
||||
## Синхронизация с партнёрскими серверами
|
||||
## Синхронизация пользовательских blockchain
|
||||
|
||||
Сервер должен синхронизировать блоки блокчейна и DM с серверами-партнёрами из `sync_servers`.
|
||||
Детали: `docs/Blockchain/sync-between-servers.md`
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync удалён; не восстанавливать его. `ListBlockchainHeads` остаётся read-only API тестового издателя.
|
||||
|
||||
## Деплой
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
plugins {
|
||||
id 'java'
|
||||
}
|
||||
|
||||
group = 'shine'
|
||||
version = '1.0.0'
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(17)
|
||||
}
|
||||
}
|
||||
|
||||
repositories { mavenCentral() }
|
||||
|
||||
dependencies {
|
||||
implementation project(':shine-server-config')
|
||||
implementation project(':shine-server-db')
|
||||
implementation project(':shine-server-crypto')
|
||||
implementation project(':shine-server-blockchain')
|
||||
implementation project(':shine-server-net-protocol')
|
||||
implementation project(':shine-server-solana-users-sync')
|
||||
|
||||
implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2'
|
||||
implementation 'org.bouncycastle:bcprov-jdk18on:1.78.1'
|
||||
implementation 'org.slf4j:slf4j-api:2.0.16'
|
||||
|
||||
testImplementation 'org.junit.jupiter:junit-jupiter:5.11.0'
|
||||
}
|
||||
|
||||
test { useJUnitPlatform() }
|
||||
@@ -0,0 +1,103 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/** Minimal ANS-104 binary bundle writer/reader. */
|
||||
public final class Ans104Bundle {
|
||||
public record Entry(byte[] id32, byte[] rawDataItem) {}
|
||||
|
||||
private Ans104Bundle() {}
|
||||
|
||||
public static byte[] write(List<byte[]> rawItems) {
|
||||
if (rawItems == null || rawItems.isEmpty()) throw new IllegalArgumentException("ANS-104 bundle is empty");
|
||||
if (rawItems.size() > 1_000_000) throw new IllegalArgumentException("Too many ANS-104 items");
|
||||
|
||||
List<Ans104DataItem> parsed = new ArrayList<>(rawItems.size());
|
||||
long total = 32L + 64L * rawItems.size();
|
||||
for (byte[] raw : rawItems) {
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
if (!item.verifySignature()) throw new IllegalArgumentException("Invalid ANS-104 DataItem signature");
|
||||
parsed.add(item);
|
||||
total = Math.addExact(total, raw.length);
|
||||
}
|
||||
if (total > Integer.MAX_VALUE) throw new IllegalArgumentException("Bundle too large for in-memory publisher: " + total);
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream((int) total);
|
||||
out.writeBytes(uint256LE(rawItems.size()));
|
||||
for (int i = 0; i < rawItems.size(); i++) {
|
||||
out.writeBytes(uint256LE(rawItems.get(i).length));
|
||||
out.writeBytes(parsed.get(i).id32());
|
||||
}
|
||||
for (byte[] raw : rawItems) out.writeBytes(raw);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static List<Entry> read(byte[] bundle, int maxItems) {
|
||||
if (bundle == null || bundle.length < 32) throw new IllegalArgumentException("ANS-104 bundle too short");
|
||||
long countLong = readUint256AsLong(bundle, 0);
|
||||
if (countLong <= 0 || countLong > Math.max(1, maxItems)) {
|
||||
throw new IllegalArgumentException("Bad ANS-104 bundle item count: " + countLong);
|
||||
}
|
||||
int count = (int) countLong;
|
||||
long headerLong = 32L + 64L * count;
|
||||
if (headerLong > bundle.length) throw new IllegalArgumentException("ANS-104 bundle header truncated");
|
||||
int header = (int) headerLong;
|
||||
long[] sizes = new long[count];
|
||||
byte[][] ids = new byte[count][];
|
||||
int hp = 32;
|
||||
long payloadBytes = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
sizes[i] = readUint256AsLong(bundle, hp); hp += 32;
|
||||
ids[i] = Arrays.copyOfRange(bundle, hp, hp + 32); hp += 32;
|
||||
if (sizes[i] <= 0 || sizes[i] > Integer.MAX_VALUE) throw new IllegalArgumentException("Bad DataItem size: " + sizes[i]);
|
||||
payloadBytes = Math.addExact(payloadBytes, sizes[i]);
|
||||
}
|
||||
if (headerLong + payloadBytes != bundle.length) {
|
||||
throw new IllegalArgumentException("ANS-104 bundle size mismatch: header=" + headerLong + " payload=" + payloadBytes + " actual=" + bundle.length);
|
||||
}
|
||||
List<Entry> out = new ArrayList<>(count);
|
||||
int p = header;
|
||||
for (int i = 0; i < count; i++) {
|
||||
int len = (int) sizes[i];
|
||||
byte[] raw = Arrays.copyOfRange(bundle, p, p + len);
|
||||
p += len;
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
if (!Arrays.equals(ids[i], item.id32())) throw new IllegalArgumentException("Bundle entry ID mismatch at index " + i);
|
||||
out.add(new Entry(ids[i], raw));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
public static byte[] find(byte[] bundle, byte[] wantedId32, int maxItems) {
|
||||
if (wantedId32 == null || wantedId32.length != 32) throw new IllegalArgumentException("wanted ID must be 32 bytes");
|
||||
for (Entry e : read(bundle, maxItems)) {
|
||||
if (Arrays.equals(e.id32(), wantedId32)) return e.rawDataItem();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** ANS-104 bundle integers are 32-byte unsigned little-endian values. */
|
||||
static byte[] uint256LE(long value) {
|
||||
if (value < 0) throw new IllegalArgumentException("negative uint256");
|
||||
byte[] out = new byte[32];
|
||||
long v = value;
|
||||
for (int i = 0; i < 8; i++) { out[i] = (byte) (v & 0xff); v >>>= 8; }
|
||||
return out;
|
||||
}
|
||||
|
||||
static long readUint256AsLong(byte[] data, int offset) {
|
||||
if (offset < 0 || offset + 32 > data.length) throw new IllegalArgumentException("uint256 truncated");
|
||||
for (int i = offset + 8; i < offset + 32; i++) {
|
||||
if (data[i] != 0) throw new IllegalArgumentException("uint256 exceeds signed long range");
|
||||
}
|
||||
long v = 0;
|
||||
for (int i = 7; i >= 0; i--) v = (v << 8) | (data[offset + i] & 0xffL);
|
||||
if (v < 0) throw new IllegalArgumentException("uint256 exceeds signed long range");
|
||||
return v;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
package server.archive;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.sync.ArweavePublishSignal;
|
||||
|
||||
import java.util.Base64;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentLinkedQueue;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Publisher с двумя путями доставки:
|
||||
* Серверный Turbo publisher обслуживает candidate-блоки ротации ключей.
|
||||
* Пользовательские CORE/CONTENT в режиме client_only загружает браузер.
|
||||
*/
|
||||
public final class ArweaveBlockPublisherScheduler {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
|
||||
private static final long RETRY_MIN_PENDING_AGE_MS = 60_000L;
|
||||
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
|
||||
private static final AtomicBoolean IMMEDIATE_DRAIN_SCHEDULED = new AtomicBoolean(false);
|
||||
private static final ConcurrentLinkedQueue<ArweavePublishSignal.PendingRef> IMMEDIATE_QUEUE = new ConcurrentLinkedQueue<>();
|
||||
private static final ConcurrentHashMap<String, Long> PENDING_SINCE_MS = new ConcurrentHashMap<>();
|
||||
|
||||
private static ScheduledExecutorService executor;
|
||||
private static ArweaveBlockPublisherService service;
|
||||
private static ArweaveBlocksConfig config;
|
||||
|
||||
private ArweaveBlockPublisherScheduler() {}
|
||||
|
||||
public static void startOrLog() {
|
||||
ArweaveBlocksConfig cfg;
|
||||
try { cfg = ArweaveBlocksConfig.load(); cfg.validatePublisher(); }
|
||||
catch (Exception e) { log.error("Cannot read/validate Arweave block publisher config", e); return; }
|
||||
if (!cfg.publishEnabled()) { log.info("Arweave user-block publisher disabled (mode=none)"); return; }
|
||||
if (!STARTED.compareAndSet(false,true)) return;
|
||||
try {
|
||||
config = cfg;
|
||||
service = new ArweaveBlockPublisherService(cfg);
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "shine-arweave-block-publisher"); t.setDaemon(true); return t;
|
||||
});
|
||||
|
||||
if (cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO) {
|
||||
ArweavePublishSignal.setListener(ArweaveBlockPublisherScheduler::enqueueImmediateTurboPublish);
|
||||
}
|
||||
|
||||
Runnable retryTask = () -> {
|
||||
try {
|
||||
if (config.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO) {
|
||||
long nowMs = System.currentTimeMillis();
|
||||
service.runRetryCycle(
|
||||
id -> isOldEnoughForRetry(id, nowMs),
|
||||
id -> PENDING_SINCE_MS.remove(idKey(id))
|
||||
);
|
||||
} else {
|
||||
service.runCycle();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("Arweave block publish retry cycle failed", e);
|
||||
}
|
||||
};
|
||||
long retryInitialDelayMinutes = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO
|
||||
? cfg.publishIntervalMinutes()
|
||||
: 0L;
|
||||
executor.scheduleWithFixedDelay(retryTask, retryInitialDelayMinutes, cfg.publishIntervalMinutes(), TimeUnit.MINUTES);
|
||||
log.info("Arweave user-block publisher enabled: mode={} immediateTurbo={} retryInterval={}m retryMinAge={}s",
|
||||
cfg.publishMode(), cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO,
|
||||
cfg.publishIntervalMinutes(), RETRY_MIN_PENDING_AGE_MS / 1000L);
|
||||
} catch (Exception e) {
|
||||
ArweavePublishSignal.clearListener();
|
||||
STARTED.set(false);
|
||||
log.error("Arweave user-block publisher failed to start", e);
|
||||
}
|
||||
}
|
||||
|
||||
private static void enqueueImmediateTurboPublish(ArweavePublishSignal.PendingRef item) {
|
||||
if (!STARTED.get() || config == null || config.publishMode() != ArweaveBlocksConfig.PublishMode.TURBO) return;
|
||||
PENDING_SINCE_MS.putIfAbsent(idKey(item.dataItemId()), System.currentTimeMillis());
|
||||
IMMEDIATE_QUEUE.offer(item);
|
||||
scheduleImmediateDrain();
|
||||
}
|
||||
|
||||
private static boolean isOldEnoughForRetry(byte[] dataItemId, long nowMs) {
|
||||
Long pendingSince = PENDING_SINCE_MS.get(idKey(dataItemId));
|
||||
// Нет записи в памяти => pending пережил старт процесса и уже считается зависшим.
|
||||
return pendingSince == null || nowMs - pendingSince >= RETRY_MIN_PENDING_AGE_MS;
|
||||
}
|
||||
|
||||
private static String idKey(byte[] dataItemId) {
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(dataItemId);
|
||||
}
|
||||
|
||||
private static void scheduleImmediateDrain() {
|
||||
ScheduledExecutorService currentExecutor = executor;
|
||||
if (currentExecutor == null || currentExecutor.isShutdown()) return;
|
||||
if (!IMMEDIATE_DRAIN_SCHEDULED.compareAndSet(false, true)) return;
|
||||
try {
|
||||
currentExecutor.execute(ArweaveBlockPublisherScheduler::drainImmediateQueue);
|
||||
} catch (RuntimeException e) {
|
||||
IMMEDIATE_DRAIN_SCHEDULED.set(false);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private static void drainImmediateQueue() {
|
||||
try {
|
||||
ArweavePublishSignal.PendingRef item;
|
||||
while ((item = IMMEDIATE_QUEUE.poll()) != null) {
|
||||
try {
|
||||
boolean resolved = service.publishAcceptedNow(item);
|
||||
if (resolved) PENDING_SINCE_MS.remove(idKey(item.dataItemId()));
|
||||
} catch (Exception e) {
|
||||
// Turbo недоступен: не держим поток клиента и не молотим всю очередь одной и той же ошибкой.
|
||||
// Все элементы уже надёжно лежат в БД с pending=TRUE; плановый цикл подберёт их после min-age.
|
||||
log.warn("Immediate Turbo publish failed; pending blocks will be retried by the periodic cycle: {}", e.getMessage());
|
||||
IMMEDIATE_QUEUE.clear();
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
IMMEDIATE_DRAIN_SCHEDULED.set(false);
|
||||
if (!IMMEDIATE_QUEUE.isEmpty()) scheduleImmediateDrain();
|
||||
}
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
ArweavePublishSignal.clearListener();
|
||||
IMMEDIATE_QUEUE.clear();
|
||||
PENDING_SINCE_MS.clear();
|
||||
IMMEDIATE_DRAIN_SCHEDULED.set(false);
|
||||
ScheduledExecutorService e = executor;
|
||||
executor = null;
|
||||
service = null;
|
||||
config = null;
|
||||
STARTED.set(false);
|
||||
if (e != null) e.shutdownNow();
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package server.archive;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
import shine.db.dao.KeyRotationCandidateBlocksDAO;
|
||||
import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
||||
import server.sync.ArweavePublishSignal;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Серверный publisher candidate-блоков ротации; пользовательские пары ведёт браузер. */
|
||||
public final class ArweaveBlockPublisherService {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherService.class);
|
||||
|
||||
private final ArweaveBlocksConfig cfg;
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
|
||||
private final TurboDataItemUploader turboUploader;
|
||||
|
||||
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
|
||||
cfg.validatePublisher();
|
||||
this.cfg = cfg;
|
||||
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Мгновенная попытка для только что принятого DataItem. Вызывается только из фонового executor-а:
|
||||
* сетевой запрос AddBlock не ждёт результат Turbo. Если запись уже успел обработать другой цикл, это no-op.
|
||||
* При ошибке pending-флаг в БД не меняется, поэтому обычный runCycle() повторит публикацию позже.
|
||||
*/
|
||||
public boolean publishAcceptedNow(ArweavePublishSignal.PendingRef pending) throws Exception {
|
||||
if (cfg.publishMode() != ArweaveBlocksConfig.PublishMode.TURBO) return false;
|
||||
byte[] id = pending.dataItemId();
|
||||
if (pending.kind() == ArweavePublishSignal.Kind.KEY_ROTATION_CANDIDATE) {
|
||||
KeyRotationCandidateBlockEntry entry = candidateBlocksDAO.getPendingArweaveByDataItemId(id);
|
||||
if (entry == null) return true;
|
||||
byte[] raw = entry.getBlockBytes();
|
||||
if (raw == null || raw.length == 0) return false;
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
|
||||
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public int runCycle() throws Exception {
|
||||
return runCycle(id -> true, id -> {});
|
||||
}
|
||||
|
||||
/** Плановый retry может отфильтровать слишком свежие pending-записи и получить callback успешных id. */
|
||||
public int runRetryCycle(Predicate<byte[]> eligible, Consumer<byte[]> onPublished) throws Exception {
|
||||
return runCycle(eligible == null ? id -> true : eligible, onPublished == null ? id -> {} : onPublished);
|
||||
}
|
||||
|
||||
private int runCycle(Predicate<byte[]> eligible, Consumer<byte[]> onPublished) throws Exception {
|
||||
if (cfg.publishMode() == ArweaveBlocksConfig.PublishMode.NONE) return 0;
|
||||
|
||||
int maxItems = cfg.publishMaxItems();
|
||||
int attempted = 0;
|
||||
int published = 0;
|
||||
|
||||
// Ротация приоритетна: пользователь уже заблокирован для обычной записи и ждёт завершения копирования.
|
||||
List<KeyRotationCandidateBlockEntry> rotationCandidates = candidateBlocksDAO.listPendingArweave(maxItems);
|
||||
rotationCandidates = rotationCandidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
|
||||
if (!rotationCandidates.isEmpty()) {
|
||||
attempted += rotationCandidates.size();
|
||||
published += switch (cfg.publishMode()) {
|
||||
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
|
||||
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||
case NONE -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
// Пользовательские блоки в режиме client_only публикует браузер.
|
||||
return published;
|
||||
}
|
||||
|
||||
private int publishTurboRotation(List<KeyRotationCandidateBlockEntry> candidates, Consumer<byte[]> onPublished) throws Exception {
|
||||
int published = 0;
|
||||
Exception firstFailure = null;
|
||||
for (KeyRotationCandidateBlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
log.debug("Turbo published key-rotation DataItem {} chain={} block={}",
|
||||
result.dataItemId(), e.getCandidateBlockchainName(), e.getBlockNumber());
|
||||
} catch (Exception ex) {
|
||||
if (firstFailure == null) firstFailure = ex;
|
||||
log.warn("Turbo key-rotation publish failed: chain={} block={} bytes={} error={}",
|
||||
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length, ex.getMessage());
|
||||
}
|
||||
}
|
||||
if (published > 0) log.info("Published {} SHiNE key-rotation DataItems through Turbo", published);
|
||||
if (published == 0 && firstFailure != null) throw firstFailure;
|
||||
return published;
|
||||
}
|
||||
|
||||
private int publishTurbo(List<BlockEntry> candidates, Consumer<byte[]> onPublished) throws Exception {
|
||||
int published = 0;
|
||||
Exception firstFailure = null;
|
||||
for (BlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
log.debug("Turbo published SHiNE DataItem {} chain={} block={}", result.dataItemId(), e.getBchName(), e.getBlockNumber());
|
||||
} catch (Exception ex) {
|
||||
if (firstFailure == null) firstFailure = ex;
|
||||
log.warn("Turbo publish failed: chain={} block={} bytes={} error={}",
|
||||
e.getBchName(), e.getBlockNumber(), raw.length, ex.getMessage());
|
||||
}
|
||||
}
|
||||
if (published > 0) log.info("Published {} SHiNE test DataItems through Turbo", published);
|
||||
if (published == 0 && firstFailure != null) throw firstFailure;
|
||||
return published;
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package server.archive;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
public final class ArweaveBlockSyncScheduler {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncScheduler.class);
|
||||
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
|
||||
private static ScheduledExecutorService executor;
|
||||
private ArweaveBlockSyncScheduler() {}
|
||||
|
||||
public static void startOrLog() {
|
||||
ArweaveBlocksConfig cfg;
|
||||
try { cfg = ArweaveBlocksConfig.load(); }
|
||||
catch (Exception e) { log.error("Cannot read Arweave block sync config", e); return; }
|
||||
if (!cfg.syncEnabled()) { log.info("Arweave user-block sync disabled"); return; }
|
||||
if (!STARTED.compareAndSet(false,true)) return;
|
||||
try {
|
||||
ArweaveBlockSyncService service = new ArweaveBlockSyncService(cfg);
|
||||
// Один поток намеренно сериализует полный discovery и быстрые retry уже найденных DataItem.
|
||||
executor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t=new Thread(r,"shine-arweave-block-sync");t.setDaemon(true);return t; });
|
||||
Runnable task=()->{try{service.runCycle();}catch(Exception e){log.error("Arweave block sync cycle failed",e);}};
|
||||
Runnable retryTask=()->{try{service.runRetryCycle();}catch(Exception e){log.error("Arweave block fast retry failed",e);}};
|
||||
executor.scheduleWithFixedDelay(task,0,cfg.syncIntervalMinutes(),TimeUnit.MINUTES);
|
||||
executor.scheduleWithFixedDelay(retryTask,cfg.syncLocationRetrySeconds(),cfg.syncLocationRetrySeconds(),TimeUnit.SECONDS);
|
||||
log.info("Arweave user-block sync enabled: interval={}m locationRetry={}s gateway={} turboApi={}",
|
||||
cfg.syncIntervalMinutes(),cfg.syncLocationRetrySeconds(),cfg.syncGateway(),cfg.syncTurboApiBase());
|
||||
} catch (Exception e) { STARTED.set(false); log.error("Arweave user-block sync failed to start",e); }
|
||||
}
|
||||
public static void close(){ScheduledExecutorService e=executor;if(e!=null)e.shutdownNow();}
|
||||
}
|
||||
+897
@@ -0,0 +1,897 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.BchBlockEntry;
|
||||
import server.archive.registration.VerifiedFreeRegistrationImporter;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
|
||||
import server.sync.BlockchainResyncGuard;
|
||||
import shine.db.DbController;
|
||||
import shine.db.KeyEncodingUtil;
|
||||
import utils.config.AppConfig;
|
||||
import shine.db.dao.ArweaveBlockImportDAO;
|
||||
import shine.db.dao.BlockchainStateDAO;
|
||||
import shine.db.dao.BlocksDAO;
|
||||
import shine.db.entities.BlockEntry;
|
||||
import shine.db.dao.BlockchainForkSegmentsDAO;
|
||||
import shine.db.dao.CanonicalChainResolver;
|
||||
import shine.db.dao.ChannelReadStateDAO;
|
||||
import shine.db.dao.BlockchainResyncCleanupDAO;
|
||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
||||
import shine.db.dao.RegistrationIdentityDAO;
|
||||
import shine.db.entities.BlockchainStateEntry;
|
||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Discovers signed CORE items and registration certificates in the active App namespace.
|
||||
* Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
|
||||
*/
|
||||
public final class ArweaveBlockSyncService {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Base64.Decoder B64URL = Base64.getUrlDecoder();
|
||||
|
||||
private final ArweaveBlocksConfig cfg;
|
||||
private final HttpClient http = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build();
|
||||
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter(
|
||||
AppConfig.getInstance().getBoolean("freeRegistration.email.allowReuse", false));
|
||||
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||
private final Net_AddBlock_Handler addBlock = new Net_AddBlock_Handler();
|
||||
private final BlockchainForkSegmentsDAO segmentsDAO = BlockchainForkSegmentsDAO.getInstance();
|
||||
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
|
||||
private final BlockchainResyncCleanupDAO cleanupDAO = BlockchainResyncCleanupDAO.getInstance();
|
||||
|
||||
// DataItem уже виден через GraphQL, но его физические координаты внутри ANS-104 bundle
|
||||
// ещё не появились у индексатора. Полный discovery остаётся редким, а эти ID ретраятся часто.
|
||||
private final Map<String, PendingDownload> unresolvedDownloads = new LinkedHashMap<>();
|
||||
|
||||
public ArweaveBlockSyncService(ArweaveBlocksConfig cfg) { this.cfg = cfg; }
|
||||
|
||||
public void runCycle() throws Exception {
|
||||
recoverInterruptedCanonicalRebuilds();
|
||||
discover();
|
||||
discoverFreeRegistrations();
|
||||
drainQueue();
|
||||
}
|
||||
|
||||
/** Быстрый retry только для уже обнаруженных DataItem, без повторного полного GraphQL discovery. */
|
||||
public void runRetryCycle() throws Exception {
|
||||
int queued = retryPendingDownloads();
|
||||
if (queued > 0) drainQueue();
|
||||
}
|
||||
|
||||
private void discover() throws Exception {
|
||||
long stored = importDAO.getLastBlockHeight();
|
||||
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
|
||||
String cursor = null;
|
||||
long maxHeight = minHeight;
|
||||
long lowestRetryHeight = Long.MAX_VALUE;
|
||||
int discovered = 0;
|
||||
|
||||
do {
|
||||
JsonNode response = graphQlPage(minHeight, cursor);
|
||||
JsonNode txs = response.path("data").path("transactions");
|
||||
if (response.has("errors")) throw new IOException("Arweave GraphQL errors: " + response.path("errors"));
|
||||
JsonNode edges = txs.path("edges");
|
||||
if (!edges.isArray()) throw new IOException("Arweave GraphQL returned no transactions.edges");
|
||||
|
||||
String nextCursor = null;
|
||||
for (JsonNode edge : edges) {
|
||||
nextCursor = edge.path("cursor").asText(null);
|
||||
JsonNode node = edge.path("node");
|
||||
String dataItemId = node.path("id").asText("").trim();
|
||||
long height = node.path("block").path("height").asLong(-1L);
|
||||
if (dataItemId.isBlank() || height < 0) continue;
|
||||
maxHeight = Math.max(maxHeight, height);
|
||||
|
||||
byte[] id32;
|
||||
try {
|
||||
id32 = B64URL.decode(dataItemId);
|
||||
if (id32.length != 32) throw new IllegalArgumentException("id length=" + id32.length);
|
||||
} catch (Exception e) {
|
||||
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
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);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
DownloadedEvent downloaded = downloadEvent(dataItemId);
|
||||
if (downloaded.registration()) {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
continue; // Не парсить регистрацию как BchBlockEntry.
|
||||
}
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
lowestRetryHeight = Math.min(lowestRetryHeight, height);
|
||||
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
|
||||
log.info("Signed DataItem {} visible at height {} but raw ANS-104 bytes are not ready yet; queued for fast retry: {}",
|
||||
dataItemId, height, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
lowestRetryHeight = Math.min(lowestRetryHeight, height);
|
||||
log.warn("Cannot retrieve signed DataItem {} at height {} yet: {}", dataItemId, height, e.getMessage());
|
||||
}
|
||||
}
|
||||
boolean hasNext = txs.path("pageInfo").path("hasNextPage").asBoolean(false);
|
||||
cursor = hasNext ? nextCursor : null;
|
||||
if (hasNext && (cursor == null || cursor.isBlank())) throw new IOException("GraphQL hasNextPage without cursor");
|
||||
} while (cursor != null);
|
||||
|
||||
// Keep inclusive overlap. If a gateway has indexed GraphQL before offsets, do not advance past that item.
|
||||
long checkpoint = lowestRetryHeight == Long.MAX_VALUE ? maxHeight : Math.min(maxHeight, lowestRetryHeight);
|
||||
importDAO.setLastBlockHeight(checkpoint, System.currentTimeMillis());
|
||||
if (discovered > 0) {
|
||||
log.info("Arweave discovery queued {} new SHiNE test DataItems; checkpoint={}", discovered, checkpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private int retryPendingDownloads() throws Exception {
|
||||
if (unresolvedDownloads.isEmpty()) return 0;
|
||||
|
||||
int queued = 0;
|
||||
int attempted = 0;
|
||||
List<PendingDownload> snapshot = new ArrayList<>(unresolvedDownloads.values());
|
||||
for (PendingDownload pending : snapshot) {
|
||||
if (attempted >= cfg.syncPageSize()) break;
|
||||
attempted++;
|
||||
|
||||
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());
|
||||
continue;
|
||||
}
|
||||
|
||||
DownloadedEvent downloaded;
|
||||
try {
|
||||
downloaded = downloadEvent(pending.dataItemId());
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||
log.debug("ANS-104 DataItem {} still waits for location/raw bytes: {}", pending.dataItemId(), e.getMessage());
|
||||
continue;
|
||||
} catch (Exception e) {
|
||||
// Не долбим явно плохой ответ каждые 30 секунд. Полный discovery попробует его снова позднее.
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
log.warn("Fast retry stopped for signed DataItem {} until next discovery: {}", pending.dataItemId(), e.getMessage());
|
||||
continue;
|
||||
}
|
||||
|
||||
if (downloaded.registration()) {
|
||||
try {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
} catch (Exception e) {
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
||||
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
||||
queued++;
|
||||
}
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
}
|
||||
|
||||
if (queued > 0) {
|
||||
log.info("Fast Arweave retry queued {} signed DataItems; {} still unresolved", queued, unresolvedDownloads.size());
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
||||
private void drainQueue() throws Exception {
|
||||
int passes = 0;
|
||||
int importedTotal = 0;
|
||||
boolean progress;
|
||||
Set<String> replayedLogins = new HashSet<>();
|
||||
do {
|
||||
progress = false;
|
||||
|
||||
// Phase 1 is global: validate every pending DataItem and discover all signed segment
|
||||
// ancestry before any canonical/orphan decision is made.
|
||||
prepareAllSegmentMetadata();
|
||||
|
||||
// Phase 2 is deterministic logical replay order, never Arweave height/order.
|
||||
List<ArweaveBlockImportDAO.QueueItem> pending = importDAO.listPendingValidated(cfg.syncQueueBatchSize());
|
||||
if (pending.isEmpty()) break;
|
||||
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
||||
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
||||
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
|
||||
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
||||
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
||||
continue;
|
||||
}
|
||||
int activeFork = forkOf(activeUser.getBlockchainName());
|
||||
if (!isAncestryComplete(q.parsedLogin(), activeFork)) {
|
||||
importDAO.setPendingError(q.dataItemId(), "ancestry_incomplete", System.currentTimeMillis());
|
||||
continue;
|
||||
}
|
||||
|
||||
int canonicalFork;
|
||||
try (Connection cc = DbController.getInstance().getConnection()) {
|
||||
canonicalFork = canonical.resolveFork(cc, q.parsedLogin(), activeFork, q.parsedBlockNumber());
|
||||
}
|
||||
if (canonicalFork != q.parsedForkNumber()) {
|
||||
importDAO.reject(q.dataItemId(), "orphan_noncanonical", System.currentTimeMillis());
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
Ans104DataItem item;
|
||||
BchBlockEntry parsedBlock;
|
||||
try {
|
||||
parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
|
||||
item = parsedBlock.getCoreDataItem();
|
||||
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
|
||||
} catch (Exception e) {
|
||||
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
|
||||
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
||||
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
||||
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
||||
importDAO.reject(q.dataItemId(), "validated_owner_mapping_changed", System.currentTimeMillis());
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
ensureState(physicalUser, parsedBlock);
|
||||
Net_AddBlock_Handler.ArweaveImportResult result = addBlock.addBlockFromReplay(
|
||||
physicalUser.getBlockchainName(), q.rawDataItem());
|
||||
if (result.ok()) {
|
||||
importDAO.delete(q.dataItemId());
|
||||
importedTotal++;
|
||||
replayedLogins.add(q.parsedLogin());
|
||||
progress = true;
|
||||
rebuildIfLocalOrphansExist(q.parsedLogin(), activeFork);
|
||||
continue;
|
||||
}
|
||||
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)
|
||||
|| "prev_line_block_not_found".equals(reason) || "channel_not_found".equals(reason)
|
||||
|| "chain_resync_in_progress".equals(reason)) {
|
||||
importDAO.setPendingError(q.dataItemId(), reason, System.currentTimeMillis());
|
||||
} else {
|
||||
importDAO.reject(q.dataItemId(), reason, System.currentTimeMillis());
|
||||
progress = true;
|
||||
}
|
||||
}
|
||||
passes++;
|
||||
} while (progress && passes < 1000);
|
||||
|
||||
// Replay deliberately suppresses live unread/push side effects. Recompute the server-owned
|
||||
// unread projection from final canonical channel contents and preserved signed read_count.
|
||||
if (!replayedLogins.isEmpty()) {
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
boolean ac = c.getAutoCommit(); c.setAutoCommit(false);
|
||||
try {
|
||||
for (String login : replayedLogins) {
|
||||
ChannelReadStateDAO.getInstance().recalculateUnreadForOwnedChannels(c, login, System.currentTimeMillis());
|
||||
}
|
||||
c.commit();
|
||||
} catch (Exception e) {
|
||||
c.rollback(); throw e;
|
||||
} finally { c.setAutoCommit(ac); }
|
||||
}
|
||||
}
|
||||
if (importedTotal > 0) log.info("Imported {} SHiNE test DataItems from Arweave", importedTotal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Phase 1 of Arweave recovery: scan the complete persistent PENDING queue and register only
|
||||
* immutable segment ancestry metadata. No block is applied or rejected here.
|
||||
*/
|
||||
private void prepareAllSegmentMetadata() throws Exception {
|
||||
String sql = "SELECT data_item_id,raw_data_item FROM arweave_block_import_queue WHERE status=? AND metadata_validated=FALSE ORDER BY block_height DESC, first_seen_at_ms DESC";
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, ArweaveBlockImportDAO.STATUS_PENDING);
|
||||
ps.setFetchSize(Math.max(100, cfg.syncQueueBatchSize()));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
byte[] id = rs.getBytes(1);
|
||||
byte[] raw = rs.getBytes(2);
|
||||
if (raw == null || raw.length == 0) {
|
||||
importDAO.reject(id, "empty_data_item", System.currentTimeMillis());
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
// Metadata is trusted only after complete ANS-104 validation.
|
||||
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
|
||||
Ans104DataItem item = b.getCoreDataItem();
|
||||
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
|
||||
|
||||
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
||||
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
||||
continue;
|
||||
}
|
||||
int fork = forkOf(owner.getBlockchainName());
|
||||
|
||||
// Only signed structural anchor blocks can create/modify ancestry metadata.
|
||||
if (fork == 1 && b.blockNumber == 0) {
|
||||
if (!(b.body instanceof blockchain.body.HeaderBody))
|
||||
throw new IllegalArgumentException("fork1 block #0 is not HEADER");
|
||||
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
|
||||
owner.getLogin(), 1, null, -1, null, 0, System.currentTimeMillis()));
|
||||
} else if (b.body instanceof blockchain.body.ForkBody fb) {
|
||||
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
|
||||
if (b.blockNumber != fb.forkPointBlockNumber + 1)
|
||||
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
|
||||
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
|
||||
if (parent == null || parent.getBlockchainName() == null
|
||||
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
||||
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
||||
int parentFork = forkOf(parent.getBlockchainName());
|
||||
if (parentFork >= fork) throw new IllegalArgumentException("TECH_FORK parent fork is not older");
|
||||
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
|
||||
owner.getLogin(), fork, parentFork,
|
||||
fb.forkPointBlockNumber, fb.forkPointBlockHash32,
|
||||
fb.forkPointBlockNumber + 1, System.currentTimeMillis()));
|
||||
}
|
||||
|
||||
importDAO.markMetadataValidated(id, owner.getLogin(), fork, b.blockNumber, b.getHash32(), System.currentTimeMillis());
|
||||
} catch (Exception e) {
|
||||
importDAO.reject(id, "invalid_data_item: " + e.getMessage(), System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** True only when rotation ancestry is known all the way back to fork1. */
|
||||
private boolean isAncestryComplete(String login, int activeFork) throws Exception {
|
||||
int f = activeFork;
|
||||
Set<Integer> seen = new HashSet<>();
|
||||
while (true) {
|
||||
if (f < 1 || !seen.add(f)) return false;
|
||||
BlockchainForkSegmentsDAO.Segment seg = segmentsDAO.get(login, f);
|
||||
if (seg == null) return false;
|
||||
if (seg.parentForkNumber() == null) {
|
||||
return f == 1 && seg.firstPhysicalBlockNumber() == 0;
|
||||
}
|
||||
f = seg.parentForkNumber();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
|
||||
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
|
||||
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
|
||||
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
|
||||
*/
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
|
||||
if (solana != null) return solana;
|
||||
|
||||
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
|
||||
if (solana != null) return solana;
|
||||
if (owner32 == null || owner32.length != 32) return null;
|
||||
|
||||
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT login, blockchain_key
|
||||
FROM user_identity_current
|
||||
WHERE registration_status='FREE_CERT' AND blockchain_key=?
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, blockchainKey);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
|
||||
if (solana != null) return solana;
|
||||
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
|
||||
String login = blockchainName.substring(0, blockchainName.length() - 4);
|
||||
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
|
||||
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
|
||||
}
|
||||
|
||||
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
|
||||
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
|
||||
owner.setLogin(login);
|
||||
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
|
||||
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
|
||||
owner.setPaidLimitBytes(0L);
|
||||
return owner;
|
||||
}
|
||||
|
||||
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
|
||||
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
|
||||
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
|
||||
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
||||
if(seg!=null&&seg.parentForkNumber()!=null){
|
||||
s.setLastBlockNumber(seg.forkPointBlockNumber());s.setLastBlockHash(seg.forkPointBlockHash());
|
||||
try(var c=shine.db.DbController.getInstance().getConnection();var ps=c.prepareStatement("SELECT COALESCE(SUM(octet_length(block_bytes)),0) FROM blocks_store WHERE LOWER(login)=LOWER(?) AND block_number<=? AND fork_number=shine_canonical_fork(?,?,block_number)")){
|
||||
ps.setString(1,user.getLogin());ps.setInt(2,seg.forkPointBlockNumber());ps.setString(3,user.getLogin());ps.setInt(4,seg.parentForkNumber());try(var rs=ps.executeQuery()){if(rs.next())s.setFileSizeBytes(rs.getLong(1));}
|
||||
}
|
||||
} else{s.setLastBlockNumber(-1);s.setLastBlockHash(null);}
|
||||
s.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(s);
|
||||
if(existing!=null)stateDAO.upsert(s);
|
||||
}
|
||||
private static int forkOf(String n){int d=n.lastIndexOf('-');return Integer.parseInt(n.substring(d+1));}
|
||||
|
||||
/** Resume a durable canonical rebuild that was interrupted after staging/cleanup/replay. */
|
||||
private void recoverInterruptedCanonicalRebuilds() throws Exception {
|
||||
List<String> logins=new ArrayList<>();
|
||||
try(Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement ps=c.prepareStatement("SELECT DISTINCT login FROM canonical_rebuild_staging ORDER BY login");
|
||||
ResultSet rs=ps.executeQuery()){
|
||||
while(rs.next())logins.add(rs.getString(1));
|
||||
}
|
||||
for(String login:logins){
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
|
||||
if(u==null||u.getBlockchainName()==null)continue;
|
||||
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A server may learn a deep fork only through Arweave after already materializing the old branch.
|
||||
* If any local raw block is non-canonical under the current PDA fork, stage the canonical raw set
|
||||
* and rebuild projections exactly like local key rotation does.
|
||||
*/
|
||||
private void rebuildIfLocalOrphansExist(String login,int activeFork)throws Exception{
|
||||
if(!hasNonCanonicalLocalBlocks(login,activeFork))return;
|
||||
if(!hasGenericStaging(login))stageLocalCanonicalBlocks(login,activeFork);
|
||||
validateGenericStaging(login);
|
||||
replayDurableCanonicalStaging(login,activeFork);
|
||||
}
|
||||
|
||||
private boolean hasNonCanonicalLocalBlocks(String login,int activeFork)throws SQLException{
|
||||
String sql="SELECT 1 FROM blocks_store b WHERE LOWER(b.login)=LOWER(?) AND b.fork_number<>shine_canonical_fork(?,?,b.block_number) LIMIT 1";
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement(sql)){
|
||||
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);try(ResultSet rs=ps.executeQuery()){return rs.next();}
|
||||
}
|
||||
}
|
||||
private boolean hasGenericStaging(String login)throws SQLException{
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT 1 FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) LIMIT 1")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){return rs.next();}
|
||||
}
|
||||
}
|
||||
private void stageLocalCanonicalBlocks(String login,int activeFork)throws Exception{
|
||||
try(Connection c=DbController.getInstance().getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
|
||||
try(PreparedStatement d=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){d.setString(1,login);d.executeUpdate();}
|
||||
String q="""
|
||||
SELECT block_number,fork_number,block_bytes,block_hash
|
||||
FROM blocks_store b
|
||||
WHERE LOWER(login)=LOWER(?) AND fork_number=shine_canonical_fork(?,?,block_number)
|
||||
ORDER BY block_number ASC
|
||||
""";
|
||||
String ins="INSERT INTO canonical_rebuild_staging(login,logical_block_number,physical_fork_number,block_bytes,block_hash) VALUES(?,?,?,?,?)";
|
||||
try(PreparedStatement ps=c.prepareStatement(q);PreparedStatement out=c.prepareStatement(ins)){
|
||||
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);
|
||||
try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
out.setString(1,login);out.setInt(2,rs.getInt(1));out.setInt(3,rs.getInt(2));out.setBytes(4,rs.getBytes(3));out.setBytes(5,rs.getBytes(4));out.addBatch();
|
||||
}}out.executeBatch();
|
||||
}
|
||||
c.commit();
|
||||
}catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(ac);}}
|
||||
}
|
||||
private void validateGenericStaging(String login)throws Exception{
|
||||
int expected=0,last=-1;byte[] previous=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
|
||||
BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
|
||||
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
|
||||
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
|
||||
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
|
||||
previous=hash;last=n;expected++;
|
||||
}}
|
||||
}
|
||||
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
||||
}
|
||||
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
|
||||
try{
|
||||
validateGenericStaging(login);
|
||||
cleanupDAO.cleanupLoginForCanonicalReplay(login);
|
||||
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
|
||||
String bch=login+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}
|
||||
}
|
||||
cleanupDAO.finalizeCanonicalReplay(login);
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){ps.setString(1,login);ps.executeUpdate();}
|
||||
}finally{BlockchainResyncGuard.end(activeName);}
|
||||
}
|
||||
|
||||
|
||||
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
|
||||
private void discoverFreeRegistrations() throws Exception {
|
||||
long stored;
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
|
||||
ResultSet rs = ps.executeQuery()) {
|
||||
stored = rs.next() ? rs.getLong(1) : 0;
|
||||
}
|
||||
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
|
||||
long high = minHeight;
|
||||
long retryFrom = Long.MAX_VALUE;
|
||||
String cursor = null;
|
||||
int count = 0;
|
||||
do {
|
||||
JsonNode response = graphQlPage(minHeight, cursor, true);
|
||||
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
|
||||
JsonNode txs = response.path("data").path("transactions");
|
||||
JsonNode edges = txs.path("edges");
|
||||
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
|
||||
String next = null;
|
||||
for (JsonNode edge : edges) {
|
||||
next = edge.path("cursor").asText(null);
|
||||
JsonNode node = edge.path("node");
|
||||
String id = node.path("id").asText("").trim();
|
||||
long height = node.path("block").path("height").asLong(-1);
|
||||
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
|
||||
high = Math.max(high, height);
|
||||
try {
|
||||
byte[] idBytes = B64URL.decode(id);
|
||||
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
|
||||
DownloadedDataItem item = downloadSignedDataItem(id);
|
||||
if (!isRegistrationItem(item.rawDataItem()))
|
||||
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
|
||||
registrationImporter.importSigned(item.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
count++;
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
retryFrom = Math.min(retryFrom, height);
|
||||
log.debug("Registration DataItem {} is not downloadable yet", id);
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
|
||||
} catch (Exception e) {
|
||||
retryFrom = Math.min(retryFrom, height);
|
||||
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
|
||||
}
|
||||
}
|
||||
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
|
||||
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
|
||||
throw new IOException("Registration GraphQL cursor missing");
|
||||
} while (cursor != null);
|
||||
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
UPDATE free_registration_arweave_sync_state
|
||||
SET last_block_height=?, updated_at_ms=? WHERE id=1
|
||||
""")) {
|
||||
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
|
||||
}
|
||||
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
|
||||
}
|
||||
|
||||
private static boolean isRegistrationItem(byte[] raw) {
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
|
||||
}
|
||||
|
||||
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
|
||||
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
|
||||
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(first.rawDataItem())) {
|
||||
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
|
||||
}
|
||||
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
|
||||
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
|
||||
return new DownloadedEvent(first.rootTxId(), container, false);
|
||||
}
|
||||
|
||||
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
||||
return graphQlPage(minHeight, cursor, false);
|
||||
}
|
||||
|
||||
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
|
||||
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
||||
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
|
||||
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
|
||||
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
|
||||
+ cfg.syncPageSize() + ", after:" + after
|
||||
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
||||
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/graphql"))
|
||||
.timeout(Duration.ofSeconds(60)).header("Content-Type","application/json").header("Accept","application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8)).build();
|
||||
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) throw new IOException("GraphQL HTTP " + resp.statusCode());
|
||||
return MAPPER.readTree(resp.body());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gateway по /{dataItemId} обычно отдаёт только payload. Для импорта SHiNE нужен полный
|
||||
* подписанный ANS-104 DataItem, поэтому сначала резолвим rootTx + offset + size, а затем
|
||||
* читаем точный range из root L1 transaction.
|
||||
*/
|
||||
private DownloadedDataItem downloadSignedDataItem(String dataItemId) throws Exception {
|
||||
DataItemLocation location = resolveDataItemLocation(dataItemId);
|
||||
long endInclusive = location.rootOffset() + location.size() - 1;
|
||||
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/raw/" + location.rootTxId()))
|
||||
.timeout(Duration.ofMinutes(2))
|
||||
.header("Range", "bytes=" + location.rootOffset() + "-" + endInclusive)
|
||||
.header("Accept", "application/octet-stream")
|
||||
.GET().build();
|
||||
HttpResponse<InputStream> resp = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
|
||||
try (InputStream in = resp.body()) {
|
||||
if (resp.statusCode() != 206) {
|
||||
if (isRetryableHttpStatus(resp.statusCode())) {
|
||||
throw new RetryableDataItemDownloadException(
|
||||
"root range is temporarily unavailable via " + location.source() + ": HTTP " + resp.statusCode());
|
||||
}
|
||||
throw new IOException("Gateway ignored root range for DataItem " + dataItemId + ": HTTP " + resp.statusCode());
|
||||
}
|
||||
byte[] bytes = readExactlyBounded(in, Math.toIntExact(location.size()));
|
||||
if (bytes.length != location.size()) {
|
||||
throw new RetryableDataItemDownloadException(
|
||||
"truncated DataItem range: expected=" + location.size() + " got=" + bytes.length);
|
||||
}
|
||||
Ans104DataItem parsed = new Ans104DataItem(bytes);
|
||||
byte[] expectedId = B64URL.decode(dataItemId);
|
||||
if (!Arrays.equals(parsed.id32(), expectedId)) {
|
||||
throw new IOException("Range returned another ANS-104 DataItem for " + dataItemId);
|
||||
}
|
||||
return new DownloadedDataItem(location.rootTxId(), bytes);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Координаты считаются только подсказкой транспорта: источник может ошибиться, поэтому после
|
||||
* range-read всё равно обязательно сверяется настоящий ANS-104 DataItem ID и затем подпись.
|
||||
*/
|
||||
private DataItemLocation resolveDataItemLocation(String dataItemId) throws Exception {
|
||||
List<String> misses = new ArrayList<>(3);
|
||||
|
||||
try {
|
||||
DataItemLocation location = getArIoIndexedLocation(dataItemId);
|
||||
if (location != null) return location;
|
||||
misses.add("ar-io=404");
|
||||
} catch (Exception e) {
|
||||
misses.add("ar-io=" + shortError(e));
|
||||
}
|
||||
|
||||
try {
|
||||
DataItemLocation location = getTurboLocation(dataItemId);
|
||||
if (location != null) return location;
|
||||
misses.add("turbo=404");
|
||||
} catch (Exception e) {
|
||||
misses.add("turbo=" + shortError(e));
|
||||
}
|
||||
|
||||
try {
|
||||
DataItemLocation location = getHeadLocation(dataItemId);
|
||||
if (location != null) return location;
|
||||
misses.add("head=no-location");
|
||||
} catch (Exception e) {
|
||||
misses.add("head=" + shortError(e));
|
||||
}
|
||||
|
||||
throw new RetryableDataItemDownloadException(
|
||||
"ANS-104 location not available yet (" + String.join(", ", misses) + ")");
|
||||
}
|
||||
|
||||
/** Самый дешёвый путь: локальный индекс AR.IO gateway. */
|
||||
private DataItemLocation getArIoIndexedLocation(String dataItemId) throws Exception {
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/ar-io/offsets/" + dataItemId))
|
||||
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
|
||||
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (resp.statusCode() == 404) return null;
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
|
||||
}
|
||||
JsonNode offsets = MAPPER.readTree(resp.body());
|
||||
return validateLocation("ar-io", dataItemId,
|
||||
offsets.path("rootTxId").asText("").trim(),
|
||||
offsets.path("rootOffset").asLong(-1L),
|
||||
offsets.path("size").asLong(-1L));
|
||||
}
|
||||
|
||||
/** Turbo часто знает координаты раньше общего gateway index. */
|
||||
private DataItemLocation getTurboLocation(String dataItemId) throws Exception {
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncTurboApiBase()) + "/tx/" + dataItemId + "/offsets"))
|
||||
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
|
||||
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if (resp.statusCode() == 404) return null;
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
|
||||
}
|
||||
JsonNode offsets = MAPPER.readTree(resp.body());
|
||||
return validateLocation("turbo", dataItemId,
|
||||
offsets.path("rootBundleId").asText("").trim(),
|
||||
offsets.path("startOffsetInRootBundle").asLong(-1L),
|
||||
offsets.path("rawContentLength").asLong(-1L));
|
||||
}
|
||||
|
||||
/**
|
||||
* Последний fallback: успешный HEAD/GET AR.IO может вернуть координаты DataItem в headers.
|
||||
* Поддерживаем несколько имён headers, чтобы пережить различия версий gateway.
|
||||
*/
|
||||
private DataItemLocation getHeadLocation(String dataItemId) throws Exception {
|
||||
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/" + dataItemId))
|
||||
.timeout(Duration.ofSeconds(45))
|
||||
.header("Accept", "application/octet-stream")
|
||||
.method("HEAD", HttpRequest.BodyPublishers.noBody())
|
||||
.build();
|
||||
HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
|
||||
if (resp.statusCode() == 404) return null;
|
||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||
throw new IOException("HTTP " + resp.statusCode());
|
||||
}
|
||||
|
||||
String rootTxId = firstHeader(resp, "X-AR-IO-Root-Transaction-Id");
|
||||
long offset = firstLongHeader(resp,
|
||||
"X-AR-IO-Root-Item-Offset",
|
||||
"X-AR-IO-Root-Data-Item-Offset",
|
||||
"X-AR-IO-Data-Item-Offset");
|
||||
long size = firstLongHeader(resp,
|
||||
"X-AR-IO-Root-Item-Size",
|
||||
"X-AR-IO-Data-Item-Size");
|
||||
if (rootTxId == null || offset < 0 || size <= 0) return null;
|
||||
return validateLocation("head", dataItemId, rootTxId, offset, size);
|
||||
}
|
||||
|
||||
private DataItemLocation validateLocation(String source, String dataItemId, String rootTxId, long rootOffset, long size)
|
||||
throws IOException {
|
||||
if (!isArweaveId(rootTxId) || rootOffset < 0 || size <= 0) {
|
||||
throw new IOException("bad location for " + dataItemId + ": rootTxId=" + rootTxId
|
||||
+ " offset=" + rootOffset + " size=" + size);
|
||||
}
|
||||
if (size > cfg.syncMaxDataItemBytes()) {
|
||||
throw new IOException("DataItem exceeds syncMaxDataItemBytes: " + size);
|
||||
}
|
||||
if (size > Integer.MAX_VALUE) throw new IOException("DataItem is too large for in-memory import: " + size);
|
||||
if (rootOffset > Long.MAX_VALUE - size) throw new IOException("DataItem offset overflow");
|
||||
return new DataItemLocation(rootTxId, rootOffset, size, source);
|
||||
}
|
||||
|
||||
private static String firstHeader(HttpResponse<?> response, String name) {
|
||||
return response.headers().firstValue(name).map(String::trim).filter(v -> !v.isEmpty()).orElse(null);
|
||||
}
|
||||
|
||||
private static long firstLongHeader(HttpResponse<?> response, String... names) {
|
||||
for (String name : names) {
|
||||
String value = firstHeader(response, name);
|
||||
if (value == null) continue;
|
||||
try { return Long.parseLong(value); }
|
||||
catch (NumberFormatException ignored) { }
|
||||
}
|
||||
return -1L;
|
||||
}
|
||||
|
||||
private static boolean isArweaveId(String value) {
|
||||
if (value == null || value.length() != 43) return false;
|
||||
try { return B64URL.decode(value).length == 32; }
|
||||
catch (IllegalArgumentException e) { return false; }
|
||||
}
|
||||
|
||||
private static boolean isRetryableHttpStatus(int status) {
|
||||
return status == 404 || status == 408 || status == 425 || status == 429 || status >= 500;
|
||||
}
|
||||
|
||||
private static String shortError(Exception e) {
|
||||
String message = e.getMessage();
|
||||
return safe(message == null || message.isBlank() ? e.getClass().getSimpleName() : message);
|
||||
}
|
||||
|
||||
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
|
||||
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
|
||||
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
|
||||
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
|
||||
|
||||
private static final class RetryableDataItemDownloadException extends IOException {
|
||||
private RetryableDataItemDownloadException(String message) { super(message); }
|
||||
}
|
||||
|
||||
private static byte[] readExactlyBounded(InputStream in, int expected) throws IOException {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(expected);
|
||||
byte[] buf = new byte[Math.min(64 * 1024, Math.max(1024, expected))];
|
||||
int remaining = expected;
|
||||
while (remaining > 0) {
|
||||
int n = in.read(buf, 0, Math.min(buf.length, remaining));
|
||||
if (n < 0) break;
|
||||
out.write(buf, 0, n);
|
||||
remaining -= n;
|
||||
}
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
String v = value == null ? "" : value.replace('\n',' ').replace('\r',' ').trim();
|
||||
return v.length() <= 500 ? v : v.substring(0, 500);
|
||||
}
|
||||
private static String trim(String s){return String.valueOf(s==null?"":s).trim().replaceAll("/+$","");}
|
||||
private static String escapeGraphQl(String s){return s.replace("\\","\\\\").replace("\"","\\\"");}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.ShineProtocolTags;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Configuration of per-user-block ANS-104 Arweave/Turbo transport. */
|
||||
public record ArweaveBlocksConfig(
|
||||
PublishMode publishMode,
|
||||
int publishIntervalMinutes,
|
||||
int publishMaxItems,
|
||||
long publishMaxBundleBytes,
|
||||
String publishGateway,
|
||||
Path walletJwkPath,
|
||||
int minConfirmations,
|
||||
int confirmPollSeconds,
|
||||
int confirmTimeoutMinutes,
|
||||
String turboUploadUrl,
|
||||
String turboPaidByAddress,
|
||||
Path turboWalletJwkPath,
|
||||
boolean syncEnabled,
|
||||
int syncIntervalMinutes,
|
||||
int syncPageSize,
|
||||
int syncQueueBatchSize,
|
||||
long syncStartBlockHeight,
|
||||
long syncMaxDataItemBytes,
|
||||
String syncGateway,
|
||||
String syncTurboApiBase,
|
||||
int syncLocationRetrySeconds
|
||||
) {
|
||||
public enum PublishMode {
|
||||
TURBO,
|
||||
ARWEAVE,
|
||||
NONE;
|
||||
|
||||
static PublishMode parse(String value) {
|
||||
String normalized = value == null ? "none" : value.trim().toLowerCase(Locale.ROOT);
|
||||
return switch (normalized) {
|
||||
case "turbo" -> TURBO;
|
||||
case "arweave" -> ARWEAVE;
|
||||
case "none", "" -> NONE;
|
||||
default -> throw new IllegalArgumentException(
|
||||
"arweave.blocks.publish.mode must be turbo, arweave or none; got: " + value);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
|
||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
|
||||
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
|
||||
|
||||
public static ArweaveBlocksConfig load() {
|
||||
AppConfig c = AppConfig.getInstance();
|
||||
long maxDataItemBytes = parseLong(c.getParam("arweave.blocks.sync.maxDataItemBytes"), Ans104DataItem.MAX_DATA_ITEM_BYTES);
|
||||
if (maxDataItemBytes > Ans104DataItem.MAX_DATA_ITEM_BYTES) maxDataItemBytes = Ans104DataItem.MAX_DATA_ITEM_BYTES;
|
||||
return new ArweaveBlocksConfig(
|
||||
PublishMode.parse(c.getParam("arweave.blocks.publish.mode")),
|
||||
positive(c.getInt("arweave.blocks.publish.intervalMinutes", 15), "publish.intervalMinutes"),
|
||||
positive(c.getInt("arweave.blocks.publish.maxItems", 10_000), "publish.maxItems"),
|
||||
positiveLong(parseLong(c.getParam("arweave.blocks.publish.maxBundleBytes"), 128L * 1024 * 1024), "publish.maxBundleBytes"),
|
||||
orDefault(c.getParam("arweave.blocks.publish.gateway"), "https://arweave.net"),
|
||||
optionalPath(c.getParam("arweave.blocks.publish.walletJwkPath")),
|
||||
nonNegative(c.getInt("arweave.blocks.publish.minConfirmations", 0), "publish.minConfirmations"),
|
||||
positive(c.getInt("arweave.blocks.publish.confirmPollSeconds", 30), "publish.confirmPollSeconds"),
|
||||
positive(c.getInt("arweave.blocks.publish.confirmTimeoutMinutes", 180), "publish.confirmTimeoutMinutes"),
|
||||
orDefault(c.getParam("arweave.blocks.publish.turbo.uploadUrl"), "https://turbo.ardrive.io/tx"),
|
||||
blankToNull(c.getParam("arweave.blocks.publish.turbo.paidByAddress")),
|
||||
optionalPath(c.getParam("arweave.blocks.publish.turbo.walletJwkPath")),
|
||||
c.getBoolean("arweave.blocks.sync.enabled", false),
|
||||
positive(c.getInt("arweave.blocks.sync.intervalMinutes", 15), "sync.intervalMinutes"),
|
||||
clamp(c.getInt("arweave.blocks.sync.pageSize", 100), 1, 100),
|
||||
positive(c.getInt("arweave.blocks.sync.queueBatchSize", 10_000), "sync.queueBatchSize"),
|
||||
nonNegativeLong(parseLong(c.getParam("arweave.blocks.sync.startBlockHeight"), 0L), "sync.startBlockHeight"),
|
||||
positiveLong(maxDataItemBytes, "sync.maxDataItemBytes"),
|
||||
orDefault(c.getParam("arweave.blocks.sync.gateway"), "https://turbo-gateway.com"),
|
||||
orDefault(c.getParam("arweave.blocks.sync.turboApiBase"), "https://turbo.ardrive.io"),
|
||||
positive(c.getInt("arweave.blocks.sync.locationRetrySeconds", 30), "sync.locationRetrySeconds")
|
||||
);
|
||||
}
|
||||
|
||||
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
|
||||
|
||||
public void validatePublisher() {
|
||||
if (publishMode == PublishMode.ARWEAVE) {
|
||||
throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
|
||||
}
|
||||
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
|
||||
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
|
||||
}
|
||||
}
|
||||
|
||||
private static String orDefault(String v, String d) { return v == null || v.isBlank() ? d : v.trim(); }
|
||||
private static String blankToNull(String v) { return v == null || v.isBlank() ? null : v.trim(); }
|
||||
private static Path optionalPath(String v) { return v == null || v.isBlank() ? null : Path.of(v.trim()); }
|
||||
private static long parseLong(String v, long d) { return v == null || v.isBlank() ? d : Long.parseLong(v.trim()); }
|
||||
private static int positive(int v,String n){if(v<=0)throw new IllegalArgumentException(n+" must be >0");return v;}
|
||||
private static int nonNegative(int v,String n){if(v<0)throw new IllegalArgumentException(n+" must be >=0");return v;}
|
||||
private static long positiveLong(long v,String n){if(v<=0)throw new IllegalArgumentException(n+" must be >0");return v;}
|
||||
private static long nonNegativeLong(long v,String n){if(v<0)throw new IllegalArgumentException(n+" must be >=0");return v;}
|
||||
private static int clamp(int v,int min,int max){return Math.max(min,Math.min(max,v));}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package server.archive;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.*;
|
||||
import java.security.spec.MGF1ParameterSpec;
|
||||
import java.security.spec.PSSParameterSpec;
|
||||
import java.security.spec.RSAPrivateCrtKeySpec;
|
||||
import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/** Existing native Arweave L1 transport adapted to upload in-memory ANS-104 bundles. */
|
||||
public final class ArweaveL1Uploader {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveL1Uploader.class);
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Base64.Encoder B64 = Base64.getUrlEncoder().withoutPadding();
|
||||
private static final Base64.Decoder B64D = Base64.getUrlDecoder();
|
||||
|
||||
public record Tag(String name, String value) {}
|
||||
public record UploadResult(String txId, byte[] txIdBytes) {}
|
||||
|
||||
private final ArweaveBlocksConfig cfg;
|
||||
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(20)).build();
|
||||
private volatile Wallet wallet;
|
||||
|
||||
public ArweaveL1Uploader(ArweaveBlocksConfig cfg) { this.cfg = Objects.requireNonNull(cfg); }
|
||||
|
||||
public UploadResult upload(byte[] data, List<Tag> tags) throws Exception {
|
||||
if (data == null || data.length == 0) throw new IllegalArgumentException("Arweave upload data is empty");
|
||||
Wallet w = wallet();
|
||||
String gateway = trimGateway(cfg.publishGateway());
|
||||
ArweaveMerkle.Prepared merkle = ArweaveMerkle.prepare(data);
|
||||
String anchor = getRequiredText(gateway, "/tx_anchor");
|
||||
String reward = getRequiredText(gateway, "/price/" + data.length);
|
||||
if (!reward.matches("^\\d+$")) throw new IOException("Bad Arweave price: " + reward);
|
||||
verifyBalance(gateway, w.address(), reward);
|
||||
|
||||
List<List<byte[]>> tagList = new ArrayList<>();
|
||||
List<Map<String,String>> jsonTags = new ArrayList<>();
|
||||
for (Tag tag : tags == null ? List.<Tag>of() : tags) addTag(jsonTags, tagList, tag.name(), tag.value());
|
||||
|
||||
byte[] signaturePayload = deepHash(List.of(
|
||||
utf8("2"), b64Decode(w.owner()), new byte[0], utf8("0"), utf8(reward),
|
||||
b64Decode(anchor), tagList, utf8(Integer.toString(data.length)), merkle.dataRoot()
|
||||
));
|
||||
byte[] rawSignature = signPayload(w.privateKey(), signaturePayload);
|
||||
byte[] txIdBytes = sha256(rawSignature);
|
||||
String txId = b64(txIdBytes);
|
||||
|
||||
Map<String,Object> tx = new LinkedHashMap<>();
|
||||
tx.put("format",2); tx.put("id",txId); tx.put("last_tx",anchor); tx.put("owner",w.owner());
|
||||
tx.put("tags",jsonTags); tx.put("target",""); tx.put("quantity","0");
|
||||
tx.put("data_root",b64(merkle.dataRoot())); tx.put("data_size",Integer.toString(data.length)); tx.put("data","");
|
||||
tx.put("reward",reward); tx.put("signature",b64(rawSignature));
|
||||
postJsonExpect2xx(gateway + "/tx", tx, Duration.ofSeconds(60));
|
||||
|
||||
for (int i=0;i<merkle.chunks().size();i++) {
|
||||
ArweaveMerkle.Chunk meta=merkle.chunks().get(i); ArweaveMerkle.Proof proof=merkle.proofs().get(i);
|
||||
Map<String,Object> body=new LinkedHashMap<>();
|
||||
body.put("data_root",b64(merkle.dataRoot())); body.put("data_size",Integer.toString(data.length));
|
||||
body.put("data_path",b64(proof.proof())); body.put("offset",Long.toString(proof.offset()));
|
||||
body.put("chunk",b64(ArweaveMerkle.readChunk(data,meta)));
|
||||
postChunkWithRetry(gateway,body,i,merkle.chunks().size());
|
||||
}
|
||||
if (cfg.minConfirmations() > 0) waitForConfirmations(txId);
|
||||
log.info("ANS-104 bundle uploaded to Arweave: tx={} bytes={} items-transported",txId,data.length);
|
||||
return new UploadResult(txId,txIdBytes);
|
||||
}
|
||||
|
||||
private int waitForConfirmations(String txId) throws Exception {
|
||||
String gateway=trimGateway(cfg.publishGateway());
|
||||
long deadline=System.currentTimeMillis()+cfg.confirmTimeoutMinutes()*60_000L; int last=0;
|
||||
while(System.currentTimeMillis()<deadline){
|
||||
HttpRequest req=HttpRequest.newBuilder(URI.create(gateway+"/tx/"+txId+"/status")).timeout(Duration.ofSeconds(20)).GET().build();
|
||||
HttpResponse<String> resp=http.send(req,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if(resp.statusCode()==200){JsonNode j=MAPPER.readTree(resp.body());last=j.path("number_of_confirmations").asInt(0);if(last>=cfg.minConfirmations())return last;}
|
||||
else if(resp.statusCode()!=202&&resp.statusCode()!=404)log.warn("Arweave status tx={} HTTP {}",txId,resp.statusCode());
|
||||
Thread.sleep(cfg.confirmPollSeconds()*1000L);
|
||||
}
|
||||
throw new IOException("Arweave confirmation timeout for "+txId+", last="+last);
|
||||
}
|
||||
|
||||
private void postChunkWithRetry(String gateway,Map<String,Object> body,int index,int total)throws Exception{
|
||||
Exception last=null;
|
||||
for(int attempt=1;attempt<=12;attempt++)try{postJsonExpect2xx(gateway+"/chunk",body,Duration.ofSeconds(60));return;}catch(Exception e){last=e;if(attempt==12)break;Thread.sleep(5000L);}
|
||||
throw new IOException("Failed Arweave chunk "+(index+1)+"/"+total,last);
|
||||
}
|
||||
private void postJsonExpect2xx(String url,Object body,Duration timeout)throws Exception{
|
||||
HttpRequest req=HttpRequest.newBuilder(URI.create(url)).timeout(timeout).header("Content-Type","application/json").header("Accept","application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofString(MAPPER.writeValueAsString(body),StandardCharsets.UTF_8)).build();
|
||||
HttpResponse<String> resp=http.send(req,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if(resp.statusCode()<200||resp.statusCode()>=300)throw new IOException("HTTP "+resp.statusCode()+" "+safe(resp.body()));
|
||||
}
|
||||
private void verifyBalance(String gateway,String address,String reward)throws Exception{
|
||||
String balance=getRequiredText(gateway,"/wallet/"+address+"/balance");
|
||||
if(balance.matches("^\\d+$")&&new BigInteger(balance).compareTo(new BigInteger(reward))<0)throw new IllegalStateException("Not enough AR: balance="+balance+" reward="+reward);
|
||||
}
|
||||
private String getRequiredText(String gateway,String path)throws Exception{
|
||||
HttpRequest req=HttpRequest.newBuilder(URI.create(gateway+path)).timeout(Duration.ofSeconds(20)).GET().build();
|
||||
HttpResponse<String> resp=http.send(req,HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
if(resp.statusCode()<200||resp.statusCode()>=300)throw new IOException("Arweave HTTP "+resp.statusCode()+" for "+path+": "+safe(resp.body()));
|
||||
String s=resp.body()==null?"":resp.body().trim();if(s.isBlank())throw new IOException("Empty Arweave response for "+path);return s;
|
||||
}
|
||||
private Wallet wallet()throws Exception{
|
||||
Wallet local=wallet;if(local!=null)return local;synchronized(this){if(wallet!=null)return wallet;
|
||||
JsonNode jwk=MAPPER.readTree(Files.readString(cfg.walletJwkPath(),StandardCharsets.UTF_8));String owner=required(jwk,"n");
|
||||
PrivateKey pk=buildPrivateKey(jwk);String address=b64(sha256(b64Decode(owner)));return wallet=new Wallet(owner,address,pk);}
|
||||
}
|
||||
private static PrivateKey buildPrivateKey(JsonNode jwk)throws GeneralSecurityException{
|
||||
RSAPrivateCrtKeySpec spec=new RSAPrivateCrtKeySpec(big(required(jwk,"n")),big(required(jwk,"e")),big(required(jwk,"d")),big(required(jwk,"p")),big(required(jwk,"q")),big(required(jwk,"dp")),big(required(jwk,"dq")),big(required(jwk,"qi")));
|
||||
return KeyFactory.getInstance("RSA").generatePrivate(spec);
|
||||
}
|
||||
private static byte[] signPayload(PrivateKey key,byte[] payload)throws GeneralSecurityException{
|
||||
Signature s=Signature.getInstance("RSASSA-PSS");s.setParameter(new PSSParameterSpec("SHA-256","MGF1",MGF1ParameterSpec.SHA256,32,1));s.initSign(key);s.update(payload);return s.sign();
|
||||
}
|
||||
private static byte[] deepHash(Object data)throws GeneralSecurityException{
|
||||
if(data instanceof List<?> list){byte[] acc=sha384(utf8("list"+list.size()));for(Object item:list)acc=sha384(concat(acc,deepHash(item)));return acc;}
|
||||
if(!(data instanceof byte[] bytes))throw new IllegalArgumentException("deepHash byte[]/List expected");return sha384(concat(sha384(utf8("blob"+bytes.length)),sha384(bytes)));
|
||||
}
|
||||
private static void addTag(List<Map<String,String>> json,List<List<byte[]>> raw,String name,String value){byte[]n=utf8(name),v=utf8(value);Map<String,String>m=new LinkedHashMap<>();m.put("name",b64(n));m.put("value",b64(v));json.add(m);raw.add(List.of(n,v));}
|
||||
private static String required(JsonNode n,String f){String s=n==null?"":n.path(f).asText("").trim();if(s.isBlank())throw new IllegalStateException("Arweave JWK missing "+f);return s;}
|
||||
private static BigInteger big(String s){return new BigInteger(1,b64Decode(s));}
|
||||
private static String trimGateway(String s){return(s==null?"https://arweave.net":s.trim()).replaceAll("/+$","");}
|
||||
private static byte[] utf8(String s){return String.valueOf(s==null?"":s).getBytes(StandardCharsets.UTF_8);}
|
||||
private static byte[] b64Decode(String s){return B64D.decode(s);}private static String b64(byte[]b){return B64.encodeToString(b);}
|
||||
private static byte[] sha256(byte[]b)throws GeneralSecurityException{return MessageDigest.getInstance("SHA-256").digest(b);}private static byte[] sha384(byte[]b)throws GeneralSecurityException{return MessageDigest.getInstance("SHA-384").digest(b);}
|
||||
private static byte[] concat(byte[]...a){int n=0;for(byte[]x:a)n=Math.addExact(n,x.length);byte[]o=new byte[n];int p=0;for(byte[]x:a){System.arraycopy(x,0,o,p,x.length);p+=x.length;}return o;}
|
||||
private static String safe(String s){s=String.valueOf(s==null?"":s).replace('\n',' ').replace('\r',' ').trim();return s.length()<=250?s:s.substring(0,250)+"...";}
|
||||
private record Wallet(String owner,String address,PrivateKey privateKey){}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
package server.archive;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Arweave v2 data Merkle tree/proofs. Алгоритм повторяет arweave-js merkle.ts.
|
||||
*/
|
||||
final class ArweaveMerkle {
|
||||
static final int MAX_CHUNK_SIZE = 256 * 1024;
|
||||
static final int MIN_CHUNK_SIZE = 32 * 1024;
|
||||
|
||||
record Chunk(byte[] dataHash, long minByteRange, long maxByteRange) {
|
||||
long size() { return maxByteRange - minByteRange; }
|
||||
}
|
||||
record Proof(long offset, byte[] proof) {}
|
||||
record Prepared(byte[] dataRoot, List<Chunk> chunks, List<Proof> proofs) {}
|
||||
|
||||
private sealed interface Node permits Leaf, Branch {
|
||||
byte[] id();
|
||||
long maxByteRange();
|
||||
}
|
||||
private record Leaf(byte[] id, byte[] dataHash, long minByteRange, long maxByteRange) implements Node {}
|
||||
private record Branch(byte[] id, long byteRange, long maxByteRange, Node left, Node right) implements Node {}
|
||||
|
||||
private ArweaveMerkle() {}
|
||||
|
||||
|
||||
static Prepared prepare(byte[] data) throws IOException {
|
||||
if (data == null || data.length == 0) throw new IOException("Arweave data is empty");
|
||||
List<Chunk> chunks = chunkBytes(data);
|
||||
List<Node> leaves = new ArrayList<>(chunks.size());
|
||||
for (Chunk c : chunks) {
|
||||
byte[] id = sha256(concat(sha256(c.dataHash()), sha256(note(c.maxByteRange()))));
|
||||
leaves.add(new Leaf(id, c.dataHash(), c.minByteRange(), c.maxByteRange()));
|
||||
}
|
||||
Node root = buildLayers(leaves);
|
||||
List<Proof> proofs = new ArrayList<>();
|
||||
resolveProofs(root, new byte[0], proofs);
|
||||
if (!chunks.isEmpty() && chunks.get(chunks.size() - 1).size() == 0) {
|
||||
chunks = new ArrayList<>(chunks);
|
||||
chunks.remove(chunks.size() - 1);
|
||||
proofs.remove(proofs.size() - 1);
|
||||
}
|
||||
if (chunks.size() != proofs.size()) throw new IOException("Arweave Merkle: chunks/proofs mismatch");
|
||||
return new Prepared(root.id(), List.copyOf(chunks), List.copyOf(proofs));
|
||||
}
|
||||
|
||||
private static List<Chunk> chunkBytes(byte[] data) {
|
||||
List<Chunk> out = new ArrayList<>();
|
||||
long remaining = data.length;
|
||||
long cursor = 0;
|
||||
int p = 0;
|
||||
while (remaining >= MAX_CHUNK_SIZE) {
|
||||
long chunkSize = MAX_CHUNK_SIZE;
|
||||
long next = remaining - MAX_CHUNK_SIZE;
|
||||
if (next > 0 && next < MIN_CHUNK_SIZE) chunkSize = (remaining + 1) / 2;
|
||||
byte[] chunk = Arrays.copyOfRange(data, p, p + (int) chunkSize);
|
||||
out.add(new Chunk(sha256(chunk), cursor, cursor + chunkSize));
|
||||
p += (int) chunkSize;
|
||||
cursor += chunkSize;
|
||||
remaining -= chunkSize;
|
||||
}
|
||||
byte[] rest = Arrays.copyOfRange(data, p, p + (int) remaining);
|
||||
out.add(new Chunk(sha256(rest), cursor, cursor + remaining));
|
||||
return out;
|
||||
}
|
||||
|
||||
static byte[] readChunk(byte[] data, Chunk c) throws IOException {
|
||||
long len = c.size();
|
||||
if (data == null || len < 0 || len > Integer.MAX_VALUE || c.minByteRange() < 0 || c.maxByteRange() > data.length) {
|
||||
throw new IOException("Invalid Arweave chunk range");
|
||||
}
|
||||
return Arrays.copyOfRange(data, (int) c.minByteRange(), (int) c.maxByteRange());
|
||||
}
|
||||
|
||||
static Prepared prepare(Path file) throws IOException {
|
||||
long fileSize = Files.size(file);
|
||||
List<Chunk> chunks = chunkFile(file, fileSize);
|
||||
List<Node> leaves = new ArrayList<>(chunks.size());
|
||||
for (Chunk c : chunks) {
|
||||
byte[] id = sha256(concat(sha256(c.dataHash()), sha256(note(c.maxByteRange()))));
|
||||
leaves.add(new Leaf(id, c.dataHash(), c.minByteRange(), c.maxByteRange()));
|
||||
}
|
||||
if (leaves.isEmpty()) throw new IOException("Arweave Merkle: нет leaves");
|
||||
Node root = buildLayers(leaves);
|
||||
List<Proof> proofs = new ArrayList<>();
|
||||
resolveProofs(root, new byte[0], proofs);
|
||||
|
||||
// arweave-js строит root вместе с нулевым последним chunk при точном кратном 256KiB,
|
||||
// но сам нулевой chunk/proof не загружает.
|
||||
if (!chunks.isEmpty() && chunks.get(chunks.size() - 1).size() == 0) {
|
||||
chunks = new ArrayList<>(chunks);
|
||||
chunks.remove(chunks.size() - 1);
|
||||
proofs.remove(proofs.size() - 1);
|
||||
}
|
||||
if (chunks.size() != proofs.size()) throw new IOException("Arweave Merkle: chunks/proofs mismatch");
|
||||
return new Prepared(root.id(), List.copyOf(chunks), List.copyOf(proofs));
|
||||
}
|
||||
|
||||
private static List<Chunk> chunkFile(Path file, long fileSize) throws IOException {
|
||||
List<Chunk> out = new ArrayList<>();
|
||||
long remaining = fileSize;
|
||||
long cursor = 0;
|
||||
try (InputStream in = new BufferedInputStream(Files.newInputStream(file))) {
|
||||
while (remaining >= MAX_CHUNK_SIZE) {
|
||||
long chunkSize = MAX_CHUNK_SIZE;
|
||||
long next = remaining - MAX_CHUNK_SIZE;
|
||||
if (next > 0 && next < MIN_CHUNK_SIZE) {
|
||||
chunkSize = (remaining + 1) / 2;
|
||||
}
|
||||
byte[] data = readExact(in, (int)chunkSize);
|
||||
out.add(new Chunk(sha256(data), cursor, cursor + chunkSize));
|
||||
cursor += chunkSize;
|
||||
remaining -= chunkSize;
|
||||
}
|
||||
byte[] rest = readExact(in, (int)remaining);
|
||||
out.add(new Chunk(sha256(rest), cursor, cursor + remaining));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Node buildLayers(List<Node> nodes) {
|
||||
if (nodes.size() < 2) return nodes.get(0);
|
||||
List<Node> next = new ArrayList<>((nodes.size() + 1) / 2);
|
||||
for (int i = 0; i < nodes.size(); i += 2) {
|
||||
Node left = nodes.get(i);
|
||||
Node right = i + 1 < nodes.size() ? nodes.get(i + 1) : null;
|
||||
if (right == null) {
|
||||
next.add(left);
|
||||
continue;
|
||||
}
|
||||
long byteRange = left.maxByteRange();
|
||||
byte[] id = sha256(concat(
|
||||
sha256(left.id()),
|
||||
sha256(right.id()),
|
||||
sha256(note(byteRange))
|
||||
));
|
||||
next.add(new Branch(id, byteRange, right.maxByteRange(), left, right));
|
||||
}
|
||||
return buildLayers(next);
|
||||
}
|
||||
|
||||
private static void resolveProofs(Node node, byte[] prefix, List<Proof> out) {
|
||||
if (node instanceof Leaf leaf) {
|
||||
out.add(new Proof(leaf.maxByteRange() - 1,
|
||||
concat(prefix, leaf.dataHash(), note(leaf.maxByteRange()))));
|
||||
return;
|
||||
}
|
||||
Branch b = (Branch) node;
|
||||
byte[] partial = concat(prefix, b.left().id(), b.right().id(), note(b.byteRange()));
|
||||
resolveProofs(b.left(), partial, out);
|
||||
resolveProofs(b.right(), partial, out);
|
||||
}
|
||||
|
||||
static byte[] readChunk(Path file, Chunk c) throws IOException {
|
||||
long len = c.size();
|
||||
if (len < 0 || len > Integer.MAX_VALUE) throw new IOException("Некорректный Arweave chunk size: " + len);
|
||||
try (RandomAccessFile raf = new RandomAccessFile(file.toFile(), "r")) {
|
||||
raf.seek(c.minByteRange());
|
||||
byte[] data = new byte[(int)len];
|
||||
raf.readFully(data);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] readExact(InputStream in, int len) throws IOException {
|
||||
byte[] out = new byte[len];
|
||||
int pos = 0;
|
||||
while (pos < len) {
|
||||
int n = in.read(out, pos, len - pos);
|
||||
if (n < 0) throw new EOFException("Неожиданный EOF");
|
||||
pos += n;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] note(long value) {
|
||||
if (value < 0) throw new IllegalArgumentException("negative note");
|
||||
byte[] out = new byte[32];
|
||||
long v = value;
|
||||
for (int i = 31; i >= 0 && v != 0; i--) {
|
||||
out[i] = (byte)(v & 0xff);
|
||||
v >>>= 8;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static byte[] sha256(byte[] data) {
|
||||
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
|
||||
private static byte[] concat(byte[]... arrays) {
|
||||
int len = 0;
|
||||
for (byte[] a : arrays) len = Math.addExact(len, a.length);
|
||||
byte[] out = new byte[len];
|
||||
int p=0;
|
||||
for (byte[] a : arrays) { System.arraycopy(a,0,out,p,a.length); p+=a.length; }
|
||||
return out;
|
||||
}
|
||||
}
|
||||
+70
@@ -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;
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Duration;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Uploads an already user-signed ANS-104 DataItem to Turbo without modifying it. */
|
||||
public final class TurboDataItemUploader {
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
private static final Base64.Encoder B64URL = Base64.getUrlEncoder().withoutPadding();
|
||||
private static final Base64.Decoder B64URL_DECODER = Base64.getUrlDecoder();
|
||||
|
||||
public record UploadResult(String dataItemId, String owner) {}
|
||||
|
||||
private final ArweaveBlocksConfig cfg;
|
||||
private final HttpClient http = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(20))
|
||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||
.build();
|
||||
private volatile String resolvedPaidByAddress;
|
||||
|
||||
public TurboDataItemUploader(ArweaveBlocksConfig cfg) {
|
||||
this.cfg = Objects.requireNonNull(cfg);
|
||||
}
|
||||
|
||||
public UploadResult upload(byte[] rawDataItem, byte[] expectedId32) throws Exception {
|
||||
if (rawDataItem == null || rawDataItem.length == 0) throw new IllegalArgumentException("Turbo DataItem is empty");
|
||||
Ans104DataItem item = new Ans104DataItem(rawDataItem);
|
||||
if (!item.verifySignature()) throw new IllegalArgumentException("Turbo DataItem has bad ANS-104 signature");
|
||||
if (expectedId32 != null && !Arrays.equals(item.id32(), expectedId32)) {
|
||||
throw new IllegalArgumentException("Turbo DataItem id does not match blocks.data_item_id");
|
||||
}
|
||||
|
||||
String expectedId = B64URL.encodeToString(item.id32());
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(cfg.turboUploadUrl()))
|
||||
.timeout(Duration.ofMinutes(2))
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.header("Accept", "application/json")
|
||||
.POST(HttpRequest.BodyPublishers.ofByteArray(rawDataItem));
|
||||
String paidBy = paidByAddress();
|
||||
if (paidBy != null) request.header("x-paid-by", paidBy);
|
||||
|
||||
HttpResponse<String> response = http.send(request.build(), HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||
String body = response.body() == null ? "" : response.body().trim();
|
||||
if (response.statusCode() == 409 && body.toLowerCase().contains("data item exists")) {
|
||||
return new UploadResult(expectedId, B64URL.encodeToString(item.owner32()));
|
||||
}
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300) {
|
||||
String hint = response.statusCode() == 402
|
||||
? " (Turbo payment required: check server credits / Credit Share Approval / x-paid-by)"
|
||||
: "";
|
||||
throw new IOException("Turbo HTTP " + response.statusCode() + hint + ": " + safe(body));
|
||||
}
|
||||
|
||||
if (body.isBlank()) return new UploadResult(expectedId, B64URL.encodeToString(item.owner32()));
|
||||
JsonNode json;
|
||||
try { json = MAPPER.readTree(body); }
|
||||
catch (Exception ignored) { return new UploadResult(expectedId, B64URL.encodeToString(item.owner32())); }
|
||||
String returnedId = json.path("id").asText("").trim();
|
||||
if (!returnedId.isBlank() && !returnedId.equals(expectedId)) {
|
||||
throw new IOException("Turbo returned another DataItem id: expected=" + expectedId + " got=" + returnedId);
|
||||
}
|
||||
return new UploadResult(expectedId, json.path("owner").asText(""));
|
||||
}
|
||||
|
||||
/**
|
||||
* x-paid-by contains the payer's public native address, never the private key.
|
||||
* A configured Arweave JWK is used only to derive that public address.
|
||||
*/
|
||||
private String paidByAddress() throws Exception {
|
||||
if (resolvedPaidByAddress != null) return resolvedPaidByAddress.isBlank() ? null : resolvedPaidByAddress;
|
||||
synchronized (this) {
|
||||
if (resolvedPaidByAddress != null) return resolvedPaidByAddress.isBlank() ? null : resolvedPaidByAddress;
|
||||
String explicit = cfg.turboPaidByAddress();
|
||||
if (explicit != null && !explicit.isBlank()) return resolvedPaidByAddress = explicit.trim();
|
||||
if (cfg.turboWalletJwkPath() == null) {
|
||||
resolvedPaidByAddress = "";
|
||||
return null;
|
||||
}
|
||||
JsonNode jwk = MAPPER.readTree(Files.readString(cfg.turboWalletJwkPath(), StandardCharsets.UTF_8));
|
||||
String modulus = jwk.path("n").asText("").trim();
|
||||
if (modulus.isBlank()) throw new IllegalStateException("Turbo payer JWK missing n");
|
||||
byte[] owner = B64URL_DECODER.decode(modulus);
|
||||
resolvedPaidByAddress = B64URL.encodeToString(MessageDigest.getInstance("SHA-256").digest(owner));
|
||||
return resolvedPaidByAddress;
|
||||
}
|
||||
}
|
||||
|
||||
private static String safe(String value) {
|
||||
String v = value == null ? "" : value.replace('\n',' ').replace('\r',' ').trim();
|
||||
return v.length() <= 500 ? v : v.substring(0, 500);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashSet;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/** Список разрешённых доменов для бесплатной регистрации; читается при старте Java-сервера. */
|
||||
public final class AllowedEmailDomains {
|
||||
// Обычные ASCII-домены (в том числе punycode), без масок, пробелов и URL.
|
||||
private static final Pattern DOMAIN = Pattern.compile(
|
||||
"(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+");
|
||||
private final Set<String> domains;
|
||||
|
||||
private AllowedEmailDomains(Set<String> domains) {
|
||||
this.domains = Set.copyOf(domains);
|
||||
}
|
||||
|
||||
/** Ошибки чтения, пустой или неверный список — ошибка запуска регистрации (fail-closed). */
|
||||
public static AllowedEmailDomains load(Path file) throws IOException {
|
||||
if (!Files.isRegularFile(file))
|
||||
throw new IOException("Email domain allowlist is missing: " + file.toAbsolutePath());
|
||||
Set<String> result = new HashSet<>();
|
||||
int lineNumber = 0;
|
||||
for (String line : Files.readAllLines(file, StandardCharsets.UTF_8)) {
|
||||
lineNumber++;
|
||||
String domain = line.strip().toLowerCase(Locale.ROOT);
|
||||
if (domain.isEmpty() || domain.startsWith("#")) continue;
|
||||
if (!DOMAIN.matcher(domain).matches())
|
||||
throw new IOException("Invalid allowed email domain at " + file + ":" + lineNumber);
|
||||
result.add(domain);
|
||||
}
|
||||
if (result.isEmpty())
|
||||
throw new IOException("Email domain allowlist is empty: " + file.toAbsolutePath());
|
||||
return new AllowedEmailDomains(result);
|
||||
}
|
||||
|
||||
/** Сопоставление строго по части после одного символа @, без wildcard и суффиксов. */
|
||||
public boolean permits(String email) {
|
||||
if (email == null) return false;
|
||||
String value = email.strip().toLowerCase(Locale.ROOT);
|
||||
int at = value.indexOf('@');
|
||||
if (at <= 0 || at != value.lastIndexOf('@')) return false;
|
||||
return domains.contains(value.substring(at + 1));
|
||||
}
|
||||
}
|
||||
+83
@@ -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();}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import server.archive.ArweaveBlocksConfig;
|
||||
import server.archive.TurboDataItemUploader;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationApiBridge;
|
||||
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||
import shine.db.DbController;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.io.PrintWriter;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.SQLFeatureNotSupportedException;
|
||||
import java.util.Base64;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/** Единственная точка подключения API без циклической зависимости Gradle-модулей. */
|
||||
public final class FreeRegistrationApiBootstrap {
|
||||
private static volatile FreeRegistrationWorkflow workflow;
|
||||
private static volatile LocalRegistrarSigner signer;
|
||||
private static volatile ExternalRegistrar external;
|
||||
public static ExternalRegistrar externalRegistrar() { return external; }
|
||||
private FreeRegistrationApiBootstrap() {}
|
||||
|
||||
public static synchronized void startOrThrow() throws Exception {
|
||||
if (workflow != null) return;
|
||||
AppConfig cfg=AppConfig.getInstance();
|
||||
LocalRegistrarSigner newSigner=null;
|
||||
ExternalRegistrar newExternal=null;
|
||||
FreeRegistrationIssuer issuer=null;
|
||||
FreeRegistrationPublisher publisher=null;
|
||||
RegistrationEmailSender emailSender=null;
|
||||
AllowedEmailDomains allowedEmailDomains=null;
|
||||
String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
|
||||
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
|
||||
if (freeRegistrationEnabled) {
|
||||
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
|
||||
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
|
||||
// Относительный путь — от WorkingDirectory процесса Java.
|
||||
allowedEmailDomains = AllowedEmailDomains.load(Path.of(domainsFile));
|
||||
boolean allowEmailReuse=cfg.getBoolean("freeRegistration.email.allowReuse",false);
|
||||
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
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);
|
||||
FreeRegistrationIssuer.validateConfiguredNamespace(dbSource(), newSigner, freeNamespace,
|
||||
cfg.getStringOrEmpty("server.SHiNE.login"));
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
} else throw new IllegalStateException("Unknown freeRegistration.signerMode");
|
||||
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),
|
||||
new VerifiedFreeRegistrationImporter(allowEmailReuse));
|
||||
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
|
||||
String resendKey=System.getenv("RESEND_API_KEY");
|
||||
if(resendKey==null || resendKey.isBlank())
|
||||
resendKey=cfg.getStringOrEmpty("freeRegistration.email.apiKey");
|
||||
emailSender=new ResendRegistrationEmailSender(resendKey,
|
||||
cfg.getStringOrEmpty("freeRegistration.email.from").isBlank()
|
||||
? "SHiNE <noreply@shineup.me>"
|
||||
: cfg.getStringOrEmpty("freeRegistration.email.from"));
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
|
||||
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
|
||||
freeRegistrationEnabled ? freeNamespace : "");
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; external=newExternal; workflow=newWorkflow;
|
||||
}
|
||||
public static synchronized void close() {
|
||||
RegistrationApiBridge.uninstall();
|
||||
workflow=null;
|
||||
if(signer!=null) signer.close();
|
||||
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 {
|
||||
Map<String,Object> out=new LinkedHashMap<>();
|
||||
switch(op) {
|
||||
case "GetNamespaces" -> {
|
||||
out.put("namespaces",w.listNamespaces().stream().map(ns->Map.of(
|
||||
"name",ns.namespace(), "type",ns.type(), "minLocalLength",ns.minLoginLength(),
|
||||
"registrationFeeLamports",ns.priceLamports(), "currencyCode",ns.currencyCode(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
|
||||
)).toList());
|
||||
}
|
||||
case "CheckRegistrationLogin" -> {
|
||||
var info=w.checkLogin(req.getFullLogin());
|
||||
out.put("loginAvailable",info.loginAvailable());
|
||||
out.put("namespaceType",info.namespaceType());
|
||||
out.put("minLocalLength",info.minLocalLength());
|
||||
out.put("registrationFeeLamports",info.registrationFeeLamports());
|
||||
out.put("currencyCode",info.currencyCode());
|
||||
}
|
||||
case "CheckRegistrationEmail" -> {
|
||||
var check=w.checkEmail(req.getEmail());
|
||||
out.put("emailAvailable",check.emailAvailable());
|
||||
out.put("emailStatus",check.emailStatus());
|
||||
}
|
||||
case "StartFreeRegistration" -> {
|
||||
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
|
||||
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
|
||||
out.put("challengeId",state.challengeId()); out.put("expiresAtMs",state.expiresAtMs());
|
||||
}
|
||||
case "ConfirmFreeRegistration" -> {
|
||||
var value=w.confirm(req.getChallengeId(),req.getCode());
|
||||
out.put("fullLogin",value.fullLogin());out.put("dataItemId",value.dataItemId());
|
||||
out.put("publicationStatus",value.state());out.put("chainConfirmed",false);
|
||||
}
|
||||
case "GetRegistrationStatus" -> {
|
||||
var value=w.getStatus(req.getFullLogin());
|
||||
out.put("registrationStatus",value.status());
|
||||
out.put("dataItemId",value.dataItemId()==null?"":value.dataItemId());
|
||||
out.put("publicationStatus",value.publicationStatus()==null?"":value.publicationStatus());
|
||||
// Публичная историческая часть сертификата для бесплатного → Solana upgrade.
|
||||
if("FREE_CERT".equals(value.status())) {
|
||||
out.put("innerSignature64B64",value.innerSignature64B64()==null?"":value.innerSignature64B64());
|
||||
out.put("rootPublicKey",value.rootPublicKey()==null?"":value.rootPublicKey());
|
||||
out.put("blockchainPublicKey",value.blockchainPublicKey()==null?"":value.blockchainPublicKey());
|
||||
out.put("clientPublicKey",value.clientPublicKey()==null?"":value.clientPublicKey());
|
||||
out.put("defaultServerLogin",value.defaultServerLogin()==null?"":value.defaultServerLogin());
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException("Unknown registration operation");
|
||||
}
|
||||
return out;
|
||||
}
|
||||
private static byte[] decodeKey(String base64) {
|
||||
if(base64==null || base64.length()>64)throw new IllegalArgumentException("Invalid public key");
|
||||
byte[] decoded=Base64.getDecoder().decode(base64);
|
||||
if(decoded.length!=32)throw new IllegalArgumentException("Invalid public key length");
|
||||
return decoded;
|
||||
}
|
||||
private static DataSource dbSource() {
|
||||
return new DataSource() {
|
||||
@Override public Connection getConnection() throws SQLException {return DbController.getInstance().getConnection();}
|
||||
@Override public Connection getConnection(String u,String p) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||
@Override public PrintWriter getLogWriter(){return null;}
|
||||
@Override public void setLogWriter(PrintWriter p){}
|
||||
@Override public void setLoginTimeout(int t){}
|
||||
@Override public int getLoginTimeout(){return 0;}
|
||||
@Override public Logger getParentLogger(){return Logger.getGlobal();}
|
||||
@Override public <T> T unwrap(Class<T> type) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||
@Override public boolean isWrapperFor(Class<?> type){return false;}
|
||||
};
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.ShineProtocolTags;
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.text.Normalizer;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
|
||||
public final class FreeRegistrationCertificateV1 {
|
||||
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
|
||||
private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
|
||||
|
||||
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||
byte[] clientKey, byte[] innerSignature,
|
||||
byte[] emailSha256, byte[] owner32, String idBase64Url) {}
|
||||
|
||||
private FreeRegistrationCertificateV1() {}
|
||||
|
||||
public static String validateLogin(String login) {
|
||||
if (login == null || !login.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
|
||||
throw new IllegalArgumentException("Full login must use ASCII letters (any local-part case), lowercase namespace, <= 30 bytes");
|
||||
return login;
|
||||
}
|
||||
|
||||
public static byte[] identityFields(String login, byte[] root32, byte[] blockchain32, byte[] client32) {
|
||||
byte[] name = validateLogin(login).getBytes(StandardCharsets.UTF_8);
|
||||
require32(root32); require32(blockchain32); require32(client32);
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.write(1); out.write(0); out.write(name.length); out.writeBytes(name);
|
||||
out.writeBytes(root32); out.writeBytes(blockchain32); out.writeBytes(client32);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static byte[] innerMessage(byte[] identity) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
out.writeBytes(DOMAIN); out.writeBytes(identity);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
public static String normalizeEmail(String email) {
|
||||
if (email == null) throw new IllegalArgumentException("Email is required");
|
||||
String value = Normalizer.normalize(email.strip(), Normalizer.Form.NFC).toLowerCase(Locale.ROOT);
|
||||
if (value.isBlank() || value.indexOf('@') < 1 || value.contains(" "))
|
||||
throw new IllegalArgumentException("Invalid email");
|
||||
return value;
|
||||
}
|
||||
|
||||
public static byte[] emailHash(String email) {
|
||||
return sha256(normalizeEmail(email).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email, RegistrarSigner signer) {
|
||||
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[] inner = signer.sign(innerMessage(fields));
|
||||
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
|
||||
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||
payload.writeBytes(fields);
|
||||
payload.writeBytes(inner);
|
||||
payload.writeBytes(emailHash);
|
||||
byte[] data = payload.toByteArray();
|
||||
byte[] owner = signer.publicKey32();
|
||||
require32(owner);
|
||||
byte[] outer = signer.sign(Ans104DataItem.buildSigningMessage(owner, TAGS, data));
|
||||
byte[] raw = Ans104DataItem.serializeEd25519(outer, owner, TAGS, data);
|
||||
verify(raw, owner);
|
||||
return raw;
|
||||
}
|
||||
|
||||
public static Verified verify(byte[] signedDataItem, byte[] registrarPublicKey32) {
|
||||
require32(registrarPublicKey32);
|
||||
Ans104DataItem item = new Ans104DataItem(signedDataItem);
|
||||
if (!item.ownerEquals(registrarPublicKey32) || !item.verifySignature())
|
||||
throw new IllegalArgumentException("Invalid outer ANS-104 registrar signature");
|
||||
if (!item.tags().equals(TAGS) || item.target().length != 0 || item.anchor().length != 0)
|
||||
throw new IllegalArgumentException("Unexpected registration tags/target/anchor");
|
||||
byte[] data = item.data();
|
||||
if (data.length < 3 + 96 + 64 + 32 || data[0] != 1 || data[1] != 0)
|
||||
throw new IllegalArgumentException("Invalid certificate version/length");
|
||||
int len = data[2] & 0xff;
|
||||
if (data.length != 3 + len + 96 + 64 + 32)
|
||||
throw new IllegalArgumentException("Invalid certificate byte length");
|
||||
String login = validateLogin(new String(data, 3, len, StandardCharsets.UTF_8));
|
||||
int offset = 3 + len;
|
||||
byte[] root = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] blockchain = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] client = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||
byte[] innerSig = Arrays.copyOfRange(data, offset, offset+64); offset += 64;
|
||||
byte[] emailSha = Arrays.copyOfRange(data, offset, offset+32);
|
||||
byte[] fields = Arrays.copyOfRange(data, 0, 3 + len + 96);
|
||||
if (!Ed25519Util.verify(innerMessage(fields), innerSig, registrarPublicKey32))
|
||||
throw new IllegalArgumentException("Invalid inner certificate signature");
|
||||
return new Verified(login, root, blockchain, client, innerSig, emailSha,
|
||||
item.owner32(), Base64.getUrlEncoder().withoutPadding().encodeToString(item.id32()));
|
||||
}
|
||||
|
||||
private static void require32(byte[] key) {
|
||||
if (key == null || key.length != 32) throw new IllegalArgumentException("Expected 32-byte public key");
|
||||
}
|
||||
private static byte[] sha256(byte[] data) {
|
||||
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import sync.util.Base58Util;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||
public final class FreeRegistrationIssuer {
|
||||
private final DataSource db;
|
||||
private final RegistrationCertificateSigner signer;
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||
this(db, signer, false);
|
||||
}
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer, boolean allowEmailReuse) {
|
||||
this(db, 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.signer = java.util.Objects.requireNonNull(signer);
|
||||
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. */
|
||||
synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||
byte[] client32, String email) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(fullLogin);
|
||||
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
|
||||
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
|
||||
try (Connection conn = db.getConnection()) {
|
||||
conn.setReadOnly(true);
|
||||
String sql = """
|
||||
SELECT namespace_type, min_localpart_len, registrar_pubkey, default_server_login
|
||||
FROM shine_namespace_current WHERE namespace = ?
|
||||
""";
|
||||
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||
statement.setString(1, namespace);
|
||||
try (ResultSet rs = statement.executeQuery()) {
|
||||
if (!rs.next() || rs.getInt("namespace_type") != 2 ||
|
||||
fullLogin.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||
throw new IllegalArgumentException("Free namespace is unavailable");
|
||||
byte[] nsPub = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (!Arrays.equals(nsPub, signer.publicKey32()))
|
||||
throw new IllegalStateException("Registrar public key does not match on-chain namespace");
|
||||
String server = rs.getString("default_server_login");
|
||||
if (server == null || server.isBlank())
|
||||
throw new IllegalStateException("Free namespace server is not configured");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
|
||||
ps.setString(1, fullLogin.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
if (!allowEmailReuse) {
|
||||
try (PreparedStatement ps = conn.prepareStatement(
|
||||
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||
ps.setBytes(1, expectedEmail);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||
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;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import server.archive.TurboDataItemUploader;
|
||||
import blockchain.Ans104DataItem;
|
||||
|
||||
/** Отдельный транспорт регистрации. Публикация не является пользовательским AddBlock. */
|
||||
public final class FreeRegistrationPublisher {
|
||||
private final FreeRegistrationIssuer issuer;
|
||||
private final TurboDataItemUploader uploader;
|
||||
private final VerifiedFreeRegistrationImporter importer;
|
||||
|
||||
public FreeRegistrationPublisher(FreeRegistrationIssuer issuer, TurboDataItemUploader uploader,
|
||||
VerifiedFreeRegistrationImporter importer) {
|
||||
this.issuer = java.util.Objects.requireNonNull(issuer);
|
||||
this.uploader = java.util.Objects.requireNonNull(uploader);
|
||||
this.importer = java.util.Objects.requireNonNull(importer);
|
||||
}
|
||||
/** Для повтора ПОСЛЕ потери ACK передавайте точно те же signedBytes. */
|
||||
public VerifiedFreeRegistrationImporter.ImportResult publishSigned(byte[] signedBytes) throws Exception {
|
||||
Ans104DataItem parsed = new Ans104DataItem(signedBytes);
|
||||
importer.validateForUpload(signedBytes); // строго до HTTP/Turbo списания кредитов
|
||||
// Импорт на этой точке вызовет полную проверку обеих подписей и namespace
|
||||
// ПОСЛЕ успешного ACK Turbo, а не до окончательного подтверждения Arweave.
|
||||
TurboDataItemUploader.UploadResult acknowledged = uploader.upload(signedBytes, parsed.id32());
|
||||
String expectedId = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(parsed.id32());
|
||||
if (!expectedId.equals(acknowledged.dataItemId()))
|
||||
throw new IllegalStateException("Unexpected Turbo DataItem id");
|
||||
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||
}
|
||||
}
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import shine.db.DbController;
|
||||
import java.security.SecureRandom;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.time.Duration;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.Base64;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/** Внутренний state machine публичных операций регистрации v2. */
|
||||
public final class FreeRegistrationWorkflow {
|
||||
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, int currencyCode, String serverLogin) {}
|
||||
public record Availability(boolean nameFree, boolean emailHashFree) {}
|
||||
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports, int currencyCode) {}
|
||||
public record EmailCheck(boolean emailAvailable, String emailStatus) {}
|
||||
public record Started(String challengeId, long expiresAtMs) {}
|
||||
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
|
||||
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
|
||||
String rootPublicKey, String blockchainPublicKey, String clientPublicKey,
|
||||
String defaultServerLogin) {}
|
||||
|
||||
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
|
||||
long expiresAtMs, byte[] codeHash, int attempts, boolean delivered,
|
||||
boolean verified, byte[] signedBytes) {
|
||||
Draft update(int attempts, boolean delivered, boolean verified, byte[] signedBytes) {
|
||||
return new Draft(login, root, blockchain, client, email, expiresAtMs,
|
||||
codeHash, attempts, delivered, verified, signedBytes);
|
||||
}
|
||||
}
|
||||
private final Map<String, Draft> pending = new ConcurrentHashMap<>();
|
||||
// Не храним в БД почтовые адреса, пока регистрация не завершилась.
|
||||
private final Map<String, Long> recentEmails = new HashMap<>();
|
||||
private final Map<String, Long> recentLogins = new HashMap<>();
|
||||
private final java.util.ArrayDeque<Long> globalSendTimes = new java.util.ArrayDeque<>();
|
||||
private static final long TTL_MS = Duration.ofHours(1).toMillis();
|
||||
private static final long EMAIL_COOLDOWN_MS = Duration.ofMinutes(1).toMillis();
|
||||
private static final long GLOBAL_WINDOW_MS = Duration.ofHours(1).toMillis();
|
||||
private static final int MAX_EMAILS_PER_HOUR = 60;
|
||||
private static final int MAX_ATTEMPTS = 5;
|
||||
private static final int MAX_PENDING = 512;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private final FreeRegistrationIssuer issuer;
|
||||
private final FreeRegistrationPublisher publisher;
|
||||
private final RegistrationEmailSender emailSender;
|
||||
private final boolean allowTestCode;
|
||||
private final boolean allowEmailReuse;
|
||||
private final AllowedEmailDomains allowedEmailDomains;
|
||||
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
|
||||
private final String freeRegistrationNamespace;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
|
||||
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
|
||||
if (emailSender != null && allowedEmailDomains == null)
|
||||
throw new IllegalArgumentException("Allowed email domain list is required");
|
||||
this.allowedEmailDomains = allowedEmailDomains;
|
||||
this.issuer = issuer;
|
||||
this.publisher = publisher;
|
||||
this.emailSender = emailSender;
|
||||
this.allowTestCode = allowTestCode;
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
|
||||
}
|
||||
private static String normalizeConfiguredNamespace(String value) {
|
||||
String namespace = value == null ? "" : value.trim();
|
||||
if (namespace.isEmpty()) return "";
|
||||
if (!namespace.matches("[a-z0-9_]+"))
|
||||
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
|
||||
return namespace;
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
|
||||
emailSender == null ? null : loadDefaultEmailDomains(), "");
|
||||
}
|
||||
private static AllowedEmailDomains loadDefaultEmailDomains() {
|
||||
try {
|
||||
return AllowedEmailDomains.load(java.nio.file.Path.of("allowed-email-domains.txt"));
|
||||
} catch (java.io.IOException e) {
|
||||
throw new IllegalStateException("Cannot load allowed email domains", e);
|
||||
}
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, false);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender) {
|
||||
this(issuer, publisher, emailSender, false);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
|
||||
this(issuer, publisher, null);
|
||||
}
|
||||
public List<NamespaceInfo> listNamespaces() throws Exception {
|
||||
List<NamespaceInfo> result = new ArrayList<>();
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
|
||||
FROM shine_namespace_current
|
||||
WHERE namespace_type = 1 OR (namespace_type = 2 AND namespace = ?)
|
||||
ORDER BY namespace
|
||||
""")) {
|
||||
ps.setString(1, freeRegistrationNamespace);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
while (rs.next()) result.add(new NamespaceInfo(rs.getString(1),rs.getInt(2),rs.getInt(3),
|
||||
rs.getString(4),rs.getInt(5),rs.getString(6)));
|
||||
}
|
||||
}
|
||||
return List.copyOf(result);
|
||||
}
|
||||
public LoginCheck checkLogin(String login) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(login);
|
||||
String namespace=login.substring(login.indexOf('@')+1);
|
||||
try (Connection c=DbController.getInstance().getConnection()) {
|
||||
int type, minimum, currencyCode; String fee;
|
||||
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports,currency_code FROM shine_namespace_current WHERE namespace=?")) {
|
||||
p.setString(1,namespace);
|
||||
try (ResultSet rs=p.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
|
||||
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
|
||||
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
|
||||
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
|
||||
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
|
||||
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
}
|
||||
}
|
||||
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
|
||||
p.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee,currencyCode); }
|
||||
}
|
||||
}
|
||||
}
|
||||
public EmailCheck checkEmail(String email) throws Exception {
|
||||
// До запроса к БД: отсутствие разрешения не должно раскрывать занятость email.
|
||||
String normalizedEmail = FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||
if (allowedEmailDomains == null || !allowedEmailDomains.permits(normalizedEmail))
|
||||
return new EmailCheck(false, "DOMAIN_NOT_ALLOWED");
|
||||
byte[] hash=FreeRegistrationCertificateV1.emailHash(normalizedEmail);
|
||||
if (allowEmailReuse) return new EmailCheck(true, "AVAILABLE");
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
p.setBytes(1,hash);
|
||||
try(ResultSet rs=p.executeQuery()) { return rs.next() ? new EmailCheck(false, "ALREADY_REGISTERED")
|
||||
: new EmailCheck(true, "AVAILABLE"); }
|
||||
}
|
||||
}
|
||||
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
|
||||
public Availability availability(String login,String email) throws Exception {
|
||||
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
|
||||
}
|
||||
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
|
||||
if (issuer == null || publisher == null || emailSender == null)
|
||||
throw new IllegalStateException("Free registration is disabled");
|
||||
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
|
||||
LoginCheck checked = checkLogin(login);
|
||||
if (checked.namespaceType()!=2 || !checked.loginAvailable())
|
||||
throw new IllegalStateException("Login is unavailable");
|
||||
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
|
||||
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||
String normalizedLogin=login.toLowerCase(java.util.Locale.ROOT);
|
||||
byte[] id=new byte[32]; RANDOM.nextBytes(id);
|
||||
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
|
||||
String code=RegistrationEmailCode.generate();
|
||||
long now=System.currentTimeMillis();
|
||||
long expires=now+TTL_MS;
|
||||
Draft draft=new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,
|
||||
expires,RegistrationEmailCode.hash(challenge,code),0,false,false,null);
|
||||
synchronized (this) {
|
||||
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < now);
|
||||
recentEmails.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||
recentLogins.entrySet().removeIf(e->e.getValue() < now-TTL_MS);
|
||||
while(!globalSendTimes.isEmpty() && globalSendTimes.peekFirst() < now-GLOBAL_WINDOW_MS)
|
||||
globalSendTimes.removeFirst();
|
||||
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||
if (now-recentEmails.getOrDefault(cleanEmail,0L) < EMAIL_COOLDOWN_MS ||
|
||||
now-recentLogins.getOrDefault(normalizedLogin,0L) < EMAIL_COOLDOWN_MS)
|
||||
throw new IllegalStateException("Please wait before requesting another code");
|
||||
if (globalSendTimes.size() >= MAX_EMAILS_PER_HOUR)
|
||||
throw new IllegalStateException("Email verification temporarily limited");
|
||||
recentEmails.put(cleanEmail,now);
|
||||
recentLogins.put(normalizedLogin,now);
|
||||
globalSendTimes.addLast(now);
|
||||
pending.put(challenge,draft);
|
||||
}
|
||||
try {
|
||||
// Не блокируем monitor workflow на время HTTP-запроса к Resend.
|
||||
emailSender.sendVerificationCode(cleanEmail,code);
|
||||
} catch (Exception e) {
|
||||
synchronized (this) {
|
||||
pending.remove(challenge);
|
||||
recentEmails.remove(cleanEmail,now);
|
||||
recentLogins.remove(normalizedLogin,now);
|
||||
globalSendTimes.removeFirstOccurrence(now);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
synchronized (this) {
|
||||
// Новый успешно отправленный код заменяет старые заявки на тот же login/email.
|
||||
pending.entrySet().removeIf(e -> !e.getKey().equals(challenge) &&
|
||||
(e.getValue().email.equals(cleanEmail) ||
|
||||
e.getValue().login.equalsIgnoreCase(login)));
|
||||
pending.computeIfPresent(challenge,(key,d)->d.update(d.attempts,true,d.verified,d.signedBytes));
|
||||
}
|
||||
return new Started(challenge,expires);
|
||||
}
|
||||
boolean isValidVerificationCode(byte[] expectedHash, String challenge, String code) {
|
||||
return (allowTestCode && "777777".equals(code))
|
||||
|| RegistrationEmailCode.matches(expectedHash, challenge, code);
|
||||
}
|
||||
|
||||
public synchronized Completed confirm(String challenge, String code) throws Exception {
|
||||
if (publisher == null) throw new IllegalStateException("Free registration disabled");
|
||||
if (challenge == null || challenge.isBlank())
|
||||
throw new IllegalArgumentException("Registration challenge missing");
|
||||
Draft d=pending.get(challenge);
|
||||
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
|
||||
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
|
||||
}
|
||||
if (!d.delivered) throw new IllegalStateException("Verification email is not delivered yet");
|
||||
if (!d.verified) {
|
||||
if (!isValidVerificationCode(d.codeHash, challenge, code)) {
|
||||
if (d.attempts+1 >= MAX_ATTEMPTS) pending.remove(challenge);
|
||||
else pending.put(challenge,d.update(d.attempts+1,true,false,d.signedBytes));
|
||||
throw new IllegalArgumentException("Invalid email code");
|
||||
}
|
||||
// Если Turbo не ответит, подтверждённая заявка может быть повторена до TTL.
|
||||
d=d.update(d.attempts,true,true,d.signedBytes);
|
||||
pending.put(challenge,d);
|
||||
}
|
||||
byte[] signed=d.signedBytes;
|
||||
if(signed==null) {
|
||||
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email);
|
||||
d=d.update(d.attempts,true,true,signed);
|
||||
pending.put(challenge,d);
|
||||
}
|
||||
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
|
||||
// Повтор использует тот же подписанный DataItem, без смены ключей и адреса email.
|
||||
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
|
||||
}
|
||||
public State getStatus(String login) throws Exception {
|
||||
FreeRegistrationCertificateV1.validateLogin(login);
|
||||
try (Connection c=DbController.getInstance().getConnection();
|
||||
PreparedStatement p=c.prepareStatement("""
|
||||
SELECT i.registration_status,i.free_data_item_id,f.publication_status,f.inner_signature,
|
||||
i.root_key,i.blockchain_key,i.client_key,n.default_server_login
|
||||
FROM user_identity_current i
|
||||
LEFT JOIN free_registration_certificate f ON f.data_item_id=i.free_data_item_id
|
||||
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||
WHERE i.normalized_login=?
|
||||
""")) {
|
||||
p.setString(1,login.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet r=p.executeQuery()) {
|
||||
return r.next()?new State(r.getString(1),r.getString(2),r.getString(3),
|
||||
r.getBytes(4)==null?null:Base64.getEncoder().encodeToString(r.getBytes(4)),
|
||||
r.getString(5),r.getString(6),r.getString(7),r.getString(8))
|
||||
:new State("NOT_FOUND",null,null,null,null,null,null,null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import utils.crypto.Ed25519Util;
|
||||
import utils.config.AppConfig;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/** Временный signer. Файл вне Git: одно значение Base64 от 32-байтного Ed25519 seed. */
|
||||
public final class LocalRegistrarSigner implements RegistrarSigner {
|
||||
private final byte[] seed32;
|
||||
private final byte[] publicKey32;
|
||||
private boolean closed;
|
||||
|
||||
public LocalRegistrarSigner(byte[] seed) {
|
||||
if (seed == null || seed.length != 32) throw new IllegalArgumentException("Registrar seed must be 32 bytes");
|
||||
this.seed32 = seed.clone();
|
||||
this.publicKey32 = Ed25519Util.derivePublicKey(seed32);
|
||||
}
|
||||
|
||||
public static LocalRegistrarSigner fromConfig(AppConfig config) throws Exception {
|
||||
if (!config.getBoolean("freeRegistration.enabled", false))
|
||||
throw new IllegalStateException("Free registration is disabled");
|
||||
String path = config.getStringOrEmpty("freeRegistration.registrarSeedFile");
|
||||
if (path.isEmpty()) throw new IllegalStateException("Registrar key path is not configured");
|
||||
byte[] seed = Base64.getDecoder().decode(Files.readString(Path.of(path), StandardCharsets.UTF_8).trim());
|
||||
try { return new LocalRegistrarSigner(seed); }
|
||||
finally { Arrays.fill(seed, (byte) 0); }
|
||||
}
|
||||
|
||||
@Override public synchronized byte[] publicKey32() { return publicKey32.clone(); }
|
||||
@Override public synchronized byte[] sign(byte[] message) {
|
||||
if (closed) throw new IllegalStateException("Signer closed");
|
||||
return Ed25519Util.sign(message, seed32);
|
||||
}
|
||||
@Override public synchronized void close() {
|
||||
Arrays.fill(seed32, (byte) 0);
|
||||
closed = true;
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Интерфейс приватного регистратора: private key не передаётся в бизнес-логику. */
|
||||
public interface RegistrarSigner extends AutoCloseable {
|
||||
byte[] publicKey32();
|
||||
byte[] sign(byte[] message);
|
||||
@Override default void close() {}
|
||||
}
|
||||
+7
@@ -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;
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Одноразовый код не сохраняется в открытом виде и не попадает в журнал. */
|
||||
final class RegistrationEmailCode {
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
private RegistrationEmailCode() {}
|
||||
|
||||
static String generate() {
|
||||
return String.format(java.util.Locale.ROOT, "%06d", RANDOM.nextInt(1_000_000));
|
||||
}
|
||||
|
||||
static byte[] hash(String challengeId, String code) {
|
||||
try {
|
||||
MessageDigest md = MessageDigest.getInstance("SHA-256");
|
||||
return md.digest((challengeId + ":" + code).getBytes(StandardCharsets.UTF_8));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 unavailable", e);
|
||||
}
|
||||
}
|
||||
|
||||
static boolean matches(byte[] expectedHash, String challengeId, String submitted) {
|
||||
return submitted != null && submitted.matches("[0-9]{6}") &&
|
||||
MessageDigest.isEqual(expectedHash, hash(challengeId, submitted));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Отправка кода. Детали внешнего почтового провайдера не влияют на протокол регистрации. */
|
||||
@FunctionalInterface
|
||||
public interface RegistrationEmailSender {
|
||||
void sendVerificationCode(String recipient, String code) throws Exception;
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
|
||||
/** Транзакционная отправка через Resend: HTTP API, без SMTP и внешней Java SDK. */
|
||||
public final class ResendRegistrationEmailSender implements RegistrationEmailSender {
|
||||
private static final URI ENDPOINT = URI.create("https://api.resend.com/emails");
|
||||
private static final String SUBJECT = "SHiNE — код подтверждения email";
|
||||
private final HttpClient client = HttpClient.newBuilder()
|
||||
.connectTimeout(Duration.ofSeconds(5)).build();
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
private final String apiKey;
|
||||
private final String from;
|
||||
|
||||
public ResendRegistrationEmailSender(String apiKey, String from) {
|
||||
if (apiKey == null || apiKey.isBlank())
|
||||
throw new IllegalStateException("Resend API key is required for free registration");
|
||||
if (from == null || from.isBlank())
|
||||
throw new IllegalStateException("Sender email is missing");
|
||||
this.apiKey = apiKey.trim();
|
||||
this.from = from.trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendVerificationCode(String recipient, String code) throws Exception {
|
||||
if (recipient == null || recipient.isBlank() || !code.matches("[0-9]{6}"))
|
||||
throw new IllegalArgumentException("Invalid email verification request");
|
||||
String text = "Добро пожаловать в SHiNE!\n\n"
|
||||
+ "Для завершения регистрации введите код подтверждения:\n\n"
|
||||
+ code + "\n\n"
|
||||
+ "Код действителен в течение 1 часа.\n\n"
|
||||
+ "Если вы не регистрировались в SHiNE, просто проигнорируйте это письмо.\n\n"
|
||||
+ "Команда SHiNE";
|
||||
String html = "<div style=\"font-family:Arial,sans-serif;max-width:520px;margin:auto;"
|
||||
+ "padding:24px;color:#1d2433;line-height:1.6\">"
|
||||
+ "<h2 style=\"margin:0 0 20px\">Добро пожаловать в SHiNE!</h2>"
|
||||
+ "<p>Для завершения регистрации введите код подтверждения:</p>"
|
||||
+ "<p style=\"font-size:32px;font-weight:700;letter-spacing:6px\">" + code + "</p>"
|
||||
+ "<p>Код действителен в течение 1 часа.</p>"
|
||||
+ "<p style=\"color:#5d6470\">Если вы не регистрировались в SHiNE, "
|
||||
+ "просто проигнорируйте это письмо.</p><p>Команда SHiNE</p></div>";
|
||||
String json = mapper.writeValueAsString(Map.of(
|
||||
"from", from, "to", new String[]{recipient}, "subject", SUBJECT,
|
||||
"text", text, "html", html));
|
||||
HttpRequest request = HttpRequest.newBuilder(ENDPOINT)
|
||||
.header("Authorization", "Bearer " + apiKey)
|
||||
.header("Content-Type", "application/json")
|
||||
.timeout(Duration.ofSeconds(12))
|
||||
.POST(HttpRequest.BodyPublishers.ofString(json))
|
||||
.build();
|
||||
// Тело ошибки не выводим: нельзя логировать email или токен провайдера.
|
||||
HttpResponse<Void> response = client.send(request, HttpResponse.BodyHandlers.discarding());
|
||||
if (response.statusCode() < 200 || response.statusCode() >= 300)
|
||||
throw new IllegalStateException("Resend delivery rejected (HTTP " + response.statusCode() + ")");
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import shine.db.DbController;
|
||||
import sync.util.Base58Util;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
/** Только верифицированный сертификат. Локальная БД — проекция Arweave/Solana. */
|
||||
public final class VerifiedFreeRegistrationImporter {
|
||||
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
|
||||
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public VerifiedFreeRegistrationImporter() {
|
||||
this(false);
|
||||
}
|
||||
|
||||
public VerifiedFreeRegistrationImporter(boolean allowEmailReuse) {
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
}
|
||||
|
||||
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
|
||||
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
|
||||
if (raw == null || raw.length < 200 || raw.length > 16_384)
|
||||
throw new IllegalArgumentException("Invalid registration size");
|
||||
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||
String login = extractCanonicalLogin(item);
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
String namespace = login.substring(login.indexOf('@') + 1);
|
||||
var cert = FreeRegistrationCertificateV1.verify(raw, readRegistrar(c, namespace, login));
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT free_data_item_id FROM user_identity_current WHERE normalized_login=?")) {
|
||||
ps.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Login is already registered");
|
||||
}
|
||||
}
|
||||
if (!allowEmailReuse) {
|
||||
try (PreparedStatement ps = c.prepareStatement(
|
||||
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||
ps.setBytes(1, cert.emailSha256());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||
}
|
||||
}
|
||||
}
|
||||
return cert;
|
||||
}
|
||||
}
|
||||
|
||||
/** Единая точка импорта: один и тот же raw ANS-104 из Turbo и Arweave. */
|
||||
public ImportResult importSigned(byte[] raw, Provenance provenance) throws Exception {
|
||||
if (raw == null || raw.length > 16_384 || raw.length < 200)
|
||||
throw new IllegalArgumentException("Invalid registration data item size");
|
||||
// Сначала разбираем/проверяем структурный контейнер, затем сверяем owner с on-chain namespace.
|
||||
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||
String login = extractCanonicalLogin(item);
|
||||
String namespace = login.substring(login.indexOf('@') + 1);
|
||||
try (Connection c = DbController.getInstance().getConnection()) {
|
||||
boolean oldAutoCommit = c.getAutoCommit();
|
||||
c.setAutoCommit(false);
|
||||
try {
|
||||
byte[] registrar = readRegistrar(c, namespace, login);
|
||||
FreeRegistrationCertificateV1.Verified cert = FreeRegistrationCertificateV1.verify(raw, registrar);
|
||||
String id = cert.idBase64Url();
|
||||
String publication = provenance == Provenance.ARWEAVE_CONFIRMED ? "ARWEAVE_CONFIRMED" : "TURBO_ACCEPTED";
|
||||
long now = System.currentTimeMillis();
|
||||
// Защита от коллизий и двойного импорта: имя и email захвачены индексами UNIQUE.
|
||||
try (PreparedStatement check = c.prepareStatement("""
|
||||
SELECT f.raw_signed_data_item, f.publication_status, u.root_key, u.client_key,
|
||||
u.blockchain_key FROM free_registration_certificate f
|
||||
JOIN user_identity_current u ON u.login=f.login
|
||||
WHERE f.data_item_id=? FOR UPDATE OF f
|
||||
""")) {
|
||||
check.setString(1, id);
|
||||
try (ResultSet r = check.executeQuery()) {
|
||||
if (r.next()) {
|
||||
if (!Arrays.equals(raw, r.getBytes(1)))
|
||||
throw new SQLException("DataItem id collision with different raw bytes");
|
||||
if (!r.getString(3).equals(Base58Util.encode(cert.rootKey())) ||
|
||||
!r.getString(4).equals(Base58Util.encode(cert.clientKey())) ||
|
||||
!r.getString(5).equals(Base58Util.encode(cert.blockchainKey())))
|
||||
throw new SQLException("Accepted identity keys conflict with certificate");
|
||||
if (provenance == Provenance.ARWEAVE_CONFIRMED) {
|
||||
try (PreparedStatement up = c.prepareStatement("""
|
||||
UPDATE free_registration_certificate SET publication_status='ARWEAVE_CONFIRMED',last_seen_at_ms=?
|
||||
WHERE data_item_id=?
|
||||
""")) {
|
||||
up.setLong(1, now); up.setString(2, id); up.executeUpdate();
|
||||
}
|
||||
}
|
||||
c.commit();
|
||||
return new ImportResult(login, id, true, provenance);
|
||||
}
|
||||
}
|
||||
}
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
INSERT INTO user_identity_current (
|
||||
login, normalized_login, namespace, registration_source, registration_status,
|
||||
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||
VALUES (?, ?, ?, 'ARWEAVE', 'FREE_CERT', NULL, ?, ?, ?, ?, ?, false, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login); insert.setString(2, login.toLowerCase(java.util.Locale.ROOT)); insert.setString(3, namespace);
|
||||
insert.setString(4, id); insert.setString(5, Base58Util.encode(cert.rootKey()));
|
||||
insert.setString(6, Base58Util.encode(cert.clientKey()));
|
||||
insert.setString(7, Base58Util.encode(cert.blockchainKey()));
|
||||
insert.setString(8, login.toLowerCase(java.util.Locale.ROOT) + "-001"); insert.setLong(9, now); insert.setLong(10, now);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
// blockchain_state — обязательная runtime-проекция новой цепочки.
|
||||
// Без неё первый пользовательский AddBlock (например, «О себе») будет
|
||||
// отклонён ещё до проверки подписи.
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
INSERT INTO blockchain_state_store (
|
||||
login, fork_number, blockchain_key, size_limit, file_size_bytes,
|
||||
last_block_number, last_block_hash, updated_at_ms)
|
||||
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
|
||||
""")) {
|
||||
// blockchain_state — техническая проекция chain: её ключ
|
||||
// совпадает с normalized_login и blockchain_name, а не с
|
||||
// отображаемым написанием login в сертификате.
|
||||
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
|
||||
// как и у пользователей, импортированных из Solana PDA.
|
||||
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
|
||||
insert.setBytes(3, new byte[32]);
|
||||
insert.setLong(4, now);
|
||||
insert.executeUpdate();
|
||||
}
|
||||
try (PreparedStatement insert = c.prepareStatement("""
|
||||
INSERT INTO free_registration_certificate (
|
||||
data_item_id, login, namespace, email_sha256, inner_signature,
|
||||
raw_signed_data_item, publication_status, registered_at_ms, last_seen_at_ms)
|
||||
VALUES (?,?,?,?,?,?,?,?,?)
|
||||
""")) {
|
||||
insert.setString(1, id); insert.setString(2, login); insert.setString(3, namespace);
|
||||
insert.setBytes(4, cert.emailSha256()); insert.setBytes(5, cert.innerSignature());
|
||||
insert.setBytes(6, raw); insert.setString(7, publication);
|
||||
insert.setLong(8, now); insert.setLong(9, now); insert.executeUpdate();
|
||||
}
|
||||
c.commit();
|
||||
return new ImportResult(login, id, false, provenance);
|
||||
} catch (Exception e) {
|
||||
c.rollback(); throw e;
|
||||
} finally { c.setAutoCommit(oldAutoCommit); }
|
||||
}
|
||||
}
|
||||
|
||||
private static String extractCanonicalLogin(blockchain.Ans104DataItem item) {
|
||||
boolean marker = item.tags().contains(new blockchain.Ans104DataItem.Tag("t", "reg"));
|
||||
if (!marker) throw new IllegalArgumentException("Not a registration DataItem");
|
||||
byte[] bytes = item.data();
|
||||
if (bytes.length < 3 || bytes[0] != 1 || bytes[1] != 0) throw new IllegalArgumentException("Bad certificate header");
|
||||
int len = bytes[2] & 0xff;
|
||||
if (len < 3 || len > 30 || bytes.length < 3 + len + 96 + 64 + 32)
|
||||
throw new IllegalArgumentException("Invalid certificate login length");
|
||||
return FreeRegistrationCertificateV1.validateLogin(
|
||||
new String(bytes, 3, len, java.nio.charset.StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static byte[] readRegistrar(Connection c, String namespace, String login) throws Exception {
|
||||
try (PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT registrar_pubkey, min_localpart_len, default_server_login
|
||||
FROM shine_namespace_current WHERE namespace=? AND namespace_type=2
|
||||
""")) {
|
||||
ps.setString(1, namespace);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalStateException("Unknown/free namespace not yet synchronized");
|
||||
if (login.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||
throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
if (rs.getString("default_server_login") == null || rs.getString("default_server_login").isBlank())
|
||||
throw new IllegalArgumentException("Namespace has no access server");
|
||||
byte[] key = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||
if (key.length != 32) throw new IllegalArgumentException("Invalid registrar pubkey");
|
||||
return key;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
|
||||
@@ -0,0 +1,36 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
final class Ans104BundleTest {
|
||||
@Test
|
||||
void writeReadAndFindPreserveExactDataItems() {
|
||||
byte[] a = item("a");
|
||||
byte[] b = item("b");
|
||||
byte[] bundle = Ans104Bundle.write(List.of(a, b));
|
||||
|
||||
List<Ans104Bundle.Entry> entries = Ans104Bundle.read(bundle, 10);
|
||||
assertEquals(2, entries.size());
|
||||
assertArrayEquals(a, entries.get(0).rawDataItem());
|
||||
assertArrayEquals(b, entries.get(1).rawDataItem());
|
||||
|
||||
byte[] bId = new Ans104DataItem(b).id32();
|
||||
assertArrayEquals(b, Ans104Bundle.find(bundle, bId, 10));
|
||||
}
|
||||
|
||||
private static byte[] item(String payload) {
|
||||
byte[] privateKey = Ed25519Util.generatePrivateKeyFromString("bundle-" + payload);
|
||||
byte[] owner = Ed25519Util.derivePublicKey(privateKey);
|
||||
byte[] data = payload.getBytes(StandardCharsets.UTF_8);
|
||||
List<Ans104DataItem.Tag> tags = List.of(new Ans104DataItem.Tag(blockchain.ShineProtocolTags.APP_TAG_NAME, blockchain.ShineProtocolTags.APP_TAG_VALUE));
|
||||
byte[] signature = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, data), privateKey);
|
||||
return Ans104DataItem.serializeEd25519(signature, owner, tags, data);
|
||||
}
|
||||
}
|
||||
+43
@@ -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");
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package server.archive;
|
||||
|
||||
import server.archive.registration.*;
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.ShineProtocolTags;
|
||||
import utils.crypto.Ed25519Util;
|
||||
import java.util.Arrays;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Standalone test (no legacy signed fixture): certificate issue/verify for CURRENT App tag. */
|
||||
public final class FreeRegistrationCertificateV1Check {
|
||||
static final HexFormat HEX = HexFormat.of();
|
||||
public static void main(String[] args) throws Exception {
|
||||
byte[] seed = Ed25519Util.generatePrivateKeyFromString("TEST-only-reg-v1-check");
|
||||
byte[] root = HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8");
|
||||
byte[] chain = HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7");
|
||||
byte[] client = HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d");
|
||||
try (var signer = new LocalRegistrarSigner(seed)) {
|
||||
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
|
||||
" Alice.Example+Tag@Example.COM ", signer);
|
||||
var item = new Ans104DataItem(cert);
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE))
|
||||
throw new AssertionError("Current App tag missing");
|
||||
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|
||||
|| !Arrays.equals(result.blockchainKey(), chain) || !Arrays.equals(result.clientKey(), client))
|
||||
throw new AssertionError("Certificate identity corrupted");
|
||||
if (!Arrays.equals(result.emailSha256(), HEX.parseHex(
|
||||
"cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
|
||||
throw new AssertionError("Email normalization differs");
|
||||
byte[] bad = cert.clone(); bad[bad.length - 1] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||
throw new AssertionError("Email bit flip accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
bad = cert.clone(); bad[bad.length - 40] ^= 1;
|
||||
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||
throw new AssertionError("Inner signature tampering accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
|
||||
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package server.archive;
|
||||
|
||||
import server.archive.registration.*;
|
||||
import javax.sql.DataSource;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/** Только проверки без БД/сети; полное E2E требует PostgreSQL и Turbo. */
|
||||
public final class FreeRegistrationWorkflowLocalCheck {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var signer = new RegistrarSigner() {
|
||||
public byte[] publicKey32() { return new byte[32]; }
|
||||
public byte[] sign(byte[] message) { return new byte[64]; }
|
||||
};
|
||||
DataSource noDb = new DataSource() {
|
||||
public java.sql.Connection getConnection() throws java.sql.SQLException { throw new java.sql.SQLException("No database in local test"); }
|
||||
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException { return getConnection(); }
|
||||
public java.io.PrintWriter getLogWriter() {return null;}
|
||||
public void setLogWriter(java.io.PrintWriter x) {}
|
||||
public void setLoginTimeout(int x) {}
|
||||
public int getLoginTimeout() {return 0;}
|
||||
public java.util.logging.Logger getParentLogger() {return java.util.logging.Logger.getAnonymousLogger();}
|
||||
public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {throw new java.sql.SQLException("unsupported");}
|
||||
public boolean isWrapperFor(Class<?> iface) {return false;}
|
||||
};
|
||||
var issuer = new FreeRegistrationIssuer(noDb, signer);
|
||||
var importer = new VerifiedFreeRegistrationImporter();
|
||||
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(ArweaveBlocksConfig.load()), importer),
|
||||
(email, code) -> { throw new AssertionError("No real email in an offline check"); },
|
||||
false, false, AllowedEmailDomains.load(Files.isRegularFile(Path.of("allowed-email-domains.txt"))
|
||||
? Path.of("allowed-email-domains.txt") : Path.of("../allowed-email-domains.txt")));
|
||||
try { workflow.confirm("unknown", "123456"); throw new AssertionError("Missing challenge accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||
throw new AssertionError("Invalid bytes accepted"); }
|
||||
catch (IllegalArgumentException expected) { }
|
||||
System.out.println("PASS: workflow missing challenge + reject invalid signed bytes");
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.*;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
|
||||
/** Offline tests with real signed fixtures and fake upload/download callbacks (no network). */
|
||||
public final class M4ArchiveBlockPairCheck {
|
||||
private static int checks;
|
||||
private static final HexFormat HEX = HexFormat.of();
|
||||
@FunctionalInterface interface Action { void run() throws Exception; }
|
||||
private static void ok(boolean value) { checks++; if (!value) throw new AssertionError("check " + checks); }
|
||||
private static void reject(Class<? extends Exception> type, Action action) throws Exception {
|
||||
try { action.run(); } catch (Exception e) { ok(type.isInstance(e)); return; }
|
||||
throw new AssertionError("Expected " + type);
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
var lines = Files.readAllLines(Path.of(args[0]));
|
||||
for (String line : lines.subList(1, lines.size())) {
|
||||
String[] v = line.split("\t");
|
||||
byte[] core = HEX.parseHex(v[6]), content = HEX.parseHex(v[8]);
|
||||
byte[] coreId = new Ans104DataItem(core).id32(), contentId = new Ans104DataItem(content).id32();
|
||||
byte[] pair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(content));
|
||||
List<byte[]> sent = new ArrayList<>();
|
||||
var ack = ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
ok(Arrays.equals(new Ans104DataItem(raw).id32(), id)); sent.add(raw); return HEX.formatHex(id);
|
||||
});
|
||||
ok(sent.size() == 2); ok(Arrays.equals(sent.get(0), content)); ok(Arrays.equals(sent.get(1), core));
|
||||
ok(ack.equals(HEX.formatHex(coreId)));
|
||||
sent.clear();
|
||||
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
sent.add(raw); throw new IOException("CONTENT not accepted");
|
||||
}));
|
||||
ok(sent.size() == 1); ok(Arrays.equals(sent.get(0), content));
|
||||
sent.clear();
|
||||
reject(IOException.class, () -> ArchiveBlockPair.publish(pair, coreId, (raw, id) -> {
|
||||
sent.add(raw); if (Arrays.equals(id, coreId)) throw new IOException("CORE not accepted"); return null;
|
||||
}));
|
||||
ok(sent.size() == 2);
|
||||
ArchiveBlockPair.publish(pair, coreId, (raw, id) -> { sent.add(raw); return null; });
|
||||
ok(sent.size() == 4); ok(Arrays.equals(sent.get(0), sent.get(2))); ok(Arrays.equals(sent.get(1), sent.get(3)));
|
||||
byte[] restored = ArchiveBlockPair.download(core, coreId, id -> { ok(Arrays.equals(id, contentId)); return content; });
|
||||
ok(Arrays.equals(restored, pair));
|
||||
reject(IOException.class, () -> ArchiveBlockPair.download(core, coreId, id -> { throw new IOException("CONTENT not visible yet"); }));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> core));
|
||||
byte[] damaged = content.clone(); damaged[damaged.length - 1] ^= 1;
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, coreId, id -> damaged));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.download(core, contentId, id -> { throw new AssertionError("Unverified CORE requested CONTENT"); }));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(pair, contentId, (raw,id) -> { throw new AssertionError("Wrong CORE published"); }));
|
||||
byte[] badPair = CoreContentContainer.pack(new Ans104DataItem(core), new Ans104DataItem(damaged));
|
||||
reject(IllegalArgumentException.class, () -> ArchiveBlockPair.publish(badPair, coreId, (raw,id) -> { throw new AssertionError("Invalid CONTENT published"); }));
|
||||
}
|
||||
System.out.println("PASS: " + checks + " archive pair checks (order, exact retry, missing CONTENT, wrong ID, signature/hash)");
|
||||
}
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Самостоятельный офлайн-тест: javac AllowedEmailDomains.java AllowedEmailDomainsCheck.java + java. */
|
||||
public final class AllowedEmailDomainsCheck {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Path dir = Files.createTempDirectory("shine-email-domains-test-");
|
||||
try {
|
||||
Path file = dir.resolve("allowed-email-domains.txt");
|
||||
Files.writeString(file, "# Test\n Gmail.com \nproton.me\n\n", StandardCharsets.UTF_8);
|
||||
AllowedEmailDomains allowed = AllowedEmailDomains.load(file);
|
||||
expect(allowed.permits("User@GMAIL.COM"), "case insensitive match");
|
||||
expect(allowed.permits(" user@proton.me "), "trimmed match");
|
||||
expect(!allowed.permits("user@gmail.com.evil.org"), "suffix bypass");
|
||||
expect(!allowed.permits("user@sub.gmail.com"), "subdomain bypass");
|
||||
expect(!allowed.permits("user@other.com"), "unknown domain");
|
||||
expect(!allowed.permits("user@@gmail.com"), "invalid multiple @");
|
||||
expect(!allowed.permits("@gmail.com"), "missing local part");
|
||||
expect(!allowed.permits(null), "null address");
|
||||
Files.writeString(file, "# no domains\n \n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "empty file");
|
||||
Files.writeString(file, "*.gmail.com\n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "wildcard not allowed");
|
||||
Files.writeString(file, "gmail.com\ninvalid_domain\n", StandardCharsets.UTF_8);
|
||||
expectLoadFailure(file, "invalid line not ignored");
|
||||
Files.delete(file);
|
||||
expectLoadFailure(file, "missing file");
|
||||
System.out.println("PASS: allowed email domains, strict matching, fail-closed");
|
||||
} finally {
|
||||
try (var files = Files.list(dir)) { files.forEach(path -> {try {Files.deleteIfExists(path);}catch(Exception ex){throw new RuntimeException(ex);}}); }
|
||||
Files.deleteIfExists(dir);
|
||||
}
|
||||
}
|
||||
|
||||
private static void expect(boolean condition, String scenario) {
|
||||
if (!condition) throw new AssertionError(scenario);
|
||||
}
|
||||
private static void expectLoadFailure(Path file, String scenario) throws Exception {
|
||||
try {
|
||||
AllowedEmailDomains.load(file);
|
||||
throw new AssertionError("Invalid allowlist accepted: " + scenario);
|
||||
} catch (java.io.IOException expected) { }
|
||||
}
|
||||
}
|
||||
+22
@@ -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";
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package server.archive.registration;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
class FreeRegistrationNamespaceConfigurationTest {
|
||||
@Test
|
||||
void acceptsLowercaseNamespaceForLocalFreeRegistration() {
|
||||
assertDoesNotThrow(() -> new FreeRegistrationWorkflow(
|
||||
null, null, null, false, false, null, "testfree"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMixedCaseNamespaceInsteadOfSilentlyServingAnotherNamespace() {
|
||||
assertThrows(IllegalArgumentException.class, () -> new FreeRegistrationWorkflow(
|
||||
null, null, null, false, false, null, "TestFree"));
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Локальная проверка генератора и сверки кода без БД/HTTP. */
|
||||
public final class RegistrationEmailCodeCheck {
|
||||
public static void main(String[] args) {
|
||||
for (int i=0; i<1000; ++i) {
|
||||
String code = RegistrationEmailCode.generate();
|
||||
if (!code.matches("[0-9]{6}")) throw new AssertionError("Wrong length");
|
||||
byte[] hash = RegistrationEmailCode.hash("challenge-id", code);
|
||||
if (!RegistrationEmailCode.matches(hash, "challenge-id", code)) throw new AssertionError("Cannot verify");
|
||||
if (RegistrationEmailCode.matches(hash, "another-challenge", code)) throw new AssertionError("Challenge replay");
|
||||
if (RegistrationEmailCode.matches(hash, "challenge-id", "1111")) throw new AssertionError("Old demo code accepted");
|
||||
if (RegistrationEmailCode.matches(hash, "challenge-id", "bad")) throw new AssertionError("Bad code accepted");
|
||||
}
|
||||
System.out.println("PASS: email code generation and challenge binding");
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package server.archive.registration;
|
||||
|
||||
/** Offline проверка часового TTL на уровне UX отдельно; bypass должен быть строго opt-in. */
|
||||
public final class RegistrationEmailSettingsCheck {
|
||||
public static void main(String[] args) {
|
||||
byte[] digest = RegistrationEmailCode.hash("challenge", "123456");
|
||||
var safe = new FreeRegistrationWorkflow(null, null, null, false);
|
||||
var test = new FreeRegistrationWorkflow(null, null, null, true);
|
||||
if (safe.isValidVerificationCode(digest, "challenge", "777777"))
|
||||
throw new AssertionError("Cheat unexpectedly enabled by default");
|
||||
if (!test.isValidVerificationCode(digest, "challenge", "777777"))
|
||||
throw new AssertionError("Explicit test code not accepted");
|
||||
if (!safe.isValidVerificationCode(digest, "challenge", "123456"))
|
||||
throw new AssertionError("Real code rejected");
|
||||
if (test.isValidVerificationCode(digest, "challenge", "1111"))
|
||||
throw new AssertionError("Old demo code unexpectedly accepted");
|
||||
if (test.isValidVerificationCode(digest, "challenge", "777778"))
|
||||
throw new AssertionError("Invalid code unexpectedly accepted");
|
||||
System.out.println("PASS: real code and opt-in test code");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
package blockchain;
|
||||
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Minimal ANS-104 DataItem parser/verifier used by SHiNE.
|
||||
*
|
||||
* SHiNE accepts only generic Ed25519 signature type 2:
|
||||
* uint16le signatureType
|
||||
* signature[64]
|
||||
* owner[32]
|
||||
* target_present[1] + target[32] when present
|
||||
* anchor_present[1] + anchor[32] when present
|
||||
* tags_count uint64le
|
||||
* tags_size uint64le
|
||||
* avro_tags[tags_size]
|
||||
* data[*]
|
||||
*
|
||||
* The signing message matches the deployed arbundles/Turbo DataItem implementation:
|
||||
* deepHash(["dataitem", "1", signatureType, owner, target, anchor, rawAvroTags, data]).
|
||||
*/
|
||||
public final class Ans104DataItem {
|
||||
public static final int SIGNATURE_TYPE_ED25519 = 2;
|
||||
public static final int SIGNATURE_LEN = 64;
|
||||
public static final int OWNER_LEN = 32;
|
||||
public static final int OPTIONAL_FIELD_LEN = 32;
|
||||
public static final int ID_LEN = 32;
|
||||
public static final int MAX_DATA_ITEM_BYTES = 8 * 1024 * 1024;
|
||||
public static final int MAX_TAGS_BYTES = 64 * 1024;
|
||||
public static final long MAX_TAGS_COUNT = 128;
|
||||
|
||||
public record Tag(String name, String value) {}
|
||||
|
||||
private final int signatureType;
|
||||
private final byte[] signature;
|
||||
private final byte[] owner;
|
||||
private final byte[] target;
|
||||
private final byte[] anchor;
|
||||
private final long tagsCount;
|
||||
private final byte[] rawTags;
|
||||
private final List<Tag> tags;
|
||||
private final byte[] data;
|
||||
private final byte[] rawBytes;
|
||||
private final byte[] id;
|
||||
|
||||
public Ans104DataItem(byte[] bytes) {
|
||||
Objects.requireNonNull(bytes, "bytes == null");
|
||||
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8) {
|
||||
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
|
||||
}
|
||||
if (bytes.length > MAX_DATA_ITEM_BYTES) {
|
||||
throw new IllegalArgumentException("ANS-104 DataItem too large: " + bytes.length);
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
||||
this.signatureType = Short.toUnsignedInt(bb.getShort());
|
||||
if (signatureType != SIGNATURE_TYPE_ED25519) {
|
||||
throw new IllegalArgumentException("Unsupported ANS-104 signature type: " + signatureType + " (expected 2)");
|
||||
}
|
||||
|
||||
this.signature = readExact(bb, SIGNATURE_LEN, "signature");
|
||||
this.owner = readExact(bb, OWNER_LEN, "owner");
|
||||
this.target = readOptional32(bb, "target");
|
||||
this.anchor = readOptional32(bb, "anchor");
|
||||
|
||||
this.tagsCount = readUnsignedLongAsNonNegative(bb, "tags_count");
|
||||
long tagsSizeLong = readUnsignedLongAsNonNegative(bb, "tags_size");
|
||||
if (tagsCount > MAX_TAGS_COUNT) {
|
||||
throw new IllegalArgumentException("Too many ANS-104 tags: " + tagsCount);
|
||||
}
|
||||
if (tagsSizeLong > MAX_TAGS_BYTES || tagsSizeLong > bb.remaining()) {
|
||||
throw new IllegalArgumentException("Bad ANS-104 tags_size: " + tagsSizeLong + ", remaining=" + bb.remaining());
|
||||
}
|
||||
this.rawTags = readExact(bb, (int) tagsSizeLong, "tags");
|
||||
this.tags = Collections.unmodifiableList(parseAvroTags(rawTags, tagsCount));
|
||||
this.data = new byte[bb.remaining()];
|
||||
bb.get(this.data);
|
||||
this.rawBytes = Arrays.copyOf(bytes, bytes.length);
|
||||
this.id = sha256(signature);
|
||||
}
|
||||
|
||||
public int signatureType() { return signatureType; }
|
||||
public byte[] signature64() { return Arrays.copyOf(signature, signature.length); }
|
||||
public byte[] owner32() { return Arrays.copyOf(owner, owner.length); }
|
||||
public byte[] target() { return Arrays.copyOf(target, target.length); }
|
||||
public byte[] anchor() { return Arrays.copyOf(anchor, anchor.length); }
|
||||
public long tagsCount() { return tagsCount; }
|
||||
public byte[] rawTags() { return Arrays.copyOf(rawTags, rawTags.length); }
|
||||
public List<Tag> tags() { return tags; }
|
||||
public byte[] data() { return Arrays.copyOf(data, data.length); }
|
||||
public byte[] rawBytes() { return Arrays.copyOf(rawBytes, rawBytes.length); }
|
||||
public byte[] id32() { return Arrays.copyOf(id, id.length); }
|
||||
|
||||
public String tagValue(String name) {
|
||||
if (name == null) return null;
|
||||
for (Tag tag : tags) {
|
||||
if (name.equals(tag.name())) return tag.value();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public boolean hasTag(String name, String value) {
|
||||
for (Tag tag : tags) {
|
||||
if (Objects.equals(name, tag.name()) && Objects.equals(value, tag.value())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public boolean verifySignature() {
|
||||
return Ed25519Util.verify(signingMessage(), signature, owner);
|
||||
}
|
||||
|
||||
public boolean ownerEquals(byte[] expectedOwner32) {
|
||||
return expectedOwner32 != null && expectedOwner32.length == OWNER_LEN && Arrays.equals(owner, expectedOwner32);
|
||||
}
|
||||
|
||||
public byte[] signingMessage() {
|
||||
// Проверяем именно подписанные исходные байты, не повторную Avro-сериализацию.
|
||||
return signingMessageRaw(owner, target, anchor, rawTags, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the exact ANS-104 signing message for generic Ed25519 DataItems.
|
||||
* Useful for SHiNE clients/tests that must sign a DataItem before serializing it.
|
||||
*/
|
||||
public static byte[] buildSigningMessage(byte[] owner32, List<Tag> tags, byte[] data) {
|
||||
return buildSigningMessage(owner32, new byte[0], new byte[0], tags, data);
|
||||
}
|
||||
|
||||
public static byte[] buildSigningMessage(byte[] owner32, byte[] target, byte[] anchor, List<Tag> tags, byte[] data) {
|
||||
requireLen(owner32, OWNER_LEN, "owner");
|
||||
byte[] safeTarget = target == null ? new byte[0] : Arrays.copyOf(target, target.length);
|
||||
byte[] safeAnchor = anchor == null ? new byte[0] : Arrays.copyOf(anchor, anchor.length);
|
||||
if (!(safeTarget.length == 0 || safeTarget.length == OPTIONAL_FIELD_LEN)) {
|
||||
throw new IllegalArgumentException("target must be empty or 32 bytes");
|
||||
}
|
||||
if (!(safeAnchor.length == 0 || safeAnchor.length == OPTIONAL_FIELD_LEN)) {
|
||||
throw new IllegalArgumentException("anchor must be empty or 32 bytes");
|
||||
}
|
||||
List<Tag> safeTags = validateTags(tags);
|
||||
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
|
||||
|
||||
byte[] rawTags = serializeAvroTags(safeTags);
|
||||
return signingMessageRaw(owner32, safeTarget, safeAnchor, rawTags, safeData);
|
||||
}
|
||||
|
||||
private static byte[] signingMessageRaw(byte[] owner32, byte[] safeTarget, byte[] safeAnchor, byte[] rawTags, byte[] safeData) {
|
||||
return deepHash(List.of(
|
||||
utf8("dataitem"),
|
||||
utf8("1"),
|
||||
utf8(Integer.toString(SIGNATURE_TYPE_ED25519)),
|
||||
Arrays.copyOf(owner32, owner32.length),
|
||||
safeTarget,
|
||||
safeAnchor,
|
||||
rawTags,
|
||||
safeData
|
||||
));
|
||||
}
|
||||
|
||||
/** Serialize one SHiNE-ready ANS-104 DataItem with empty target/anchor. */
|
||||
public static byte[] serializeEd25519(byte[] signature64, byte[] owner32, List<Tag> tags, byte[] data) {
|
||||
requireLen(signature64, SIGNATURE_LEN, "signature");
|
||||
requireLen(owner32, OWNER_LEN, "owner");
|
||||
List<Tag> safeTags = validateTags(tags);
|
||||
byte[] rawTags = serializeAvroTags(safeTags);
|
||||
byte[] safeData = data == null ? new byte[0] : data;
|
||||
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(
|
||||
2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + rawTags.length + safeData.length);
|
||||
writeU16LE(out, SIGNATURE_TYPE_ED25519);
|
||||
out.writeBytes(signature64);
|
||||
out.writeBytes(owner32);
|
||||
out.write(0); // target absent
|
||||
out.write(0); // anchor absent
|
||||
writeU64LE(out, safeTags.size());
|
||||
writeU64LE(out, rawTags.length);
|
||||
out.writeBytes(rawTags);
|
||||
out.writeBytes(safeData);
|
||||
return out.toByteArray();
|
||||
}
|
||||
|
||||
private static byte[] readOptional32(ByteBuffer bb, String name) {
|
||||
if (!bb.hasRemaining()) throw new IllegalArgumentException("Missing " + name + " presence byte");
|
||||
int present = Byte.toUnsignedInt(bb.get());
|
||||
if (present == 0) return new byte[0];
|
||||
if (present != 1) throw new IllegalArgumentException("Bad " + name + " presence byte: " + present);
|
||||
return readExact(bb, OPTIONAL_FIELD_LEN, name);
|
||||
}
|
||||
|
||||
private static byte[] readExact(ByteBuffer bb, int len, String field) {
|
||||
if (len < 0 || bb.remaining() < len) {
|
||||
throw new IllegalArgumentException("ANS-104 " + field + " truncated: need=" + len + " remaining=" + bb.remaining());
|
||||
}
|
||||
byte[] out = new byte[len];
|
||||
bb.get(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
private static long readUnsignedLongAsNonNegative(ByteBuffer bb, String field) {
|
||||
if (bb.remaining() < 8) throw new IllegalArgumentException("Missing ANS-104 " + field);
|
||||
long v = bb.getLong();
|
||||
if (v < 0) throw new IllegalArgumentException("ANS-104 " + field + " exceeds signed long range");
|
||||
return v;
|
||||
}
|
||||
|
||||
private static List<Tag> validateTags(List<Tag> tags) {
|
||||
List<Tag> safe = tags == null ? List.of() : List.copyOf(tags);
|
||||
if (safe.size() > MAX_TAGS_COUNT) {
|
||||
throw new IllegalArgumentException("Too many ANS-104 tags: " + safe.size());
|
||||
}
|
||||
for (Tag tag : safe) {
|
||||
if (tag == null || tag.name() == null || tag.value() == null || tag.name().isEmpty() || tag.value().isEmpty()) {
|
||||
throw new IllegalArgumentException("ANS-104 tag name/value must be non-empty");
|
||||
}
|
||||
if (utf8(tag.name()).length > 1024) throw new IllegalArgumentException("ANS-104 tag name exceeds 1024 bytes");
|
||||
if (utf8(tag.value()).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
private static byte[] serializeAvroTags(List<Tag> tags) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
if (!tags.isEmpty()) {
|
||||
writeAvroLong(out, tags.size());
|
||||
for (Tag tag : tags) {
|
||||
writeAvroString(out, tag.name());
|
||||
writeAvroString(out, tag.value());
|
||||
}
|
||||
}
|
||||
writeAvroLong(out, 0); // array terminator; also the complete encoding for an empty array
|
||||
byte[] raw = out.toByteArray();
|
||||
if (raw.length > MAX_TAGS_BYTES) throw new IllegalArgumentException("ANS-104 tags exceed " + MAX_TAGS_BYTES + " bytes");
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static void writeAvroString(ByteArrayOutputStream out, String value) {
|
||||
byte[] bytes = utf8(value);
|
||||
writeAvroLong(out, bytes.length);
|
||||
out.writeBytes(bytes);
|
||||
}
|
||||
|
||||
private static void writeAvroLong(ByteArrayOutputStream out, long value) {
|
||||
long n = (value << 1) ^ (value >> 63);
|
||||
while ((n & ~0x7fL) != 0) {
|
||||
out.write((int) ((n & 0x7f) | 0x80));
|
||||
n >>>= 7;
|
||||
}
|
||||
out.write((int) n);
|
||||
}
|
||||
|
||||
private static void writeU16LE(ByteArrayOutputStream out, int value) {
|
||||
out.write(value & 0xff);
|
||||
out.write((value >>> 8) & 0xff);
|
||||
}
|
||||
|
||||
private static void writeU64LE(ByteArrayOutputStream out, long value) {
|
||||
for (int i = 0; i < 8; i++) out.write((int) ((value >>> (8 * i)) & 0xff));
|
||||
}
|
||||
|
||||
private static void requireLen(byte[] bytes, int expected, String name) {
|
||||
if (bytes == null || bytes.length != expected) {
|
||||
throw new IllegalArgumentException(name + " must be " + expected + " bytes");
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
|
||||
if (raw.length == 0 && declaredCount == 0) return List.of();
|
||||
AvroCursor c = new AvroCursor(raw);
|
||||
List<Tag> out = new ArrayList<>();
|
||||
boolean terminated = false;
|
||||
while (!c.eof()) {
|
||||
long count = c.readLong();
|
||||
if (count == 0) { terminated = true; break; }
|
||||
int blockEnd = -1;
|
||||
if (count < 0) {
|
||||
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
|
||||
count = -count;
|
||||
long blockBytes = c.readLong();
|
||||
if (blockBytes < 0 || blockBytes > raw.length - c.p) throw new IllegalArgumentException("Invalid Avro tag block size");
|
||||
blockEnd = c.p + (int) blockBytes;
|
||||
}
|
||||
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
|
||||
throw new IllegalArgumentException("Too many Avro tags");
|
||||
}
|
||||
for (long i = 0; i < count; i++) {
|
||||
String name = c.readString();
|
||||
String value = c.readString();
|
||||
if (name.isEmpty() || value.isEmpty()) throw new IllegalArgumentException("ANS-104 tag name/value must be non-empty");
|
||||
if (name.getBytes(StandardCharsets.UTF_8).length > 1024) throw new IllegalArgumentException("ANS-104 tag name exceeds 1024 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));
|
||||
}
|
||||
if (blockEnd != -1 && c.p != blockEnd) throw new IllegalArgumentException("Avro tag block size mismatch");
|
||||
}
|
||||
if (!terminated) throw new IllegalArgumentException("Missing Avro array terminator");
|
||||
if (!c.eof()) {
|
||||
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
|
||||
}
|
||||
if (out.size() != declaredCount) {
|
||||
throw new IllegalArgumentException("ANS-104 tags_count mismatch: declared=" + declaredCount + " parsed=" + out.size());
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static final class AvroCursor {
|
||||
private final byte[] data;
|
||||
private int p;
|
||||
private AvroCursor(byte[] data) { this.data = data == null ? new byte[0] : data; }
|
||||
boolean eof() { return p == data.length; }
|
||||
long readLong() {
|
||||
long raw = 0;
|
||||
int shift = 0;
|
||||
while (true) {
|
||||
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
|
||||
int b = data[p++] & 0xff;
|
||||
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
|
||||
raw |= (long) (b & 0x7f) << shift;
|
||||
if ((b & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
if (shift > 63) throw new IllegalArgumentException("Avro long too large");
|
||||
}
|
||||
return (raw >>> 1) ^ -(raw & 1L);
|
||||
}
|
||||
String readString() {
|
||||
long len = readLong();
|
||||
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
|
||||
throw new IllegalArgumentException("Bad Avro string length: " + len);
|
||||
}
|
||||
String s;
|
||||
try { s = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data, p, (int) len)).toString(); }
|
||||
catch (java.nio.charset.CharacterCodingException e) { throw new IllegalArgumentException("Invalid UTF-8 Avro tag", e); }
|
||||
p += (int) len;
|
||||
return s;
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] deepHash(Object item) {
|
||||
if (item instanceof byte[] bytes) {
|
||||
return deepHashBlob(bytes);
|
||||
}
|
||||
if (item instanceof List<?> items) {
|
||||
byte[] acc = sha384(utf8("list" + items.size()));
|
||||
for (Object child : items) {
|
||||
acc = sha384(concat(acc, deepHash(child)));
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
throw new IllegalArgumentException("Unsupported deepHash item: " + (item == null ? "null" : item.getClass()));
|
||||
}
|
||||
|
||||
private static byte[] deepHashBlob(byte[] bytes) {
|
||||
byte[] tag = utf8("blob" + bytes.length);
|
||||
return sha384(concat(sha384(tag), sha384(bytes)));
|
||||
}
|
||||
|
||||
private static byte[] utf8(String s) { return s.getBytes(StandardCharsets.UTF_8); }
|
||||
private static byte[] sha256(byte[] b) { return digest("SHA-256", b); }
|
||||
private static byte[] sha384(byte[] b) { return digest("SHA-384", b); }
|
||||
private static byte[] digest(String alg, byte[] b) {
|
||||
try { return MessageDigest.getInstance(alg).digest(b); }
|
||||
catch (Exception e) { throw new IllegalStateException(alg + " unavailable", e); }
|
||||
}
|
||||
private static byte[] concat(byte[] a, byte[] b) {
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream(a.length + b.length);
|
||||
out.writeBytes(a); out.writeBytes(b); return out.toByteArray();
|
||||
}
|
||||
}
|
||||
+120
-308
@@ -9,363 +9,175 @@ import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* BchBlockEntry — универсальный блок формата SHiNE (Frame v0).
|
||||
* SHiNE user block, Frame v1, carried as the data payload of an ANS-104 DataItem.
|
||||
*
|
||||
* =========================================================================
|
||||
* FRAME v0 — ФИКСИРОВАННЫЙ ФОРМАТ БЛОКА (ДОКУМЕНТ ПРОТОКОЛА)
|
||||
* =========================================================================
|
||||
* The constructor accepts the complete serialized ANS-104 DataItem because this is
|
||||
* exactly what is stored in PostgreSQL and exchanged between servers.
|
||||
*
|
||||
* Все числа BigEndian.
|
||||
* SHiNE Frame v1 (all integer fields BigEndian):
|
||||
* [2] frameCode = 0x0001
|
||||
* [32] prevHash32 = SHA-256(Frame v1 bytes of previous SHiNE block)
|
||||
* [32] back32Hash32 = SHA-256(Frame v1 bytes of block N-32), or zero for N<32
|
||||
* [4] blockSize = exact Frame v1 byte length
|
||||
* [4] blockNumber
|
||||
* [8] timestamp unix seconds
|
||||
* [2] type
|
||||
* [2] subType
|
||||
* [2] version
|
||||
* [N] bodyBytes
|
||||
*
|
||||
* PREIMAGE (входит в blockSize, подписывается):
|
||||
* [2] frameCode (uint16) код/версия рамки:
|
||||
* - 0x0000 = Frame v0 (текущий)
|
||||
* [32] prevHash32 (bytes) SHA-256(preimage) предыдущего блока (цепочка)
|
||||
* [4] blockSize (int32) размер preimage (в байтах), ВКЛЮЧАЯ frameCode,
|
||||
* НО БЕЗ sigMarker и БЕЗ signature64
|
||||
* [4] blockNumber (int32) глобальный номер блока (>=0)
|
||||
* [8] timestamp (int64) unix seconds
|
||||
* [2] type (uint16) тип сообщения
|
||||
* [2] subType (uint16) подтип сообщения
|
||||
* [2] version (uint16) версия формата сообщения
|
||||
* [N] bodyBytes (bytes) тело сообщения (БЕЗ type/subType/version)
|
||||
*
|
||||
* TAIL (НЕ входит в blockSize, НЕ подписывается в Frame v0):
|
||||
* [2] sigMarker (uint16) маркер подписи:
|
||||
* - 0x0100 (256) = далее подпись Ed25519 64 байта
|
||||
* [64] signature64 (bytes) Ed25519 signature над hash32
|
||||
*
|
||||
* hash32 НЕ хранится в блоке.
|
||||
* hash32 вычисляется при парсинге:
|
||||
* preimage = первые blockSize байт
|
||||
* hash32 = SHA-256(preimage)
|
||||
*
|
||||
* Правила MVP-парсера (Frame v0):
|
||||
* - frameCode должен быть строго 0x0000, иначе REJECT.
|
||||
* - sigMarker должен быть строго 0x0100, иначе REJECT.
|
||||
* - подпись обязана присутствовать всегда (sigMarker+signature64).
|
||||
* - НИКАКИХ fallback-веток “если маркер другой, то подписи нет/другой хвост”.
|
||||
*
|
||||
* Важно по безопасности:
|
||||
* - sigMarker в v0 не входит в подписываемые байты → его можно подменить,
|
||||
* поэтому единственная безопасная логика: "если не 0x0100 — reject".
|
||||
* =========================================================================
|
||||
* The user signature is NOT stored in this frame. It is the single Ed25519/Solana
|
||||
* signature of the surrounding ANS-104 DataItem.
|
||||
*/
|
||||
public final class BchBlockEntry {
|
||||
|
||||
public static final int SIGNATURE_LEN = 64;
|
||||
public static final int HASH_LEN = 32;
|
||||
|
||||
public static final int FRAME_CODE_LEN = 2;
|
||||
public static final int SIG_MARKER_LEN = 2;
|
||||
|
||||
/** Frame v0 */
|
||||
public static final int FRAME_CODE_V0 = 0x0000;
|
||||
|
||||
/** sigMarker: 256 = 0x0100 */
|
||||
public static final int SIG_MARKER_ED25519 = 0x0100;
|
||||
|
||||
/**
|
||||
* Максимальный допустимый размер блока (fullBytes = preimage + sigMarker + signature),
|
||||
* чтобы не уложить сервер по памяти/диску.
|
||||
*/
|
||||
public static final int MAX_BLOCK_FULL_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Насколько блок может “обгонять” текущее время (защита от кривых часов/вбросов).
|
||||
* Если timestamp больше now + 60 сек — блок считаем неверным.
|
||||
*/
|
||||
public static final int FRAME_CODE_V1 = 0x0001;
|
||||
public static final int MAX_BLOCK_FULL_BYTES = Ans104DataItem.MAX_DATA_ITEM_BYTES;
|
||||
public static final long MAX_FUTURE_SECONDS = 60;
|
||||
public static final int FRAME_HEADER_SIZE = 2 + 32 + 32 + 4 + 4 + 8 + 2 + 2 + 2;
|
||||
|
||||
/**
|
||||
* Размер фиксированной части PREIMAGE (без bodyBytes).
|
||||
*
|
||||
* PREIMAGE header:
|
||||
* frameCode(2) + prevHash32(32) + blockSize(4) + blockNumber(4) + timestamp(8)
|
||||
* + type(2) + subType(2) + version(2)
|
||||
*/
|
||||
public static final int PREIMAGE_HEADER_SIZE =
|
||||
2 // frameCode
|
||||
+ 32 // prevHash32
|
||||
+ 4 // blockSize
|
||||
+ 4 // blockNumber
|
||||
+ 8 // timestamp
|
||||
+ 2 // type
|
||||
+ 2 // subType
|
||||
+ 2; // version
|
||||
|
||||
/** Минимальный полный размер блока (без bodyBytes). */
|
||||
public static final int MIN_FULL_BYTES =
|
||||
PREIMAGE_HEADER_SIZE + SIG_MARKER_LEN + SIGNATURE_LEN;
|
||||
|
||||
// --- HEADER (PREIMAGE) ---
|
||||
public final int frameCode; // uint16 (v0=0)
|
||||
public final byte[] prevHash32; // 32
|
||||
public final int blockSize; // preimage size (включая frameCode)
|
||||
public final int blockNumber; // >=0
|
||||
public final int frameCode;
|
||||
public final byte[] prevHash32;
|
||||
public final byte[] back32Hash32;
|
||||
public final int blockSize;
|
||||
public final int blockNumber;
|
||||
public final long timestamp;
|
||||
public final short type;
|
||||
public final short subType;
|
||||
public final short version;
|
||||
|
||||
// --- BODY (PREIMAGE) ---
|
||||
public final byte[] bodyBytes;
|
||||
|
||||
/** Распарсенное тело (создаётся сразу при парсинге блока). */
|
||||
public final BodyRecord body;
|
||||
|
||||
// --- TAIL ---
|
||||
public final int sigMarker; // uint16 (v0: 0x0100)
|
||||
private final byte[] signature64; // 64
|
||||
private final Ans104DataItem dataItem;
|
||||
private final Ans104DataItem contentItem;
|
||||
private final CoreRecord coreRecord;
|
||||
private final ContentRecord contentRecord;
|
||||
private final byte[] frameBytes;
|
||||
private final byte[] hash32;
|
||||
|
||||
// --- derived ---
|
||||
private final byte[] hash32; // 32, computed
|
||||
private final byte[] preimage; // blockSize bytes
|
||||
private final byte[] fullBytes; // preimage + sigMarker + signature
|
||||
|
||||
/* ===================================================================== */
|
||||
/* ====================== Конструктор из байт ========================== */
|
||||
/* ===================================================================== */
|
||||
|
||||
public BchBlockEntry(byte[] fullBytes) {
|
||||
Objects.requireNonNull(fullBytes, "fullBytes == null");
|
||||
|
||||
if (fullBytes.length < MIN_FULL_BYTES) {
|
||||
throw new IllegalArgumentException("Block too short: " + fullBytes.length + " < " + MIN_FULL_BYTES);
|
||||
}
|
||||
if (fullBytes.length > MAX_BLOCK_FULL_BYTES) {
|
||||
throw new IllegalArgumentException("Block too large: " + fullBytes.length + " > " + MAX_BLOCK_FULL_BYTES);
|
||||
/** Parse a complete serialized ANS-104 DataItem containing one SHiNE Frame v1. */
|
||||
public BchBlockEntry(byte[] fullDataItemBytes) {
|
||||
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
|
||||
this.dataItem = new Ans104DataItem(fullDataItemBytes);
|
||||
this.contentItem = null;
|
||||
this.coreRecord = null;
|
||||
this.contentRecord = null;
|
||||
this.frameBytes = dataItem.data();
|
||||
if (frameBytes.length < FRAME_HEADER_SIZE) {
|
||||
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(fullBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
|
||||
// [2] frameCode
|
||||
ByteBuffer bb = ByteBuffer.wrap(frameBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
this.frameCode = Short.toUnsignedInt(bb.getShort());
|
||||
if (this.frameCode != FRAME_CODE_V0) {
|
||||
throw new IllegalArgumentException(String.format(
|
||||
"Bad frameCode: 0x%04X (expected 0x%04X)", this.frameCode, FRAME_CODE_V0
|
||||
));
|
||||
if (frameCode != FRAME_CODE_V1) {
|
||||
throw new IllegalArgumentException(String.format("Bad SHiNE frameCode: 0x%04X (expected 0x%04X)", frameCode, FRAME_CODE_V1));
|
||||
}
|
||||
|
||||
// [32] prevHash32
|
||||
this.prevHash32 = new byte[32];
|
||||
bb.get(this.prevHash32);
|
||||
|
||||
// [4] blockSize
|
||||
bb.get(prevHash32);
|
||||
this.back32Hash32 = new byte[32];
|
||||
bb.get(back32Hash32);
|
||||
this.blockSize = bb.getInt();
|
||||
if (blockSize < PREIMAGE_HEADER_SIZE) {
|
||||
throw new IllegalArgumentException("blockSize too small: " + blockSize + " < " + PREIMAGE_HEADER_SIZE);
|
||||
if (blockSize != frameBytes.length || blockSize < FRAME_HEADER_SIZE) {
|
||||
throw new IllegalArgumentException("SHiNE blockSize mismatch: declared=" + blockSize + " actual=" + frameBytes.length);
|
||||
}
|
||||
|
||||
// fullLen must match exactly: blockSize + sigMarker(2) + signature(64)
|
||||
int expectedFullLen = blockSize + SIG_MARKER_LEN + SIGNATURE_LEN;
|
||||
if (expectedFullLen != fullBytes.length) {
|
||||
throw new IllegalArgumentException("blockSize mismatch: blockSize=" + blockSize
|
||||
+ " expectedFullLen=" + expectedFullLen
|
||||
+ " fullLen=" + fullBytes.length);
|
||||
}
|
||||
if (expectedFullLen > MAX_BLOCK_FULL_BYTES) {
|
||||
throw new IllegalArgumentException("Block too large by blockSize: " + expectedFullLen + " > " + MAX_BLOCK_FULL_BYTES);
|
||||
}
|
||||
|
||||
// [4] blockNumber
|
||||
this.blockNumber = bb.getInt();
|
||||
if (this.blockNumber < 0) {
|
||||
throw new IllegalArgumentException("blockNumber < 0: " + this.blockNumber);
|
||||
}
|
||||
|
||||
// [8] timestamp
|
||||
if (blockNumber < 0) throw new IllegalArgumentException("blockNumber < 0: " + blockNumber);
|
||||
this.timestamp = bb.getLong();
|
||||
|
||||
// запрет “в будущее” больше чем на 1 минуту
|
||||
long now = Instant.now().getEpochSecond();
|
||||
if (this.timestamp > now + MAX_FUTURE_SECONDS) {
|
||||
throw new IllegalArgumentException("timestamp is too far in future: ts=" + this.timestamp
|
||||
+ " now=" + now + " maxFutureSec=" + MAX_FUTURE_SECONDS);
|
||||
if (timestamp > now + MAX_FUTURE_SECONDS) {
|
||||
throw new IllegalArgumentException("timestamp is too far in future: ts=" + timestamp + " now=" + now);
|
||||
}
|
||||
|
||||
// [2][2][2] type/subType/version
|
||||
this.type = bb.getShort();
|
||||
this.subType = bb.getShort();
|
||||
this.version = bb.getShort();
|
||||
|
||||
// [N] bodyBytes
|
||||
int bodyLen = blockSize - PREIMAGE_HEADER_SIZE;
|
||||
if (bodyLen < 0) {
|
||||
throw new IllegalArgumentException("Invalid body length: " + bodyLen);
|
||||
}
|
||||
this.bodyBytes = new byte[bodyLen];
|
||||
bb.get(this.bodyBytes);
|
||||
|
||||
// TAIL: [2] sigMarker
|
||||
this.sigMarker = Short.toUnsignedInt(bb.getShort());
|
||||
if (this.sigMarker != SIG_MARKER_ED25519) {
|
||||
throw new IllegalArgumentException(String.format(
|
||||
"Bad sigMarker: 0x%04X (expected 0x%04X)", this.sigMarker, SIG_MARKER_ED25519
|
||||
));
|
||||
this.bodyBytes = new byte[bb.remaining()];
|
||||
bb.get(bodyBytes);
|
||||
this.body = BodyRecordParser.parse(type, subType, version, bodyBytes);
|
||||
this.hash32 = BchCryptoVerifier.sha256(frameBytes);
|
||||
}
|
||||
|
||||
// TAIL: [64] signature64
|
||||
this.signature64 = new byte[SIGNATURE_LEN];
|
||||
bb.get(this.signature64);
|
||||
|
||||
// preimage = первые blockSize байт (включая frameCode)
|
||||
this.preimage = Arrays.copyOfRange(fullBytes, 0, blockSize);
|
||||
|
||||
// hash32 = sha256(preimage)
|
||||
this.hash32 = BchCryptoVerifier.sha256(preimage);
|
||||
|
||||
// parse body по header.type/subType/version + ОБЯЗАТЕЛЬНЫЙ check()
|
||||
this.body = BodyRecordParser.parse(this.type, this.subType, this.version, this.bodyBytes);
|
||||
|
||||
this.fullBytes = Arrays.copyOf(fullBytes, fullBytes.length);
|
||||
|
||||
if (bb.remaining() != 0) {
|
||||
throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
|
||||
}
|
||||
/** M1: явная точка входа для пары. Runtime переключается на неё в M2–M5. */
|
||||
public static BchBlockEntry fromCoreContent(byte[] container) {
|
||||
return new BchBlockEntry(CoreContentContainer.unpack(container));
|
||||
}
|
||||
|
||||
/* ===================================================================== */
|
||||
/* ====================== Конструктор сборки ============================ */
|
||||
/* ===================================================================== */
|
||||
|
||||
public BchBlockEntry(byte[] prevHash32,
|
||||
int blockNumber,
|
||||
long timestamp,
|
||||
short type,
|
||||
short subType,
|
||||
short version,
|
||||
byte[] bodyBytes,
|
||||
byte[] signature64) {
|
||||
|
||||
Objects.requireNonNull(prevHash32, "prevHash32 == null");
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
Objects.requireNonNull(signature64, "signature64 == null");
|
||||
|
||||
if (prevHash32.length != 32) throw new IllegalArgumentException("prevHash32 != 32");
|
||||
if (signature64.length != SIGNATURE_LEN) throw new IllegalArgumentException("signature64 != 64");
|
||||
|
||||
if (blockNumber < 0) {
|
||||
throw new IllegalArgumentException("blockNumber < 0: " + blockNumber);
|
||||
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();
|
||||
}
|
||||
|
||||
// запрет “в будущее” больше чем на 1 минуту
|
||||
long now = Instant.now().getEpochSecond();
|
||||
if (timestamp > now + MAX_FUTURE_SECONDS) {
|
||||
throw new IllegalArgumentException("timestamp is too far in future: ts=" + timestamp
|
||||
+ " now=" + now + " maxFutureSec=" + MAX_FUTURE_SECONDS);
|
||||
public boolean isCoreContent() { return coreRecord != null; }
|
||||
public CoreRecord getCoreRecord() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return coreRecord;
|
||||
}
|
||||
|
||||
this.frameCode = FRAME_CODE_V0;
|
||||
this.prevHash32 = Arrays.copyOf(prevHash32, 32);
|
||||
this.blockNumber = blockNumber;
|
||||
this.timestamp = timestamp;
|
||||
this.type = type;
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
this.bodyBytes = Arrays.copyOf(bodyBytes, bodyBytes.length);
|
||||
|
||||
// blockSize = размер preimage (включая frameCode)
|
||||
this.blockSize = PREIMAGE_HEADER_SIZE + this.bodyBytes.length;
|
||||
|
||||
int fullLen = this.blockSize + SIG_MARKER_LEN + SIGNATURE_LEN;
|
||||
if (fullLen > MAX_BLOCK_FULL_BYTES) {
|
||||
throw new IllegalArgumentException("Block too large: " + fullLen + " > " + MAX_BLOCK_FULL_BYTES);
|
||||
public ContentRecord getContentRecord() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return contentRecord;
|
||||
}
|
||||
|
||||
// parse body по header + ОБЯЗАТЕЛЬНЫЙ check()
|
||||
this.body = BodyRecordParser.parse(this.type, this.subType, this.version, this.bodyBytes);
|
||||
|
||||
// tail marker фиксирован
|
||||
this.sigMarker = SIG_MARKER_ED25519;
|
||||
this.signature64 = Arrays.copyOf(signature64, SIGNATURE_LEN);
|
||||
|
||||
// build preimage
|
||||
ByteBuffer pre = ByteBuffer.allocate(blockSize).order(ByteOrder.BIG_ENDIAN);
|
||||
pre.putShort((short) (FRAME_CODE_V0 & 0xFFFF));
|
||||
pre.put(this.prevHash32);
|
||||
pre.putInt(this.blockSize);
|
||||
pre.putInt(this.blockNumber);
|
||||
pre.putLong(this.timestamp);
|
||||
pre.putShort(this.type);
|
||||
pre.putShort(this.subType);
|
||||
pre.putShort(this.version);
|
||||
pre.put(this.bodyBytes);
|
||||
|
||||
this.preimage = pre.array();
|
||||
this.hash32 = BchCryptoVerifier.sha256(preimage);
|
||||
|
||||
// build fullBytes: preimage + sigMarker + signature64
|
||||
ByteBuffer full = ByteBuffer.allocate(fullLen).order(ByteOrder.BIG_ENDIAN);
|
||||
full.put(this.preimage);
|
||||
full.putShort((short) (SIG_MARKER_ED25519 & 0xFFFF));
|
||||
full.put(this.signature64);
|
||||
this.fullBytes = full.array();
|
||||
public Ans104DataItem getCoreDataItem() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return dataItem;
|
||||
}
|
||||
|
||||
/* ===================================================================== */
|
||||
/* ============================ Getters ================================= */
|
||||
/* ===================================================================== */
|
||||
|
||||
public byte[] getPreimageBytes() {
|
||||
return Arrays.copyOf(preimage, preimage.length);
|
||||
public Ans104DataItem getContentDataItem() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return contentItem;
|
||||
}
|
||||
|
||||
/** Возвращает подпись Ed25519 (64 байта). */
|
||||
public byte[] getSignature64() {
|
||||
return Arrays.copyOf(signature64, SIGNATURE_LEN);
|
||||
}
|
||||
|
||||
/** Возвращает hash32 = SHA-256(preimage). */
|
||||
public byte[] getHash32() {
|
||||
return Arrays.copyOf(hash32, HASH_LEN);
|
||||
}
|
||||
|
||||
/** Возвращает полный блок: preimage + sigMarker + signature. */
|
||||
public byte[] toBytes() {
|
||||
return Arrays.copyOf(fullBytes, fullBytes.length);
|
||||
/** Legacy API: не позволяет принять одну подпись за проверку пары. */
|
||||
public Ans104DataItem getDataItem() {
|
||||
if (isCoreContent()) throw new IllegalStateException("Используйте явные CORE/CONTENT accessors");
|
||||
return dataItem;
|
||||
}
|
||||
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
|
||||
/** Kept as an alias for code/docs that called the old field preimage. */
|
||||
public byte[] getPreimageBytes() { return getFrameBytes(); }
|
||||
public byte[] getSignature64() { return dataItem.signature64(); }
|
||||
public byte[] getOwner32() { return dataItem.owner32(); }
|
||||
public byte[] getDataItemId32() { return dataItem.id32(); }
|
||||
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
|
||||
/** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
|
||||
public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
String timeIso;
|
||||
try {
|
||||
timeIso = Instant.ofEpochSecond(timestamp).toString();
|
||||
} catch (Exception e) {
|
||||
timeIso = "некорректныйTimestamp";
|
||||
}
|
||||
|
||||
return "BchBlockEntry{"
|
||||
+ "FRAME{frameCode=0x" + hex4(frameCode)
|
||||
+ "}, HDR{"
|
||||
+ "blockSize=" + blockSize
|
||||
+ ", blockNumber=" + blockNumber
|
||||
+ ", timestamp=" + timestamp + " (" + timeIso + ")"
|
||||
+ ", type=" + (type & 0xFFFF)
|
||||
+ ", subType=" + (subType & 0xFFFF)
|
||||
+ ", version=" + (version & 0xFFFF)
|
||||
+ ", prevHash32(hex)=" + toHex(prevHash32)
|
||||
+ "}"
|
||||
+ ", BODY{len=" + (bodyBytes == null ? -1 : bodyBytes.length) + "}"
|
||||
+ ", TAIL{sigMarker=0x" + hex4(sigMarker) + ", signature64(hex)=" + toHex(signature64) + "}"
|
||||
+ ", DERIVED{hash32(hex)=" + toHex(hash32) + "}"
|
||||
+ "}";
|
||||
}
|
||||
|
||||
private static String hex4(int v) {
|
||||
String s = Integer.toHexString(v & 0xFFFF);
|
||||
while (s.length() < 4) s = "0" + s;
|
||||
return s;
|
||||
return "BchBlockEntry{" +
|
||||
"frameCode=0x" + Integer.toHexString(frameCode) +
|
||||
", blockNumber=" + blockNumber +
|
||||
", timestamp=" + timestamp +
|
||||
", type=" + (type & 0xffff) +
|
||||
", subType=" + (subType & 0xffff) +
|
||||
", version=" + (version & 0xffff) +
|
||||
", bodyLen=" + bodyBytes.length +
|
||||
", dataItemId=" + toHex(getDataItemId32()) +
|
||||
", blockHash=" + toHex(hash32) +
|
||||
'}';
|
||||
}
|
||||
|
||||
private static String toHex(byte[] bytes) {
|
||||
if (bytes == null) return "null";
|
||||
char[] HEX = "0123456789abcdef".toCharArray();
|
||||
char[] h = "0123456789abcdef".toCharArray();
|
||||
char[] out = new char[bytes.length * 2];
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
int vv = bytes[i] & 0xFF;
|
||||
out[i * 2] = HEX[vv >>> 4];
|
||||
out[i * 2 + 1] = HEX[vv & 0x0F];
|
||||
int v = bytes[i] & 0xff;
|
||||
out[i * 2] = h[v >>> 4]; out[i * 2 + 1] = h[v & 15];
|
||||
}
|
||||
return new String(out);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user