SHA256
Compare commits
91
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 |
+12
@@ -136,3 +136,15 @@ shine-UI/assets/navbar_preview.png
|
||||
*.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,3 +1,9 @@
|
||||
# Актуальная архитектура SHiNE
|
||||
|
||||
Начинать с [Blockchain](docs/Blockchain/README.md) и [общей архитектуры](docs/ARCHITECTURE.md). Активный runtime CORE/CONTENT, App=test5599. Прямая межсерверная репликация блоков не используется. Не менять протокол или независимые подсистемы без согласования. Интеграционную приёмку и production deploy выполнять отдельно с разрешения пользователя.
|
||||
|
||||
---
|
||||
|
||||
# Инструкции для агентов SHiNE
|
||||
|
||||
Этот файл относится к репозиторию SHiNE. По умолчанию писать документацию, пользовательские пояснения и сообщения коммитов на русском языке.
|
||||
|
||||
@@ -19,18 +19,22 @@
|
||||
|
||||
## Базовое правило для обычных коммитов
|
||||
|
||||
- Перед каждым новым коммитом обязательно обновлять версии в `VERSION.properties`.
|
||||
- Версии обновляются только вместе с изменениями соответствующего продукта: 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
|
||||
|
||||
|
||||
+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
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
MODE="${1:-potentiometer-adc-test}"
|
||||
PORT="${PORT:-}"
|
||||
|
||||
case "$MODE" in
|
||||
potentiometer-adc-test)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test"
|
||||
;;
|
||||
buzzer-gpio6-test)
|
||||
SKETCH_DIR="$ROOT_DIR/test_sketches/buzzer_gpio6_test"
|
||||
BUILD_DIR="$ROOT_DIR/.arduino-build/build-buzzer-gpio6-test"
|
||||
;;
|
||||
*)
|
||||
echo "Unknown mode: $MODE" >&2
|
||||
echo "Known modes: potentiometer-adc-test, buzzer-gpio6-test" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
if [[ -z "$PORT" ]]; then
|
||||
PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')"
|
||||
fi
|
||||
|
||||
if [[ -z "$PORT" ]]; then
|
||||
echo "No serial port found. Set PORT=/dev/ttyACM0 explicitly." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
FQBN="esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi"
|
||||
|
||||
echo "== Mode: $MODE"
|
||||
echo "== Sketch: $SKETCH_DIR"
|
||||
echo "== Port: $PORT"
|
||||
echo "== FQBN: $FQBN"
|
||||
|
||||
arduino-cli compile \
|
||||
--fqbn "$FQBN" \
|
||||
--build-path "$BUILD_DIR" \
|
||||
"$SKETCH_DIR"
|
||||
|
||||
arduino-cli upload \
|
||||
--fqbn "$FQBN" \
|
||||
-p "$PORT" \
|
||||
--input-dir "$BUILD_DIR" \
|
||||
"$SKETCH_DIR"
|
||||
|
||||
echo
|
||||
echo "== Done."
|
||||
@@ -1,3 +0,0 @@
|
||||
# AGENTS
|
||||
|
||||
This folder contains a temporary GPIO6 buzzer diagnostic for ESP32-S3-LCD-2. Keep screen/serial strings in English.
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
// Buzzer module wiring: GND -> GND, VCC -> 3V3, I/O -> P1 IO6 / GPIO6.
|
||||
static constexpr uint8_t PIN_BUZZER = 6;
|
||||
static constexpr uint32_t STEP_MS = 1800;
|
||||
static uint8_t gStep = 0;
|
||||
static uint32_t gChangedMs = 0;
|
||||
|
||||
static void applyStep(uint8_t step) {
|
||||
ledcDetach(PIN_BUZZER);
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
delay(80);
|
||||
switch (step) {
|
||||
case 0:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, HIGH);
|
||||
Serial.println("TEST 1: GPIO6 HIGH - active-high module should sound");
|
||||
break;
|
||||
case 1:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("TEST 2: GPIO6 LOW - active-low module should sound");
|
||||
break;
|
||||
case 2:
|
||||
ledcAttach(PIN_BUZZER, 1800, 8);
|
||||
ledcWriteTone(PIN_BUZZER, 1800);
|
||||
ledcWrite(PIN_BUZZER, 180);
|
||||
Serial.println("TEST 3: GPIO6 PWM 1800 Hz - passive module should sound");
|
||||
break;
|
||||
default:
|
||||
pinMode(PIN_BUZZER, OUTPUT);
|
||||
digitalWrite(PIN_BUZZER, LOW);
|
||||
Serial.println("SILENCE");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
Serial.println("GPIO6 BUZZER TEST: HIGH, LOW, PWM, SILENCE. Each step lasts 1.8 seconds.");
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (millis() - gChangedMs < STEP_MS) return;
|
||||
gStep = (gStep + 1) % 4;
|
||||
applyStep(gStep);
|
||||
gChangedMs = millis();
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
# AGENTS
|
||||
|
||||
## Назначение папки
|
||||
|
||||
Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`.
|
||||
|
||||
Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`.
|
||||
|
||||
## Обязательная синхронизация
|
||||
|
||||
При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`.
|
||||
|
||||
Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений.
|
||||
|
||||
## Язык экрана
|
||||
|
||||
Экранные строки в скетче оставлять на английском языке.
|
||||
@@ -1,73 +0,0 @@
|
||||
# Potentiometer ADC Test for ESP32-S3-LCD-2
|
||||
|
||||
Тестовый скетч для Waveshare `ESP32-S3-LCD-2`.
|
||||
|
||||
Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`.
|
||||
|
||||
## Пины
|
||||
|
||||
Используются пины с разъёма `P1` платы:
|
||||
|
||||
- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра.
|
||||
- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима.
|
||||
- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`.
|
||||
- `GND` — земля.
|
||||
|
||||
Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant.
|
||||
|
||||
## Режимы
|
||||
|
||||
Переключение:
|
||||
|
||||
- touch-кнопка `3-WIRE`;
|
||||
- touch-кнопка `2-WIRE`;
|
||||
- серийная команда `m`;
|
||||
- короткое нажатие `BOOT / GPIO0`.
|
||||
|
||||
Сброс min/max:
|
||||
|
||||
- touch-кнопка `RESET`;
|
||||
- серийная команда `r`.
|
||||
|
||||
## 3-Wire Mode
|
||||
|
||||
Правильное подключение:
|
||||
|
||||
- один край потенциометра -> `3V3`;
|
||||
- второй край потенциометра -> `GND`;
|
||||
- средний ползунок -> `GPIO2 / IO2`.
|
||||
|
||||
Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`.
|
||||
|
||||
## 2-Wire Mode
|
||||
|
||||
Грубое подключение:
|
||||
|
||||
- один край потенциометра -> `GPIO6 / IO6`;
|
||||
- средний ползунок -> `GPIO2 / IO2`;
|
||||
- второй край не подключать.
|
||||
|
||||
`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс.
|
||||
|
||||
## Экранные данные
|
||||
|
||||
На экране выводятся:
|
||||
|
||||
- режим и схема пинов;
|
||||
- raw ADC и millivolts;
|
||||
- абсолютный процент от `0..3300 mV`;
|
||||
- калиброванный процент по найденному min/max;
|
||||
- min/max/span;
|
||||
- EMA-сглаживание;
|
||||
- примерная оценка сопротивления;
|
||||
- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`;
|
||||
- координаты последнего touch;
|
||||
- serial-подсказка.
|
||||
|
||||
## Сборка
|
||||
|
||||
Из папки `main-device`:
|
||||
|
||||
```bash
|
||||
./burn.sh potentiometer-adc-test
|
||||
```
|
||||
-348
@@ -1,348 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
#include <Arduino_GFX_Library.h>
|
||||
#include <Wire.h>
|
||||
#include <bsp_cst816.h>
|
||||
|
||||
#define PIN_LCD_SCLK 39
|
||||
#define PIN_LCD_MOSI 38
|
||||
#define PIN_LCD_MISO 40
|
||||
#define PIN_LCD_DC 42
|
||||
#define PIN_LCD_RST -1
|
||||
#define PIN_LCD_CS 45
|
||||
#define PIN_LCD_BL 1
|
||||
|
||||
#define PIN_TP_SDA 48
|
||||
#define PIN_TP_SCL 47
|
||||
|
||||
#define PIN_ADC_WIPER 2
|
||||
#define PIN_DRIVE_2WIRE 6
|
||||
#define PIN_BOOT_BUTTON 0
|
||||
|
||||
static const uint16_t DISP_W = 320;
|
||||
static const uint16_t DISP_H = 240;
|
||||
static const uint32_t ADC_FULL_MV = 3300;
|
||||
static const float POT_OHMS = 50000.0f;
|
||||
static const float ROUGH_PULLDOWN_OHMS = 45000.0f;
|
||||
|
||||
static const uint16_t C_BG = 0x0841;
|
||||
static const uint16_t C_PANEL = 0x18E3;
|
||||
static const uint16_t C_CARD = 0x2126;
|
||||
static const uint16_t C_TEXT = 0xF7BE;
|
||||
static const uint16_t C_MUTE = 0x8C71;
|
||||
static const uint16_t C_ACCENT = 0x05DF;
|
||||
static const uint16_t C_OK = 0x47E8;
|
||||
static const uint16_t C_WARN = 0xFD20;
|
||||
static const uint16_t C_BAD = 0xF986;
|
||||
static const uint16_t C_BORDER = 0x4208;
|
||||
|
||||
struct Rect {
|
||||
int16_t x;
|
||||
int16_t y;
|
||||
int16_t w;
|
||||
int16_t h;
|
||||
};
|
||||
|
||||
enum class Mode : uint8_t {
|
||||
ThreeWire,
|
||||
TwoWire,
|
||||
};
|
||||
|
||||
struct Sample {
|
||||
uint16_t raw;
|
||||
uint32_t mv;
|
||||
uint16_t rawMinBurst;
|
||||
uint16_t rawMaxBurst;
|
||||
};
|
||||
|
||||
Arduino_DataBus *bus = new Arduino_ESP32SPI(
|
||||
PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO);
|
||||
Arduino_GFX *gfx = new Arduino_ST7789(
|
||||
bus, PIN_LCD_RST, 1, true, 240, 320);
|
||||
|
||||
static const Rect BTN_3WIRE = {10, 38, 94, 30};
|
||||
static const Rect BTN_2WIRE = {113, 38, 94, 30};
|
||||
static const Rect BTN_RESET = {216, 38, 94, 30};
|
||||
|
||||
static Mode gMode = Mode::ThreeWire;
|
||||
static uint32_t gLastUiMs = 0;
|
||||
static uint32_t gLastSerialMs = 0;
|
||||
static uint32_t gMinMv = 0xFFFFFFFF;
|
||||
static uint32_t gMaxMv = 0;
|
||||
static float gEmaMv = 0.0f;
|
||||
static bool gHasEma = false;
|
||||
static bool gTouchOk = false;
|
||||
static uint16_t gLastTouchX = 0;
|
||||
static uint16_t gLastTouchY = 0;
|
||||
static bool gBootWasDown = false;
|
||||
static uint32_t gBootLastChangeMs = 0;
|
||||
|
||||
static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) {
|
||||
gfx->setTextSize(size);
|
||||
gfx->setTextColor(color);
|
||||
gfx->setCursor(x, y);
|
||||
gfx->print(text);
|
||||
}
|
||||
|
||||
static void drawButton(const Rect &r, const char *label, bool active) {
|
||||
uint16_t fill = active ? C_ACCENT : C_CARD;
|
||||
uint16_t text = active ? C_BG : C_TEXT;
|
||||
gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill);
|
||||
gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER);
|
||||
int16_t tx = r.x + 10;
|
||||
int16_t ty = r.y + 10;
|
||||
drawText(tx, ty, label, text, 1);
|
||||
}
|
||||
|
||||
static bool contains(const Rect &r, uint16_t x, uint16_t y) {
|
||||
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
|
||||
}
|
||||
|
||||
static const char *modeName() {
|
||||
return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE";
|
||||
}
|
||||
|
||||
static void resetRange() {
|
||||
gMinMv = 0xFFFFFFFF;
|
||||
gMaxMv = 0;
|
||||
gHasEma = false;
|
||||
}
|
||||
|
||||
static void configurePins() {
|
||||
pinMode(PIN_ADC_WIPER, INPUT);
|
||||
analogReadResolution(12);
|
||||
analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db);
|
||||
|
||||
if (gMode == Mode::TwoWire) {
|
||||
pinMode(PIN_DRIVE_2WIRE, OUTPUT);
|
||||
digitalWrite(PIN_DRIVE_2WIRE, HIGH);
|
||||
pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN);
|
||||
} else {
|
||||
pinMode(PIN_DRIVE_2WIRE, INPUT);
|
||||
pinMode(PIN_ADC_WIPER, INPUT);
|
||||
}
|
||||
}
|
||||
|
||||
static void setMode(Mode mode) {
|
||||
if (gMode == mode) return;
|
||||
gMode = mode;
|
||||
configurePins();
|
||||
resetRange();
|
||||
}
|
||||
|
||||
static Sample readSample() {
|
||||
const uint8_t count = 32;
|
||||
uint32_t rawSum = 0;
|
||||
uint32_t mvSum = 0;
|
||||
uint16_t rawMin = 4095;
|
||||
uint16_t rawMax = 0;
|
||||
|
||||
for (uint8_t i = 0; i < count; i++) {
|
||||
uint16_t raw = analogRead(PIN_ADC_WIPER);
|
||||
uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER);
|
||||
rawSum += raw;
|
||||
mvSum += mv;
|
||||
if (raw < rawMin) rawMin = raw;
|
||||
if (raw > rawMax) rawMax = raw;
|
||||
delayMicroseconds(250);
|
||||
}
|
||||
|
||||
Sample s;
|
||||
s.raw = rawSum / count;
|
||||
s.mv = mvSum / count;
|
||||
s.rawMinBurst = rawMin;
|
||||
s.rawMaxBurst = rawMax;
|
||||
return s;
|
||||
}
|
||||
|
||||
static uint8_t percentFromMv(uint32_t mv) {
|
||||
if (mv >= ADC_FULL_MV) return 100;
|
||||
return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV);
|
||||
}
|
||||
|
||||
static uint8_t calibratedPercent(uint32_t mv, uint32_t span) {
|
||||
if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0;
|
||||
uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span;
|
||||
return (uint8_t)min<uint32_t>(pct, 100);
|
||||
}
|
||||
|
||||
static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) {
|
||||
if (mv < 30) return "OPEN/GND";
|
||||
if (mv > 3250) return "SATURATED";
|
||||
if (span < 20) return "NO SPAN";
|
||||
if (pctAbs < 15) return "LOW";
|
||||
if (pctAbs > 85) return "HIGH";
|
||||
return "MID";
|
||||
}
|
||||
|
||||
static float estimateOhms(uint32_t mv) {
|
||||
if (gMode == Mode::ThreeWire) {
|
||||
return POT_OHMS * ((float)percentFromMv(mv) / 100.0f);
|
||||
}
|
||||
if (mv < 5) return -1.0f;
|
||||
if (mv >= ADC_FULL_MV) return 0.0f;
|
||||
return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f);
|
||||
}
|
||||
|
||||
static void drawStaticUi() {
|
||||
gfx->fillScreen(C_BG);
|
||||
drawText(10, 8, "POT ADC TEST", C_TEXT, 2);
|
||||
drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1);
|
||||
drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire);
|
||||
drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire);
|
||||
drawButton(BTN_RESET, "RESET", false);
|
||||
|
||||
gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER);
|
||||
gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER);
|
||||
gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER);
|
||||
}
|
||||
|
||||
static void drawBar(uint8_t pct, uint16_t color) {
|
||||
int x = 18;
|
||||
int y = 123;
|
||||
int w = 284;
|
||||
int h = 10;
|
||||
gfx->fillRect(x, y, w, h, C_BORDER);
|
||||
gfx->fillRect(x, y, (w * pct) / 100, h, color);
|
||||
}
|
||||
|
||||
static void updateUi() {
|
||||
Sample s = readSample();
|
||||
if (s.mv < gMinMv) gMinMv = s.mv;
|
||||
if (s.mv > gMaxMv) gMaxMv = s.mv;
|
||||
uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0;
|
||||
|
||||
if (!gHasEma) {
|
||||
gEmaMv = (float)s.mv;
|
||||
gHasEma = true;
|
||||
} else {
|
||||
gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f;
|
||||
}
|
||||
|
||||
uint8_t pctAbs = percentFromMv(s.mv);
|
||||
uint8_t pctCal = calibratedPercent(s.mv, span);
|
||||
float ohms = estimateOhms(s.mv);
|
||||
const char *status = statusText(s.mv, span, pctAbs);
|
||||
uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK :
|
||||
strcmp(status, "NO SPAN") == 0 ? C_WARN :
|
||||
strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT;
|
||||
|
||||
char line[96];
|
||||
gfx->fillRect(9, 77, 302, 62, C_BG);
|
||||
snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName());
|
||||
drawText(16, 84, line, C_ACCENT, 1);
|
||||
snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu",
|
||||
s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f));
|
||||
drawText(16, 101, line, C_TEXT, 1);
|
||||
snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u",
|
||||
pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst));
|
||||
drawText(16, 115, line, C_TEXT, 1);
|
||||
drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor);
|
||||
|
||||
gfx->fillRect(9, 149, 302, 52, C_BG);
|
||||
snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV",
|
||||
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span);
|
||||
drawText(16, 156, line, C_TEXT, 1);
|
||||
if (ohms < 0) {
|
||||
snprintf(line, sizeof(line), "ohm: open/too high status:%s", status);
|
||||
} else {
|
||||
snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s",
|
||||
ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status);
|
||||
}
|
||||
drawText(16, 172, line, statusColor, 1);
|
||||
snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r",
|
||||
gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY);
|
||||
drawText(16, 188, line, C_MUTE, 1);
|
||||
|
||||
gfx->fillRect(9, 209, 302, 22, C_BG);
|
||||
if (gMode == Mode::ThreeWire) {
|
||||
drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1);
|
||||
} else {
|
||||
drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1);
|
||||
}
|
||||
|
||||
Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n",
|
||||
modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal,
|
||||
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span,
|
||||
(unsigned)(s.rawMaxBurst - s.rawMinBurst), status);
|
||||
}
|
||||
|
||||
static void handleTouch() {
|
||||
bsp_touch_read();
|
||||
uint16_t x = 0;
|
||||
uint16_t y = 0;
|
||||
if (!bsp_touch_get_coordinates(&x, &y)) return;
|
||||
gLastTouchX = x;
|
||||
gLastTouchY = y;
|
||||
|
||||
if (contains(BTN_3WIRE, x, y)) {
|
||||
setMode(Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
} else if (contains(BTN_2WIRE, x, y)) {
|
||||
setMode(Mode::TwoWire);
|
||||
drawStaticUi();
|
||||
} else if (contains(BTN_RESET, x, y)) {
|
||||
resetRange();
|
||||
}
|
||||
}
|
||||
|
||||
static void handleBootButton() {
|
||||
bool down = digitalRead(PIN_BOOT_BUTTON) == LOW;
|
||||
uint32_t now = millis();
|
||||
if (down != gBootWasDown && now - gBootLastChangeMs > 40) {
|
||||
gBootWasDown = down;
|
||||
gBootLastChangeMs = now;
|
||||
if (!down) {
|
||||
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void handleSerial() {
|
||||
while (Serial.available() > 0) {
|
||||
char c = (char)Serial.read();
|
||||
if (c == 'm' || c == 'M') {
|
||||
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||
drawStaticUi();
|
||||
} else if (c == 'r' || c == 'R') {
|
||||
resetRange();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(100);
|
||||
Serial.println("ESP32-S3-LCD-2 potentiometer ADC test");
|
||||
Serial.println("Commands: m=switch mode, r=reset min/max");
|
||||
|
||||
pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP);
|
||||
configurePins();
|
||||
|
||||
if (!gfx->begin()) {
|
||||
Serial.println("gfx->begin() failed");
|
||||
}
|
||||
pinMode(PIN_LCD_BL, OUTPUT);
|
||||
digitalWrite(PIN_LCD_BL, HIGH);
|
||||
|
||||
Wire.begin(PIN_TP_SDA, PIN_TP_SCL);
|
||||
gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H);
|
||||
|
||||
drawStaticUi();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
handleSerial();
|
||||
handleBootButton();
|
||||
if (gTouchOk) handleTouch();
|
||||
|
||||
uint32_t now = millis();
|
||||
if (now - gLastUiMs >= 250) {
|
||||
updateUi();
|
||||
gLastUiMs = now;
|
||||
}
|
||||
if (now - gLastSerialMs >= 5000) {
|
||||
Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6.");
|
||||
gLastSerialMs = now;
|
||||
}
|
||||
}
|
||||
@@ -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,29 +32,10 @@ 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" ;;
|
||||
usb-contact-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_test" ;;
|
||||
usb-contact-debug-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_sensor_debug_test" ;;
|
||||
usb-contact-resistance-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_resistance_test" ;;
|
||||
usb-contact-screen-start-stub) SKETCH_DIR="${ROOT_DIR}/test_sketches/usb_contact_screen_start_stub" ;;
|
||||
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, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
|
||||
echo "Use one of: registration-signer, hello, widgets, audio" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
@@ -74,10 +55,14 @@ compile_args=(
|
||||
--library "${DEMO_BASE}/libraries/XPowersLib"
|
||||
--library "${DEMO_BASE}/libraries/lvgl"
|
||||
--library "${DEMO_BASE}/libraries/Mylibrary"
|
||||
--library "${ROOT_DIR}/simple_av_test"
|
||||
"${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"
|
||||
|
||||
+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. полный сброс действительно очищает сохранённое состояние.
|
||||
@@ -1,203 +0,0 @@
|
||||
# USB contact sensor test
|
||||
|
||||
Diagnostic sketches:
|
||||
|
||||
- `main-device/test_sketches/usb_contact_sensor_test/usb_contact_sensor_test.ino`
|
||||
- `main-device/test_sketches/usb_contact_sensor_debug_test/usb_contact_sensor_debug_test.ino`
|
||||
- `main-device/test_sketches/breath_dual_mode_monitor/breath_dual_mode_monitor.ino`
|
||||
- `main-device/test_sketches/usb_contact_resistance_test/usb_contact_resistance_test.ino`
|
||||
- `main-device/test_sketches/usb_contact_screen_start_stub/usb_contact_screen_start_stub.ino`
|
||||
|
||||
## Purpose
|
||||
|
||||
Use the ESP32-S3 native USB data pair as a removable two-wire dry-contact input without making this mode persistent.
|
||||
|
||||
- `GPIO19` = native USB `D-`
|
||||
- `GPIO20` = native USB `D+`
|
||||
|
||||
## Boot behavior
|
||||
|
||||
Every normal reset starts in ordinary native USB mode. The sketch does not save sensor mode in NVS or any other persistent storage.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `USB CONTACT TEST`
|
||||
- mode: `USB mode`
|
||||
- state: `READY`
|
||||
- action button: `Start`
|
||||
|
||||
Until `Start` is pressed, the sketch does not reconfigure GPIO19/20.
|
||||
|
||||
## Sensor mode
|
||||
|
||||
After `Start`:
|
||||
|
||||
- GPIO19 is configured as `OUTPUT LOW`
|
||||
- GPIO20 is configured as `INPUT_PULLUP`
|
||||
- a passive switch/contact is connected between USB `D-` and `D+`
|
||||
- open contact => GPIO20 reads HIGH => UI shows `OPEN`
|
||||
- closed contact => GPIO20 reads LOW => UI shows `CLOSED`
|
||||
- contact changes use a 20 ms debounce
|
||||
|
||||
Native USB data is intentionally unavailable while sensor mode owns GPIO19/20. The UI warns not to connect the port to a computer in this state.
|
||||
|
||||
The action button changes to `Restart to USB`. Pressing it calls `ESP.restart()`; after reboot normal USB mode is restored.
|
||||
|
||||
A physical reset/power cycle has the same effect. The ESP32-S3 ROM download mode remains available through the board's BOOT procedure if recovery is needed.
|
||||
|
||||
## Debug version
|
||||
|
||||
The debug sketch starts in normal USB mode and shows raw touch diagnostics on screen. The on-screen `START` button is intentionally diagnostic only: it confirms touch/LVGL button events and does not reconfigure GPIO19/20.
|
||||
|
||||
Sensor mode starts from the physical BOOT/user button on GPIO0, active LOW. The button is debounced for 35 ms, then the UI shows `START RECEIVED` / `STARTING...`, waits 250 ms so the visual transition is rendered, and only then reconfigures USB D-/D+ as the contact input.
|
||||
|
||||
While in sensor mode, pressing the BOOT/user button again restarts the device and returns normal USB mode on the next boot.
|
||||
|
||||
## Resistance version
|
||||
|
||||
The `usb_contact_resistance_test` sketch starts in normal USB mode and does not reconfigure GPIO19/20 until `Start` is tapped.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `USB RESISTANCE TEST`
|
||||
- mode: `USB mode`
|
||||
- state: `READY`
|
||||
- action button: `Start`
|
||||
|
||||
After `Start`:
|
||||
|
||||
- GPIO19 / USB `D-` is configured as `OUTPUT HIGH`
|
||||
- GPIO20 / USB `D+` is configured as ADC input
|
||||
- the measured resistance is connected between `D-` and `D+`
|
||||
- a known external 10 kΩ pulldown resistor must be connected from `D+` to `GND` for meaningful ohm calculation
|
||||
- UI shows calculated resistance, raw ADC value, and measured `D+` millivolts
|
||||
- very low ADC voltage is shown as `OPEN`
|
||||
- near-source voltage is shown as `SHORT / LOW`
|
||||
|
||||
The calculation assumes a divider where the unknown resistance is the high-side resistor from 3.3 V to ADC and the known 10 kΩ resistor is the low-side resistor from ADC to GND:
|
||||
|
||||
`Rx = 10000 * (3300 / Vadc - 1)`
|
||||
|
||||
This test is intended to check whether the USB contact pair can be reused as an ADC-measured resistance input, for example before wiring a 10 kΩ potentiometer. Native USB data is unavailable while resistance mode owns GPIO19/20. Pressing `Restart to USB` calls `ESP.restart()`; after reboot normal USB mode is restored.
|
||||
|
||||
## GFX breath monitor version
|
||||
|
||||
The `usb_contact_screen_start_stub` sketch is a breath monitor firmware based on the production `Arduino_GFX` display path instead of LVGL.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `USB CONTACT`
|
||||
- title in the current version: `BREATH MONITOR`
|
||||
- state: `READY`
|
||||
- action button: `START`
|
||||
|
||||
After tapping `START`:
|
||||
|
||||
- GPIO19 is configured as `OUTPUT LOW`
|
||||
- GPIO20 is configured as `INPUT_PULLUP`
|
||||
- closed contact is treated as `EXHALE`
|
||||
- open contact is treated as `INHALE`
|
||||
- one breathing cycle is measured from one stable `EXHALE` start to the next stable `EXHALE` start
|
||||
- contact changes use an 80 ms debounce
|
||||
- UI shows current cycle duration, arithmetic average duration over the last 5 completed cycles, and elapsed time from start
|
||||
- the physical user/BOOT button opens and closes the settings screen
|
||||
- settings screen has three touch sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
|
||||
- settings are persisted in NVS and restored after power off/on
|
||||
- quiet cycle tick volume uses a compressed quiet scale: previous low audible levels are moved near `9..10`
|
||||
- alert volume uses a gentler low range; level `5` equals the previous maximum alert level
|
||||
- the working screen uses a static frame and only updates value regions to avoid display flicker
|
||||
- the main screen header/status line and the bottom short-average streak line redraw only when their text changes
|
||||
- the `START` button is a flat rounded rectangle with a border; there is no pause button in this version
|
||||
- every new cycle start plays one quiet confirmation beep
|
||||
- if the arithmetic average of the last up to 5 completed cycles is shorter than the selected limit, the device plays warning beeps: 1 beep for the first short average in a row, 2 beeps for the second, up to 5 beeps
|
||||
- completed cycles shorter than 1.5 seconds are ignored as contact bounce
|
||||
- if the current cycle exceeds 60 seconds, the main screen shows `PAUSE`; that long cycle is skipped and the next `EXHALE` start begins a fresh cycle from zero
|
||||
- reset/power cycle restores ordinary native USB boot
|
||||
|
||||
This version is intended to monitor breathing cadence from a dry-contact USB D-/D+ sensor.
|
||||
|
||||
## Dual-mode GFX breath monitor version
|
||||
|
||||
The `breath_dual_mode_monitor` sketch reuses the production-style `Arduino_GFX` visual approach, audio path, settings sliders, and average-cycle alert behavior from the USB contact breath monitor. It supports two start modes on one firmware: USB contact sensor mode and external button mode.
|
||||
|
||||
Initial screen:
|
||||
|
||||
- title: `BREATH MONITOR`
|
||||
- state: `READY`
|
||||
- action button: `START USB SENSOR`
|
||||
- action button: `START MANUAL MONITOR`
|
||||
- action button: `START POT 3-WIRE`
|
||||
- action button: `START POT 2-WIRE`
|
||||
- action button: `START POT CAL`
|
||||
- action button: `START PIN DIAG`
|
||||
|
||||
After `START USB SENSOR`:
|
||||
|
||||
- GPIO19 / USB `D-` is configured as `OUTPUT LOW`
|
||||
- GPIO20 / USB `D+` is configured as `INPUT_PULLUP`
|
||||
- closed contact is treated as `EXHALE`
|
||||
- open contact is treated as `INHALE`
|
||||
- USB sensor cycles shorter than 3 seconds are ignored without resetting the current cycle timer
|
||||
- a short `KEY3 / GPIO18` press opens or closes settings in USB sensor mode
|
||||
- the bottom line shows the durations of the last 5 accepted USB sensor cycles
|
||||
|
||||
After `START MANUAL MONITOR`:
|
||||
|
||||
- `KEY3 / GPIO18` is the external `INHALE` button, active LOW
|
||||
- `BOOT / GPIO0` is the external `EXHALE` button, active LOW
|
||||
- do not hold `BOOT` while booting or resetting the board
|
||||
- the mode title is `MANUAL MONITOR`
|
||||
- accepted manual phases strictly alternate: `INHALE`, then `EXHALE`; a repeated current button or `EXHALE` before the first `INHALE` is ignored without a beep or timer reset
|
||||
- each accepted button press plays one quiet confirmation beep and starts a fresh `Phase time` timer for that inhale or exhale
|
||||
- the working screen does not show touch `INHALE`/`EXHALE` buttons
|
||||
- long-holding `KEY3 / INHALE` for about 850 ms opens settings; the long press still counts as an inhale press
|
||||
- while settings are open, the next `KEY3 / INHALE` press closes settings and also counts as an inhale press
|
||||
|
||||
After `START POT 3-WIRE`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH` and works as the 3.3 V side of the potentiometer test
|
||||
- `GPIO20 / USB D+` is configured as ADC input and must be connected to the potentiometer wiper
|
||||
- `USB GND` must be connected to the other edge pin of the potentiometer
|
||||
- the screen shows position `0..100%`, a bar, ADC raw value, measured millivolts, and estimated `0..50 kΩ` resistance
|
||||
- if ADC saturates or reaches an unsafe high-voltage threshold, the firmware releases `D-` and `D+` to `INPUT`, beeps, and shows `USB/PIN FAULT`
|
||||
- this is only best-effort software protection; ESP32-S3 GPIO pins are not 5 V tolerant, so external wiring must still prevent 5 V from reaching `D+` or `D-`
|
||||
|
||||
After `START POT 2-WIRE`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
|
||||
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
|
||||
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
|
||||
- the screen shows rough position, raw ADC, millivolts, and rough estimated resistance
|
||||
- this mode is intentionally approximate because the ESP32 internal pulldown value is not precise and can vary between boards
|
||||
- use `START POT 3-WIRE` for stable and more linear future breath sensing
|
||||
|
||||
After `START POT CAL`:
|
||||
|
||||
- `GPIO19 / USB D-` is configured as `OUTPUT HIGH`
|
||||
- `GPIO20 / USB D+` is configured as ADC input with internal pulldown
|
||||
- connect only two potentiometer pins between `D-` and `D+`: the wiper and one edge pin
|
||||
- the firmware tracks the observed minimum and maximum ADC millivolts
|
||||
- the screen shows a calibrated `0..100%` position within the observed range, current millivolts, raw ADC, min-max range, and state
|
||||
- `KEY3 / GPIO18` resets the learned min-max calibration
|
||||
- this mode is for relative position testing on weak or shifted USB-pin ranges; it does not report real resistance
|
||||
|
||||
After `START PIN DIAG`:
|
||||
|
||||
- the firmware runs two alternating USB pin drive/read checks
|
||||
- Test A drives `GPIO19 / USB D-` HIGH and reads `GPIO20 / USB D+` as ADC
|
||||
- Test B drives `GPIO20 / USB D+` HIGH and reads `GPIO19 / USB D-` as ADC
|
||||
- shorting `D-` and `D+` should make the ADC side rise if the pins are actually controllable as GPIO
|
||||
- if both tests stay near 0 mV, the USB cable/host, USB PHY, or board wiring is likely holding the lines and the USB data pins are not usable as an analog sensor in that setup
|
||||
|
||||
In both modes:
|
||||
|
||||
- one breathing cycle is measured from one `EXHALE` tap to the next `EXHALE` tap
|
||||
- inhale before any exhale does not create a cycle
|
||||
- button-mode cycles shorter than 1.5 seconds are ignored
|
||||
- USB sensor cycles shorter than 3 seconds are ignored
|
||||
- the UI shows current cycle time, arithmetic average over the last 5 completed cycles, elapsed session time, selected limit, long-pause count, short-average count, and current short-average streak
|
||||
- the lower numeric fields use a larger font than before
|
||||
- if the average of the last up to 5 completed cycles is shorter than the selected limit, warning beeps are played like in the USB contact breath monitor
|
||||
- if the current cycle reaches 60 seconds, 5 loud warning beeps are played, then after 5 seconds another 5 loud warning beeps are played, repeating until the user changes phase / exits the long cycle
|
||||
- in manual monitor mode, a single loud warning beep is also played at 35, 40, 45, 50, and 55 seconds of an unchanged inhale or exhale; the repeated five-beep alarm starts at 60 seconds
|
||||
- settings keep the same sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
|
||||
@@ -19,7 +19,7 @@ SHiNE — проект децентрализованного общения: б
|
||||
|
||||
## Самостоятельный запуск
|
||||
|
||||
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
|
||||
Основной сервер собирается Gradle из корня репозитория. Для локального запуска предусмотрены `./gradlew startLocal` и `./gradlew startLocalWithBuild`; состав и требования этих задач зависят от локальной конфигурации. Начните с [инструкций по развёртыванию](deploy/README.md) и [примера настроек](application.properties.example). Клиент находится в `shine-UI/`. Для `./gradlew startLocal` скопируйте `application.properties.example` в `SHiNE-server/application.properties` и заполните параметры своей среды. При `java -jar` внешний `application.properties` ищется в текущем рабочем каталоге. Встроенный файл необязателен. Публичное пошаговое руководство по установке всего комплекса ещё готовится.
|
||||
|
||||
## Документация
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# SHiNE Browser Plugin Wallet
|
||||
|
||||
> Статус: старая версия. Плагин находится в разработке и пока не работает.
|
||||
|
||||
Chrome-compatible Manifest V3 plugin for SHiNE wallet-session login.
|
||||
|
||||
## Что уже умеет
|
||||
|
||||
@@ -29,9 +29,9 @@ SHiNE-server — серверная часть мессенджера SHiNE: Web
|
||||
|
||||
## Настройка сервера в Solana (Solana PDA)
|
||||
|
||||
Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.2 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint.
|
||||
Серверный аккаунт SHiNE регистрируется как обычный `user_pda` формата 1.0 с присутствующим `ServerProfileBlock`. Отдельного `is_server` в PDA нет: наличие server profile означает, что аккаунт объявляет серверный endpoint.
|
||||
|
||||
PDA 1.2 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave.
|
||||
PDA 1.0 сейчас допускает **один** адрес сервера (`address_format_type + address_format_version + address`). Бинарный блок использует count/array, чтобы будущая версия протокола могла увеличить лимит без смены структуры блока. Прямой список `sync_servers` удалён: пользовательские blockchain синхронизируются через Arweave.
|
||||
|
||||
Клиенты читают server PDA из Solana, получают опубликованный endpoint и подключаются к нему. Межсерверная доставка DM через access-server routing остаётся отдельным механизмом.
|
||||
|
||||
@@ -45,7 +45,7 @@ shine-UI/server-ui.html
|
||||
- `shine-UI/server-ui/create-server-pda.html` — первичная регистрация серверного аккаунта;
|
||||
- `shine-UI/server-ui/update-server-pda.html` — обновление адреса сервера.
|
||||
|
||||
PDA 1.2 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root.
|
||||
PDA 1.0 использует три постоянные роли ключей: `root` (cold recovery), `blockchain` (обычный authority и подпись блоков) и `client` (клиент/кошелёк). Обычный update авторизуется активным последним blockchain key; root используется для recovery и может менять root.
|
||||
|
||||
Актуальные адреса программ Solana (devnet):
|
||||
- `shine_users`: `SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6`
|
||||
@@ -55,7 +55,7 @@ PDA 1.2 использует три постоянные роли ключей:
|
||||
|
||||
## Синхронизация пользовательских blockchain
|
||||
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync пока может оставаться как inert legacy, но не должен включаться в runtime.
|
||||
Прямой peer-to-peer blockchain sync через `sync_servers` отключён. Сервер восстанавливает и синхронизирует пользовательские записи через Arweave. Код старого peer-sync удалён; не восстанавливать его. `ListBlockchainHeads` остаётся read-only API тестового издателя.
|
||||
|
||||
## Деплой
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package server.archive;
|
||||
|
||||
import blockchain.Ans104DataItem;
|
||||
import blockchain.BchBlockEntry;
|
||||
import blockchain.CoreContentContainer;
|
||||
import blockchain.CoreContentTransport;
|
||||
import java.time.Instant;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Thin adapter for the existing archive queues. No signing, state or independent retry. */
|
||||
final class ArchiveBlockPair {
|
||||
private ArchiveBlockPair() {}
|
||||
|
||||
@FunctionalInterface interface Upload<R> {
|
||||
R upload(byte[] raw, byte[] id) throws Exception;
|
||||
}
|
||||
@FunctionalInterface interface Download {
|
||||
byte[] download(byte[] id) throws Exception;
|
||||
}
|
||||
|
||||
/** Returns CORE acknowledgement only after both uploads succeed. */
|
||||
static <R> R publish(byte[] container, byte[] expectedCoreId, Upload<R> uploader) throws Exception {
|
||||
BchBlockEntry block = BchBlockEntry.fromCoreContent(container);
|
||||
Ans104DataItem core = block.getCoreDataItem(), content = block.getContentDataItem();
|
||||
if (!Arrays.equals(core.id32(), expectedCoreId)) throw new IllegalArgumentException("CORE id mismatch");
|
||||
uploader.upload(content.rawBytes(), content.id32());
|
||||
return uploader.upload(core.rawBytes(), core.id32());
|
||||
}
|
||||
|
||||
/** Download by signed reference, not by search tag or the CORE bundle location. */
|
||||
static byte[] download(byte[] coreRaw, byte[] expectedCoreId, Download downloader) throws Exception {
|
||||
Ans104DataItem core = new Ans104DataItem(coreRaw);
|
||||
var record = CoreContentTransport.verifyCore(core, core.owner32(), expectedCoreId, Instant.now().getEpochSecond());
|
||||
Ans104DataItem content = new Ans104DataItem(downloader.download(record.contentDataItemId32()));
|
||||
CoreContentTransport.verifyContent(record, content, core.owner32());
|
||||
return CoreContentContainer.pack(core, content);
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -14,8 +14,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Publisher с двумя путями доставки:
|
||||
* 1) Turbo — немедленная неблокирующая попытка для только что принятого блока;
|
||||
* 2) плановый fixed-delay цикл — страховочная добивка только зависших pending-записей.
|
||||
* Серверный Turbo publisher обслуживает candidate-блоки ротации ключей.
|
||||
* Пользовательские CORE/CONTENT в режиме client_only загружает браузер.
|
||||
*/
|
||||
public final class ArweaveBlockPublisherScheduler {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
|
||||
|
||||
+8
-96
@@ -8,24 +8,22 @@ import shine.db.entities.BlockEntry;
|
||||
import shine.db.entities.KeyRotationCandidateBlockEntry;
|
||||
import server.sync.ArweavePublishSignal;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/** Publishes locally-created signed user DataItems through the configured transport. */
|
||||
/** Серверный 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 ArweaveL1Uploader arweaveUploader;
|
||||
private final TurboDataItemUploader turboUploader;
|
||||
|
||||
public ArweaveBlockPublisherService(ArweaveBlocksConfig cfg) {
|
||||
cfg.validatePublisher();
|
||||
this.cfg = cfg;
|
||||
this.arweaveUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.ARWEAVE ? new ArweaveL1Uploader(cfg) : null;
|
||||
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
|
||||
}
|
||||
|
||||
@@ -42,22 +40,13 @@ public final class ArweaveBlockPublisherService {
|
||||
if (entry == null) return true;
|
||||
byte[] raw = entry.getBlockBytes();
|
||||
if (raw == null || raw.length == 0) return false;
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
|
||||
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
|
||||
return true;
|
||||
}
|
||||
|
||||
BlockEntry entry = blocksDAO.getPendingArweaveByDataItemId(id);
|
||||
if (entry == null) return true;
|
||||
byte[] raw = entry.getBlockBytes();
|
||||
if (raw == null || raw.length == 0) return false;
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
|
||||
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
public int runCycle() throws Exception {
|
||||
@@ -83,22 +72,12 @@ public final class ArweaveBlockPublisherService {
|
||||
attempted += rotationCandidates.size();
|
||||
published += switch (cfg.publishMode()) {
|
||||
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
|
||||
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates);
|
||||
case ARWEAVE -> throw new IllegalStateException("CORE/CONTENT requires Turbo");
|
||||
case NONE -> 0;
|
||||
};
|
||||
}
|
||||
|
||||
int remaining = Math.max(0, maxItems - attempted);
|
||||
if (remaining == 0) return published;
|
||||
|
||||
List<BlockEntry> candidates = blocksDAO.listPendingArweave(remaining);
|
||||
candidates = candidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
|
||||
if (candidates.isEmpty()) return published;
|
||||
published += switch (cfg.publishMode()) {
|
||||
case TURBO -> publishTurbo(candidates, onPublished);
|
||||
case ARWEAVE -> publishDirectArweave(candidates);
|
||||
case NONE -> 0;
|
||||
};
|
||||
// Пользовательские блоки в режиме client_only публикует браузер.
|
||||
return published;
|
||||
}
|
||||
|
||||
@@ -110,7 +89,7 @@ public final class ArweaveBlockPublisherService {
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
@@ -135,7 +114,7 @@ public final class ArweaveBlockPublisherService {
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
try {
|
||||
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
|
||||
TurboDataItemUploader.UploadResult result = ArchiveBlockPair.publish(raw, id, turboUploader::upload);
|
||||
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
|
||||
onPublished.accept(id);
|
||||
published++;
|
||||
@@ -151,71 +130,4 @@ public final class ArweaveBlockPublisherService {
|
||||
return published;
|
||||
}
|
||||
|
||||
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
|
||||
List<byte[]> items = new ArrayList<>();
|
||||
List<byte[]> ids = new ArrayList<>();
|
||||
long estimated = 32;
|
||||
for (KeyRotationCandidateBlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
long next = estimated + 64L + raw.length;
|
||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
||||
if (next > cfg.publishMaxBundleBytes()) {
|
||||
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
||||
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
|
||||
continue;
|
||||
}
|
||||
items.add(raw);
|
||||
ids.add(id);
|
||||
estimated = next;
|
||||
}
|
||||
if (items.isEmpty()) return 0;
|
||||
|
||||
byte[] bundle = Ans104Bundle.write(items);
|
||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
||||
);
|
||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
||||
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
||||
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
||||
items.size(), result.txId(), bundle.length);
|
||||
return items.size();
|
||||
}
|
||||
|
||||
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
|
||||
List<byte[]> items = new ArrayList<>();
|
||||
List<byte[]> ids = new ArrayList<>();
|
||||
long estimated = 32;
|
||||
for (BlockEntry e : candidates) {
|
||||
byte[] raw = e.getBlockBytes();
|
||||
byte[] id = e.getDataItemId();
|
||||
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
|
||||
long next = estimated + 64L + raw.length;
|
||||
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
|
||||
if (next > cfg.publishMaxBundleBytes()) {
|
||||
log.error("One DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
|
||||
e.getBchName(), e.getBlockNumber(), raw.length);
|
||||
continue;
|
||||
}
|
||||
items.add(raw);
|
||||
ids.add(id);
|
||||
estimated = next;
|
||||
}
|
||||
if (items.isEmpty()) return 0;
|
||||
|
||||
byte[] bundle = Ans104Bundle.write(items);
|
||||
List<ArweaveL1Uploader.Tag> rootTags = List.of(
|
||||
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
|
||||
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
|
||||
);
|
||||
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
|
||||
blocksDAO.markArweavePublished(ids, System.currentTimeMillis());
|
||||
log.info("Published {} SHiNE test DataItems in direct Arweave root tx {} (bundle={} bytes)",
|
||||
items.size(), result.txId(), bundle.length);
|
||||
return items.size();
|
||||
}
|
||||
}
|
||||
|
||||
+134
-28
@@ -10,15 +10,18 @@ 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;
|
||||
|
||||
@@ -38,9 +41,8 @@ import java.time.Duration;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
|
||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
||||
* or inside a direct server-created ANS-104 bundle.
|
||||
* Discovers signed CORE items and registration certificates in the active App namespace.
|
||||
* Fetches signed CONTENT by the ID in CORE; the existing queue holds one complete pair.
|
||||
*/
|
||||
public final class ArweaveBlockSyncService {
|
||||
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockSyncService.class);
|
||||
@@ -114,14 +116,33 @@ public final class ArweaveBlockSyncService {
|
||||
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
|
||||
continue;
|
||||
}
|
||||
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) {
|
||||
if (blocksDAO.existsByDataItemId(id32)) {
|
||||
// Локально принятый блок должен получить подтверждение Arweave без повторного применения.
|
||||
try {
|
||||
DownloadedEvent published = downloadEvent(dataItemId);
|
||||
BlockEntry local = blocksDAO.getByDataItemId(id32);
|
||||
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
|
||||
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
|
||||
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
|
||||
} else {
|
||||
log.warn("Arweave DataItem {} differs from locally accepted bytes", dataItemId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
lowestRetryHeight = Math.min(lowestRetryHeight, height);
|
||||
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
|
||||
continue;
|
||||
}
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
continue;
|
||||
}
|
||||
if (importDAO.exists(id32)) {
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
DownloadedEvent downloaded = downloadEvent(dataItemId);
|
||||
if (downloaded.registration()) {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
unresolvedDownloads.remove(dataItemId);
|
||||
@@ -162,14 +183,26 @@ public final class ArweaveBlockSyncService {
|
||||
if (attempted >= cfg.syncPageSize()) break;
|
||||
attempted++;
|
||||
|
||||
if (blocksDAO.existsByDataItemId(pending.id32()) || importDAO.exists(pending.id32())) {
|
||||
if (blocksDAO.existsByDataItemId(pending.id32())) {
|
||||
try {
|
||||
DownloadedEvent published = downloadEvent(pending.dataItemId());
|
||||
BlockEntry local = blocksDAO.getByDataItemId(pending.id32());
|
||||
if (local != null && Arrays.equals(local.getBlockBytes(), published.rawDataItem())) {
|
||||
shine.db.dao.BlockPublicationsDAO.getInstance().arweaveConfirmed(
|
||||
local.getLogin(), local.getForkNumber(), local.getBlockNumber(), System.currentTimeMillis());
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
}
|
||||
} catch (Exception e) { log.debug("Arweave pair {} still unavailable: {}", pending.dataItemId(), e.getMessage()); }
|
||||
continue;
|
||||
}
|
||||
if (importDAO.exists(pending.id32())) {
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
continue;
|
||||
}
|
||||
|
||||
DownloadedDataItem downloaded;
|
||||
DownloadedEvent downloaded;
|
||||
try {
|
||||
downloaded = downloadSignedDataItem(pending.dataItemId());
|
||||
downloaded = downloadEvent(pending.dataItemId());
|
||||
} catch (RetryableDataItemDownloadException e) {
|
||||
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
|
||||
unresolvedDownloads.remove(pending.dataItemId());
|
||||
@@ -183,7 +216,7 @@ public final class ArweaveBlockSyncService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||
if (downloaded.registration()) {
|
||||
try {
|
||||
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||
@@ -225,7 +258,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (pending.isEmpty()) break;
|
||||
for (ArweaveBlockImportDAO.QueueItem q : pending) {
|
||||
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
|
||||
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
|
||||
SolanaUserPdaCurrentEntry activeUser = resolveChainOwnerByLogin(q.parsedLogin());
|
||||
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
|
||||
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -249,15 +282,16 @@ public final class ArweaveBlockSyncService {
|
||||
Ans104DataItem item;
|
||||
BchBlockEntry parsedBlock;
|
||||
try {
|
||||
item = new Ans104DataItem(q.rawDataItem());
|
||||
parsedBlock = new BchBlockEntry(q.rawDataItem());
|
||||
parsedBlock = BchBlockEntry.fromCoreContent(q.rawDataItem());
|
||||
item = parsedBlock.getCoreDataItem();
|
||||
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
|
||||
} catch (Exception e) {
|
||||
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
|
||||
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
|
||||
progress = true;
|
||||
continue;
|
||||
}
|
||||
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry physicalUser = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (physicalUser == null || physicalUser.getBlockchainName() == null
|
||||
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|
||||
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
|
||||
@@ -278,6 +312,14 @@ public final class ArweaveBlockSyncService {
|
||||
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)) {
|
||||
@@ -328,14 +370,11 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
try {
|
||||
// Metadata is trusted only after complete ANS-104 validation.
|
||||
Ans104DataItem item = new Ans104DataItem(raw);
|
||||
BchBlockEntry b = BchBlockEntry.fromCoreContent(raw);
|
||||
Ans104DataItem item = b.getCoreDataItem();
|
||||
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
|
||||
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
|
||||
throw new IllegalArgumentException("bad App tag");
|
||||
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
|
||||
BchBlockEntry b = new BchBlockEntry(raw);
|
||||
|
||||
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
|
||||
SolanaUserPdaCurrentEntry owner = resolveChainOwnerByBlockchainKey(item.owner32());
|
||||
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
|
||||
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
|
||||
continue;
|
||||
@@ -352,7 +391,7 @@ public final class ArweaveBlockSyncService {
|
||||
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
|
||||
if (b.blockNumber != fb.forkPointBlockNumber + 1)
|
||||
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
|
||||
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
|
||||
SolanaUserPdaCurrentEntry parent = resolveChainOwnerByBlockchainKey(fb.parentBlockchainKey32);
|
||||
if (parent == null || parent.getBlockchainName() == null
|
||||
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
|
||||
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
|
||||
@@ -388,9 +427,64 @@ public final class ArweaveBlockSyncService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Обычный пользователь подтверждается текущим Solana PDA. У бесплатной регистрации PDA
|
||||
* намеренно отсутствует: её проверяемая идентичность хранится в сертификате. Для обеих
|
||||
* моделей импортёр должен сопоставить ANS-104 owner с уже проверенной локальной записью,
|
||||
* иначе блоки FREE_CERT никогда не смогут попасть на другой сервер.
|
||||
*/
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByLogin(String login) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByLogin(login);
|
||||
if (solana != null) return solana;
|
||||
|
||||
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||
if (identity == null || !identity.isFree() || identity.blockchainKey() == null || identity.blockchainKey().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return freeCertificateOwner(identity.fullLogin(), identity.blockchainKey());
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainKey(byte[] owner32) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainKey(owner32);
|
||||
if (solana != null) return solana;
|
||||
if (owner32 == null || owner32.length != 32) return null;
|
||||
|
||||
String blockchainKey = KeyEncodingUtil.encodeBase58(owner32);
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT login, blockchain_key
|
||||
FROM user_identity_current
|
||||
WHERE registration_status='FREE_CERT' AND blockchain_key=?
|
||||
LIMIT 1
|
||||
""")) {
|
||||
ps.setString(1, blockchainKey);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next() ? freeCertificateOwner(rs.getString("login"), rs.getString("blockchain_key")) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private SolanaUserPdaCurrentEntry resolveChainOwnerByBlockchainName(String blockchainName) throws SQLException {
|
||||
SolanaUserPdaCurrentEntry solana = usersDAO.getByBlockchainName(blockchainName);
|
||||
if (solana != null) return solana;
|
||||
if (blockchainName == null || !blockchainName.endsWith("-001")) return null;
|
||||
String login = blockchainName.substring(0, blockchainName.length() - 4);
|
||||
SolanaUserPdaCurrentEntry free = resolveChainOwnerByLogin(login);
|
||||
return free != null && blockchainName.equalsIgnoreCase(free.getBlockchainName()) ? free : null;
|
||||
}
|
||||
|
||||
private static SolanaUserPdaCurrentEntry freeCertificateOwner(String login, String blockchainKey) {
|
||||
SolanaUserPdaCurrentEntry owner = new SolanaUserPdaCurrentEntry();
|
||||
owner.setLogin(login);
|
||||
owner.setBlockchainName(login.toLowerCase(Locale.ROOT) + "-001");
|
||||
owner.setBlockchainKey(KeyEncodingUtil.base58KeyToBase64_32(blockchainKey));
|
||||
owner.setPaidLimitBytes(0L);
|
||||
return owner;
|
||||
}
|
||||
|
||||
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
|
||||
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
|
||||
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes());s.setFileSizeBytes(0L);
|
||||
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
|
||||
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
|
||||
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
|
||||
@@ -414,7 +508,7 @@ public final class ArweaveBlockSyncService {
|
||||
while(rs.next())logins.add(rs.getString(1));
|
||||
}
|
||||
for(String login:logins){
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);
|
||||
if(u==null||u.getBlockchainName()==null)continue;
|
||||
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
|
||||
}
|
||||
@@ -467,7 +561,7 @@ public final class ArweaveBlockSyncService {
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
|
||||
BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
|
||||
BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
|
||||
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
|
||||
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
|
||||
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
|
||||
@@ -477,17 +571,17 @@ public final class ArweaveBlockSyncService {
|
||||
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
|
||||
}
|
||||
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
|
||||
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
SolanaUserPdaCurrentEntry u=resolveChainOwnerByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
|
||||
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
|
||||
try{
|
||||
validateGenericStaging(login);
|
||||
cleanupDAO.cleanupLoginForCanonicalReplay(login);
|
||||
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
long cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
|
||||
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
|
||||
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
|
||||
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=BchBlockEntry.fromCoreContent(raw);
|
||||
String bch=login+"-"+String.format("%03d",f);
|
||||
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
if(f!=currentFork){SolanaUserPdaCurrentEntry forkOwner=resolveChainOwnerByBlockchainName(bch);long limit=forkOwner==null?0L:forkOwner.getPaidLimitBytes();BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
|
||||
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
|
||||
cumulative+=raw.length;prevNumber=n;prevHash=hash;
|
||||
}}
|
||||
@@ -565,6 +659,17 @@ public final class ArweaveBlockSyncService {
|
||||
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
|
||||
}
|
||||
|
||||
/** Preserve original CORE root/height; CONTENT may be in an entirely different root bundle. */
|
||||
private DownloadedEvent downloadEvent(String dataItemId) throws Exception {
|
||||
DownloadedDataItem first = downloadSignedDataItem(dataItemId);
|
||||
if (isRegistrationItem(first.rawDataItem())) {
|
||||
return new DownloadedEvent(first.rootTxId(), first.rawDataItem(), true);
|
||||
}
|
||||
byte[] container = ArchiveBlockPair.download(first.rawDataItem(), B64URL.decode(dataItemId),
|
||||
contentId -> downloadSignedDataItem(Base64.getUrlEncoder().withoutPadding().encodeToString(contentId)).rawDataItem());
|
||||
return new DownloadedEvent(first.rootTxId(), container, false);
|
||||
}
|
||||
|
||||
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
||||
return graphQlPage(minHeight, cursor, false);
|
||||
}
|
||||
@@ -763,6 +868,7 @@ public final class ArweaveBlockSyncService {
|
||||
|
||||
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
|
||||
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
|
||||
private record DownloadedEvent(String rootTxId, byte[] rawDataItem, boolean registration) {}
|
||||
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
|
||||
|
||||
private static final class RetryableDataItemDownloadException extends IOException {
|
||||
|
||||
+3
-3
@@ -49,7 +49,7 @@ public record ArweaveBlocksConfig(
|
||||
}
|
||||
|
||||
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
|
||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE;
|
||||
public static final String TEST_TAG_VALUE = ShineProtocolTags.CORE_NAMESPACE;
|
||||
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
|
||||
|
||||
public static ArweaveBlocksConfig load() {
|
||||
@@ -84,8 +84,8 @@ public record ArweaveBlocksConfig(
|
||||
public boolean publishEnabled() { return publishMode != PublishMode.NONE; }
|
||||
|
||||
public void validatePublisher() {
|
||||
if (publishMode == PublishMode.ARWEAVE && walletJwkPath == null) {
|
||||
throw new IllegalArgumentException("arweave.blocks.publish.walletJwkPath is required for mode=arweave");
|
||||
if (publishMode == PublishMode.ARWEAVE) {
|
||||
throw new IllegalArgumentException("CORE/CONTENT user-block publication requires mode=turbo (or none)");
|
||||
}
|
||||
if (publishMode == PublishMode.TURBO && (turboUploadUrl == null || turboUploadUrl.isBlank())) {
|
||||
throw new IllegalArgumentException("arweave.blocks.publish.turbo.uploadUrl is required for mode=turbo");
|
||||
|
||||
+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;
|
||||
}
|
||||
}
|
||||
+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();}
|
||||
}
|
||||
+21
-5
@@ -23,17 +23,22 @@ import java.util.logging.Logger;
|
||||
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;
|
||||
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||
String freeNamespace=cfg.getStringOrEmpty("freeRegistration.namespace").trim();
|
||||
boolean freeRegistrationEnabled=cfg.getBoolean("freeRegistration.enabled",false) && !freeNamespace.isEmpty();
|
||||
if (freeRegistrationEnabled) {
|
||||
String domainsFile = cfg.getStringOrEmpty("freeRegistration.email.allowedDomainsFile");
|
||||
if (domainsFile.isBlank()) domainsFile = "allowed-email-domains.txt";
|
||||
// Относительный путь — от WorkingDirectory процесса Java.
|
||||
@@ -43,8 +48,16 @@ public final class FreeRegistrationApiBootstrap {
|
||||
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||
issuer=new FreeRegistrationIssuer(dbSource(),newSigner,allowEmailReuse);
|
||||
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));
|
||||
// Секрет берём ТОЛЬКО из окружения, не из файлов репозитория.
|
||||
@@ -58,15 +71,18 @@ public final class FreeRegistrationApiBootstrap {
|
||||
}
|
||||
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher,emailSender,
|
||||
cfg.getBoolean("freeRegistration.email.allowTestCode",false),
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains);
|
||||
cfg.getBoolean("freeRegistration.email.allowReuse",false), allowedEmailDomains,
|
||||
freeRegistrationEnabled ? freeNamespace : "");
|
||||
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||
signer=newSigner; workflow=newWorkflow;
|
||||
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<>();
|
||||
|
||||
+8
-5
@@ -16,10 +16,7 @@ import java.util.Locale;
|
||||
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
|
||||
public final class FreeRegistrationCertificateV1 {
|
||||
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
|
||||
private static final List<Ans104DataItem.Tag> TAGS = List.of(
|
||||
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
private static final List<Ans104DataItem.Tag> TAGS = ShineProtocolTags.CORE_REGISTRATION_TAGS;
|
||||
|
||||
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||
byte[] clientKey, byte[] innerSignature,
|
||||
@@ -62,13 +59,19 @@ public final class FreeRegistrationCertificateV1 {
|
||||
|
||||
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(email));
|
||||
payload.writeBytes(emailHash);
|
||||
byte[] data = payload.toByteArray();
|
||||
byte[] owner = signer.publicKey32();
|
||||
require32(owner);
|
||||
|
||||
+46
-2
@@ -11,7 +11,7 @@ import java.util.Arrays;
|
||||
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||
public final class FreeRegistrationIssuer {
|
||||
private final DataSource db;
|
||||
private final RegistrarSigner signer;
|
||||
private final RegistrationCertificateSigner signer;
|
||||
private final boolean allowEmailReuse;
|
||||
|
||||
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||
@@ -19,11 +19,49 @@ public final class FreeRegistrationIssuer {
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -69,6 +107,12 @@ public final class FreeRegistrationIssuer {
|
||||
}
|
||||
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
|
||||
byte[] signed = signer.issue(fullLogin, root32, blockchain32, client32, expectedEmail);
|
||||
var verified = FreeRegistrationCertificateV1.verify(signed, signer.publicKey32());
|
||||
if (!fullLogin.equals(verified.login()) || !Arrays.equals(root32, verified.rootKey()) ||
|
||||
!Arrays.equals(blockchain32, verified.blockchainKey()) || !Arrays.equals(client32, verified.clientKey()) ||
|
||||
!Arrays.equals(expectedEmail, verified.emailSha256()))
|
||||
throw new IllegalStateException("Registrar returned mismatched certificate");
|
||||
return signed;
|
||||
}
|
||||
}
|
||||
|
||||
+28
-6
@@ -51,10 +51,12 @@ public final class FreeRegistrationWorkflow {
|
||||
private final boolean allowTestCode;
|
||||
private final boolean allowEmailReuse;
|
||||
private final AllowedEmailDomains allowedEmailDomains;
|
||||
/** Единственный type-2 namespace, для которого этот сервер является регистратором. */
|
||||
private final String freeRegistrationNamespace;
|
||||
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
AllowedEmailDomains allowedEmailDomains, String freeRegistrationNamespace) {
|
||||
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||
if (issuer != null && emailSender == null) throw new IllegalArgumentException("Email sender is required");
|
||||
if (emailSender != null && allowedEmailDomains == null)
|
||||
@@ -65,11 +67,24 @@ public final class FreeRegistrationWorkflow {
|
||||
this.emailSender = emailSender;
|
||||
this.allowTestCode = allowTestCode;
|
||||
this.allowEmailReuse = allowEmailReuse;
|
||||
this.freeRegistrationNamespace = normalizeConfiguredNamespace(freeRegistrationNamespace);
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse,
|
||||
AllowedEmailDomains allowedEmailDomains) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse, allowedEmailDomains, "");
|
||||
}
|
||||
private static String normalizeConfiguredNamespace(String value) {
|
||||
String namespace = value == null ? "" : value.trim();
|
||||
if (namespace.isEmpty()) return "";
|
||||
if (!namespace.matches("[a-z0-9_]+"))
|
||||
throw new IllegalArgumentException("Free registration namespace must use lowercase ASCII letters, digits or _");
|
||||
return namespace;
|
||||
}
|
||||
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher,
|
||||
RegistrationEmailSender emailSender, boolean allowTestCode, boolean allowEmailReuse) {
|
||||
this(issuer, publisher, emailSender, allowTestCode, allowEmailReuse,
|
||||
emailSender == null ? null : loadDefaultEmailDomains());
|
||||
emailSender == null ? null : loadDefaultEmailDomains(), "");
|
||||
}
|
||||
private static AllowedEmailDomains loadDefaultEmailDomains() {
|
||||
try {
|
||||
@@ -94,10 +109,15 @@ public final class FreeRegistrationWorkflow {
|
||||
try (Connection c = DbController.getInstance().getConnection();
|
||||
PreparedStatement ps = c.prepareStatement("""
|
||||
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,currency_code,default_server_login
|
||||
FROM shine_namespace_current ORDER BY namespace
|
||||
"""); ResultSet rs = ps.executeQuery()) {
|
||||
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)));
|
||||
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);
|
||||
}
|
||||
@@ -111,6 +131,8 @@ public final class FreeRegistrationWorkflow {
|
||||
try (ResultSet rs=p.executeQuery()) {
|
||||
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
|
||||
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3); currencyCode=rs.getInt(4);
|
||||
if (type == 2 && !namespace.equals(freeRegistrationNamespace))
|
||||
throw new IllegalArgumentException("Free registration is unavailable for this namespace");
|
||||
if (currencyCode != 1) throw new IllegalStateException("Unsupported namespace currency");
|
||||
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||
}
|
||||
|
||||
+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;
|
||||
}
|
||||
+5
-2
@@ -122,9 +122,12 @@ public final class VerifiedFreeRegistrationImporter {
|
||||
INSERT INTO blockchain_state_store (
|
||||
login, fork_number, blockchain_key, size_limit, file_size_bytes,
|
||||
last_block_number, last_block_hash, updated_at_ms)
|
||||
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
|
||||
VALUES (?, 1, ?, 0, 0, -1, ?, ?)
|
||||
""")) {
|
||||
insert.setString(1, login);
|
||||
// blockchain_state — техническая проекция chain: её ключ
|
||||
// совпадает с normalized_login и blockchain_name, а не с
|
||||
// отображаемым написанием login в сертификате.
|
||||
insert.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
|
||||
// как и у пользователей, импортированных из Solana PDA.
|
||||
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
|
||||
|
||||
+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");
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -19,7 +19,7 @@ public final class FreeRegistrationCertificateV1Check {
|
||||
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
|
||||
" Alice.Example+Tag@Example.COM ", signer);
|
||||
var item = new Ans104DataItem(cert);
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
|
||||
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE))
|
||||
throw new AssertionError("Current App tag missing");
|
||||
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|
||||
@@ -37,7 +37,7 @@ public final class FreeRegistrationCertificateV1Check {
|
||||
throw new AssertionError("Inner signature tampering accepted"); }
|
||||
catch (IllegalArgumentException expected) {}
|
||||
}
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
|
||||
System.out.println("PASS: current App=" + ShineProtocolTags.CORE_NAMESPACE
|
||||
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||
}
|
||||
}
|
||||
|
||||
+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)");
|
||||
}
|
||||
}
|
||||
+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"));
|
||||
}
|
||||
}
|
||||
@@ -56,7 +56,7 @@ public final class Ans104DataItem {
|
||||
|
||||
public Ans104DataItem(byte[] bytes) {
|
||||
Objects.requireNonNull(bytes, "bytes == null");
|
||||
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8 + 1) {
|
||||
if (bytes.length < 2 + SIGNATURE_LEN + OWNER_LEN + 1 + 1 + 8 + 8) {
|
||||
throw new IllegalArgumentException("ANS-104 DataItem too short: " + bytes.length);
|
||||
}
|
||||
if (bytes.length > MAX_DATA_ITEM_BYTES) {
|
||||
@@ -126,7 +126,8 @@ public final class Ans104DataItem {
|
||||
}
|
||||
|
||||
public byte[] signingMessage() {
|
||||
return buildSigningMessage(owner, target, anchor, tags, data);
|
||||
// Проверяем именно подписанные исходные байты, не повторную Avro-сериализацию.
|
||||
return signingMessageRaw(owner, target, anchor, rawTags, data);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,6 +152,10 @@ public final class Ans104DataItem {
|
||||
byte[] safeData = data == null ? new byte[0] : Arrays.copyOf(data, data.length);
|
||||
|
||||
byte[] rawTags = serializeAvroTags(safeTags);
|
||||
return signingMessageRaw(owner32, safeTarget, safeAnchor, rawTags, safeData);
|
||||
}
|
||||
|
||||
private static byte[] signingMessageRaw(byte[] owner32, byte[] safeTarget, byte[] safeAnchor, byte[] rawTags, byte[] safeData) {
|
||||
return deepHash(List.of(
|
||||
utf8("dataitem"),
|
||||
utf8("1"),
|
||||
@@ -270,15 +275,20 @@ public final class Ans104DataItem {
|
||||
}
|
||||
|
||||
private static List<Tag> parseAvroTags(byte[] raw, long declaredCount) {
|
||||
if (raw.length == 0 && declaredCount == 0) return List.of();
|
||||
AvroCursor c = new AvroCursor(raw);
|
||||
List<Tag> out = new ArrayList<>();
|
||||
boolean terminated = false;
|
||||
while (!c.eof()) {
|
||||
long count = c.readLong();
|
||||
if (count == 0) break;
|
||||
if (count == 0) { terminated = true; break; }
|
||||
int blockEnd = -1;
|
||||
if (count < 0) {
|
||||
if (count == Long.MIN_VALUE) throw new IllegalArgumentException("Invalid Avro count");
|
||||
count = -count;
|
||||
long blockBytes = c.readLong();
|
||||
if (blockBytes < 0) throw new IllegalArgumentException("Negative Avro tag block size");
|
||||
if (blockBytes < 0 || blockBytes > raw.length - c.p) throw new IllegalArgumentException("Invalid Avro tag block size");
|
||||
blockEnd = c.p + (int) blockBytes;
|
||||
}
|
||||
if (count > MAX_TAGS_COUNT || out.size() + count > MAX_TAGS_COUNT) {
|
||||
throw new IllegalArgumentException("Too many Avro tags");
|
||||
@@ -291,7 +301,9 @@ public final class Ans104DataItem {
|
||||
if (value.getBytes(StandardCharsets.UTF_8).length > 3072) throw new IllegalArgumentException("ANS-104 tag value exceeds 3072 bytes");
|
||||
out.add(new Tag(name, value));
|
||||
}
|
||||
if (blockEnd != -1 && c.p != blockEnd) throw new IllegalArgumentException("Avro tag block size mismatch");
|
||||
}
|
||||
if (!terminated) throw new IllegalArgumentException("Missing Avro array terminator");
|
||||
if (!c.eof()) {
|
||||
throw new IllegalArgumentException("Trailing bytes in ANS-104 Avro tags");
|
||||
}
|
||||
@@ -312,6 +324,7 @@ public final class Ans104DataItem {
|
||||
while (true) {
|
||||
if (p >= data.length) throw new IllegalArgumentException("Truncated Avro long");
|
||||
int b = data[p++] & 0xff;
|
||||
if (shift == 63 && (b & 0xfe) != 0) throw new IllegalArgumentException("Avro long too large");
|
||||
raw |= (long) (b & 0x7f) << shift;
|
||||
if ((b & 0x80) == 0) break;
|
||||
shift += 7;
|
||||
@@ -324,7 +337,9 @@ public final class Ans104DataItem {
|
||||
if (len < 0 || len > Integer.MAX_VALUE || p + len > data.length) {
|
||||
throw new IllegalArgumentException("Bad Avro string length: " + len);
|
||||
}
|
||||
String s = new String(data, p, (int) len, StandardCharsets.UTF_8);
|
||||
String s;
|
||||
try { s = StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(data, p, (int) len)).toString(); }
|
||||
catch (java.nio.charset.CharacterCodingException e) { throw new IllegalArgumentException("Invalid UTF-8 Avro tag", e); }
|
||||
p += (int) len;
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -49,6 +49,9 @@ public final class BchBlockEntry {
|
||||
public final BodyRecord body;
|
||||
|
||||
private final Ans104DataItem dataItem;
|
||||
private final Ans104DataItem contentItem;
|
||||
private final CoreRecord coreRecord;
|
||||
private final ContentRecord contentRecord;
|
||||
private final byte[] frameBytes;
|
||||
private final byte[] hash32;
|
||||
|
||||
@@ -56,6 +59,9 @@ public final class BchBlockEntry {
|
||||
public BchBlockEntry(byte[] fullDataItemBytes) {
|
||||
Objects.requireNonNull(fullDataItemBytes, "fullDataItemBytes == null");
|
||||
this.dataItem = new Ans104DataItem(fullDataItemBytes);
|
||||
this.contentItem = null;
|
||||
this.coreRecord = null;
|
||||
this.contentRecord = null;
|
||||
this.frameBytes = dataItem.data();
|
||||
if (frameBytes.length < FRAME_HEADER_SIZE) {
|
||||
throw new IllegalArgumentException("SHiNE Frame v1 too short: " + frameBytes.length);
|
||||
@@ -90,7 +96,57 @@ public final class BchBlockEntry {
|
||||
this.hash32 = BchCryptoVerifier.sha256(frameBytes);
|
||||
}
|
||||
|
||||
public Ans104DataItem getDataItem() { return dataItem; }
|
||||
/** M1: явная точка входа для пары. Runtime переключается на неё в M2–M5. */
|
||||
public static BchBlockEntry fromCoreContent(byte[] container) {
|
||||
return new BchBlockEntry(CoreContentContainer.unpack(container));
|
||||
}
|
||||
|
||||
private BchBlockEntry(CoreContentContainer.Parts pair) {
|
||||
this.dataItem = pair.core();
|
||||
this.contentItem = pair.content();
|
||||
// Подписи и связь пары проверяются до предоставления смыслового тела.
|
||||
// Owner здесь self-claimed; вызывающий код обязан проверить авторизованный ключ.
|
||||
var verified = CoreContentTransport.verifyPair(dataItem, dataItem.id32(), contentItem,
|
||||
dataItem.owner32(), Instant.now().getEpochSecond());
|
||||
this.coreRecord = verified.core();
|
||||
this.contentRecord = verified.content();
|
||||
this.frameBytes = coreRecord.toBytes();
|
||||
this.frameCode = CoreRecord.FRAME_CODE;
|
||||
this.prevHash32 = coreRecord.prevCoreHash32();
|
||||
this.back32Hash32 = null; // Отсутствует в протоколе; не синтезируем.
|
||||
this.blockSize = frameBytes.length;
|
||||
this.blockNumber = coreRecord.blockNumber();
|
||||
this.timestamp = coreRecord.timestamp();
|
||||
this.type = (short) contentRecord.type();
|
||||
this.subType = (short) contentRecord.subType();
|
||||
this.version = (short) contentRecord.version();
|
||||
this.bodyBytes = contentRecord.bodyBytes();
|
||||
this.body = ContentBodyParser.parseForCore(coreRecord, contentRecord);
|
||||
this.hash32 = coreRecord.coreHash32();
|
||||
}
|
||||
|
||||
public boolean isCoreContent() { return coreRecord != null; }
|
||||
public CoreRecord getCoreRecord() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return coreRecord;
|
||||
}
|
||||
public ContentRecord getContentRecord() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return contentRecord;
|
||||
}
|
||||
public Ans104DataItem getCoreDataItem() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return dataItem;
|
||||
}
|
||||
public Ans104DataItem getContentDataItem() {
|
||||
if (!isCoreContent()) throw new IllegalStateException("Не CORE/CONTENT");
|
||||
return contentItem;
|
||||
}
|
||||
/** Legacy API: не позволяет принять одну подпись за проверку пары. */
|
||||
public Ans104DataItem getDataItem() {
|
||||
if (isCoreContent()) throw new IllegalStateException("Используйте явные CORE/CONTENT accessors");
|
||||
return dataItem;
|
||||
}
|
||||
public byte[] getFrameBytes() { return Arrays.copyOf(frameBytes, frameBytes.length); }
|
||||
/** Kept as an alias for code/docs that called the old field preimage. */
|
||||
public byte[] getPreimageBytes() { return getFrameBytes(); }
|
||||
@@ -98,8 +154,8 @@ public final class BchBlockEntry {
|
||||
public byte[] getOwner32() { return dataItem.owner32(); }
|
||||
public byte[] getDataItemId32() { return dataItem.id32(); }
|
||||
public byte[] getHash32() { return Arrays.copyOf(hash32, hash32.length); }
|
||||
/** Full serialized ANS-104 DataItem. */
|
||||
public byte[] toBytes() { return dataItem.rawBytes(); }
|
||||
/** Исходный DataItem (legacy) либо контейнер двух исходных подписанных DataItem. */
|
||||
public byte[] toBytes() { return isCoreContent() ? CoreContentContainer.pack(dataItem, contentItem) : dataItem.rawBytes(); }
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
@@ -22,6 +22,13 @@ public final class BchCryptoVerifier {
|
||||
Objects.requireNonNull(block, "block == null");
|
||||
Objects.requireNonNull(publicKey32, "publicKey32 == null");
|
||||
if (publicKey32.length != 32) throw new IllegalArgumentException("publicKey32 != 32");
|
||||
if (block.isCoreContent()) {
|
||||
try {
|
||||
CoreContentTransport.verifyPair(block.getCoreDataItem(), block.getDataItemId32(),
|
||||
block.getContentDataItem(), publicKey32, java.time.Instant.now().getEpochSecond());
|
||||
return true;
|
||||
} catch (IllegalArgumentException e) { return false; }
|
||||
}
|
||||
return block.getDataItem().ownerEquals(publicKey32) && block.getDataItem().verifySignature();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,10 @@ public final class BodyRecordParser {
|
||||
int v = version & 0xFFFF;
|
||||
int st = subType & 0xFFFF;
|
||||
|
||||
// TECH supports Header v1 and CreateChannel current format (ver=1).
|
||||
// TECH accepts only the current 1.0 body format.
|
||||
if (t == (CreateChannelBody.TYPE & 0xFFFF)) {
|
||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF) && v == (HeaderBody.VER & 0xFFFF)) {
|
||||
if (st == (HeaderBody.SUBTYPE_COMPAT & 0xFFFF)
|
||||
&& v == (HeaderBody.VER & 0xFFFF)) {
|
||||
return new HeaderBody(subType, version, bodyBytes).check();
|
||||
}
|
||||
if (st == (CreateChannelBody.SUBTYPE & 0xFFFF)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package blockchain;
|
||||
|
||||
import blockchain.body.*;
|
||||
|
||||
/** Смысловой парсер новой эпохи. Не выполняет проверки существования целей и состояния БД. */
|
||||
public final class ContentBodyParser {
|
||||
private ContentBodyParser() {}
|
||||
public static boolean isChannelText(int subType) {
|
||||
return switch (subType) {
|
||||
case MsgSubType.TEXT_POST, MsgSubType.TEXT_EDIT_POST, MsgSubType.TEXT_REPOST,
|
||||
MsgSubType.TEXT_CHANNEL_META, MsgSubType.TEXT_CHANNEL_DELETE, MsgSubType.TEXT_ENTRYPOINT,
|
||||
MsgSubType.TEXT_EXERCISE, MsgSubType.TEXT_SERVICE, MsgSubType.TEXT_COURSE -> true;
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
/** Проверяет соответствие линии, затем разбирает CONTENT без legacy-префикса. */
|
||||
public static BodyRecord parseForCore(CoreRecord core, ContentRecord content) {
|
||||
if (!java.util.Arrays.equals(core.contentHash32(), content.contentHash32()))
|
||||
throw new IllegalArgumentException("CONTENT hash не совпадает с CORE");
|
||||
boolean header = content.type() == 0 && content.subType() == MsgSubType.HEADER_COMPAT;
|
||||
if (content.version() != 1)
|
||||
throw new IllegalArgumentException("Неподдерживаемая версия CONTENT body");
|
||||
if (header != (core.blockNumber() == 0)) throw new IllegalArgumentException("HEADER только в CORE №0");
|
||||
CoreRecord.Line line = core.line();
|
||||
int expected = switch (content.type()) {
|
||||
case 0 -> header ? -1 : CoreRecord.TECH;
|
||||
case 1 -> isChannelText(content.subType()) ? -2 : -1;
|
||||
case 3 -> CoreRecord.CONNECTION;
|
||||
case 4 -> CoreRecord.PROFILE;
|
||||
default -> -1;
|
||||
};
|
||||
boolean match = expected == -1 ? line == null : line != null &&
|
||||
(expected == -2 ? LineIndex.isChannel(line.lineCode()) : line.lineCode() == expected);
|
||||
if (!match) throw new IllegalArgumentException("CONTENT не соответствует линии CORE");
|
||||
short s = (short) content.subType(), v = (short) content.version();
|
||||
byte[] bytes = content.bodyBytes();
|
||||
BodyRecord body = switch (content.type()) {
|
||||
case 0 -> switch (s) {
|
||||
case MsgSubType.HEADER_COMPAT -> new HeaderBody(s, v, bytes);
|
||||
case MsgSubType.TECH_CREATE_CHANNEL -> new CreateChannelBody(s, v, bytes, line);
|
||||
case MsgSubType.TECH_FORK -> new ForkBody(s, v, bytes, line);
|
||||
default -> throw new IllegalArgumentException("Неизвестный TECH subtype");
|
||||
};
|
||||
case 1 -> {
|
||||
if (isChannelText(content.subType())) yield new TextLineBody(s, v, bytes, line);
|
||||
yield switch (s) {
|
||||
case MsgSubType.TEXT_REPLY, MsgSubType.TEXT_EDIT_REPLY -> new TextReplyBody(s, v, bytes);
|
||||
case MsgSubType.TEXT_RATING -> new TextRatingBody(s, v, bytes);
|
||||
default -> throw new IllegalArgumentException("Неизвестный TEXT subtype");
|
||||
};
|
||||
}
|
||||
case 2 -> new ReactionBody(s, v, bytes);
|
||||
case 3 -> new ConnectionBody(s, v, bytes, line);
|
||||
case 4 -> new UserParamBody(s, v, bytes, line);
|
||||
case 5 -> new StatusActionBody(s, v, bytes);
|
||||
default -> throw new IllegalArgumentException("Неизвестный CONTENT type");
|
||||
};
|
||||
return body.check();
|
||||
}
|
||||
/** Для нового события, в дополнение к проверкам БД и авторизации вызывающим кодом. */
|
||||
public static BodyRecord parseForCreate(CoreRecord core, ContentRecord content) {
|
||||
BodyRecord body = parseForCore(core, content);
|
||||
if (body instanceof CreateChannelBody create) create.checkForCreate();
|
||||
return body;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package blockchain;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Objects;
|
||||
|
||||
/** Бинарный CONTENT v1. Неизвестные типы разбираются как raw envelope. */
|
||||
public final class ContentRecord {
|
||||
public static final int CONTENT_CODE = 1, HEADER_SIZE = 7;
|
||||
// Верхняя граница payload; полный ANS-104 дополнительно ограничен собственным лимитом.
|
||||
public static final int MAX_PAYLOAD_SIZE = Ans104DataItem.MAX_DATA_ITEM_BYTES - 117;
|
||||
private final int type, subType, version;
|
||||
private final byte[] body;
|
||||
public ContentRecord(int type, int subType, int version, byte[] body) {
|
||||
if ((type & ~0xffff) != 0 || (subType & ~0xffff) != 0 || (version & ~0xffff) != 0)
|
||||
throw new IllegalArgumentException("Ожидается uint16");
|
||||
Objects.requireNonNull(body);
|
||||
if (body.length > MAX_PAYLOAD_SIZE - HEADER_SIZE) throw new IllegalArgumentException("CONTENT слишком большой");
|
||||
this.type = type; this.subType = subType; this.version = version; this.body = body.clone();
|
||||
}
|
||||
public static ContentRecord parse(byte[] bytes) {
|
||||
if (bytes == null || bytes.length < HEADER_SIZE || bytes.length > MAX_PAYLOAD_SIZE)
|
||||
throw new IllegalArgumentException("Неверная длина CONTENT");
|
||||
ByteBuffer b = ByteBuffer.wrap(bytes);
|
||||
if (Byte.toUnsignedInt(b.get()) != CONTENT_CODE) throw new IllegalArgumentException("Неверный contentCode");
|
||||
int t = Short.toUnsignedInt(b.getShort()), s = Short.toUnsignedInt(b.getShort()), v = Short.toUnsignedInt(b.getShort());
|
||||
byte[] body = new byte[b.remaining()]; b.get(body);
|
||||
return new ContentRecord(t, s, v, body);
|
||||
}
|
||||
public byte[] toBytes() { return ByteBuffer.allocate(HEADER_SIZE + body.length).put((byte) CONTENT_CODE)
|
||||
.putShort((short) type).putShort((short) subType).putShort((short) version).put(body).array(); }
|
||||
public int type() { return type; }
|
||||
public int subType() { return subType; }
|
||||
public int version() { return version; }
|
||||
public byte[] bodyBytes() { return body.clone(); }
|
||||
public byte[] contentHash32() { return ProtocolHash.sha256(toBytes()); }
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package blockchain;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Внутренний block_bytes: u32 BE размер CORE, затем два исходных ANS-104. Не DataItem. */
|
||||
public final class CoreContentContainer {
|
||||
private CoreContentContainer() {}
|
||||
public static final int MAX_CORE_ITEM_BYTES = 65865;
|
||||
public static final int MAX_CONTAINER_BYTES = 4 + MAX_CORE_ITEM_BYTES + Ans104DataItem.MAX_DATA_ITEM_BYTES;
|
||||
private static final int MIN_ITEM_BYTES = 116;
|
||||
|
||||
public record Parts(Ans104DataItem core, Ans104DataItem content) {}
|
||||
|
||||
public static Parts unpack(byte[] bytes) {
|
||||
if (bytes == null || bytes.length < 4 + 2 * MIN_ITEM_BYTES || bytes.length > MAX_CONTAINER_BYTES)
|
||||
throw new IllegalArgumentException("Неверная длина контейнера CORE/CONTENT");
|
||||
long n = Integer.toUnsignedLong(ByteBuffer.wrap(bytes).getInt());
|
||||
long rest = bytes.length - 4L - n;
|
||||
checkLengths(n, rest);
|
||||
int end = 4 + (int) n;
|
||||
return new Parts(new Ans104DataItem(Arrays.copyOfRange(bytes, 4, end)),
|
||||
new Ans104DataItem(Arrays.copyOfRange(bytes, end, bytes.length)));
|
||||
}
|
||||
|
||||
public static byte[] pack(Ans104DataItem core, Ans104DataItem content) {
|
||||
byte[] c = core.rawBytes(), p = content.rawBytes();
|
||||
checkLengths(c.length, p.length);
|
||||
return ByteBuffer.allocate(4 + c.length + p.length).putInt(c.length).put(c).put(p).array();
|
||||
}
|
||||
|
||||
private static void checkLengths(long core, long content) {
|
||||
if (core < MIN_ITEM_BYTES || core > MAX_CORE_ITEM_BYTES || content < MIN_ITEM_BYTES || content > Ans104DataItem.MAX_DATA_ITEM_BYTES)
|
||||
throw new IllegalArgumentException("Неверная длина CORE/CONTENT DataItem");
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package blockchain;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import utils.crypto.Ed25519Util;
|
||||
|
||||
/** Новый транспорт; не переключает существующий runtime Frame v1. */
|
||||
public final class CoreContentTransport {
|
||||
private CoreContentTransport() {}
|
||||
public static List<Ans104DataItem.Tag> coreTags(CoreRecord core) {
|
||||
var tags = new ArrayList<Ans104DataItem.Tag>();
|
||||
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.CORE_NAMESPACE));
|
||||
tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_NUMBER_TAG_NAME, Integer.toString(core.blockNumber())));
|
||||
if (core.line() != null) tags.add(new Ans104DataItem.Tag(ShineProtocolTags.CORE_LINE_TAG_NAME, lineTag(core.line().lineCode())));
|
||||
return List.copyOf(tags);
|
||||
}
|
||||
public static String lineTag(int code) {
|
||||
return switch (code) {
|
||||
case CoreRecord.PROFILE -> "P";
|
||||
case CoreRecord.CONNECTION -> "C";
|
||||
case CoreRecord.TECH -> "T";
|
||||
default -> {
|
||||
if (code < 0 || code > CoreRecord.MAX_BLOCK_NUMBER) throw new IllegalArgumentException("Неизвестный системный тег линии");
|
||||
yield Integer.toString(code);
|
||||
}
|
||||
};
|
||||
}
|
||||
private static void require(boolean ok, String message) { if (!ok) throw new IllegalArgumentException(message); }
|
||||
private static void verify(Ans104DataItem item, byte[] expectedOwner, byte[] expectedId) {
|
||||
require(item.ownerEquals(ProtocolHash.copy32(expectedOwner)), "Неавторизованный owner");
|
||||
require(Arrays.equals(item.id32(), ProtocolHash.copy32(expectedId)), "DataItem ID не совпадает");
|
||||
require(item.verifySignature(), "Неверная подпись ANS-104");
|
||||
}
|
||||
public static CoreRecord verifyCore(Ans104DataItem item, byte[] authorizedOwner, byte[] expectedId, long nowSeconds) {
|
||||
verify(item, authorizedOwner, expectedId);
|
||||
CoreRecord core = CoreRecord.parse(item.data()); core.checkTimestamp(nowSeconds);
|
||||
List<Ans104DataItem.Tag> expected = coreTags(core);
|
||||
for (String name : List.of("App", "n", "l")) {
|
||||
var actual = item.tags().stream().filter(t -> t.name().equals(name)).toList();
|
||||
var wanted = expected.stream().filter(t -> t.name().equals(name)).toList();
|
||||
require(actual.equals(wanted), "Некорректный тег CORE: " + name);
|
||||
}
|
||||
require(item.tags().stream().noneMatch(t -> t.name().equals("t") || t.name().equals("c")), "Legacy теги CORE запрещены");
|
||||
return core;
|
||||
}
|
||||
/** Только соответствие payload подписанному CORE; это не проверка собственной подписи CONTENT. */
|
||||
public static ContentRecord verifyPayload(CoreRecord core, byte[] payload) {
|
||||
require(payload != null && payload.length <= ContentRecord.MAX_PAYLOAD_SIZE, "Неверная длина CONTENT");
|
||||
byte[] snapshot = payload.clone();
|
||||
require(Arrays.equals(core.contentHash32(), ProtocolHash.sha256(snapshot)), "CONTENT hash не совпадает");
|
||||
return ContentRecord.parse(snapshot);
|
||||
}
|
||||
/** authorizedOwner должен быть owner уже проверенного CORE, а не произвольный ключ CONTENT. */
|
||||
public static ContentRecord verifyContent(CoreRecord core, Ans104DataItem item, byte[] authorizedOwner) {
|
||||
verify(item, authorizedOwner, core.contentDataItemId32());
|
||||
require(item.tags().stream().noneMatch(t -> List.of("App", "n", "l", "t", "c").contains(t.name())), "CONTENT не должен иметь поисковые теги SHiNE");
|
||||
return verifyPayload(core, item.data());
|
||||
}
|
||||
public record VerifiedPair(CoreRecord core, ContentRecord content) {}
|
||||
/** Криптографическая проверка пары; семантика проверяется ContentBodyParser отдельно. */
|
||||
public static VerifiedPair verifyPair(Ans104DataItem coreItem, byte[] expectedCoreId, Ans104DataItem contentItem,
|
||||
byte[] authorizedOwner, long nowSeconds) {
|
||||
CoreRecord core = verifyCore(coreItem, authorizedOwner, expectedCoreId, nowSeconds);
|
||||
return new VerifiedPair(core, verifyContent(core, contentItem, coreItem.owner32()));
|
||||
}
|
||||
/** Для локального тестового издателя; production сервер не получает приватный ключ пользователя. */
|
||||
public static Ans104DataItem sign(byte[] payload, List<Ans104DataItem.Tag> tags, byte[] seed) {
|
||||
byte[] owner = Ed25519Util.derivePublicKey(seed);
|
||||
byte[] sig = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, payload), seed);
|
||||
return new Ans104DataItem(Ans104DataItem.serializeEd25519(sig, owner, tags, payload));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package blockchain;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.Arrays;
|
||||
|
||||
/** Неизменяемый бинарный CORE v2; проверка ссылок на историю выполняется отдельно. */
|
||||
public final class CoreRecord {
|
||||
public static final int BASE_SIZE = 109, LINE_SIZE = 149, FRAME_CODE = 1;
|
||||
public static final int MAX_BLOCK_NUMBER = Integer.MAX_VALUE - 1024;
|
||||
public static final int PROFILE = Integer.MAX_VALUE - 2, CONNECTION = Integer.MAX_VALUE - 1, TECH = Integer.MAX_VALUE;
|
||||
public static final long FUTURE_TOLERANCE_SECONDS = 60;
|
||||
public record Line(int lineCode, int prevLineBlockNumber, byte[] prevLineCoreHash32) {
|
||||
public Line {
|
||||
if (lineCode < 0 || prevLineBlockNumber < 0 || prevLineBlockNumber > MAX_BLOCK_NUMBER)
|
||||
throw new IllegalArgumentException("Неверный номер линии/предшественника");
|
||||
prevLineCoreHash32 = ProtocolHash.copy32(prevLineCoreHash32);
|
||||
}
|
||||
@Override public byte[] prevLineCoreHash32() { return prevLineCoreHash32.clone(); }
|
||||
@Override public boolean equals(Object other) {
|
||||
return other instanceof Line l && lineCode == l.lineCode && prevLineBlockNumber == l.prevLineBlockNumber
|
||||
&& Arrays.equals(prevLineCoreHash32, l.prevLineCoreHash32);
|
||||
}
|
||||
@Override public int hashCode() {
|
||||
return 31 * (31 * lineCode + prevLineBlockNumber) + Arrays.hashCode(prevLineCoreHash32);
|
||||
}
|
||||
}
|
||||
private final byte[] prevCoreHash32, contentHash32, contentDataItemId32;
|
||||
private final int blockNumber;
|
||||
private final long timestamp;
|
||||
private final Line line;
|
||||
|
||||
public CoreRecord(byte[] prevCoreHash32, int blockNumber, long timestamp, byte[] contentHash32,
|
||||
byte[] contentDataItemId32, Line line) {
|
||||
this.prevCoreHash32 = ProtocolHash.copy32(prevCoreHash32);
|
||||
this.contentHash32 = ProtocolHash.copy32(contentHash32);
|
||||
this.contentDataItemId32 = ProtocolHash.copy32(contentDataItemId32);
|
||||
this.blockNumber = blockNumber; this.timestamp = timestamp; this.line = line;
|
||||
if (blockNumber < 0 || blockNumber > MAX_BLOCK_NUMBER || timestamp < 0)
|
||||
throw new IllegalArgumentException("Неверный номер CORE или timestamp");
|
||||
if (blockNumber == 0 && (line != null || !Arrays.equals(this.prevCoreHash32, new byte[32])))
|
||||
throw new IllegalArgumentException("Неверный genesis CORE");
|
||||
if (line != null && (line.prevLineBlockNumber() >= blockNumber ||
|
||||
(line.lineCode() > 0 && line.lineCode() <= MAX_BLOCK_NUMBER &&
|
||||
(line.lineCode() >= blockNumber || line.prevLineBlockNumber() < line.lineCode()))))
|
||||
throw new IllegalArgumentException("Неверная ссылка линии");
|
||||
}
|
||||
public static CoreRecord parse(byte[] bytes) {
|
||||
if (bytes == null || (bytes.length != BASE_SIZE && bytes.length != LINE_SIZE))
|
||||
throw new IllegalArgumentException("CORE должен иметь 109 или 149 байт");
|
||||
ByteBuffer b = ByteBuffer.wrap(bytes);
|
||||
if (Byte.toUnsignedInt(b.get()) != FRAME_CODE) throw new IllegalArgumentException("Неверный frameCode");
|
||||
byte[] prev = read32(b); int n = b.getInt(); long t = b.getLong();
|
||||
byte[] content = read32(b), id = read32(b);
|
||||
Line line = b.hasRemaining() ? new Line(b.getInt(), b.getInt(), read32(b)) : null;
|
||||
return new CoreRecord(prev, n, t, content, id, line);
|
||||
}
|
||||
private static byte[] read32(ByteBuffer b) { byte[] v = new byte[32]; b.get(v); return v; }
|
||||
public byte[] toBytes() {
|
||||
ByteBuffer b = ByteBuffer.allocate(line == null ? BASE_SIZE : LINE_SIZE);
|
||||
b.put((byte) FRAME_CODE).put(prevCoreHash32).putInt(blockNumber).putLong(timestamp).put(contentHash32).put(contentDataItemId32);
|
||||
if (line != null) b.putInt(line.lineCode()).putInt(line.prevLineBlockNumber()).put(line.prevLineCoreHash32());
|
||||
return b.array();
|
||||
}
|
||||
public void checkTimestamp(long nowSeconds) {
|
||||
if (nowSeconds < 0 || (timestamp > nowSeconds && timestamp - nowSeconds > FUTURE_TOLERANCE_SECONDS))
|
||||
throw new IllegalArgumentException("CORE timestamp в будущем");
|
||||
}
|
||||
public int blockNumber() { return blockNumber; }
|
||||
public long timestamp() { return timestamp; }
|
||||
public Line line() { return line; }
|
||||
public byte[] prevCoreHash32() { return prevCoreHash32.clone(); }
|
||||
public byte[] contentHash32() { return contentHash32.clone(); }
|
||||
public byte[] contentDataItemId32() { return contentDataItemId32.clone(); }
|
||||
public byte[] coreHash32() { return ProtocolHash.sha256(toBytes()); }
|
||||
}
|
||||
@@ -1,17 +1,12 @@
|
||||
//package blockchain;
|
||||
//
|
||||
///**
|
||||
// * LineIndex — канонические номера линий блокчейна.
|
||||
// *
|
||||
// * Линия = независимая последовательность блоков внутри одного блокчейна.
|
||||
// */
|
||||
//public final class LineIndex {
|
||||
//
|
||||
// private LineIndex() {}
|
||||
//
|
||||
// public static final short HEADER = 0; // genesis / идентификация
|
||||
// public static final short TEXT = 1; // сообщения да надо
|
||||
// public static final short REACTION = 2; // реакции не надо
|
||||
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
|
||||
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
|
||||
//}
|
||||
package blockchain;
|
||||
|
||||
/** Канонические линии CORE v2; Frame v1 использует старую модель. */
|
||||
public final class LineIndex {
|
||||
private LineIndex() {}
|
||||
public static final int DEFAULT_CHANNEL = 0;
|
||||
public static final int USER_PROFILE = CoreRecord.PROFILE;
|
||||
public static final int CONNECTION = CoreRecord.CONNECTION;
|
||||
public static final int TECH = CoreRecord.TECH;
|
||||
public static final int MAX_CHANNEL = CoreRecord.MAX_BLOCK_NUMBER;
|
||||
public static boolean isChannel(int code) { return code >= 0 && code <= MAX_CHANNEL; }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
package blockchain;
|
||||
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.Base64;
|
||||
import java.util.HexFormat;
|
||||
|
||||
public final class ProtocolHash {
|
||||
private ProtocolHash() {}
|
||||
public static byte[] copy32(byte[] bytes) {
|
||||
if (bytes == null || bytes.length != 32) throw new IllegalArgumentException("Ожидается 32 байта");
|
||||
return bytes.clone();
|
||||
}
|
||||
public static byte[] sha256(byte[] bytes) {
|
||||
try { return MessageDigest.getInstance("SHA-256").digest(bytes); }
|
||||
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
public static String hex32(byte[] bytes) { return HexFormat.of().formatHex(copy32(bytes)); }
|
||||
public static byte[] fromHex32(String value) { return copy32(HexFormat.of().parseHex(value)); }
|
||||
public static String base64url32(byte[] bytes) { return Base64.getUrlEncoder().withoutPadding().encodeToString(copy32(bytes)); }
|
||||
public static byte[] fromBase64url32(String value) {
|
||||
byte[] result = copy32(Base64.getUrlDecoder().decode(value));
|
||||
if (!base64url32(result).equals(value)) throw new IllegalArgumentException("Неканонический base64url");
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,14 @@ package blockchain;
|
||||
public final class ShineProtocolTags {
|
||||
private ShineProtocolTags() {}
|
||||
|
||||
public static final String CORE_NAMESPACE = "test5599";
|
||||
/** Новый регистрационный сертификат остаётся отдельным объектом; используется при переключении эпохи. */
|
||||
public static final java.util.List<Ans104DataItem.Tag> CORE_REGISTRATION_TAGS = java.util.List.of(
|
||||
new Ans104DataItem.Tag("App", CORE_NAMESPACE),
|
||||
new Ans104DataItem.Tag("t", "reg"),
|
||||
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||
public static final String CORE_NUMBER_TAG_NAME = "n";
|
||||
public static final String CORE_LINE_TAG_NAME = "l";
|
||||
public static final String NAMESPACE = "test5592";
|
||||
public static final String APP_TAG_NAME = "App";
|
||||
public static final String APP_TAG_VALUE = NAMESPACE;
|
||||
|
||||
@@ -21,6 +21,9 @@ package blockchain.body;
|
||||
*/
|
||||
public interface BodyHasLine {
|
||||
|
||||
/** CORE не подписывает ordinal; до проверки канонического хвоста значение отсутствует. */
|
||||
int UNRESOLVED_SEQUENCE = -1;
|
||||
|
||||
int lineCode();
|
||||
|
||||
int prevLineBlockGlobalNumber();
|
||||
|
||||
+23
-8
@@ -1,6 +1,7 @@
|
||||
package blockchain.body;
|
||||
|
||||
import blockchain.MsgSubType;
|
||||
import blockchain.CoreRecord;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
@@ -16,6 +17,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
public static final short VER = 1;
|
||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||
|
||||
private final boolean contentOnly;
|
||||
public final short subType;
|
||||
public final short version;
|
||||
public final int prevConnectionBlockNumber;
|
||||
@@ -27,16 +29,28 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
public final byte[] toBlockHash32;
|
||||
|
||||
public ConnectionBody(short subType, short version, byte[] bodyBytes) {
|
||||
this(subType, version, bodyBytes, null);
|
||||
}
|
||||
|
||||
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||
public ConnectionBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||
this.contentOnly = line != null;
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short");
|
||||
this.prevConnectionBlockNumber = bb.getInt();
|
||||
this.prevConnectionBlockHash32 = new byte[32];
|
||||
bb.get(this.prevConnectionBlockHash32);
|
||||
this.connectionSequence = bb.getInt();
|
||||
BodyTargetSupport.ensureMin(bb, (4 + 32 + 4 + 1 + 1 + 2 + 4 + 32) - (contentOnly ? 40 : 0), "ConnectionBody too short");
|
||||
if (contentOnly) {
|
||||
this.prevConnectionBlockNumber = line.prevLineBlockNumber();
|
||||
this.prevConnectionBlockHash32 = line.prevLineCoreHash32();
|
||||
this.connectionSequence = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||
} else {
|
||||
this.prevConnectionBlockNumber = bb.getInt();
|
||||
this.prevConnectionBlockHash32 = new byte[32];
|
||||
bb.get(this.prevConnectionBlockHash32);
|
||||
this.connectionSequence = bb.getInt();
|
||||
}
|
||||
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
|
||||
this.toLogin = t.login();
|
||||
this.toForkNumber = t.forkNumber();
|
||||
@@ -47,6 +61,7 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
|
||||
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
|
||||
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
|
||||
this.contentOnly = false;
|
||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
this.prevConnectionBlockNumber = prevConnectionBlockNumber;
|
||||
@@ -64,15 +79,15 @@ public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasL
|
||||
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
|
||||
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
|
||||
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
|
||||
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
|
||||
if (!contentOnly && connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
|
||||
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override public byte[] toBytes() {
|
||||
check();
|
||||
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
|
||||
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 40) + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
|
||||
if (!contentOnly) bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
|
||||
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
+33
-14
@@ -1,6 +1,7 @@
|
||||
package blockchain.body;
|
||||
|
||||
import blockchain.MsgSubType;
|
||||
import blockchain.CoreRecord;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
@@ -42,6 +43,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
private static final int MAX_NAME_LENGTH = 32;
|
||||
public static final int MAX_DESCRIPTION_UTF8_LEN = 2048;
|
||||
|
||||
private final boolean contentOnly;
|
||||
public final short subType;
|
||||
public final short version;
|
||||
|
||||
@@ -56,6 +58,12 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
public final short channelTypeVersion;
|
||||
|
||||
public CreateChannelBody(short subType, short version, byte[] bodyBytes) {
|
||||
this(subType, version, bodyBytes, null);
|
||||
}
|
||||
|
||||
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||
public CreateChannelBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||
this.contentOnly = line != null;
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
@@ -67,16 +75,23 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
if ((this.subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
|
||||
throw new IllegalArgumentException("CreateChannelBody subType must be TECH_CREATE_CHANNEL(1), got=" + (this.subType & 0xFFFF));
|
||||
}
|
||||
if (bodyBytes.length < 4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) {
|
||||
if (bodyBytes.length < (4 + (4 + 32 + 4) + 1 + 1 + 2 + 4) - (contentOnly ? 44 : 0)) {
|
||||
throw new IllegalArgumentException("CreateChannelBody too short");
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
if (contentOnly) {
|
||||
this.lineCode = 0;
|
||||
this.prevLineNumber = line.prevLineBlockNumber();
|
||||
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||
} else {
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
}
|
||||
|
||||
int nameLen = Byte.toUnsignedInt(bb.get());
|
||||
if (nameLen <= 0) throw new IllegalArgumentException("channelNameLen is 0");
|
||||
@@ -86,7 +101,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
byte[] nameBytes = new byte[nameLen];
|
||||
bb.get(nameBytes);
|
||||
this.channelName = new String(nameBytes, StandardCharsets.UTF_8);
|
||||
this.channelName = contentOnly ? BodyTargetSupport.decodeStrictUtf8(nameBytes, "channelName") : new String(nameBytes, StandardCharsets.UTF_8);
|
||||
|
||||
int descriptionLen = Short.toUnsignedInt(bb.getShort());
|
||||
if (descriptionLen > MAX_DESCRIPTION_UTF8_LEN) {
|
||||
@@ -100,7 +115,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
} else {
|
||||
byte[] descriptionBytes = new byte[descriptionLen];
|
||||
bb.get(descriptionBytes);
|
||||
this.channelDescription = normalizeDescription(new String(descriptionBytes, StandardCharsets.UTF_8));
|
||||
this.channelDescription = normalizeDescription(contentOnly ? BodyTargetSupport.decodeStrictUtf8(descriptionBytes, "channelDescription") : new String(descriptionBytes, StandardCharsets.UTF_8));
|
||||
}
|
||||
this.channelTypeCode = bb.getShort();
|
||||
this.channelTypeVersion = bb.getShort();
|
||||
@@ -117,6 +132,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
String channelDescription,
|
||||
short channelTypeCode,
|
||||
short channelTypeVersion) {
|
||||
this.contentOnly = false;
|
||||
Objects.requireNonNull(channelName, "channelName == null");
|
||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||
|
||||
@@ -142,6 +158,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
String normalizedName = normalizeDisplayName(channelName);
|
||||
if (normalizedName.isEmpty()) throw new IllegalArgumentException("channelName is blank");
|
||||
int cpLen = normalizedName.codePointCount(0, normalizedName.length());
|
||||
if (contentOnly && normalizedName.getBytes(StandardCharsets.UTF_8).length > 255) throw new IllegalArgumentException("channelName UTF-8 too long");
|
||||
if (cpLen > MAX_NAME_LENGTH) throw new IllegalArgumentException("channelName length must be <=32");
|
||||
|
||||
String normalizedDescription = normalizeDescription(channelDescription);
|
||||
@@ -157,7 +174,7 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
|
||||
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0 for CreateChannelBody");
|
||||
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
|
||||
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
|
||||
if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1 for CreateChannelBody");
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -199,12 +216,14 @@ public final class CreateChannelBody implements BodyRecord, BodyHasLine {
|
||||
throw new IllegalArgumentException("channelDescription utf8 len must be <=2048");
|
||||
}
|
||||
|
||||
int cap = 4 + (4 + 32 + 4) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
|
||||
int cap = (contentOnly ? 0 : 44) + 1 + nameUtf8.length + 2 + descriptionUtf8.length + 4;
|
||||
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(lineCode);
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
|
||||
bb.putInt(thisLineNumber);
|
||||
if (!contentOnly) {
|
||||
bb.putInt(lineCode);
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32 == null ? ZERO32 : Arrays.copyOf(prevLineHash32, 32));
|
||||
bb.putInt(thisLineNumber);
|
||||
}
|
||||
bb.put((byte) nameUtf8.length);
|
||||
bb.put(nameUtf8);
|
||||
bb.putShort((short) (descriptionUtf8.length & 0xFFFF));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package blockchain.body;
|
||||
|
||||
import blockchain.MsgSubType;
|
||||
import blockchain.CoreRecord;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
@@ -49,6 +50,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
|
||||
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
|
||||
|
||||
private final boolean contentOnly;
|
||||
public final short subType;
|
||||
public final short version;
|
||||
|
||||
@@ -69,6 +71,12 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
public final String comment;
|
||||
|
||||
public ForkBody(short subType, short version, byte[] bodyBytes) {
|
||||
this(subType, version, bodyBytes, null);
|
||||
}
|
||||
|
||||
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||
public ForkBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||
this.contentOnly = line != null;
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
@@ -79,16 +87,23 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
|
||||
throw new IllegalArgumentException("ForkBody version must be 1");
|
||||
}
|
||||
if (bodyBytes.length < FIXED_LEN) {
|
||||
if (bodyBytes.length < FIXED_LEN - (contentOnly ? LINE_PREFIX_LEN : 0)) {
|
||||
throw new IllegalArgumentException("ForkBody too short");
|
||||
}
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
if (contentOnly) {
|
||||
this.lineCode = 0;
|
||||
this.prevLineNumber = line.prevLineBlockNumber();
|
||||
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||
} else {
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32];
|
||||
bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
}
|
||||
|
||||
this.parentBlockchainKey32 = new byte[32];
|
||||
bb.get(this.parentBlockchainKey32);
|
||||
@@ -111,7 +126,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
}
|
||||
byte[] commentBytes = new byte[commentLen];
|
||||
bb.get(commentBytes);
|
||||
this.comment = new String(commentBytes, StandardCharsets.UTF_8);
|
||||
this.comment = contentOnly ? BodyTargetSupport.decodeStrictUtf8(commentBytes, "fork comment") : new String(commentBytes, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
public ForkBody(int lineCode,
|
||||
@@ -128,6 +143,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
int discardedBlocksCount,
|
||||
int reasonCode,
|
||||
String comment) {
|
||||
this.contentOnly = false;
|
||||
this.subType = SUBTYPE;
|
||||
this.version = VER;
|
||||
this.lineCode = lineCode;
|
||||
@@ -157,7 +173,7 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
|
||||
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
|
||||
require32(prevLineHash32, "prevLineHash32");
|
||||
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
|
||||
if (!contentOnly && thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
|
||||
|
||||
require32(parentBlockchainKey32, "parentBlockchainKey32");
|
||||
require32(forkPointBlockHash32, "forkPointBlockHash32");
|
||||
@@ -186,11 +202,13 @@ public final class ForkBody implements BodyRecord, BodyHasLine {
|
||||
public byte[] toBytes() {
|
||||
check();
|
||||
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(lineCode);
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32);
|
||||
bb.putInt(thisLineNumber);
|
||||
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? FIXED_PAYLOAD_LEN : FIXED_LEN) + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
|
||||
if (!contentOnly) {
|
||||
bb.putInt(lineCode);
|
||||
bb.putInt(prevLineNumber);
|
||||
bb.put(prevLineHash32);
|
||||
bb.putInt(thisLineNumber);
|
||||
}
|
||||
bb.put(parentBlockchainKey32);
|
||||
bb.putInt(forkPointBlockNumber);
|
||||
bb.put(forkPointBlockHash32);
|
||||
|
||||
+88
-37
@@ -6,25 +6,23 @@ import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* HeaderBody — type=0, subType=0, version=1.
|
||||
* HEADER 1.0 — TECH type=0, subType=0, version=1.
|
||||
*
|
||||
* bodyBytes (BigEndian):
|
||||
* [TAG_LEN] tag ASCII
|
||||
* [1] loginLength (uint8)
|
||||
* [N] login UTF-8
|
||||
* [32] initialBlockchainKey32
|
||||
*
|
||||
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
|
||||
* It is historical identity metadata and MUST remain byte-for-byte unchanged when a
|
||||
* preserved prefix (including block #0) is republished into later forks.
|
||||
* [TAG_LEN] tag ASCII; [1] login length; [N] login UTF-8;
|
||||
* [1] accountType (0 alternative / 1 primary);
|
||||
* [2+N] previous accounts CSV for Primary only;
|
||||
* [1] license length; [M] arbitrary license UTF-8; [32] initial blockchain key.
|
||||
*/
|
||||
public final class HeaderBody implements BodyRecord {
|
||||
public static final short TYPE = 0;
|
||||
public static final short VER = 1;
|
||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||
public static final int ALTERNATIVE = 0, PRIMARY = 1;
|
||||
public static final short SUBTYPE_COMPAT = 0;
|
||||
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
|
||||
|
||||
@@ -36,57 +34,108 @@ public final class HeaderBody implements BodyRecord {
|
||||
public final String tag;
|
||||
public final String login;
|
||||
public final byte[] initialBlockchainKey32;
|
||||
public final int accountType;
|
||||
public final List<String> previousAccounts;
|
||||
public final String license;
|
||||
|
||||
public HeaderBody(short subType, short version, byte[] bodyBytes) {
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1");
|
||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
|
||||
if ((subType & 0xFFFF) != SUBTYPE_COMPAT) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if (version != VER) throw new IllegalArgumentException("HeaderBody version must be 1.0");
|
||||
if (bodyBytes.length < TAG_LEN + 1 + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
byte[] tagBytes = new byte[TAG_LEN];
|
||||
bb.get(tagBytes);
|
||||
String parsedTag = new String(tagBytes, StandardCharsets.US_ASCII);
|
||||
if (!TAG.equals(parsedTag)) throw new IllegalArgumentException("Bad tag: " + parsedTag);
|
||||
this.tag = parsedTag;
|
||||
this.tag = new String(tagBytes, StandardCharsets.US_ASCII);
|
||||
if (!TAG.equals(tag)) throw new IllegalArgumentException("Bad tag: " + tag);
|
||||
|
||||
int loginLen = Byte.toUnsignedInt(bb.get());
|
||||
if (loginLen <= 0 || bb.remaining() != loginLen + 32) throw new IllegalArgumentException("Bad HeaderBody login/key length");
|
||||
if (loginLen == 0 || bb.remaining() < loginLen + 34) throw new IllegalArgumentException("Bad HEADER login length");
|
||||
byte[] loginBytes = new byte[loginLen];
|
||||
bb.get(loginBytes);
|
||||
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
|
||||
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HEADER login");
|
||||
|
||||
this.accountType = Byte.toUnsignedInt(bb.get());
|
||||
List<String> parsedPrevious;
|
||||
if (accountType == PRIMARY) {
|
||||
if (bb.remaining() < 35) throw new IllegalArgumentException("Truncated HEADER previous accounts");
|
||||
int size = Short.toUnsignedInt(bb.getShort());
|
||||
if (size > bb.remaining() - 33) throw new IllegalArgumentException("Bad HEADER previous accounts length");
|
||||
byte[] previous = new byte[size];
|
||||
bb.get(previous);
|
||||
String csv = BodyTargetSupport.decodeStrictUtf8(previous, "HEADER previous accounts");
|
||||
parsedPrevious = csv.isEmpty() ? List.of() : List.of(csv.split(",", -1));
|
||||
} else if (accountType == ALTERNATIVE) {
|
||||
parsedPrevious = List.of();
|
||||
} else {
|
||||
throw new IllegalArgumentException("Bad HEADER account type");
|
||||
}
|
||||
this.previousAccounts = parsedPrevious;
|
||||
|
||||
int licenseSize = Byte.toUnsignedInt(bb.get());
|
||||
if (bb.remaining() != licenseSize + 32) throw new IllegalArgumentException("Bad HEADER license length");
|
||||
byte[] licenseBytes = new byte[licenseSize];
|
||||
bb.get(licenseBytes);
|
||||
this.license = BodyTargetSupport.decodeStrictUtf8(licenseBytes, "HEADER license");
|
||||
this.initialBlockchainKey32 = new byte[32];
|
||||
bb.get(this.initialBlockchainKey32);
|
||||
requireNonZeroKey(this.initialBlockchainKey32);
|
||||
bb.get(initialBlockchainKey32);
|
||||
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
|
||||
check();
|
||||
}
|
||||
|
||||
/** Creates the canonical 1.0 HEADER for a Primary account. */
|
||||
public HeaderBody(String login, byte[] initialBlockchainKey32) {
|
||||
Objects.requireNonNull(login, "login == null");
|
||||
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
|
||||
this(login, initialBlockchainKey32, "", PRIMARY, List.of());
|
||||
}
|
||||
|
||||
public static HeaderBody forCoreContent(String login, byte[] initialBlockchainKey32) {
|
||||
return new HeaderBody(login, initialBlockchainKey32);
|
||||
}
|
||||
|
||||
public static HeaderBody identity(String login, byte[] initialBlockchainKey32, String license,
|
||||
int accountType, List<String> previousAccounts) {
|
||||
return new HeaderBody(login, initialBlockchainKey32, license, accountType, previousAccounts);
|
||||
}
|
||||
|
||||
private HeaderBody(String login, byte[] initialBlockchainKey32, String license,
|
||||
int accountType, List<String> previousAccounts) {
|
||||
this.subType = SUBTYPE_COMPAT;
|
||||
this.version = VER;
|
||||
this.tag = TAG;
|
||||
this.login = login;
|
||||
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
|
||||
this.login = Objects.requireNonNull(login, "login == null");
|
||||
this.initialBlockchainKey32 = Arrays.copyOf(Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null"), initialBlockchainKey32.length);
|
||||
this.license = Objects.requireNonNull(license, "license == null");
|
||||
this.accountType = accountType;
|
||||
this.previousAccounts = List.copyOf(Objects.requireNonNull(previousAccounts, "previousAccounts == null"));
|
||||
check();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HeaderBody check() {
|
||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
||||
if ((subType & 0xFFFF) != SUBTYPE_COMPAT || version != VER) throw new IllegalArgumentException("Bad HeaderBody version");
|
||||
if (!StandardCharsets.UTF_8.newEncoder().canEncode(license) || license.getBytes(StandardCharsets.UTF_8).length > 255)
|
||||
throw new IllegalArgumentException("HEADER license must be 0..255 UTF-8 bytes");
|
||||
if (login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
|
||||
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
|
||||
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
|
||||
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
|
||||
if (!legacyLogin && !namespacedLogin) {
|
||||
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
|
||||
if (!legacyLogin && !namespacedLogin) throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
|
||||
if (loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
||||
if (accountType != ALTERNATIVE && accountType != PRIMARY) throw new IllegalArgumentException("Bad HEADER account type");
|
||||
if (previousAccounts.size() > 10 || (accountType == ALTERNATIVE && !previousAccounts.isEmpty()))
|
||||
throw new IllegalArgumentException("Bad HEADER previous account count");
|
||||
var seen = new java.util.HashSet<String>();
|
||||
seen.add(login.toLowerCase(Locale.ROOT));
|
||||
for (String prev : previousAccounts) {
|
||||
if (!(prev.matches("^[A-Za-z0-9_]{1,255}$") || (prev.length() <= 30 && prev.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$")))
|
||||
|| !seen.add(prev.toLowerCase(Locale.ROOT)))
|
||||
throw new IllegalArgumentException("Bad, duplicate or self HEADER previous account");
|
||||
}
|
||||
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
||||
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
|
||||
if (previous.length > 0xFFFF) throw new IllegalArgumentException("HEADER previous accounts are too long");
|
||||
requireNonZeroKey(initialBlockchainKey32);
|
||||
return this;
|
||||
}
|
||||
@@ -95,11 +144,13 @@ public final class HeaderBody implements BodyRecord {
|
||||
public byte[] toBytes() {
|
||||
check();
|
||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.put(TAG_ASCII);
|
||||
bb.put((byte) loginUtf8.length);
|
||||
bb.put(loginUtf8);
|
||||
bb.put(initialBlockchainKey32);
|
||||
byte[] licenseUtf8 = license.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] previous = String.join(",", previousAccounts).getBytes(StandardCharsets.UTF_8);
|
||||
int identitySize = 1 + (accountType == PRIMARY ? 2 + previous.length : 0);
|
||||
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + identitySize + 1 + licenseUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.put(TAG_ASCII).put((byte) loginUtf8.length).put(loginUtf8).put((byte) accountType);
|
||||
if (accountType == PRIMARY) bb.putShort((short) previous.length).put(previous);
|
||||
bb.put((byte) licenseUtf8.length).put(licenseUtf8).put(initialBlockchainKey32);
|
||||
return bb.array();
|
||||
}
|
||||
|
||||
@@ -112,6 +163,6 @@ public final class HeaderBody implements BodyRecord {
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}";
|
||||
return "HeaderBody{version=1.0, login='" + login + "', accountType=" + accountType + ", license=" + license + ", initialBlockchainKey32=<32 bytes>}";
|
||||
}
|
||||
}
|
||||
|
||||
+23
-7
@@ -1,6 +1,7 @@
|
||||
package blockchain.body;
|
||||
|
||||
import blockchain.MsgSubType;
|
||||
import blockchain.CoreRecord;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
@@ -27,6 +28,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
||||
public static final short VER = 1;
|
||||
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
|
||||
|
||||
private final boolean contentOnly;
|
||||
public final short subType;
|
||||
public final short version;
|
||||
public final int lineCode;
|
||||
@@ -40,17 +42,30 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
||||
public final String message;
|
||||
|
||||
public TextLineBody(short subType, short version, byte[] bodyBytes) {
|
||||
this(subType, version, bodyBytes, null);
|
||||
}
|
||||
|
||||
/** Разбор CONTENT: линия берётся из CORE, порядковый номер не подписан. */
|
||||
public TextLineBody(short subType, short version, byte[] bodyBytes, CoreRecord.Line line) {
|
||||
this.contentOnly = line != null;
|
||||
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
|
||||
this.subType = subType;
|
||||
this.version = version;
|
||||
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
|
||||
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 2, "TextLineBody too short");
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
BodyTargetSupport.ensureMin(bb, (4 + 4 + 32 + 4 + 2) - (contentOnly ? 44 : 0), "TextLineBody too short");
|
||||
if (contentOnly) {
|
||||
this.lineCode = line.lineCode();
|
||||
this.prevLineNumber = line.prevLineBlockNumber();
|
||||
this.prevLineHash32 = line.prevLineCoreHash32();
|
||||
this.thisLineNumber = BodyHasLine.UNRESOLVED_SEQUENCE;
|
||||
} else {
|
||||
this.lineCode = bb.getInt();
|
||||
this.prevLineNumber = bb.getInt();
|
||||
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
|
||||
this.thisLineNumber = bb.getInt();
|
||||
}
|
||||
|
||||
int st = subType & 0xFFFF;
|
||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
||||
@@ -88,6 +103,7 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
||||
Integer toBlockGlobalNumber,
|
||||
byte[] toBlockHash32,
|
||||
String message) {
|
||||
this.contentOnly = false;
|
||||
Objects.requireNonNull(message, "message == null");
|
||||
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
|
||||
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
|
||||
@@ -144,8 +160,8 @@ public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarge
|
||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
|
||||
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
|
||||
|
||||
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
|
||||
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
|
||||
ByteBuffer bb = ByteBuffer.allocate((contentOnly ? 0 : 44) + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
|
||||
if (!contentOnly) bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
|
||||
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
|
||||
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
|
||||
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user