SHA256
Compare commits
81
Commits
| Author | SHA256 | Date | |
|---|---|---|---|
|
|
551bdc2d65 | ||
|
|
f507bdb343 | ||
|
|
395aa62bda | ||
|
|
d2b2876a79 | ||
|
|
8bb7d39c76 | ||
|
|
e296217f21 | ||
|
|
c0257f4be2 | ||
|
|
7b88b61b22 | ||
|
|
ab61787ee7 | ||
|
|
219a65ae27 | ||
|
|
94d4665185 | ||
|
|
ce97171d5a | ||
|
|
a22f590395 | ||
|
|
a520c5c5e1 | ||
|
|
cab26bbf41 | ||
|
|
6c8159c5f7 | ||
|
|
df0e9cef9b | ||
|
|
7a6ab3b35a | ||
|
|
aa5addb5d9 | ||
|
|
b67d06ce43 | ||
|
|
8d9a580f50 | ||
|
|
45eb77f431 | ||
|
|
2be6fe3ff9 | ||
|
|
a380900ec8 | ||
|
|
bca788c5e6 | ||
|
|
e77aaa3675 | ||
|
|
d25894149b | ||
|
|
68eec2b28b | ||
|
|
694aaf1f0e | ||
|
|
5caa4ce0ae | ||
|
|
af5b26c934 | ||
|
|
6997bc7600 | ||
|
|
9eedbf60a8 | ||
|
|
6294646922 | ||
|
|
42797b1a43 | ||
|
|
8c3751aba0 | ||
|
|
f40353725e | ||
|
|
3f0d71f788 | ||
|
|
f2ba7ce630 | ||
|
|
edc3d50136 | ||
|
|
a7a600035a | ||
|
|
3f05806563 | ||
|
|
2fb19ee66d | ||
|
|
d91ca5fbb3 | ||
|
|
7173f33d5f | ||
|
|
b3f9e1fe21 | ||
|
|
401ba918ad | ||
|
|
82d5a768f8 | ||
|
|
835109c81a | ||
|
|
d5f2c12fe7 | ||
|
|
11f169b080 | ||
|
|
96d23b16fc | ||
|
|
26db18e250 | ||
|
|
8fee7e1a9b | ||
|
|
e7cf98889b | ||
|
|
3fdff2a92b | ||
|
|
4d5a485933 | ||
|
|
b9cbbb857b | ||
|
|
56de0f2c74 | ||
|
|
68fe0532ce | ||
|
|
3edde418a2 | ||
|
|
923f281bf6 | ||
|
|
9ea276ba77 | ||
|
|
cfb0f9b734 | ||
|
|
993930eb82 | ||
|
|
17d6cb5be0 | ||
|
|
bb725ee451 | ||
|
|
b5ce7b0fa0 | ||
|
|
58de6a025d | ||
|
|
e6937cb49c | ||
|
|
7ac9e5a806 | ||
|
|
89630878af | ||
|
|
8b2012fad3 | ||
|
|
07ddaf5e4c | ||
|
|
4d10096ba2 | ||
|
|
5e9699613d | ||
|
|
b56a3a795f | ||
|
|
70fac068d0 | ||
|
|
d138bd9464 | ||
|
|
e14e3dfa21 | ||
|
|
30541ae4af |
@@ -79,6 +79,7 @@ shine-solana/shine/scripts/**/TEMP_*.md
|
|||||||
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
# Локальные артефакты и внешние материалы ESP32-подпроекта
|
||||||
ESP32/esp32-config-tool/
|
ESP32/esp32-config-tool/
|
||||||
ESP32/local-sketches/
|
ESP32/local-sketches/
|
||||||
|
ESP32/esp32/ESP32-S3-Touch-AMOLED-2.16/main-device/test_sketches/breath_dual_mode_monitor/
|
||||||
ESP32/**/.git/
|
ESP32/**/.git/
|
||||||
ESP32/**/.idea/
|
ESP32/**/.idea/
|
||||||
ESP32-wallet/.idea/
|
ESP32-wallet/.idea/
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
MODE="${1:-potentiometer-adc-test}"
|
||||||
|
PORT="${PORT:-}"
|
||||||
|
|
||||||
|
case "$MODE" in
|
||||||
|
potentiometer-adc-test)
|
||||||
|
SKETCH_DIR="$ROOT_DIR/test_sketches/potentiometer_adc_test"
|
||||||
|
BUILD_DIR="$ROOT_DIR/.arduino-build/build-potentiometer-adc-test"
|
||||||
|
;;
|
||||||
|
buzzer-gpio6-test)
|
||||||
|
SKETCH_DIR="$ROOT_DIR/test_sketches/buzzer_gpio6_test"
|
||||||
|
BUILD_DIR="$ROOT_DIR/.arduino-build/build-buzzer-gpio6-test"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Unknown mode: $MODE" >&2
|
||||||
|
echo "Known modes: potentiometer-adc-test, buzzer-gpio6-test" >&2
|
||||||
|
exit 2
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
if [[ -z "$PORT" ]]; then
|
||||||
|
PORT="$(arduino-cli board list | awk '/ttyACM|ttyUSB/ {print $1; exit}')"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$PORT" ]]; then
|
||||||
|
echo "No serial port found. Set PORT=/dev/ttyACM0 explicitly." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
FQBN="esp32:esp32:esp32s3:USBMode=hwcdc,CDCOnBoot=cdc,UploadSpeed=921600,CPUFreq=240,FlashMode=dio,FlashSize=16M,PartitionScheme=app3M_fat9M_16MB,PSRAM=opi"
|
||||||
|
|
||||||
|
echo "== Mode: $MODE"
|
||||||
|
echo "== Sketch: $SKETCH_DIR"
|
||||||
|
echo "== Port: $PORT"
|
||||||
|
echo "== FQBN: $FQBN"
|
||||||
|
|
||||||
|
arduino-cli compile \
|
||||||
|
--fqbn "$FQBN" \
|
||||||
|
--build-path "$BUILD_DIR" \
|
||||||
|
"$SKETCH_DIR"
|
||||||
|
|
||||||
|
arduino-cli upload \
|
||||||
|
--fqbn "$FQBN" \
|
||||||
|
-p "$PORT" \
|
||||||
|
--input-dir "$BUILD_DIR" \
|
||||||
|
"$SKETCH_DIR"
|
||||||
|
|
||||||
|
echo
|
||||||
|
echo "== Done."
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# AGENTS
|
||||||
|
|
||||||
|
This folder contains a temporary GPIO6 buzzer diagnostic for ESP32-S3-LCD-2. Keep screen/serial strings in English.
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
// Buzzer module wiring: GND -> GND, VCC -> 3V3, I/O -> P1 IO6 / GPIO6.
|
||||||
|
static constexpr uint8_t PIN_BUZZER = 6;
|
||||||
|
static constexpr uint32_t STEP_MS = 1800;
|
||||||
|
static uint8_t gStep = 0;
|
||||||
|
static uint32_t gChangedMs = 0;
|
||||||
|
|
||||||
|
static void applyStep(uint8_t step) {
|
||||||
|
ledcDetach(PIN_BUZZER);
|
||||||
|
pinMode(PIN_BUZZER, OUTPUT);
|
||||||
|
digitalWrite(PIN_BUZZER, LOW);
|
||||||
|
delay(80);
|
||||||
|
switch (step) {
|
||||||
|
case 0:
|
||||||
|
pinMode(PIN_BUZZER, OUTPUT);
|
||||||
|
digitalWrite(PIN_BUZZER, HIGH);
|
||||||
|
Serial.println("TEST 1: GPIO6 HIGH - active-high module should sound");
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
pinMode(PIN_BUZZER, OUTPUT);
|
||||||
|
digitalWrite(PIN_BUZZER, LOW);
|
||||||
|
Serial.println("TEST 2: GPIO6 LOW - active-low module should sound");
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
ledcAttach(PIN_BUZZER, 1800, 8);
|
||||||
|
ledcWriteTone(PIN_BUZZER, 1800);
|
||||||
|
ledcWrite(PIN_BUZZER, 180);
|
||||||
|
Serial.println("TEST 3: GPIO6 PWM 1800 Hz - passive module should sound");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
pinMode(PIN_BUZZER, OUTPUT);
|
||||||
|
digitalWrite(PIN_BUZZER, LOW);
|
||||||
|
Serial.println("SILENCE");
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
Serial.println("GPIO6 BUZZER TEST: HIGH, LOW, PWM, SILENCE. Each step lasts 1.8 seconds.");
|
||||||
|
applyStep(gStep);
|
||||||
|
gChangedMs = millis();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
if (millis() - gChangedMs < STEP_MS) return;
|
||||||
|
gStep = (gStep + 1) % 4;
|
||||||
|
applyStep(gStep);
|
||||||
|
gChangedMs = millis();
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# AGENTS
|
||||||
|
|
||||||
|
## Назначение папки
|
||||||
|
|
||||||
|
Эта папка содержит отдельный тестовый Arduino-скетч `potentiometer_adc_test.ino` для Waveshare `ESP32-S3-LCD-2`.
|
||||||
|
|
||||||
|
Скетч проверяет переменный резистор на обычных GPIO/ADC, без использования USB `D+ / D-`.
|
||||||
|
|
||||||
|
## Обязательная синхронизация
|
||||||
|
|
||||||
|
При любом изменении `potentiometer_adc_test.ino` обязательно обновлять рядом лежащий `README.md`.
|
||||||
|
|
||||||
|
Если меняются экранные тексты, режимы, пины подключения, правила расчёта, touch-кнопки или serial-команды, описание в `README.md` должно быть обновлено в том же наборе изменений.
|
||||||
|
|
||||||
|
## Язык экрана
|
||||||
|
|
||||||
|
Экранные строки в скетче оставлять на английском языке.
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
# Potentiometer ADC Test for ESP32-S3-LCD-2
|
||||||
|
|
||||||
|
Тестовый скетч для Waveshare `ESP32-S3-LCD-2`.
|
||||||
|
|
||||||
|
Назначение: проверить переменный резистор `RP 6045-B50K` через обычные GPIO/ADC, без использования USB `D+ / D-`.
|
||||||
|
|
||||||
|
## Пины
|
||||||
|
|
||||||
|
Используются пины с разъёма `P1` платы:
|
||||||
|
|
||||||
|
- `GPIO2 / IO2` — ADC-вход, сюда подключается ползунок потенциометра.
|
||||||
|
- `GPIO6 / IO6` — DRIVE-выход для грубого 2-проводного режима.
|
||||||
|
- `3V3` — питание потенциометра для 3-проводного режима, находится на разъёме `P2`.
|
||||||
|
- `GND` — земля.
|
||||||
|
|
||||||
|
Не подавать `5V` на `GPIO2` или `GPIO6`: GPIO ESP32-S3 не являются 5V tolerant.
|
||||||
|
|
||||||
|
## Режимы
|
||||||
|
|
||||||
|
Переключение:
|
||||||
|
|
||||||
|
- touch-кнопка `3-WIRE`;
|
||||||
|
- touch-кнопка `2-WIRE`;
|
||||||
|
- серийная команда `m`;
|
||||||
|
- короткое нажатие `BOOT / GPIO0`.
|
||||||
|
|
||||||
|
Сброс min/max:
|
||||||
|
|
||||||
|
- touch-кнопка `RESET`;
|
||||||
|
- серийная команда `r`.
|
||||||
|
|
||||||
|
## 3-Wire Mode
|
||||||
|
|
||||||
|
Правильное подключение:
|
||||||
|
|
||||||
|
- один край потенциометра -> `3V3`;
|
||||||
|
- второй край потенциометра -> `GND`;
|
||||||
|
- средний ползунок -> `GPIO2 / IO2`.
|
||||||
|
|
||||||
|
Скетч показывает напряжение на ползунке, raw ADC, абсолютное положение от `0..3.3V`, калиброванное положение между найденными min/max и примерное сопротивление участка `0..50 kΩ`.
|
||||||
|
|
||||||
|
## 2-Wire Mode
|
||||||
|
|
||||||
|
Грубое подключение:
|
||||||
|
|
||||||
|
- один край потенциометра -> `GPIO6 / IO6`;
|
||||||
|
- средний ползунок -> `GPIO2 / IO2`;
|
||||||
|
- второй край не подключать.
|
||||||
|
|
||||||
|
`GPIO6` выдаёт `HIGH`, `GPIO2` читается как ADC с внутренней подтяжкой вниз. Такой режим показывает движение ползунка, но не даёт точного сопротивления: внутренняя подтяжка ESP32 имеет большой разброс.
|
||||||
|
|
||||||
|
## Экранные данные
|
||||||
|
|
||||||
|
На экране выводятся:
|
||||||
|
|
||||||
|
- режим и схема пинов;
|
||||||
|
- raw ADC и millivolts;
|
||||||
|
- абсолютный процент от `0..3300 mV`;
|
||||||
|
- калиброванный процент по найденному min/max;
|
||||||
|
- min/max/span;
|
||||||
|
- EMA-сглаживание;
|
||||||
|
- примерная оценка сопротивления;
|
||||||
|
- статус `OPEN/LOW/MID/HIGH/SATURATED/NO SPAN`;
|
||||||
|
- координаты последнего touch;
|
||||||
|
- serial-подсказка.
|
||||||
|
|
||||||
|
## Сборка
|
||||||
|
|
||||||
|
Из папки `main-device`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./burn.sh potentiometer-adc-test
|
||||||
|
```
|
||||||
+348
@@ -0,0 +1,348 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include <Arduino_GFX_Library.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <bsp_cst816.h>
|
||||||
|
|
||||||
|
#define PIN_LCD_SCLK 39
|
||||||
|
#define PIN_LCD_MOSI 38
|
||||||
|
#define PIN_LCD_MISO 40
|
||||||
|
#define PIN_LCD_DC 42
|
||||||
|
#define PIN_LCD_RST -1
|
||||||
|
#define PIN_LCD_CS 45
|
||||||
|
#define PIN_LCD_BL 1
|
||||||
|
|
||||||
|
#define PIN_TP_SDA 48
|
||||||
|
#define PIN_TP_SCL 47
|
||||||
|
|
||||||
|
#define PIN_ADC_WIPER 2
|
||||||
|
#define PIN_DRIVE_2WIRE 6
|
||||||
|
#define PIN_BOOT_BUTTON 0
|
||||||
|
|
||||||
|
static const uint16_t DISP_W = 320;
|
||||||
|
static const uint16_t DISP_H = 240;
|
||||||
|
static const uint32_t ADC_FULL_MV = 3300;
|
||||||
|
static const float POT_OHMS = 50000.0f;
|
||||||
|
static const float ROUGH_PULLDOWN_OHMS = 45000.0f;
|
||||||
|
|
||||||
|
static const uint16_t C_BG = 0x0841;
|
||||||
|
static const uint16_t C_PANEL = 0x18E3;
|
||||||
|
static const uint16_t C_CARD = 0x2126;
|
||||||
|
static const uint16_t C_TEXT = 0xF7BE;
|
||||||
|
static const uint16_t C_MUTE = 0x8C71;
|
||||||
|
static const uint16_t C_ACCENT = 0x05DF;
|
||||||
|
static const uint16_t C_OK = 0x47E8;
|
||||||
|
static const uint16_t C_WARN = 0xFD20;
|
||||||
|
static const uint16_t C_BAD = 0xF986;
|
||||||
|
static const uint16_t C_BORDER = 0x4208;
|
||||||
|
|
||||||
|
struct Rect {
|
||||||
|
int16_t x;
|
||||||
|
int16_t y;
|
||||||
|
int16_t w;
|
||||||
|
int16_t h;
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class Mode : uint8_t {
|
||||||
|
ThreeWire,
|
||||||
|
TwoWire,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Sample {
|
||||||
|
uint16_t raw;
|
||||||
|
uint32_t mv;
|
||||||
|
uint16_t rawMinBurst;
|
||||||
|
uint16_t rawMaxBurst;
|
||||||
|
};
|
||||||
|
|
||||||
|
Arduino_DataBus *bus = new Arduino_ESP32SPI(
|
||||||
|
PIN_LCD_DC, PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_MOSI, PIN_LCD_MISO);
|
||||||
|
Arduino_GFX *gfx = new Arduino_ST7789(
|
||||||
|
bus, PIN_LCD_RST, 1, true, 240, 320);
|
||||||
|
|
||||||
|
static const Rect BTN_3WIRE = {10, 38, 94, 30};
|
||||||
|
static const Rect BTN_2WIRE = {113, 38, 94, 30};
|
||||||
|
static const Rect BTN_RESET = {216, 38, 94, 30};
|
||||||
|
|
||||||
|
static Mode gMode = Mode::ThreeWire;
|
||||||
|
static uint32_t gLastUiMs = 0;
|
||||||
|
static uint32_t gLastSerialMs = 0;
|
||||||
|
static uint32_t gMinMv = 0xFFFFFFFF;
|
||||||
|
static uint32_t gMaxMv = 0;
|
||||||
|
static float gEmaMv = 0.0f;
|
||||||
|
static bool gHasEma = false;
|
||||||
|
static bool gTouchOk = false;
|
||||||
|
static uint16_t gLastTouchX = 0;
|
||||||
|
static uint16_t gLastTouchY = 0;
|
||||||
|
static bool gBootWasDown = false;
|
||||||
|
static uint32_t gBootLastChangeMs = 0;
|
||||||
|
|
||||||
|
static void drawText(int16_t x, int16_t y, const char *text, uint16_t color, uint8_t size = 1) {
|
||||||
|
gfx->setTextSize(size);
|
||||||
|
gfx->setTextColor(color);
|
||||||
|
gfx->setCursor(x, y);
|
||||||
|
gfx->print(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void drawButton(const Rect &r, const char *label, bool active) {
|
||||||
|
uint16_t fill = active ? C_ACCENT : C_CARD;
|
||||||
|
uint16_t text = active ? C_BG : C_TEXT;
|
||||||
|
gfx->fillRoundRect(r.x, r.y, r.w, r.h, 6, fill);
|
||||||
|
gfx->drawRoundRect(r.x, r.y, r.w, r.h, 6, active ? C_ACCENT : C_BORDER);
|
||||||
|
int16_t tx = r.x + 10;
|
||||||
|
int16_t ty = r.y + 10;
|
||||||
|
drawText(tx, ty, label, text, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool contains(const Rect &r, uint16_t x, uint16_t y) {
|
||||||
|
return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h;
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *modeName() {
|
||||||
|
return gMode == Mode::ThreeWire ? "3-WIRE" : "2-WIRE";
|
||||||
|
}
|
||||||
|
|
||||||
|
static void resetRange() {
|
||||||
|
gMinMv = 0xFFFFFFFF;
|
||||||
|
gMaxMv = 0;
|
||||||
|
gHasEma = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void configurePins() {
|
||||||
|
pinMode(PIN_ADC_WIPER, INPUT);
|
||||||
|
analogReadResolution(12);
|
||||||
|
analogSetPinAttenuation(PIN_ADC_WIPER, ADC_11db);
|
||||||
|
|
||||||
|
if (gMode == Mode::TwoWire) {
|
||||||
|
pinMode(PIN_DRIVE_2WIRE, OUTPUT);
|
||||||
|
digitalWrite(PIN_DRIVE_2WIRE, HIGH);
|
||||||
|
pinMode(PIN_ADC_WIPER, INPUT_PULLDOWN);
|
||||||
|
} else {
|
||||||
|
pinMode(PIN_DRIVE_2WIRE, INPUT);
|
||||||
|
pinMode(PIN_ADC_WIPER, INPUT);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setMode(Mode mode) {
|
||||||
|
if (gMode == mode) return;
|
||||||
|
gMode = mode;
|
||||||
|
configurePins();
|
||||||
|
resetRange();
|
||||||
|
}
|
||||||
|
|
||||||
|
static Sample readSample() {
|
||||||
|
const uint8_t count = 32;
|
||||||
|
uint32_t rawSum = 0;
|
||||||
|
uint32_t mvSum = 0;
|
||||||
|
uint16_t rawMin = 4095;
|
||||||
|
uint16_t rawMax = 0;
|
||||||
|
|
||||||
|
for (uint8_t i = 0; i < count; i++) {
|
||||||
|
uint16_t raw = analogRead(PIN_ADC_WIPER);
|
||||||
|
uint32_t mv = analogReadMilliVolts(PIN_ADC_WIPER);
|
||||||
|
rawSum += raw;
|
||||||
|
mvSum += mv;
|
||||||
|
if (raw < rawMin) rawMin = raw;
|
||||||
|
if (raw > rawMax) rawMax = raw;
|
||||||
|
delayMicroseconds(250);
|
||||||
|
}
|
||||||
|
|
||||||
|
Sample s;
|
||||||
|
s.raw = rawSum / count;
|
||||||
|
s.mv = mvSum / count;
|
||||||
|
s.rawMinBurst = rawMin;
|
||||||
|
s.rawMaxBurst = rawMax;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t percentFromMv(uint32_t mv) {
|
||||||
|
if (mv >= ADC_FULL_MV) return 100;
|
||||||
|
return (uint8_t)((mv * 100UL + ADC_FULL_MV / 2) / ADC_FULL_MV);
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint8_t calibratedPercent(uint32_t mv, uint32_t span) {
|
||||||
|
if (span < 10 || gMinMv == 0xFFFFFFFF || mv <= gMinMv) return 0;
|
||||||
|
uint32_t pct = ((mv - gMinMv) * 100UL + span / 2) / span;
|
||||||
|
return (uint8_t)min<uint32_t>(pct, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
static const char *statusText(uint32_t mv, uint32_t span, uint8_t pctAbs) {
|
||||||
|
if (mv < 30) return "OPEN/GND";
|
||||||
|
if (mv > 3250) return "SATURATED";
|
||||||
|
if (span < 20) return "NO SPAN";
|
||||||
|
if (pctAbs < 15) return "LOW";
|
||||||
|
if (pctAbs > 85) return "HIGH";
|
||||||
|
return "MID";
|
||||||
|
}
|
||||||
|
|
||||||
|
static float estimateOhms(uint32_t mv) {
|
||||||
|
if (gMode == Mode::ThreeWire) {
|
||||||
|
return POT_OHMS * ((float)percentFromMv(mv) / 100.0f);
|
||||||
|
}
|
||||||
|
if (mv < 5) return -1.0f;
|
||||||
|
if (mv >= ADC_FULL_MV) return 0.0f;
|
||||||
|
return ROUGH_PULLDOWN_OHMS * ((float)ADC_FULL_MV / (float)mv - 1.0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void drawStaticUi() {
|
||||||
|
gfx->fillScreen(C_BG);
|
||||||
|
drawText(10, 8, "POT ADC TEST", C_TEXT, 2);
|
||||||
|
drawText(210, 12, "ESP32-S3-LCD-2", C_MUTE, 1);
|
||||||
|
drawButton(BTN_3WIRE, "3-WIRE", gMode == Mode::ThreeWire);
|
||||||
|
drawButton(BTN_2WIRE, "2-WIRE", gMode == Mode::TwoWire);
|
||||||
|
drawButton(BTN_RESET, "RESET", false);
|
||||||
|
|
||||||
|
gfx->drawRoundRect(8, 76, 304, 64, 8, C_BORDER);
|
||||||
|
gfx->drawRoundRect(8, 148, 304, 54, 8, C_BORDER);
|
||||||
|
gfx->drawRoundRect(8, 208, 304, 24, 6, C_BORDER);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void drawBar(uint8_t pct, uint16_t color) {
|
||||||
|
int x = 18;
|
||||||
|
int y = 123;
|
||||||
|
int w = 284;
|
||||||
|
int h = 10;
|
||||||
|
gfx->fillRect(x, y, w, h, C_BORDER);
|
||||||
|
gfx->fillRect(x, y, (w * pct) / 100, h, color);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateUi() {
|
||||||
|
Sample s = readSample();
|
||||||
|
if (s.mv < gMinMv) gMinMv = s.mv;
|
||||||
|
if (s.mv > gMaxMv) gMaxMv = s.mv;
|
||||||
|
uint32_t span = (gMaxMv > gMinMv) ? (gMaxMv - gMinMv) : 0;
|
||||||
|
|
||||||
|
if (!gHasEma) {
|
||||||
|
gEmaMv = (float)s.mv;
|
||||||
|
gHasEma = true;
|
||||||
|
} else {
|
||||||
|
gEmaMv = gEmaMv * 0.85f + (float)s.mv * 0.15f;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t pctAbs = percentFromMv(s.mv);
|
||||||
|
uint8_t pctCal = calibratedPercent(s.mv, span);
|
||||||
|
float ohms = estimateOhms(s.mv);
|
||||||
|
const char *status = statusText(s.mv, span, pctAbs);
|
||||||
|
uint16_t statusColor = strcmp(status, "MID") == 0 ? C_OK :
|
||||||
|
strcmp(status, "NO SPAN") == 0 ? C_WARN :
|
||||||
|
strcmp(status, "SATURATED") == 0 ? C_BAD : C_ACCENT;
|
||||||
|
|
||||||
|
char line[96];
|
||||||
|
gfx->fillRect(9, 77, 302, 62, C_BG);
|
||||||
|
snprintf(line, sizeof(line), "%s ADC=IO2 DRIVE=IO6", modeName());
|
||||||
|
drawText(16, 84, line, C_ACCENT, 1);
|
||||||
|
snprintf(line, sizeof(line), "raw:%4u mv:%4lu ema:%4lu",
|
||||||
|
s.raw, (unsigned long)s.mv, (unsigned long)(gEmaMv + 0.5f));
|
||||||
|
drawText(16, 101, line, C_TEXT, 1);
|
||||||
|
snprintf(line, sizeof(line), "abs:%3u%% cal:%3u%% jitter:%u",
|
||||||
|
pctAbs, pctCal, (unsigned)(s.rawMaxBurst - s.rawMinBurst));
|
||||||
|
drawText(16, 115, line, C_TEXT, 1);
|
||||||
|
drawBar(gMode == Mode::ThreeWire ? pctAbs : pctCal, statusColor);
|
||||||
|
|
||||||
|
gfx->fillRect(9, 149, 302, 52, C_BG);
|
||||||
|
snprintf(line, sizeof(line), "min:%4lu max:%4lu span:%4lu mV",
|
||||||
|
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span);
|
||||||
|
drawText(16, 156, line, C_TEXT, 1);
|
||||||
|
if (ohms < 0) {
|
||||||
|
snprintf(line, sizeof(line), "ohm: open/too high status:%s", status);
|
||||||
|
} else {
|
||||||
|
snprintf(line, sizeof(line), "ohm:%6.1fk%s status:%s",
|
||||||
|
ohms / 1000.0f, gMode == Mode::TwoWire ? " rough" : "", status);
|
||||||
|
}
|
||||||
|
drawText(16, 172, line, statusColor, 1);
|
||||||
|
snprintf(line, sizeof(line), "touch:%s x:%u y:%u serial:m/r",
|
||||||
|
gTouchOk ? "ok" : "off", gLastTouchX, gLastTouchY);
|
||||||
|
drawText(16, 188, line, C_MUTE, 1);
|
||||||
|
|
||||||
|
gfx->fillRect(9, 209, 302, 22, C_BG);
|
||||||
|
if (gMode == Mode::ThreeWire) {
|
||||||
|
drawText(16, 216, "Wire: 3V3-edge GND-edge IO2-wiper", C_MUTE, 1);
|
||||||
|
} else {
|
||||||
|
drawText(16, 216, "Wire: IO6-edge IO2-wiper third pin open", C_MUTE, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
Serial.printf("mode=%s raw=%u mv=%lu ema=%.1f abs=%u cal=%u min=%lu max=%lu span=%lu jitter=%u status=%s\n",
|
||||||
|
modeName(), s.raw, (unsigned long)s.mv, gEmaMv, pctAbs, pctCal,
|
||||||
|
(unsigned long)gMinMv, (unsigned long)gMaxMv, (unsigned long)span,
|
||||||
|
(unsigned)(s.rawMaxBurst - s.rawMinBurst), status);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handleTouch() {
|
||||||
|
bsp_touch_read();
|
||||||
|
uint16_t x = 0;
|
||||||
|
uint16_t y = 0;
|
||||||
|
if (!bsp_touch_get_coordinates(&x, &y)) return;
|
||||||
|
gLastTouchX = x;
|
||||||
|
gLastTouchY = y;
|
||||||
|
|
||||||
|
if (contains(BTN_3WIRE, x, y)) {
|
||||||
|
setMode(Mode::ThreeWire);
|
||||||
|
drawStaticUi();
|
||||||
|
} else if (contains(BTN_2WIRE, x, y)) {
|
||||||
|
setMode(Mode::TwoWire);
|
||||||
|
drawStaticUi();
|
||||||
|
} else if (contains(BTN_RESET, x, y)) {
|
||||||
|
resetRange();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handleBootButton() {
|
||||||
|
bool down = digitalRead(PIN_BOOT_BUTTON) == LOW;
|
||||||
|
uint32_t now = millis();
|
||||||
|
if (down != gBootWasDown && now - gBootLastChangeMs > 40) {
|
||||||
|
gBootWasDown = down;
|
||||||
|
gBootLastChangeMs = now;
|
||||||
|
if (!down) {
|
||||||
|
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||||
|
drawStaticUi();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void handleSerial() {
|
||||||
|
while (Serial.available() > 0) {
|
||||||
|
char c = (char)Serial.read();
|
||||||
|
if (c == 'm' || c == 'M') {
|
||||||
|
setMode(gMode == Mode::ThreeWire ? Mode::TwoWire : Mode::ThreeWire);
|
||||||
|
drawStaticUi();
|
||||||
|
} else if (c == 'r' || c == 'R') {
|
||||||
|
resetRange();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(100);
|
||||||
|
Serial.println("ESP32-S3-LCD-2 potentiometer ADC test");
|
||||||
|
Serial.println("Commands: m=switch mode, r=reset min/max");
|
||||||
|
|
||||||
|
pinMode(PIN_BOOT_BUTTON, INPUT_PULLUP);
|
||||||
|
configurePins();
|
||||||
|
|
||||||
|
if (!gfx->begin()) {
|
||||||
|
Serial.println("gfx->begin() failed");
|
||||||
|
}
|
||||||
|
pinMode(PIN_LCD_BL, OUTPUT);
|
||||||
|
digitalWrite(PIN_LCD_BL, HIGH);
|
||||||
|
|
||||||
|
Wire.begin(PIN_TP_SDA, PIN_TP_SCL);
|
||||||
|
gTouchOk = bsp_touch_init(&Wire, 1, DISP_W, DISP_H);
|
||||||
|
|
||||||
|
drawStaticUi();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
handleSerial();
|
||||||
|
handleBootButton();
|
||||||
|
if (gTouchOk) handleTouch();
|
||||||
|
|
||||||
|
uint32_t now = millis();
|
||||||
|
if (now - gLastUiMs >= 250) {
|
||||||
|
updateUi();
|
||||||
|
gLastUiMs = now;
|
||||||
|
}
|
||||||
|
if (now - gLastSerialMs >= 5000) {
|
||||||
|
Serial.println("Hint: m switches 3-WIRE/2-WIRE, r resets min/max. Never feed 5V into IO2/IO6.");
|
||||||
|
gLastSerialMs = now;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -49,25 +49,18 @@ case "${MODE}" in
|
|||||||
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_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-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-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" ;;
|
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" ;;
|
lvgl-nav-minimal-test) SKETCH_DIR="${ROOT_DIR}/shine_homeserver_main" ;;
|
||||||
*)
|
*)
|
||||||
echo "Unknown mode: ${MODE}" >&2
|
echo "Unknown mode: ${MODE}" >&2
|
||||||
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, usb-contact-test, usb-contact-debug-test, usb-contact-screen-start-stub" >&2
|
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test, usb-contact-test, usb-contact-debug-test, usb-contact-resistance-test, usb-contact-screen-start-stub" >&2
|
||||||
exit 2
|
exit 2
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
|
||||||
if [[ -z "${PORT}" ]]; then
|
|
||||||
if ! PORT="$(detect_port)"; then
|
|
||||||
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
|
||||||
exit 3
|
|
||||||
fi
|
|
||||||
fi
|
|
||||||
|
|
||||||
echo "== Mode: ${MODE}"
|
echo "== Mode: ${MODE}"
|
||||||
echo "== Sketch: ${SKETCH_DIR}"
|
echo "== Sketch: ${SKETCH_DIR}"
|
||||||
echo "== Port: ${PORT}"
|
|
||||||
echo "== FQBN: ${FQBN}"
|
echo "== FQBN: ${FQBN}"
|
||||||
|
|
||||||
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
mkdir -p "${BUILD_DIR}" "${OUT_DIR}"
|
||||||
@@ -91,6 +84,20 @@ if ! arduino-cli compile "${compile_args[@]}"; then
|
|||||||
arduino-cli compile --clean "${compile_args[@]}"
|
arduino-cli compile --clean "${compile_args[@]}"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${NO_UPLOAD:-0}" == "1" ]]; then
|
||||||
|
echo "== Done: compiled without upload (NO_UPLOAD=1)."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "${PORT}" ]]; then
|
||||||
|
if ! PORT="$(detect_port)"; then
|
||||||
|
echo "Failed to auto-detect ESP32 port. Set PORT=/dev/ttyACM0 ./burn.sh ${MODE}" >&2
|
||||||
|
exit 3
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "== Port: ${PORT}"
|
||||||
|
|
||||||
arduino-cli upload \
|
arduino-cli upload \
|
||||||
-p "${PORT}" \
|
-p "${PORT}" \
|
||||||
--fqbn "${FQBN}" \
|
--fqbn "${FQBN}" \
|
||||||
|
|||||||
@@ -17,6 +17,7 @@
|
|||||||
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
|
||||||
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
|
||||||
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
|
||||||
|
- `usb_contact_resistance_test/` - тест измерения сопротивления между USB D-/D+ через ADC на GPIO20; рассчитан на внешний известный резистор 10 kΩ с D+ на GND
|
||||||
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
|
||||||
|
|
||||||
## Запуск
|
## Запуск
|
||||||
@@ -33,3 +34,4 @@
|
|||||||
- `./burn.sh lvgl-russian-font-test`
|
- `./burn.sh lvgl-russian-font-test`
|
||||||
- `./burn.sh usb-contact-test`
|
- `./burn.sh usb-contact-test`
|
||||||
- `./burn.sh usb-contact-debug-test`
|
- `./burn.sh usb-contact-debug-test`
|
||||||
|
- `./burn.sh usb-contact-resistance-test`
|
||||||
|
|||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
#include <Arduino.h>
|
||||||
|
#include <Wire.h>
|
||||||
|
#include <lvgl.h>
|
||||||
|
#include <Arduino_GFX_Library.h>
|
||||||
|
#include "pin_config.h"
|
||||||
|
#include "TouchDrvCSTXXX.hpp"
|
||||||
|
|
||||||
|
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
|
||||||
|
|
||||||
|
// ESP32-S3 native USB data pins.
|
||||||
|
static constexpr int kUsbDmPin = 19; // USB D-
|
||||||
|
static constexpr int kUsbDpPin = 20; // USB D+, ADC input in resistance mode.
|
||||||
|
static constexpr uint32_t kUiRefreshMs = 120;
|
||||||
|
static constexpr uint32_t kAdcSamples = 32;
|
||||||
|
|
||||||
|
// For a stable ohm reading connect a known resistor from D+ / GPIO20 to GND.
|
||||||
|
// The measured resistance must be connected between D- / GPIO19 and D+ / GPIO20.
|
||||||
|
static constexpr float kKnownPulldownOhms = 10000.0f;
|
||||||
|
static constexpr float kSourceMillivolts = 3300.0f;
|
||||||
|
static constexpr float kOpenThresholdMillivolts = 25.0f;
|
||||||
|
|
||||||
|
static lv_disp_draw_buf_t gDrawBuf;
|
||||||
|
static lv_color_t *gBuf1 = nullptr;
|
||||||
|
static lv_color_t *gBuf2 = nullptr;
|
||||||
|
static lv_obj_t *gModeLabel = nullptr;
|
||||||
|
static lv_obj_t *gResistanceLabel = nullptr;
|
||||||
|
static lv_obj_t *gRawLabel = nullptr;
|
||||||
|
static lv_obj_t *gHintLabel = nullptr;
|
||||||
|
static lv_obj_t *gActionButton = nullptr;
|
||||||
|
static lv_obj_t *gActionButtonLabel = nullptr;
|
||||||
|
|
||||||
|
static TouchDrvCST92xx gTouch;
|
||||||
|
static int16_t gTouchX[5];
|
||||||
|
static int16_t gTouchY[5];
|
||||||
|
|
||||||
|
static bool gSensorMode = false;
|
||||||
|
static uint32_t gLastUiRefreshMs = 0;
|
||||||
|
|
||||||
|
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
|
||||||
|
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
|
||||||
|
Arduino_CO5300 *gfx = new Arduino_CO5300(
|
||||||
|
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
|
||||||
|
|
||||||
|
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
|
||||||
|
uint32_t w = area->x2 - area->x1 + 1;
|
||||||
|
uint32_t h = area->y2 - area->y1 + 1;
|
||||||
|
#if (LV_COLOR_16_SWAP != 0)
|
||||||
|
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||||
|
#else
|
||||||
|
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
|
||||||
|
#endif
|
||||||
|
lv_disp_flush_ready(disp);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void lvglTick(void *arg) {
|
||||||
|
LV_UNUSED(arg);
|
||||||
|
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
|
||||||
|
LV_UNUSED(indevDrv);
|
||||||
|
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
|
||||||
|
if (touched > 0) {
|
||||||
|
data->state = LV_INDEV_STATE_PR;
|
||||||
|
data->point.x = gTouchX[0];
|
||||||
|
data->point.y = gTouchY[0];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
data->state = LV_INDEV_STATE_REL;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t readAverageRaw() {
|
||||||
|
uint32_t sum = 0;
|
||||||
|
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||||
|
sum += analogRead(kUsbDpPin);
|
||||||
|
delayMicroseconds(250);
|
||||||
|
}
|
||||||
|
return sum / kAdcSamples;
|
||||||
|
}
|
||||||
|
|
||||||
|
static uint32_t readAverageMillivolts() {
|
||||||
|
uint32_t sum = 0;
|
||||||
|
for (uint32_t i = 0; i < kAdcSamples; i++) {
|
||||||
|
sum += analogReadMilliVolts(kUsbDpPin);
|
||||||
|
delayMicroseconds(250);
|
||||||
|
}
|
||||||
|
return sum / kAdcSamples;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void setResistanceText(float ohms) {
|
||||||
|
if (ohms >= 1000000.0f) {
|
||||||
|
String text = String(ohms / 1000000.0f, 2) + " Mohm";
|
||||||
|
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||||
|
} else if (ohms >= 1000.0f) {
|
||||||
|
String text = String(ohms / 1000.0f, 2) + " kohm";
|
||||||
|
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||||
|
} else {
|
||||||
|
String text = String(ohms, 0) + " ohm";
|
||||||
|
lv_label_set_text(gResistanceLabel, text.c_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void updateResistanceUi() {
|
||||||
|
if (!gSensorMode) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint32_t now = millis();
|
||||||
|
if (now - gLastUiRefreshMs < kUiRefreshMs) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
gLastUiRefreshMs = now;
|
||||||
|
|
||||||
|
uint32_t raw = readAverageRaw();
|
||||||
|
uint32_t millivolts = readAverageMillivolts();
|
||||||
|
|
||||||
|
if (millivolts <= kOpenThresholdMillivolts) {
|
||||||
|
lv_label_set_text(gResistanceLabel, "OPEN");
|
||||||
|
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0xFFD166), 0);
|
||||||
|
} else if (millivolts >= (uint32_t)(kSourceMillivolts - 80.0f)) {
|
||||||
|
lv_label_set_text(gResistanceLabel, "SHORT / LOW");
|
||||||
|
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||||
|
} else {
|
||||||
|
float rx = kKnownPulldownOhms * ((kSourceMillivolts / (float)millivolts) - 1.0f);
|
||||||
|
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x7CFF8A), 0);
|
||||||
|
setResistanceText(rx);
|
||||||
|
}
|
||||||
|
|
||||||
|
String rawText = "ADC raw: " + String(raw);
|
||||||
|
rawText += "\nD+ voltage: " + String(millivolts) + " mV";
|
||||||
|
rawText += "\nKnown pulldown: 10 kohm to GND";
|
||||||
|
lv_label_set_text(gRawLabel, rawText.c_str());
|
||||||
|
}
|
||||||
|
|
||||||
|
static void enterSensorMode() {
|
||||||
|
Serial.flush();
|
||||||
|
delay(30);
|
||||||
|
|
||||||
|
pinMode(kUsbDmPin, OUTPUT);
|
||||||
|
digitalWrite(kUsbDmPin, HIGH);
|
||||||
|
|
||||||
|
pinMode(kUsbDpPin, INPUT);
|
||||||
|
analogReadResolution(12);
|
||||||
|
analogSetPinAttenuation(kUsbDpPin, ADC_11db);
|
||||||
|
|
||||||
|
gSensorMode = true;
|
||||||
|
gLastUiRefreshMs = 0;
|
||||||
|
|
||||||
|
lv_label_set_text(gModeLabel, "Resistance mode");
|
||||||
|
lv_label_set_text(gHintLabel, "D- is 3.3V source. D+ is ADC input.\nUse 10 kohm from D+ to GND for accurate readings.");
|
||||||
|
lv_label_set_text(gActionButtonLabel, "Restart to USB");
|
||||||
|
updateResistanceUi();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void actionButtonEventCb(lv_event_t *event) {
|
||||||
|
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!gSensorMode) {
|
||||||
|
enterSensorMode();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lv_label_set_text(gModeLabel, "Restarting...");
|
||||||
|
lv_label_set_text(gHintLabel, "USB mode will return after reboot.");
|
||||||
|
lv_timer_handler();
|
||||||
|
delay(150);
|
||||||
|
ESP.restart();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void createUi() {
|
||||||
|
lv_obj_t *screen = lv_scr_act();
|
||||||
|
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
|
||||||
|
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
|
||||||
|
|
||||||
|
lv_obj_t *title = lv_label_create(screen);
|
||||||
|
lv_label_set_text(title, "USB RESISTANCE TEST");
|
||||||
|
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
|
||||||
|
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
|
||||||
|
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 24);
|
||||||
|
|
||||||
|
gModeLabel = lv_label_create(screen);
|
||||||
|
lv_label_set_text(gModeLabel, "USB mode");
|
||||||
|
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0xB8C8DC), 0);
|
||||||
|
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
|
||||||
|
lv_obj_align(gModeLabel, LV_ALIGN_TOP_MID, 0, 68);
|
||||||
|
|
||||||
|
gResistanceLabel = lv_label_create(screen);
|
||||||
|
lv_label_set_text(gResistanceLabel, "READY");
|
||||||
|
lv_obj_set_style_text_color(gResistanceLabel, lv_color_hex(0x72D6FF), 0);
|
||||||
|
lv_obj_set_style_text_font(gResistanceLabel, &lv_font_montserrat_40, 0);
|
||||||
|
lv_obj_align(gResistanceLabel, LV_ALIGN_CENTER, 0, -72);
|
||||||
|
|
||||||
|
gRawLabel = lv_label_create(screen);
|
||||||
|
lv_label_set_text(gRawLabel, "ADC raw: -\nD+ voltage: -\nKnown pulldown: 10 kohm to GND");
|
||||||
|
lv_obj_set_width(gRawLabel, 420);
|
||||||
|
lv_label_set_long_mode(gRawLabel, LV_LABEL_LONG_WRAP);
|
||||||
|
lv_obj_set_style_text_align(gRawLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||||
|
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0xD5DCE5), 0);
|
||||||
|
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_16, 0);
|
||||||
|
lv_obj_align(gRawLabel, LV_ALIGN_CENTER, 0, -8);
|
||||||
|
|
||||||
|
gHintLabel = lv_label_create(screen);
|
||||||
|
lv_label_set_text(gHintLabel, "USB is normal now.\nTap Start to measure resistance between D- and D+.");
|
||||||
|
lv_obj_set_width(gHintLabel, 420);
|
||||||
|
lv_label_set_long_mode(gHintLabel, LV_LABEL_LONG_WRAP);
|
||||||
|
lv_obj_set_style_text_align(gHintLabel, LV_TEXT_ALIGN_CENTER, 0);
|
||||||
|
lv_obj_set_style_text_color(gHintLabel, lv_color_hex(0xAAB7C6), 0);
|
||||||
|
lv_obj_set_style_text_font(gHintLabel, &lv_font_montserrat_14, 0);
|
||||||
|
lv_obj_align(gHintLabel, LV_ALIGN_CENTER, 0, 72);
|
||||||
|
|
||||||
|
gActionButton = lv_btn_create(screen);
|
||||||
|
lv_obj_set_size(gActionButton, 260, 72);
|
||||||
|
lv_obj_align(gActionButton, LV_ALIGN_BOTTOM_MID, 0, -42);
|
||||||
|
lv_obj_set_style_radius(gActionButton, 18, 0);
|
||||||
|
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), 0);
|
||||||
|
lv_obj_set_style_border_width(gActionButton, 0, 0);
|
||||||
|
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_CLICKED, nullptr);
|
||||||
|
|
||||||
|
gActionButtonLabel = lv_label_create(gActionButton);
|
||||||
|
lv_label_set_text(gActionButtonLabel, "Start");
|
||||||
|
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
|
||||||
|
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_22, 0);
|
||||||
|
lv_obj_center(gActionButtonLabel);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
|
||||||
|
Wire.begin(IIC_SDA, IIC_SCL);
|
||||||
|
|
||||||
|
pinMode(TP_RST, OUTPUT);
|
||||||
|
pinMode(TP_INT, INPUT);
|
||||||
|
digitalWrite(TP_RST, LOW);
|
||||||
|
delay(30);
|
||||||
|
digitalWrite(TP_RST, HIGH);
|
||||||
|
delay(50);
|
||||||
|
delay(1000);
|
||||||
|
|
||||||
|
gTouch.setPins(TP_RST, TP_INT);
|
||||||
|
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
|
||||||
|
if (!touchOk) {
|
||||||
|
Serial.println("Touch init failed");
|
||||||
|
} else {
|
||||||
|
gTouch.sleep();
|
||||||
|
gTouch.reset();
|
||||||
|
gTouch.setMaxCoordinates(480, 480);
|
||||||
|
gTouch.setSwapXY(true);
|
||||||
|
gTouch.setMirrorXY(true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
gfx->begin();
|
||||||
|
gBus->writeC8D8(0x36, 0xA0);
|
||||||
|
gfx->setBrightness(220);
|
||||||
|
gfx->fillScreen(0x0000);
|
||||||
|
|
||||||
|
lv_init();
|
||||||
|
|
||||||
|
uint32_t screenWidth = gfx->width();
|
||||||
|
uint32_t screenHeight = gfx->height();
|
||||||
|
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||||
|
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
|
||||||
|
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
|
||||||
|
|
||||||
|
static lv_disp_drv_t dispDrv;
|
||||||
|
lv_disp_drv_init(&dispDrv);
|
||||||
|
dispDrv.hor_res = screenWidth;
|
||||||
|
dispDrv.ver_res = screenHeight;
|
||||||
|
dispDrv.flush_cb = lvglFlushCb;
|
||||||
|
dispDrv.draw_buf = &gDrawBuf;
|
||||||
|
lv_disp_drv_register(&dispDrv);
|
||||||
|
|
||||||
|
static lv_indev_drv_t indevDrv;
|
||||||
|
lv_indev_drv_init(&indevDrv);
|
||||||
|
indevDrv.type = LV_INDEV_TYPE_POINTER;
|
||||||
|
indevDrv.read_cb = lvglTouchRead;
|
||||||
|
lv_indev_drv_register(&indevDrv);
|
||||||
|
|
||||||
|
const esp_timer_create_args_t lvglTickTimerArgs = {
|
||||||
|
.callback = &lvglTick,
|
||||||
|
.name = "lvgl_tick"};
|
||||||
|
esp_timer_handle_t lvglTickTimer = nullptr;
|
||||||
|
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
|
||||||
|
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
|
||||||
|
|
||||||
|
createUi();
|
||||||
|
Serial.println("USB resistance test ready; native USB remains active until Start is tapped.");
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
updateResistanceUi();
|
||||||
|
lv_timer_handler();
|
||||||
|
delay(5);
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ Diagnostic sketches:
|
|||||||
|
|
||||||
- `main-device/test_sketches/usb_contact_sensor_test/usb_contact_sensor_test.ino`
|
- `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/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`
|
- `main-device/test_sketches/usb_contact_screen_start_stub/usb_contact_screen_start_stub.ino`
|
||||||
|
|
||||||
## Purpose
|
## Purpose
|
||||||
@@ -51,6 +53,33 @@ Sensor mode starts from the physical BOOT/user button on GPIO0, active LOW. The
|
|||||||
|
|
||||||
While in sensor mode, pressing the BOOT/user button again restarts the device and returns normal USB mode on the next boot.
|
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
|
## 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.
|
The `usb_contact_screen_start_stub` sketch is a breath monitor firmware based on the production `Arduino_GFX` display path instead of LVGL.
|
||||||
@@ -86,3 +115,89 @@ After tapping `START`:
|
|||||||
- reset/power cycle restores ordinary native USB boot
|
- reset/power cycle restores ordinary native USB boot
|
||||||
|
|
||||||
This version is intended to monitor breathing cadence from a dry-contact USB D-/D+ sensor.
|
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`
|
||||||
|
|||||||
+98
-3
@@ -2,6 +2,7 @@ package server.archive;
|
|||||||
|
|
||||||
import blockchain.Ans104DataItem;
|
import blockchain.Ans104DataItem;
|
||||||
import blockchain.BchBlockEntry;
|
import blockchain.BchBlockEntry;
|
||||||
|
import server.archive.registration.VerifiedFreeRegistrationImporter;
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
@@ -36,7 +37,7 @@ import java.time.Duration;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
|
* Discovers individual App=test5592 DataItems and imports the exact signed ANS-104 bytes.
|
||||||
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
|
||||||
* or inside a direct server-created ANS-104 bundle.
|
* or inside a direct server-created ANS-104 bundle.
|
||||||
*/
|
*/
|
||||||
@@ -50,6 +51,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
.connectTimeout(Duration.ofSeconds(20))
|
.connectTimeout(Duration.ofSeconds(20))
|
||||||
.followRedirects(HttpClient.Redirect.NORMAL)
|
.followRedirects(HttpClient.Redirect.NORMAL)
|
||||||
.build();
|
.build();
|
||||||
|
private final VerifiedFreeRegistrationImporter registrationImporter = new VerifiedFreeRegistrationImporter();
|
||||||
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
private final ArweaveBlockImportDAO importDAO = ArweaveBlockImportDAO.getInstance();
|
||||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||||
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
|
||||||
@@ -68,6 +70,7 @@ public final class ArweaveBlockSyncService {
|
|||||||
public void runCycle() throws Exception {
|
public void runCycle() throws Exception {
|
||||||
recoverInterruptedCanonicalRebuilds();
|
recoverInterruptedCanonicalRebuilds();
|
||||||
discover();
|
discover();
|
||||||
|
discoverFreeRegistrations();
|
||||||
drainQueue();
|
drainQueue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,6 +119,12 @@ public final class ArweaveBlockSyncService {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
|
||||||
|
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||||
|
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
unresolvedDownloads.remove(dataItemId);
|
||||||
|
continue; // Не парсить регистрацию как BchBlockEntry.
|
||||||
|
}
|
||||||
unresolvedDownloads.remove(dataItemId);
|
unresolvedDownloads.remove(dataItemId);
|
||||||
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
|
||||||
} catch (RetryableDataItemDownloadException e) {
|
} catch (RetryableDataItemDownloadException e) {
|
||||||
@@ -172,6 +181,18 @@ public final class ArweaveBlockSyncService {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isRegistrationItem(downloaded.rawDataItem())) {
|
||||||
|
try {
|
||||||
|
registrationImporter.importSigned(downloaded.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
unresolvedDownloads.remove(pending.dataItemId());
|
||||||
|
} catch (Exception e) {
|
||||||
|
unresolvedDownloads.remove(pending.dataItemId());
|
||||||
|
unresolvedDownloads.put(pending.dataItemId(), pending);
|
||||||
|
log.debug("Registration {} awaits namespace/DB sync or retry: {}", pending.dataItemId(), e.getMessage());
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
|
||||||
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
downloaded.rawDataItem(), System.currentTimeMillis())) {
|
||||||
queued++;
|
queued++;
|
||||||
@@ -474,10 +495,84 @@ public final class ArweaveBlockSyncService {
|
|||||||
}finally{BlockchainResyncGuard.end(activeName);}
|
}finally{BlockchainResyncGuard.end(activeName);}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/** Независимый GraphQL курсор для t=reg: не смешивается с блоковой очередью. */
|
||||||
|
private void discoverFreeRegistrations() throws Exception {
|
||||||
|
long stored;
|
||||||
|
try (Connection c = DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT last_block_height FROM free_registration_arweave_sync_state WHERE id=1");
|
||||||
|
ResultSet rs = ps.executeQuery()) {
|
||||||
|
stored = rs.next() ? rs.getLong(1) : 0;
|
||||||
|
}
|
||||||
|
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
|
||||||
|
long high = minHeight;
|
||||||
|
long retryFrom = Long.MAX_VALUE;
|
||||||
|
String cursor = null;
|
||||||
|
int count = 0;
|
||||||
|
do {
|
||||||
|
JsonNode response = graphQlPage(minHeight, cursor, true);
|
||||||
|
if (response.has("errors")) throw new IOException("Registration GraphQL errors: " + response.path("errors"));
|
||||||
|
JsonNode txs = response.path("data").path("transactions");
|
||||||
|
JsonNode edges = txs.path("edges");
|
||||||
|
if (!edges.isArray()) throw new IOException("Registration GraphQL returned no edges");
|
||||||
|
String next = null;
|
||||||
|
for (JsonNode edge : edges) {
|
||||||
|
next = edge.path("cursor").asText(null);
|
||||||
|
JsonNode node = edge.path("node");
|
||||||
|
String id = node.path("id").asText("").trim();
|
||||||
|
long height = node.path("block").path("height").asLong(-1);
|
||||||
|
if (id.isBlank() || height < 0) continue; // мгновенный Turbo-импорт не зависит от height
|
||||||
|
high = Math.max(high, height);
|
||||||
|
try {
|
||||||
|
byte[] idBytes = B64URL.decode(id);
|
||||||
|
if (idBytes.length != 32) throw new IllegalArgumentException("Malformed id");
|
||||||
|
DownloadedDataItem item = downloadSignedDataItem(id);
|
||||||
|
if (!isRegistrationItem(item.rawDataItem()))
|
||||||
|
throw new IllegalArgumentException("GraphQL registration tag is not present in signed bytes");
|
||||||
|
registrationImporter.importSigned(item.rawDataItem(),
|
||||||
|
VerifiedFreeRegistrationImporter.Provenance.ARWEAVE_CONFIRMED);
|
||||||
|
count++;
|
||||||
|
} catch (RetryableDataItemDownloadException e) {
|
||||||
|
retryFrom = Math.min(retryFrom, height);
|
||||||
|
log.debug("Registration DataItem {} is not downloadable yet", id);
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
log.warn("Rejecting invalid registration DataItem {}: {}", id, e.getMessage());
|
||||||
|
} catch (Exception e) {
|
||||||
|
retryFrom = Math.min(retryFrom, height);
|
||||||
|
log.warn("Registration DataItem {} import deferred: {}", id, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cursor = txs.path("pageInfo").path("hasNextPage").asBoolean(false) ? next : null;
|
||||||
|
if (txs.path("pageInfo").path("hasNextPage").asBoolean(false) && (cursor == null || cursor.isBlank()))
|
||||||
|
throw new IOException("Registration GraphQL cursor missing");
|
||||||
|
} while (cursor != null);
|
||||||
|
long checkpoint = retryFrom == Long.MAX_VALUE ? high : Math.min(high, retryFrom);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement("""
|
||||||
|
UPDATE free_registration_arweave_sync_state
|
||||||
|
SET last_block_height=?, updated_at_ms=? WHERE id=1
|
||||||
|
""")) {
|
||||||
|
ps.setLong(1, checkpoint); ps.setLong(2, System.currentTimeMillis()); ps.executeUpdate();
|
||||||
|
}
|
||||||
|
if (count > 0) log.info("Registration discovery verified {} DataItems; checkpoint={}", count, checkpoint);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean isRegistrationItem(byte[] raw) {
|
||||||
|
Ans104DataItem item = new Ans104DataItem(raw);
|
||||||
|
return item.tags().contains(new Ans104DataItem.Tag("t", "reg"));
|
||||||
|
}
|
||||||
|
|
||||||
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
|
||||||
|
return graphQlPage(minHeight, cursor, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private JsonNode graphQlPage(long minHeight, String cursor, boolean registrationsOnly) throws Exception {
|
||||||
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
String after = cursor == null ? "null" : "\"" + escapeGraphQl(cursor) + "\"";
|
||||||
String query = "query { transactions(tags:[{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
String tagFilter = "{name:\"" + ArweaveBlocksConfig.TEST_TAG_NAME + "\",values:[\""
|
||||||
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}], block:{min:" + minHeight + "}, first:"
|
+ ArweaveBlocksConfig.TEST_TAG_VALUE + "\"]}" +
|
||||||
|
(registrationsOnly ? ",{name:\"t\",values:[\"reg\"]}" : "");
|
||||||
|
String query = "query { transactions(tags:[" + tagFilter + "], block:{min:" + minHeight + "}, first:"
|
||||||
+ cfg.syncPageSize() + ", after:" + after
|
+ cfg.syncPageSize() + ", after:" + after
|
||||||
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
+ ", sort:HEIGHT_ASC) { pageInfo { hasNextPage } edges { cursor node { id block { height } } } } }";
|
||||||
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
String body = MAPPER.writeValueAsString(Map.of("query", query));
|
||||||
|
|||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import server.archive.ArweaveBlocksConfig;
|
||||||
|
import server.archive.TurboDataItemUploader;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationApiBridge;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||||
|
import shine.db.DbController;
|
||||||
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.sql.SQLFeatureNotSupportedException;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.LinkedHashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/** Единственная точка подключения API без циклической зависимости Gradle-модулей. */
|
||||||
|
public final class FreeRegistrationApiBootstrap {
|
||||||
|
private static volatile FreeRegistrationWorkflow workflow;
|
||||||
|
private static volatile LocalRegistrarSigner signer;
|
||||||
|
private FreeRegistrationApiBootstrap() {}
|
||||||
|
|
||||||
|
public static synchronized void startOrThrow() throws Exception {
|
||||||
|
if (workflow != null) return;
|
||||||
|
AppConfig cfg=AppConfig.getInstance();
|
||||||
|
LocalRegistrarSigner newSigner=null;
|
||||||
|
FreeRegistrationIssuer issuer=null;
|
||||||
|
FreeRegistrationPublisher publisher=null;
|
||||||
|
if (cfg.getBoolean("freeRegistration.enabled",false)) {
|
||||||
|
// Не выводить seed/path в журнал ни при успешном старте, ни при ошибке.
|
||||||
|
ArweaveBlocksConfig transport=ArweaveBlocksConfig.load();
|
||||||
|
if(transport.publishMode()!=ArweaveBlocksConfig.PublishMode.TURBO)
|
||||||
|
throw new IllegalStateException("Free registration requires Turbo transport");
|
||||||
|
newSigner=LocalRegistrarSigner.fromConfig(cfg);
|
||||||
|
issuer=new FreeRegistrationIssuer(dbSource(),newSigner);
|
||||||
|
publisher=new FreeRegistrationPublisher(issuer,new TurboDataItemUploader(transport),new VerifiedFreeRegistrationImporter());
|
||||||
|
}
|
||||||
|
FreeRegistrationWorkflow newWorkflow=new FreeRegistrationWorkflow(issuer,publisher);
|
||||||
|
RegistrationApiBridge.install((op,req)->dispatch(newWorkflow,op,req));
|
||||||
|
signer=newSigner; workflow=newWorkflow;
|
||||||
|
}
|
||||||
|
public static synchronized void close() {
|
||||||
|
RegistrationApiBridge.uninstall();
|
||||||
|
workflow=null;
|
||||||
|
if(signer!=null) signer.close();
|
||||||
|
signer=null;
|
||||||
|
}
|
||||||
|
public static Map<String,Object> dispatch(FreeRegistrationWorkflow w, String op,Net_Registration_Request req) throws Exception {
|
||||||
|
Map<String,Object> out=new LinkedHashMap<>();
|
||||||
|
switch(op) {
|
||||||
|
case "GetNamespaces" -> {
|
||||||
|
out.put("namespaces",w.listNamespaces().stream().map(ns->Map.of(
|
||||||
|
"name",ns.namespace(), "type",ns.type(), "minLocalLength",ns.minLoginLength(),
|
||||||
|
"registrationFeeLamports",ns.priceLamports(), "defaultServerLogin",ns.serverLogin()==null?"":ns.serverLogin()
|
||||||
|
)).toList());
|
||||||
|
}
|
||||||
|
case "CheckRegistrationLogin" -> {
|
||||||
|
var info=w.checkLogin(req.getFullLogin());
|
||||||
|
out.put("loginAvailable",info.loginAvailable());
|
||||||
|
out.put("namespaceType",info.namespaceType());
|
||||||
|
out.put("minLocalLength",info.minLocalLength());
|
||||||
|
out.put("registrationFeeLamports",info.registrationFeeLamports());
|
||||||
|
}
|
||||||
|
case "CheckRegistrationEmail" -> out.put("emailAvailable",w.checkEmail(req.getEmail()).emailAvailable());
|
||||||
|
case "StartFreeRegistration" -> {
|
||||||
|
var state=w.start(req.getFullLogin(),decodeKey(req.getRootPublicKeyB64()),
|
||||||
|
decodeKey(req.getBlockchainPublicKeyB64()),decodeKey(req.getClientPublicKeyB64()),req.getEmail());
|
||||||
|
out.put("challengeId",state.challengeId()); out.put("expiresAtMs",state.expiresAtMs());
|
||||||
|
}
|
||||||
|
case "ConfirmFreeRegistration" -> {
|
||||||
|
var value=w.confirm(req.getChallengeId(),req.getCode());
|
||||||
|
out.put("fullLogin",value.fullLogin());out.put("dataItemId",value.dataItemId());
|
||||||
|
out.put("publicationStatus",value.state());out.put("chainConfirmed",false);
|
||||||
|
}
|
||||||
|
case "GetRegistrationStatus" -> {
|
||||||
|
var value=w.getStatus(req.getFullLogin());
|
||||||
|
out.put("registrationStatus",value.status());
|
||||||
|
out.put("dataItemId",value.dataItemId()==null?"":value.dataItemId());
|
||||||
|
out.put("publicationStatus",value.publicationStatus()==null?"":value.publicationStatus());
|
||||||
|
// Публичная историческая часть сертификата для бесплатного → Solana upgrade.
|
||||||
|
if("FREE_CERT".equals(value.status())) {
|
||||||
|
out.put("innerSignature64B64",value.innerSignature64B64()==null?"":value.innerSignature64B64());
|
||||||
|
out.put("rootPublicKey",value.rootPublicKey()==null?"":value.rootPublicKey());
|
||||||
|
out.put("blockchainPublicKey",value.blockchainPublicKey()==null?"":value.blockchainPublicKey());
|
||||||
|
out.put("clientPublicKey",value.clientPublicKey()==null?"":value.clientPublicKey());
|
||||||
|
out.put("defaultServerLogin",value.defaultServerLogin()==null?"":value.defaultServerLogin());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
default -> throw new IllegalArgumentException("Unknown registration operation");
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
private static byte[] decodeKey(String base64) {
|
||||||
|
if(base64==null || base64.length()>64)throw new IllegalArgumentException("Invalid public key");
|
||||||
|
byte[] decoded=Base64.getDecoder().decode(base64);
|
||||||
|
if(decoded.length!=32)throw new IllegalArgumentException("Invalid public key length");
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
private static DataSource dbSource() {
|
||||||
|
return new DataSource() {
|
||||||
|
@Override public Connection getConnection() throws SQLException {return DbController.getInstance().getConnection();}
|
||||||
|
@Override public Connection getConnection(String u,String p) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||||
|
@Override public PrintWriter getLogWriter(){return null;}
|
||||||
|
@Override public void setLogWriter(PrintWriter p){}
|
||||||
|
@Override public void setLoginTimeout(int t){}
|
||||||
|
@Override public int getLoginTimeout(){return 0;}
|
||||||
|
@Override public Logger getParentLogger(){return Logger.getGlobal();}
|
||||||
|
@Override public <T> T unwrap(Class<T> type) throws SQLException {throw new SQLFeatureNotSupportedException();}
|
||||||
|
@Override public boolean isWrapperFor(Class<?> type){return false;}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
+115
@@ -0,0 +1,115 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
import blockchain.ShineProtocolTags;
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.security.MessageDigest;
|
||||||
|
import java.text.Normalizer;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** Строгое формирование и проверка двух подписей нового независимого DataItem `t=reg`. */
|
||||||
|
public final class FreeRegistrationCertificateV1 {
|
||||||
|
private static final byte[] DOMAIN = "SHiNE_FREE_REG_V1\0".getBytes(StandardCharsets.UTF_8);
|
||||||
|
private static final List<Ans104DataItem.Tag> TAGS = List.of(
|
||||||
|
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
|
||||||
|
new Ans104DataItem.Tag("t", "reg"),
|
||||||
|
new Ans104DataItem.Tag("Protocol", "SHiNE-Free-Registration-V1"));
|
||||||
|
|
||||||
|
public record Verified(String login, byte[] rootKey, byte[] blockchainKey,
|
||||||
|
byte[] clientKey, byte[] innerSignature,
|
||||||
|
byte[] emailSha256, byte[] owner32, String idBase64Url) {}
|
||||||
|
|
||||||
|
private FreeRegistrationCertificateV1() {}
|
||||||
|
|
||||||
|
public static String validateLogin(String login) {
|
||||||
|
if (login == null || !login.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || login.length() > 30)
|
||||||
|
throw new IllegalArgumentException("Full login must use ASCII letters (any local-part case), lowercase namespace, <= 30 bytes");
|
||||||
|
return login;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] identityFields(String login, byte[] root32, byte[] blockchain32, byte[] client32) {
|
||||||
|
byte[] name = validateLogin(login).getBytes(StandardCharsets.UTF_8);
|
||||||
|
require32(root32); require32(blockchain32); require32(client32);
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
out.write(1); out.write(0); out.write(name.length); out.writeBytes(name);
|
||||||
|
out.writeBytes(root32); out.writeBytes(blockchain32); out.writeBytes(client32);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] innerMessage(byte[] identity) {
|
||||||
|
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||||
|
out.writeBytes(DOMAIN); out.writeBytes(identity);
|
||||||
|
return out.toByteArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String normalizeEmail(String email) {
|
||||||
|
if (email == null) throw new IllegalArgumentException("Email is required");
|
||||||
|
String value = Normalizer.normalize(email.strip(), Normalizer.Form.NFC).toLowerCase(Locale.ROOT);
|
||||||
|
if (value.isBlank() || value.indexOf('@') < 1 || value.contains(" "))
|
||||||
|
throw new IllegalArgumentException("Invalid email");
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] emailHash(String email) {
|
||||||
|
return sha256(normalizeEmail(email).getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static byte[] issue(String login, byte[] root32, byte[] blockchain32,
|
||||||
|
byte[] client32, String email, RegistrarSigner signer) {
|
||||||
|
byte[] fields = identityFields(login, root32, blockchain32, client32);
|
||||||
|
byte[] inner = signer.sign(innerMessage(fields));
|
||||||
|
if (inner.length != 64) throw new IllegalStateException("Invalid inner signature length");
|
||||||
|
ByteArrayOutputStream payload = new ByteArrayOutputStream();
|
||||||
|
payload.writeBytes(fields);
|
||||||
|
payload.writeBytes(inner);
|
||||||
|
payload.writeBytes(emailHash(email));
|
||||||
|
byte[] data = payload.toByteArray();
|
||||||
|
byte[] owner = signer.publicKey32();
|
||||||
|
require32(owner);
|
||||||
|
byte[] outer = signer.sign(Ans104DataItem.buildSigningMessage(owner, TAGS, data));
|
||||||
|
byte[] raw = Ans104DataItem.serializeEd25519(outer, owner, TAGS, data);
|
||||||
|
verify(raw, owner);
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Verified verify(byte[] signedDataItem, byte[] registrarPublicKey32) {
|
||||||
|
require32(registrarPublicKey32);
|
||||||
|
Ans104DataItem item = new Ans104DataItem(signedDataItem);
|
||||||
|
if (!item.ownerEquals(registrarPublicKey32) || !item.verifySignature())
|
||||||
|
throw new IllegalArgumentException("Invalid outer ANS-104 registrar signature");
|
||||||
|
if (!item.tags().equals(TAGS) || item.target().length != 0 || item.anchor().length != 0)
|
||||||
|
throw new IllegalArgumentException("Unexpected registration tags/target/anchor");
|
||||||
|
byte[] data = item.data();
|
||||||
|
if (data.length < 3 + 96 + 64 + 32 || data[0] != 1 || data[1] != 0)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate version/length");
|
||||||
|
int len = data[2] & 0xff;
|
||||||
|
if (data.length != 3 + len + 96 + 64 + 32)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate byte length");
|
||||||
|
String login = validateLogin(new String(data, 3, len, StandardCharsets.UTF_8));
|
||||||
|
int offset = 3 + len;
|
||||||
|
byte[] root = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] blockchain = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] client = Arrays.copyOfRange(data, offset, offset+32); offset += 32;
|
||||||
|
byte[] innerSig = Arrays.copyOfRange(data, offset, offset+64); offset += 64;
|
||||||
|
byte[] emailSha = Arrays.copyOfRange(data, offset, offset+32);
|
||||||
|
byte[] fields = Arrays.copyOfRange(data, 0, 3 + len + 96);
|
||||||
|
if (!Ed25519Util.verify(innerMessage(fields), innerSig, registrarPublicKey32))
|
||||||
|
throw new IllegalArgumentException("Invalid inner certificate signature");
|
||||||
|
return new Verified(login, root, blockchain, client, innerSig, emailSha,
|
||||||
|
item.owner32(), Base64.getUrlEncoder().withoutPadding().encodeToString(item.id32()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void require32(byte[] key) {
|
||||||
|
if (key == null || key.length != 32) throw new IllegalArgumentException("Expected 32-byte public key");
|
||||||
|
}
|
||||||
|
private static byte[] sha256(byte[] data) {
|
||||||
|
try { return MessageDigest.getInstance("SHA-256").digest(data); }
|
||||||
|
catch (Exception e) { throw new IllegalStateException("SHA-256 unavailable", e); }
|
||||||
|
}
|
||||||
|
}
|
||||||
+67
@@ -0,0 +1,67 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import sync.util.Base58Util;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.util.Arrays;
|
||||||
|
|
||||||
|
/** Выдача (без публикации). Stage 8 публикует через Turbo и импортирует тот же raw DataItem. */
|
||||||
|
public final class FreeRegistrationIssuer {
|
||||||
|
private final DataSource db;
|
||||||
|
private final RegistrarSigner signer;
|
||||||
|
|
||||||
|
public FreeRegistrationIssuer(DataSource db, RegistrarSigner signer) {
|
||||||
|
this.db = java.util.Objects.requireNonNull(db);
|
||||||
|
this.signer = java.util.Objects.requireNonNull(signer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Код 1111 учебный: не подтверждает владение email. */
|
||||||
|
public synchronized byte[] issue(String fullLogin, byte[] root32, byte[] blockchain32,
|
||||||
|
byte[] client32, String email, String code) throws Exception {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(fullLogin);
|
||||||
|
if (!"1111".equals(code)) throw new IllegalArgumentException("Invalid demo email code");
|
||||||
|
String namespace = fullLogin.substring(fullLogin.indexOf('@') + 1);
|
||||||
|
byte[] expectedEmail = FreeRegistrationCertificateV1.emailHash(email);
|
||||||
|
try (Connection conn = db.getConnection()) {
|
||||||
|
conn.setReadOnly(true);
|
||||||
|
String sql = """
|
||||||
|
SELECT namespace_type, min_localpart_len, registrar_pubkey, default_server_login
|
||||||
|
FROM shine_namespace_current WHERE namespace = ?
|
||||||
|
""";
|
||||||
|
try (PreparedStatement statement = conn.prepareStatement(sql)) {
|
||||||
|
statement.setString(1, namespace);
|
||||||
|
try (ResultSet rs = statement.executeQuery()) {
|
||||||
|
if (!rs.next() || rs.getInt("namespace_type") != 2 ||
|
||||||
|
fullLogin.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||||
|
throw new IllegalArgumentException("Free namespace is unavailable");
|
||||||
|
byte[] nsPub = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||||
|
if (!Arrays.equals(nsPub, signer.publicKey32()))
|
||||||
|
throw new IllegalStateException("Registrar public key does not match on-chain namespace");
|
||||||
|
String server = rs.getString("default_server_login");
|
||||||
|
if (server == null || server.isBlank())
|
||||||
|
throw new IllegalStateException("Free namespace server is not configured");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement ps = conn.prepareStatement(
|
||||||
|
"SELECT 1 FROM user_identity_current WHERE normalized_login = ?")) {
|
||||||
|
ps.setString(1, fullLogin.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) throw new IllegalArgumentException("Login is already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement ps = conn.prepareStatement(
|
||||||
|
"SELECT 1 FROM free_registration_certificate WHERE email_sha256 = ?")) {
|
||||||
|
ps.setBytes(1, expectedEmail);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next()) throw new IllegalArgumentException("Email hash already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Это только подписанный артефакт, не активная регистрация. Перед Turbo
|
||||||
|
// и локальным импортом обязательно повторять уникальность в транзакции БД.
|
||||||
|
return FreeRegistrationCertificateV1.issue(fullLogin, root32, blockchain32, client32, email, signer);
|
||||||
|
}
|
||||||
|
}
|
||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import server.archive.TurboDataItemUploader;
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
|
||||||
|
/** Отдельный транспорт регистрации. Публикация не является пользовательским AddBlock. */
|
||||||
|
public final class FreeRegistrationPublisher {
|
||||||
|
private final FreeRegistrationIssuer issuer;
|
||||||
|
private final TurboDataItemUploader uploader;
|
||||||
|
private final VerifiedFreeRegistrationImporter importer;
|
||||||
|
|
||||||
|
public FreeRegistrationPublisher(FreeRegistrationIssuer issuer, TurboDataItemUploader uploader,
|
||||||
|
VerifiedFreeRegistrationImporter importer) {
|
||||||
|
this.issuer = java.util.Objects.requireNonNull(issuer);
|
||||||
|
this.uploader = java.util.Objects.requireNonNull(uploader);
|
||||||
|
this.importer = java.util.Objects.requireNonNull(importer);
|
||||||
|
}
|
||||||
|
/** Для повтора ПОСЛЕ потери ACK передавайте точно те же signedBytes. */
|
||||||
|
public VerifiedFreeRegistrationImporter.ImportResult publishSigned(byte[] signedBytes) throws Exception {
|
||||||
|
Ans104DataItem parsed = new Ans104DataItem(signedBytes);
|
||||||
|
importer.validateForUpload(signedBytes); // строго до HTTP/Turbo списания кредитов
|
||||||
|
// Импорт на этой точке вызовет полную проверку обеих подписей и namespace
|
||||||
|
// ПОСЛЕ успешного ACK Turbo, а не до окончательного подтверждения Arweave.
|
||||||
|
TurboDataItemUploader.UploadResult acknowledged = uploader.upload(signedBytes, parsed.id32());
|
||||||
|
String expectedId = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(parsed.id32());
|
||||||
|
if (!expectedId.equals(acknowledged.dataItemId()))
|
||||||
|
throw new IllegalStateException("Unexpected Turbo DataItem id");
|
||||||
|
return importer.importSigned(signedBytes, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||||
|
}
|
||||||
|
public VerifiedFreeRegistrationImporter.ImportResult register(String fullLogin, byte[] root, byte[] blockchain,
|
||||||
|
byte[] client, String email, String demoCode) throws Exception {
|
||||||
|
byte[] signed = issuer.issue(fullLogin, root, blockchain, client, email, demoCode);
|
||||||
|
return publishSigned(signed);
|
||||||
|
}
|
||||||
|
}
|
||||||
+138
@@ -0,0 +1,138 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import java.security.SecureRandom;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/** Внутренний state machine публичных операций регистрации v2. */
|
||||||
|
public final class FreeRegistrationWorkflow {
|
||||||
|
public record NamespaceInfo(String namespace, int type, int minLoginLength, String priceLamports, String serverLogin) {}
|
||||||
|
public record Availability(boolean nameFree, boolean emailHashFree) {}
|
||||||
|
public record LoginCheck(boolean loginAvailable, int namespaceType, int minLocalLength, String registrationFeeLamports) {}
|
||||||
|
public record EmailCheck(boolean emailAvailable) {}
|
||||||
|
public record Started(String challengeId, long expiresAtMs) {}
|
||||||
|
public record Completed(String fullLogin, String dataItemId, String state, boolean alreadyImported) {}
|
||||||
|
public record State(String status, String dataItemId, String publicationStatus, String innerSignature64B64,
|
||||||
|
String rootPublicKey, String blockchainPublicKey, String clientPublicKey,
|
||||||
|
String defaultServerLogin) {}
|
||||||
|
|
||||||
|
private record Draft(String login, byte[] root, byte[] blockchain, byte[] client, String email,
|
||||||
|
long expiresAtMs, byte[] signedBytes) {}
|
||||||
|
private final Map<String, Draft> pending = new ConcurrentHashMap<>();
|
||||||
|
private static final long TTL_MS = Duration.ofMinutes(15).toMillis();
|
||||||
|
private static final int MAX_PENDING = 512;
|
||||||
|
private static final SecureRandom RANDOM = new SecureRandom();
|
||||||
|
private final FreeRegistrationIssuer issuer;
|
||||||
|
private final FreeRegistrationPublisher publisher;
|
||||||
|
|
||||||
|
public FreeRegistrationWorkflow(FreeRegistrationIssuer issuer, FreeRegistrationPublisher publisher) {
|
||||||
|
if ((issuer == null) != (publisher == null)) throw new IllegalArgumentException("Signer/publisher mismatch");
|
||||||
|
this.issuer = issuer;
|
||||||
|
this.publisher = publisher;
|
||||||
|
}
|
||||||
|
public List<NamespaceInfo> listNamespaces() throws Exception {
|
||||||
|
List<NamespaceInfo> result = new ArrayList<>();
|
||||||
|
try (Connection c = DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT namespace,namespace_type,min_localpart_len,registration_fee_lamports,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.getString(5)));
|
||||||
|
}
|
||||||
|
return List.copyOf(result);
|
||||||
|
}
|
||||||
|
public LoginCheck checkLogin(String login) throws Exception {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(login);
|
||||||
|
String namespace=login.substring(login.indexOf('@')+1);
|
||||||
|
try (Connection c=DbController.getInstance().getConnection()) {
|
||||||
|
int type, minimum; String fee;
|
||||||
|
try (PreparedStatement p=c.prepareStatement("SELECT namespace_type,min_localpart_len,registration_fee_lamports FROM shine_namespace_current WHERE namespace=?")) {
|
||||||
|
p.setString(1,namespace);
|
||||||
|
try (ResultSet rs=p.executeQuery()) {
|
||||||
|
if (!rs.next()) throw new IllegalArgumentException("Namespace is unavailable");
|
||||||
|
type=rs.getInt(1); minimum=rs.getInt(2); fee=rs.getString(3);
|
||||||
|
if (login.indexOf('@') < minimum) throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement p=c.prepareStatement("SELECT 1 FROM user_identity_current WHERE normalized_login=?")) {
|
||||||
|
p.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs=p.executeQuery()) { return new LoginCheck(!rs.next(),type,minimum,fee); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public EmailCheck checkEmail(String email) throws Exception {
|
||||||
|
byte[] hash=FreeRegistrationCertificateV1.emailHash(email);
|
||||||
|
try (Connection c=DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement p=c.prepareStatement("SELECT 1 FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||||
|
p.setBytes(1,hash);
|
||||||
|
try(ResultSet rs=p.executeQuery()) { return new EmailCheck(!rs.next()); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Устаревший внутренний helper: внешний API использует две отдельные операции. */
|
||||||
|
public Availability availability(String login,String email) throws Exception {
|
||||||
|
return new Availability(checkLogin(login).loginAvailable(),checkEmail(email).emailAvailable());
|
||||||
|
}
|
||||||
|
public Started start(String login, byte[] root, byte[] blockchain, byte[] client, String email) throws Exception {
|
||||||
|
if (issuer == null || publisher == null) throw new IllegalStateException("Free registration is disabled");
|
||||||
|
FreeRegistrationCertificateV1.identityFields(login,root,blockchain,client);
|
||||||
|
LoginCheck checked = checkLogin(login);
|
||||||
|
if (checked.namespaceType()!=2 || !checked.loginAvailable()) throw new IllegalStateException("Login is unavailable");
|
||||||
|
if (!checkEmail(email).emailAvailable()) throw new IllegalStateException("Email is unavailable");
|
||||||
|
String cleanEmail=FreeRegistrationCertificateV1.normalizeEmail(email);
|
||||||
|
pending.entrySet().removeIf(e->e.getValue().expiresAtMs < System.currentTimeMillis());
|
||||||
|
if (pending.size() >= MAX_PENDING) throw new IllegalStateException("Too many pending registrations");
|
||||||
|
byte[] id=new byte[32]; RANDOM.nextBytes(id);
|
||||||
|
String challenge=Base64.getUrlEncoder().withoutPadding().encodeToString(id);
|
||||||
|
long expires=System.currentTimeMillis()+TTL_MS;
|
||||||
|
pending.put(challenge,new Draft(login,root.clone(),blockchain.clone(),client.clone(),cleanEmail,expires,null));
|
||||||
|
return new Started(challenge,expires);
|
||||||
|
}
|
||||||
|
public synchronized Completed confirm(String challenge, String demoCode) throws Exception {
|
||||||
|
if (publisher == null) throw new IllegalStateException("Free registration disabled");
|
||||||
|
Draft d=pending.get(challenge);
|
||||||
|
if (d==null || d.expiresAtMs < System.currentTimeMillis()) {
|
||||||
|
pending.remove(challenge); throw new IllegalArgumentException("Registration challenge missing or expired");
|
||||||
|
}
|
||||||
|
if (!"1111".equals(demoCode)) throw new IllegalArgumentException("Invalid demo code");
|
||||||
|
// При ошибке Turbo сохраняем единожды подписанные bytes и повторно отправляем ТОТ ЖЕ DataItem.
|
||||||
|
byte[] signed=d.signedBytes;
|
||||||
|
if(signed==null) {
|
||||||
|
signed=issuer.issue(d.login,d.root,d.blockchain,d.client,d.email,demoCode);
|
||||||
|
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||||
|
}
|
||||||
|
VerifiedFreeRegistrationImporter.ImportResult result=publisher.publishSigned(signed);
|
||||||
|
// Сохраняем draft до TTL, чтобы потерянный WS-ответ не вынуждал выпускать другой сертификат.
|
||||||
|
pending.put(challenge,new Draft(d.login,d.root,d.blockchain,d.client,d.email,d.expiresAtMs,signed));
|
||||||
|
return new Completed(result.login(),result.dataItemId(),"TURBO_ACCEPTED",result.alreadyImported());
|
||||||
|
}
|
||||||
|
public State getStatus(String login) throws Exception {
|
||||||
|
FreeRegistrationCertificateV1.validateLogin(login);
|
||||||
|
try (Connection c=DbController.getInstance().getConnection();
|
||||||
|
PreparedStatement p=c.prepareStatement("""
|
||||||
|
SELECT i.registration_status,i.free_data_item_id,f.publication_status,f.inner_signature,
|
||||||
|
i.root_key,i.blockchain_key,i.client_key,n.default_server_login
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN free_registration_certificate f ON f.data_item_id=i.free_data_item_id
|
||||||
|
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||||
|
WHERE i.normalized_login=?
|
||||||
|
""")) {
|
||||||
|
p.setString(1,login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet r=p.executeQuery()) {
|
||||||
|
return r.next()?new State(r.getString(1),r.getString(2),r.getString(3),
|
||||||
|
r.getBytes(4)==null?null:Base64.getEncoder().encodeToString(r.getBytes(4)),
|
||||||
|
r.getString(5),r.getString(6),r.getString(7),r.getString(8))
|
||||||
|
:new State("NOT_FOUND",null,null,null,null,null,null,null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/** Временный signer. Файл вне Git: одно значение Base64 от 32-байтного Ed25519 seed. */
|
||||||
|
public final class LocalRegistrarSigner implements RegistrarSigner {
|
||||||
|
private final byte[] seed32;
|
||||||
|
private final byte[] publicKey32;
|
||||||
|
private boolean closed;
|
||||||
|
|
||||||
|
public LocalRegistrarSigner(byte[] seed) {
|
||||||
|
if (seed == null || seed.length != 32) throw new IllegalArgumentException("Registrar seed must be 32 bytes");
|
||||||
|
this.seed32 = seed.clone();
|
||||||
|
this.publicKey32 = Ed25519Util.derivePublicKey(seed32);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static LocalRegistrarSigner fromConfig(AppConfig config) throws Exception {
|
||||||
|
if (!config.getBoolean("freeRegistration.enabled", false))
|
||||||
|
throw new IllegalStateException("Free registration is disabled");
|
||||||
|
String path = config.getStringOrEmpty("freeRegistration.registrarSeedFile");
|
||||||
|
if (path.isEmpty()) throw new IllegalStateException("Registrar key path is not configured");
|
||||||
|
byte[] seed = Base64.getDecoder().decode(Files.readString(Path.of(path), StandardCharsets.UTF_8).trim());
|
||||||
|
try { return new LocalRegistrarSigner(seed); }
|
||||||
|
finally { Arrays.fill(seed, (byte) 0); }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override public synchronized byte[] publicKey32() { return publicKey32.clone(); }
|
||||||
|
@Override public synchronized byte[] sign(byte[] message) {
|
||||||
|
if (closed) throw new IllegalStateException("Signer closed");
|
||||||
|
return Ed25519Util.sign(message, seed32);
|
||||||
|
}
|
||||||
|
@Override public synchronized void close() {
|
||||||
|
Arrays.fill(seed32, (byte) 0);
|
||||||
|
closed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
/** Интерфейс приватного регистратора: private key не передаётся в бизнес-логику. */
|
||||||
|
public interface RegistrarSigner extends AutoCloseable {
|
||||||
|
byte[] publicKey32();
|
||||||
|
byte[] sign(byte[] message);
|
||||||
|
@Override default void close() {}
|
||||||
|
}
|
||||||
+173
@@ -0,0 +1,173 @@
|
|||||||
|
package server.archive.registration;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import sync.util.Base58Util;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.Base64;
|
||||||
|
|
||||||
|
/** Только верифицированный сертификат. Локальная БД — проекция Arweave/Solana. */
|
||||||
|
public final class VerifiedFreeRegistrationImporter {
|
||||||
|
public enum Provenance { TURBO_ACCEPTED, ARWEAVE_CONFIRMED }
|
||||||
|
public record ImportResult(String login, String dataItemId, boolean alreadyImported, Provenance provenance) {}
|
||||||
|
|
||||||
|
/** Предварительная проверка ДО Turbo: не расходовать кредиты на чужую/битую запись. */
|
||||||
|
public FreeRegistrationCertificateV1.Verified validateForUpload(byte[] raw) throws Exception {
|
||||||
|
if (raw == null || raw.length < 200 || raw.length > 16_384)
|
||||||
|
throw new IllegalArgumentException("Invalid registration size");
|
||||||
|
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||||
|
String login = extractCanonicalLogin(item);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
String namespace = login.substring(login.indexOf('@') + 1);
|
||||||
|
var cert = FreeRegistrationCertificateV1.verify(raw, readRegistrar(c, namespace, login));
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT free_data_item_id FROM user_identity_current WHERE normalized_login=?")) {
|
||||||
|
ps.setString(1, login.toLowerCase(java.util.Locale.ROOT));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||||
|
throw new IllegalArgumentException("Login is already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(
|
||||||
|
"SELECT data_item_id FROM free_registration_certificate WHERE email_sha256=?")) {
|
||||||
|
ps.setBytes(1, cert.emailSha256());
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (rs.next() && !cert.idBase64Url().equals(rs.getString(1)))
|
||||||
|
throw new IllegalArgumentException("Email hash belongs to another account");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return cert;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Единая точка импорта: один и тот же raw ANS-104 из Turbo и Arweave. */
|
||||||
|
public ImportResult importSigned(byte[] raw, Provenance provenance) throws Exception {
|
||||||
|
if (raw == null || raw.length > 16_384 || raw.length < 200)
|
||||||
|
throw new IllegalArgumentException("Invalid registration data item size");
|
||||||
|
// Сначала разбираем/проверяем структурный контейнер, затем сверяем owner с on-chain namespace.
|
||||||
|
blockchain.Ans104DataItem item = new blockchain.Ans104DataItem(raw);
|
||||||
|
String login = extractCanonicalLogin(item);
|
||||||
|
String namespace = login.substring(login.indexOf('@') + 1);
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
boolean oldAutoCommit = c.getAutoCommit();
|
||||||
|
c.setAutoCommit(false);
|
||||||
|
try {
|
||||||
|
byte[] registrar = readRegistrar(c, namespace, login);
|
||||||
|
FreeRegistrationCertificateV1.Verified cert = FreeRegistrationCertificateV1.verify(raw, registrar);
|
||||||
|
String id = cert.idBase64Url();
|
||||||
|
String publication = provenance == Provenance.ARWEAVE_CONFIRMED ? "ARWEAVE_CONFIRMED" : "TURBO_ACCEPTED";
|
||||||
|
long now = System.currentTimeMillis();
|
||||||
|
// Защита от коллизий и двойного импорта: имя и email захвачены индексами UNIQUE.
|
||||||
|
try (PreparedStatement check = c.prepareStatement("""
|
||||||
|
SELECT f.raw_signed_data_item, f.publication_status, u.root_key, u.client_key,
|
||||||
|
u.blockchain_key FROM free_registration_certificate f
|
||||||
|
JOIN user_identity_current u ON u.login=f.login
|
||||||
|
WHERE f.data_item_id=? FOR UPDATE OF f
|
||||||
|
""")) {
|
||||||
|
check.setString(1, id);
|
||||||
|
try (ResultSet r = check.executeQuery()) {
|
||||||
|
if (r.next()) {
|
||||||
|
if (!Arrays.equals(raw, r.getBytes(1)))
|
||||||
|
throw new SQLException("DataItem id collision with different raw bytes");
|
||||||
|
if (!r.getString(3).equals(Base58Util.encode(cert.rootKey())) ||
|
||||||
|
!r.getString(4).equals(Base58Util.encode(cert.clientKey())) ||
|
||||||
|
!r.getString(5).equals(Base58Util.encode(cert.blockchainKey())))
|
||||||
|
throw new SQLException("Accepted identity keys conflict with certificate");
|
||||||
|
if (provenance == Provenance.ARWEAVE_CONFIRMED) {
|
||||||
|
try (PreparedStatement up = c.prepareStatement("""
|
||||||
|
UPDATE free_registration_certificate SET publication_status='ARWEAVE_CONFIRMED',last_seen_at_ms=?
|
||||||
|
WHERE data_item_id=?
|
||||||
|
""")) {
|
||||||
|
up.setLong(1, now); up.setString(2, id); up.executeUpdate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
return new ImportResult(login, id, true, provenance);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (?, ?, ?, 'ARWEAVE', 'FREE_CERT', NULL, ?, ?, ?, ?, ?, false, ?, ?)
|
||||||
|
""")) {
|
||||||
|
insert.setString(1, login); insert.setString(2, login.toLowerCase(java.util.Locale.ROOT)); insert.setString(3, namespace);
|
||||||
|
insert.setString(4, id); insert.setString(5, Base58Util.encode(cert.rootKey()));
|
||||||
|
insert.setString(6, Base58Util.encode(cert.clientKey()));
|
||||||
|
insert.setString(7, Base58Util.encode(cert.blockchainKey()));
|
||||||
|
insert.setString(8, login.toLowerCase(java.util.Locale.ROOT) + "-001"); insert.setLong(9, now); insert.setLong(10, now);
|
||||||
|
insert.executeUpdate();
|
||||||
|
}
|
||||||
|
// blockchain_state — обязательная runtime-проекция новой цепочки.
|
||||||
|
// Без неё первый пользовательский AddBlock (например, «О себе») будет
|
||||||
|
// отклонён ещё до проверки подписи.
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
INSERT INTO blockchain_state_store (
|
||||||
|
login, fork_number, blockchain_key, size_limit, file_size_bytes,
|
||||||
|
last_block_number, last_block_hash, updated_at_ms)
|
||||||
|
VALUES (?, 1, ?, 100000, 0, -1, ?, ?)
|
||||||
|
""")) {
|
||||||
|
insert.setString(1, login);
|
||||||
|
// blockchain_state — runtime-слой: его ключ всегда Base64(32),
|
||||||
|
// как и у пользователей, импортированных из Solana PDA.
|
||||||
|
insert.setString(2, Base64.getEncoder().encodeToString(cert.blockchainKey()));
|
||||||
|
insert.setBytes(3, new byte[32]);
|
||||||
|
insert.setLong(4, now);
|
||||||
|
insert.executeUpdate();
|
||||||
|
}
|
||||||
|
try (PreparedStatement insert = c.prepareStatement("""
|
||||||
|
INSERT INTO free_registration_certificate (
|
||||||
|
data_item_id, login, namespace, email_sha256, inner_signature,
|
||||||
|
raw_signed_data_item, publication_status, registered_at_ms, last_seen_at_ms)
|
||||||
|
VALUES (?,?,?,?,?,?,?,?,?)
|
||||||
|
""")) {
|
||||||
|
insert.setString(1, id); insert.setString(2, login); insert.setString(3, namespace);
|
||||||
|
insert.setBytes(4, cert.emailSha256()); insert.setBytes(5, cert.innerSignature());
|
||||||
|
insert.setBytes(6, raw); insert.setString(7, publication);
|
||||||
|
insert.setLong(8, now); insert.setLong(9, now); insert.executeUpdate();
|
||||||
|
}
|
||||||
|
c.commit();
|
||||||
|
return new ImportResult(login, id, false, provenance);
|
||||||
|
} catch (Exception e) {
|
||||||
|
c.rollback(); throw e;
|
||||||
|
} finally { c.setAutoCommit(oldAutoCommit); }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String extractCanonicalLogin(blockchain.Ans104DataItem item) {
|
||||||
|
boolean marker = item.tags().contains(new blockchain.Ans104DataItem.Tag("t", "reg"));
|
||||||
|
if (!marker) throw new IllegalArgumentException("Not a registration DataItem");
|
||||||
|
byte[] bytes = item.data();
|
||||||
|
if (bytes.length < 3 || bytes[0] != 1 || bytes[1] != 0) throw new IllegalArgumentException("Bad certificate header");
|
||||||
|
int len = bytes[2] & 0xff;
|
||||||
|
if (len < 3 || len > 30 || bytes.length < 3 + len + 96 + 64 + 32)
|
||||||
|
throw new IllegalArgumentException("Invalid certificate login length");
|
||||||
|
return FreeRegistrationCertificateV1.validateLogin(
|
||||||
|
new String(bytes, 3, len, java.nio.charset.StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] readRegistrar(Connection c, String namespace, String login) throws Exception {
|
||||||
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT registrar_pubkey, min_localpart_len, default_server_login
|
||||||
|
FROM shine_namespace_current WHERE namespace=? AND namespace_type=2
|
||||||
|
""")) {
|
||||||
|
ps.setString(1, namespace);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (!rs.next()) throw new IllegalStateException("Unknown/free namespace not yet synchronized");
|
||||||
|
if (login.indexOf('@') < rs.getInt("min_localpart_len"))
|
||||||
|
throw new IllegalArgumentException("Login shorter than namespace minimum");
|
||||||
|
if (rs.getString("default_server_login") == null || rs.getString("default_server_login").isBlank())
|
||||||
|
throw new IllegalArgumentException("Namespace has no access server");
|
||||||
|
byte[] key = Base58Util.decode(rs.getString("registrar_pubkey"));
|
||||||
|
if (key.length != 32) throw new IllegalArgumentException("Invalid registrar pubkey");
|
||||||
|
return key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
0200a9de19b3551ace117973b80d632503bf2a55f0aa2490deb1474a280b675fa01bb2ccb5890faadcb213d3882fb21a7af13702526a569f7807b1c8b6963c0be402174553b456dddfc6908ecab1c101fe6ab21e2baa0617795b7d43a63482993fd500000300000000000000390000000000000006064170701074657374353539310274067265671050726f746f636f6c345348694e452d467265652d526567697374726174696f6e2d563100010008626f62406672656503a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b829acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd72543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559de2edfcd8b1b7a1823f56b827ddfa8a3682793e036141b526467ae346e220d08757d0a878a2f722562e6d3132ef9df04b1ab9e2f65d72bb0f48c17b7ada3e5a0acbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import server.archive.registration.*;
|
||||||
|
import blockchain.Ans104DataItem;
|
||||||
|
import blockchain.ShineProtocolTags;
|
||||||
|
import utils.crypto.Ed25519Util;
|
||||||
|
import java.util.Arrays;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
/** Standalone test (no legacy signed fixture): certificate issue/verify for CURRENT App tag. */
|
||||||
|
public final class FreeRegistrationCertificateV1Check {
|
||||||
|
static final HexFormat HEX = HexFormat.of();
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
byte[] seed = Ed25519Util.generatePrivateKeyFromString("TEST-only-reg-v1-check");
|
||||||
|
byte[] root = HEX.parseHex("03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8");
|
||||||
|
byte[] chain = HEX.parseHex("29acbae141bccaf0b22e1a94d34d0bc7361e526d0bfe12c89794bc9322966dd7");
|
||||||
|
byte[] client = HEX.parseHex("2543b92ff1095511476adc8369db6ddc933665a11978dda1404ee1066ca9559d");
|
||||||
|
try (var signer = new LocalRegistrarSigner(seed)) {
|
||||||
|
byte[] cert = FreeRegistrationCertificateV1.issue("SuperMan@free", root, chain, client,
|
||||||
|
" Alice.Example+Tag@Example.COM ", signer);
|
||||||
|
var item = new Ans104DataItem(cert);
|
||||||
|
if (!item.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE))
|
||||||
|
throw new AssertionError("Current App tag missing");
|
||||||
|
var result = FreeRegistrationCertificateV1.verify(cert, signer.publicKey32());
|
||||||
|
if (!"SuperMan@free".equals(result.login()) || !Arrays.equals(result.rootKey(), root)
|
||||||
|
|| !Arrays.equals(result.blockchainKey(), chain) || !Arrays.equals(result.clientKey(), client))
|
||||||
|
throw new AssertionError("Certificate identity corrupted");
|
||||||
|
if (!Arrays.equals(result.emailSha256(), HEX.parseHex(
|
||||||
|
"cbc605c49fd774ff4d9ea789d8f6bffa719e9774cb86f62d11fd244121150956")))
|
||||||
|
throw new AssertionError("Email normalization differs");
|
||||||
|
byte[] bad = cert.clone(); bad[bad.length - 1] ^= 1;
|
||||||
|
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||||
|
throw new AssertionError("Email bit flip accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) {}
|
||||||
|
bad = cert.clone(); bad[bad.length - 40] ^= 1;
|
||||||
|
try { FreeRegistrationCertificateV1.verify(bad, signer.publicKey32());
|
||||||
|
throw new AssertionError("Inner signature tampering accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) {}
|
||||||
|
}
|
||||||
|
System.out.println("PASS: current App=" + ShineProtocolTags.APP_TAG_VALUE
|
||||||
|
+ ", Java registrar inner+outer Ed25519, original case, email, tamper rejection");
|
||||||
|
}
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package server.archive;
|
||||||
|
|
||||||
|
import server.archive.registration.*;
|
||||||
|
import javax.sql.DataSource;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
|
||||||
|
/** Только проверки без БД/сети; полное E2E требует PostgreSQL и Turbo. */
|
||||||
|
public final class FreeRegistrationWorkflowLocalCheck {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
var signer = new RegistrarSigner() {
|
||||||
|
public byte[] publicKey32() { return new byte[32]; }
|
||||||
|
public byte[] sign(byte[] message) { return new byte[64]; }
|
||||||
|
};
|
||||||
|
DataSource noDb = new DataSource() {
|
||||||
|
public java.sql.Connection getConnection() throws java.sql.SQLException { throw new java.sql.SQLException("No database in local test"); }
|
||||||
|
public java.sql.Connection getConnection(String u, String p) throws java.sql.SQLException { return getConnection(); }
|
||||||
|
public java.io.PrintWriter getLogWriter() {return null;}
|
||||||
|
public void setLogWriter(java.io.PrintWriter x) {}
|
||||||
|
public void setLoginTimeout(int x) {}
|
||||||
|
public int getLoginTimeout() {return 0;}
|
||||||
|
public java.util.logging.Logger getParentLogger() {return java.util.logging.Logger.getAnonymousLogger();}
|
||||||
|
public <T> T unwrap(Class<T> iface) throws java.sql.SQLException {throw new java.sql.SQLException("unsupported");}
|
||||||
|
public boolean isWrapperFor(Class<?> iface) {return false;}
|
||||||
|
};
|
||||||
|
var issuer = new FreeRegistrationIssuer(noDb, signer);
|
||||||
|
var importer = new VerifiedFreeRegistrationImporter();
|
||||||
|
var workflow = new FreeRegistrationWorkflow(issuer,
|
||||||
|
new FreeRegistrationPublisher(issuer, new TurboDataItemUploader(), importer));
|
||||||
|
byte[] k1 = new byte[32], k2 = new byte[32], k3 = new byte[32];
|
||||||
|
k1[0] = 1; k2[0] = 2; k3[0] = 3;
|
||||||
|
var start = workflow.start("bob@free", k1, k2, k3, "hello@example.org");
|
||||||
|
if (start.challengeId().isBlank() || start.expiresAtMs() <= System.currentTimeMillis())
|
||||||
|
throw new AssertionError("Cannot start a bounded challenge");
|
||||||
|
try { workflow.confirm(start.challengeId(), "wrong"); throw new AssertionError("Bad demo code accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
try { workflow.confirm("unknown", "1111"); throw new AssertionError("Missing challenge accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
try { workflow.start("BOB@free", k1, k2, k3, "hello@example.org"); throw new AssertionError("Invalid login accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
try { importer.importSigned(new byte[]{1,2,3}, VerifiedFreeRegistrationImporter.Provenance.TURBO_ACCEPTED);
|
||||||
|
throw new AssertionError("Invalid bytes accepted"); }
|
||||||
|
catch (IllegalArgumentException expected) { }
|
||||||
|
System.out.println("PASS: workflow nonce/code checks + reject invalid signed bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -9,7 +9,7 @@ package blockchain;
|
|||||||
public final class ShineProtocolTags {
|
public final class ShineProtocolTags {
|
||||||
private ShineProtocolTags() {}
|
private ShineProtocolTags() {}
|
||||||
|
|
||||||
public static final String NAMESPACE = "test5591";
|
public static final String NAMESPACE = "test5592";
|
||||||
public static final String APP_TAG_NAME = "App";
|
public static final String APP_TAG_NAME = "App";
|
||||||
public static final String APP_TAG_VALUE = NAMESPACE;
|
public static final String APP_TAG_VALUE = NAMESPACE;
|
||||||
public static final String CHANNEL_TAG_NAME = "c";
|
public static final String CHANNEL_TAG_NAME = "c";
|
||||||
|
|||||||
@@ -78,8 +78,14 @@ public final class HeaderBody implements BodyRecord {
|
|||||||
public HeaderBody check() {
|
public HeaderBody check() {
|
||||||
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
|
||||||
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
|
||||||
if (!login.matches("^[A-Za-z0-9_]+$")) throw new IllegalArgumentException("Login must match ^[A-Za-z0-9_]+$");
|
|
||||||
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
|
||||||
|
// В HEADER хранится неизменяемое написание зарегистрированного login@namespace.
|
||||||
|
// Namespace остаётся lowercase, регистр локальной части сохраняется байт-в-байт.
|
||||||
|
boolean legacyLogin = login.matches("^[A-Za-z0-9_]+$");
|
||||||
|
boolean namespacedLogin = loginUtf8.length <= 30 && login.matches("^[A-Za-z0-9_]+@[a-z0-9_]+$");
|
||||||
|
if (!legacyLogin && !namespacedLogin) {
|
||||||
|
throw new IllegalArgumentException("Login must be legacy [A-Za-z0-9_]+ or registered-case login@namespace (max 30 bytes)");
|
||||||
|
}
|
||||||
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
|
||||||
requireNonZeroKey(initialBlockchainKey32);
|
requireNonZeroKey(initialBlockchainKey32);
|
||||||
return this;
|
return this;
|
||||||
|
|||||||
+32
@@ -98,6 +98,38 @@ final class TargetLoginFormatTest {
|
|||||||
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void namespacedHeaderRoundTripAcceptsPaidAndFreeUsers() {
|
||||||
|
for (String login : new String[]{"alice@free", "AlexSmith@shine", "a_B@free", "abcdefghijklmnopqrstuvwxy@free"}) {
|
||||||
|
HeaderBody source = new HeaderBody(login, INITIAL_KEY);
|
||||||
|
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, source.toBytes()).check();
|
||||||
|
assertEquals(login, parsed.login);
|
||||||
|
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void namespacedHeaderRejectsMalformedOrOversizedLogin() {
|
||||||
|
for (String login : new String[]{"alice@", "@shine", "alice@@free", "alice@FREE", "alice.free@shine", "abcdefghijklmnopqrstuvwxyz@free"}) {
|
||||||
|
assertThrows(IllegalArgumentException.class, () -> new HeaderBody(login, INITIAL_KEY), login);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void signedReferencesPreserveArbitraryLoginCaseWithoutServerSideCaseEnforcement() {
|
||||||
|
// Адресация не зависит от регистра, но блок сохраняет выбранные автором байты.
|
||||||
|
for (String login : new String[]{"AlexSmith@shine", "alexsmith@shine"}) {
|
||||||
|
TextReplyBody reply = new TextReplyBody(MsgSubType.TEXT_REPLY, login, 1, 42, HASH, "тест");
|
||||||
|
assertEquals(login, new TextReplyBody(MsgSubType.TEXT_REPLY, TextReplyBody.VER, reply.toBytes()).check().toLogin());
|
||||||
|
|
||||||
|
ReactionBody like = new ReactionBody(MsgSubType.REACTION_LIKE, login, 1, 42, HASH);
|
||||||
|
assertEquals(login, new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, like.toBytes()).check().toLogin());
|
||||||
|
|
||||||
|
ConnectionBody follow = new ConnectionBody(0, HASH, 1, MsgSubType.CONNECTION_FOLLOW, login, 1, 0, HASH);
|
||||||
|
assertEquals(login, new ConnectionBody(MsgSubType.CONNECTION_FOLLOW, ConnectionBody.VER, follow.toBytes()).check().toLogin());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static byte[] hash(int seed) {
|
private static byte[] hash(int seed) {
|
||||||
byte[] out = new byte[32];
|
byte[] out = new byte[32];
|
||||||
Arrays.fill(out, (byte) seed);
|
Arrays.fill(out, (byte) seed);
|
||||||
|
|||||||
@@ -22,8 +22,22 @@ public final class DatabaseInitializer {
|
|||||||
public static final int DB_FORMAT_VERSION = 2;
|
public static final int DB_FORMAT_VERSION = 2;
|
||||||
public static final int SCHEMA_VERSION_1 = 1;
|
public static final int SCHEMA_VERSION_1 = 1;
|
||||||
public static final int SCHEMA_VERSION_31 = 31;
|
public static final int SCHEMA_VERSION_31 = 31;
|
||||||
|
public static final int SCHEMA_VERSION_32 = 32;
|
||||||
|
public static final int SCHEMA_VERSION_33 = 33;
|
||||||
|
public static final int SCHEMA_VERSION_34 = 34;
|
||||||
|
public static final int SCHEMA_VERSION_35 = 35;
|
||||||
|
public static final int SCHEMA_VERSION_36 = 36;
|
||||||
|
public static final int SCHEMA_VERSION_37 = 37;
|
||||||
|
public static final int SCHEMA_VERSION_38 = 38;
|
||||||
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
|
||||||
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V32_RESOURCE = "postgres/migration_v32.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V33_RESOURCE = "postgres/migration_v33.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V34_RESOURCE = "postgres/migration_v34.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V35_RESOURCE = "postgres/migration_v35.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V36_RESOURCE = "postgres/migration_v36.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V37_RESOURCE = "postgres/migration_v37.sql";
|
||||||
|
public static final String POSTGRES_MIGRATION_V38_RESOURCE = "postgres/migration_v38.sql";
|
||||||
|
|
||||||
private DatabaseInitializer() {}
|
private DatabaseInitializer() {}
|
||||||
|
|
||||||
@@ -119,10 +133,39 @@ public final class DatabaseInitializer {
|
|||||||
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
|
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
|
||||||
currentVersion = readCurrentSchemaVersion(conn);
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
}
|
}
|
||||||
if (currentVersion != SCHEMA_VERSION_31) {
|
if (currentVersion == SCHEMA_VERSION_31) {
|
||||||
throw new SQLException(
|
runSqlScript(conn, POSTGRES_MIGRATION_V32_RESOURCE);
|
||||||
"Unsupported SHiNE DB v2 schema version: expected 31, found " + currentVersion);
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
}
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_32) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V33_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_33) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V34_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_34) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V35_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_35) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V36_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_36) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V37_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion == SCHEMA_VERSION_37) {
|
||||||
|
runSqlScript(conn, POSTGRES_MIGRATION_V38_RESOURCE);
|
||||||
|
currentVersion = readCurrentSchemaVersion(conn);
|
||||||
|
}
|
||||||
|
if (currentVersion != SCHEMA_VERSION_38) {
|
||||||
|
throw new SQLException(
|
||||||
|
"Unsupported SHiNE DB v2 schema version: expected 38, found " + currentVersion);
|
||||||
|
}
|
||||||
|
normalizeBlockchainStateKeysToBase64(conn);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -202,6 +245,38 @@ public final class DatabaseInitializer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* blockchain_state — runtime-проекция: публичный blockchain key хранится
|
||||||
|
* строго как Base64(32). Ранний импорт free-регистраций ошибочно сохранял
|
||||||
|
* Base58, поэтому нормализация выполняется идемпотентно при старте.
|
||||||
|
*/
|
||||||
|
private static void normalizeBlockchainStateKeysToBase64(Connection conn) throws SQLException {
|
||||||
|
record StateKey(String login, int forkNumber, String key) {}
|
||||||
|
List<StateKey> entries = new ArrayList<>();
|
||||||
|
try (Statement st = conn.createStatement();
|
||||||
|
ResultSet rs = st.executeQuery("SELECT login, fork_number, blockchain_key FROM blockchain_state_store")) {
|
||||||
|
while (rs.next()) {
|
||||||
|
entries.add(new StateKey(rs.getString("login"), rs.getInt("fork_number"), rs.getString("blockchain_key")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try (var update = conn.prepareStatement("""
|
||||||
|
UPDATE blockchain_state_store
|
||||||
|
SET blockchain_key = ?
|
||||||
|
WHERE login = ? AND fork_number = ?
|
||||||
|
""")) {
|
||||||
|
for (StateKey entry : entries) {
|
||||||
|
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(entry.key());
|
||||||
|
if (normalized == null || normalized.equals(entry.key())) continue;
|
||||||
|
update.setString(1, normalized);
|
||||||
|
update.setString(2, entry.login());
|
||||||
|
update.setInt(3, entry.forkNumber());
|
||||||
|
update.addBatch();
|
||||||
|
}
|
||||||
|
update.executeBatch();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private static void runSqlScript(Connection conn, String resourcePath) throws SQLException {
|
private static void runSqlScript(Connection conn, String resourcePath) throws SQLException {
|
||||||
String sqlScript = loadClasspathResource(resourcePath);
|
String sqlScript = loadClasspathResource(resourcePath);
|
||||||
List<String> statements = splitSqlStatements(sqlScript);
|
List<String> statements = splitSqlStatements(sqlScript);
|
||||||
|
|||||||
@@ -43,7 +43,7 @@ public final class BlockchainStateDAO {
|
|||||||
last_block_hash,
|
last_block_hash,
|
||||||
updated_at_ms
|
updated_at_ms
|
||||||
FROM blockchain_state
|
FROM blockchain_state
|
||||||
WHERE login = ? AND fork_number = ?
|
WHERE LOWER(login) = LOWER(?) AND fork_number = ?
|
||||||
""";
|
""";
|
||||||
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
@@ -197,7 +197,7 @@ public final class BlockchainStateDAO {
|
|||||||
file_size_bytes = file_size_bytes + ?,
|
file_size_bytes = file_size_bytes + ?,
|
||||||
updated_at_ms = ?
|
updated_at_ms = ?
|
||||||
WHERE
|
WHERE
|
||||||
login = ? AND fork_number = ?
|
LOWER(login) = LOWER(?) AND fork_number = ?
|
||||||
AND (file_size_bytes + ?) <= size_limit
|
AND (file_size_bytes + ?) <= size_limit
|
||||||
""";
|
""";
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
package shine.db.dao;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/** Read-only поиск по серверному индексу актуальных публичных каналов. */
|
||||||
|
public final class ChannelSearchDAO {
|
||||||
|
private ChannelSearchDAO() {}
|
||||||
|
|
||||||
|
public record Match(String ownerLogin, String slug, String displayName, String description,
|
||||||
|
String avatarAr, String avatarSha256, String ownerBlockchainName,
|
||||||
|
int rootBlockNumber, String rootBlockHashHex, int subscribersCount) {}
|
||||||
|
|
||||||
|
// LIKE ESCAPE '!' — введённые пользователем %, _ и ! трактуются буквально.
|
||||||
|
private static String escapedPattern(String text) {
|
||||||
|
return text.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String normalized(String text) {
|
||||||
|
return (text == null ? "" : text.trim()).toLowerCase(Locale.ROOT).replace('ё', 'е');
|
||||||
|
}
|
||||||
|
|
||||||
|
public static List<Match> search(Connection c, String query, String ownerLogin, int limit) throws SQLException {
|
||||||
|
String needle = normalized(query).replaceFirst("^@", "");
|
||||||
|
String ownerFilter = normalized(ownerLogin).replaceFirst("^@", "");
|
||||||
|
boolean ownerOnly = query != null && query.trim().startsWith("@") && !needle.contains("/");
|
||||||
|
String channelNeedle = needle;
|
||||||
|
if (needle.contains("/")) {
|
||||||
|
String[] parts = needle.split("/", 2);
|
||||||
|
if (ownerFilter.isBlank()) ownerFilter = parts[0];
|
||||||
|
channelNeedle = parts[1];
|
||||||
|
}
|
||||||
|
// Если указан owner/название, техническое и публичное название ищем только у владельца.
|
||||||
|
boolean hasOwner = !ownerFilter.isBlank();
|
||||||
|
String exact = channelNeedle;
|
||||||
|
String anywhere = "%" + escapedPattern(exact) + "%";
|
||||||
|
String prefix = escapedPattern(exact) + "%";
|
||||||
|
String ownerExact = ownerFilter;
|
||||||
|
String ownerPrefix = escapedPattern(ownerExact) + "%";
|
||||||
|
String ownerAnywhere = "%" + escapedPattern(ownerExact) + "%";
|
||||||
|
String sql = """
|
||||||
|
SELECT cn.owner_login, cn.slug, cn.display_name, cn.channel_description,
|
||||||
|
cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
|
||||||
|
cn.channel_root_block_number, encode(cn.channel_root_block_hash, 'hex') AS root_hash,
|
||||||
|
COALESCE(cs.subscribers_count, 0) AS subscribers_count
|
||||||
|
FROM channel_names_state cn
|
||||||
|
LEFT JOIN channel_stats_state cs
|
||||||
|
ON cs.owner_bch_name = cn.owner_bch_name
|
||||||
|
AND cs.channel_root_block_number = cn.channel_root_block_number
|
||||||
|
AND cs.channel_root_block_hash = cn.channel_root_block_hash
|
||||||
|
WHERE cn.channel_type_code = 1 AND NOT cn.is_deleted
|
||||||
|
AND (? = '' OR replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||||
|
AND (
|
||||||
|
(? = true AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||||
|
OR (? = false AND (
|
||||||
|
replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!'
|
||||||
|
OR replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!'
|
||||||
|
OR (? = false AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||||
|
OR (? = true AND ? = '' AND replace(lower(cn.owner_login), 'ё','е') LIKE ? ESCAPE '!')
|
||||||
|
))
|
||||||
|
)
|
||||||
|
ORDER BY
|
||||||
|
CASE
|
||||||
|
WHEN replace(lower(cn.display_name), 'ё','е') = ? THEN 0
|
||||||
|
WHEN replace(lower(cn.slug), 'ё','е') = ? THEN 1
|
||||||
|
WHEN replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!' THEN 2
|
||||||
|
WHEN replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!' THEN 3
|
||||||
|
WHEN replace(lower(cn.owner_login), 'ё','е') = ? THEN 4
|
||||||
|
WHEN replace(lower(cn.display_name), 'ё','е') LIKE ? ESCAPE '!' THEN 5
|
||||||
|
WHEN replace(lower(cn.slug), 'ё','е') LIKE ? ESCAPE '!' THEN 6
|
||||||
|
ELSE 7
|
||||||
|
END,
|
||||||
|
COALESCE(cs.subscribers_count, 0) DESC,
|
||||||
|
lower(cn.owner_login), lower(cn.slug), cn.owner_bch_name
|
||||||
|
LIMIT ?
|
||||||
|
""";
|
||||||
|
// ownerOnly = поиск @login. Когда указан владелец — ограничиваем выборку,
|
||||||
|
// а пустой сегмент / означает «все каналы этого пользователя».
|
||||||
|
String term = exact;
|
||||||
|
boolean filterByOwner = hasOwner && !ownerOnly;
|
||||||
|
List<Match> matches = new ArrayList<>();
|
||||||
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
int i = 1;
|
||||||
|
ps.setString(i++, filterByOwner ? ownerFilter : "");
|
||||||
|
ps.setString(i++, ownerPrefix);
|
||||||
|
ps.setBoolean(i++, ownerOnly);
|
||||||
|
ps.setString(i++, "%" + escapedPattern(term) + "%");
|
||||||
|
ps.setBoolean(i++, ownerOnly);
|
||||||
|
ps.setString(i++, anywhere);
|
||||||
|
ps.setString(i++, anywhere);
|
||||||
|
ps.setBoolean(i++, filterByOwner);
|
||||||
|
ps.setString(i++, anywhere);
|
||||||
|
ps.setBoolean(i++, filterByOwner);
|
||||||
|
ps.setString(i++, exact);
|
||||||
|
ps.setString(i++, ownerAnywhere);
|
||||||
|
ps.setString(i++, term);
|
||||||
|
ps.setString(i++, term);
|
||||||
|
ps.setString(i++, prefix);
|
||||||
|
ps.setString(i++, prefix);
|
||||||
|
ps.setString(i++, term);
|
||||||
|
ps.setString(i++, anywhere);
|
||||||
|
ps.setString(i++, anywhere);
|
||||||
|
ps.setInt(i, Math.min(50, Math.max(1, limit)));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
while (rs.next()) matches.add(new Match(
|
||||||
|
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"),
|
||||||
|
rs.getString("channel_description"), rs.getString("ava_ar"), rs.getString("ava_sha256"),
|
||||||
|
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"),
|
||||||
|
rs.getString("root_hash"), rs.getInt("subscribers_count")
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -164,9 +164,9 @@ public final class ConnectionsStateDAO {
|
|||||||
""";
|
""";
|
||||||
|
|
||||||
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
try (PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
ps.setString(1, login);
|
ps.setString(1, login.trim().toLowerCase(java.util.Locale.ROOT));
|
||||||
ps.setInt(2, relType);
|
ps.setInt(2, relType);
|
||||||
ps.setString(3, toLogin);
|
ps.setString(3, toLogin.trim().toLowerCase(java.util.Locale.ROOT));
|
||||||
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
|
||||||
ps.setBytes(5, toBlockHash);
|
ps.setBytes(5, toBlockHash);
|
||||||
ps.executeUpdate();
|
ps.executeUpdate();
|
||||||
|
|||||||
@@ -204,6 +204,53 @@ public final class CurrentUsersDAO {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Поиск логинов и публичных имён; результат не раскрывает приватные ключи PDA. */
|
||||||
|
public record SearchUserCard(String login, String displayName, String avatarAr) {}
|
||||||
|
|
||||||
|
public List<SearchUserCard> searchDirectory(String query, Boolean isServer, int limit) throws SQLException {
|
||||||
|
String term = query.trim().toLowerCase(java.util.Locale.ROOT).replace('ё', 'е');
|
||||||
|
String escaped = term.replace("!", "!!").replace("%", "!%").replace("_", "!_");
|
||||||
|
String sql = """
|
||||||
|
SELECT su.login, coalesce(up.first_name, '') AS first_name,
|
||||||
|
coalesce(up.last_name, '') AS last_name, coalesce(up.ava_ar, '') AS ava_ar
|
||||||
|
FROM user_identity_current su
|
||||||
|
LEFT JOIN user_profile_state up ON lower(up.login) = lower(su.login)
|
||||||
|
WHERE (? IS NULL OR su.is_server = ?)
|
||||||
|
AND (
|
||||||
|
replace(lower(su.login), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||||
|
OR replace(lower(coalesce(up.first_name, '') || ' ' || coalesce(up.last_name, '')), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||||
|
OR replace(lower(coalesce(up.last_name, '') || ' ' || coalesce(up.first_name, '')), 'ё', 'е') LIKE ? ESCAPE '!'
|
||||||
|
)
|
||||||
|
ORDER BY
|
||||||
|
CASE WHEN replace(lower(su.login), 'ё','е') = ? THEN 0
|
||||||
|
WHEN replace(lower(su.login), 'ё','е') LIKE ? ESCAPE '!' THEN 1
|
||||||
|
WHEN replace(lower(coalesce(up.first_name, '') || ' ' || coalesce(up.last_name, '')), 'ё', 'е') LIKE ? ESCAPE '!' THEN 2
|
||||||
|
ELSE 3 END,
|
||||||
|
lower(su.login)
|
||||||
|
LIMIT ?
|
||||||
|
""";
|
||||||
|
List<SearchUserCard> users = new ArrayList<>();
|
||||||
|
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||||
|
int i = 1;
|
||||||
|
if (isServer == null) { ps.setNull(i++, Types.BOOLEAN); ps.setNull(i++, Types.BOOLEAN); }
|
||||||
|
else { ps.setBoolean(i++, isServer); ps.setBoolean(i++, isServer); }
|
||||||
|
ps.setString(i++, escaped + "%");
|
||||||
|
ps.setString(i++, "%" + escaped + "%");
|
||||||
|
ps.setString(i++, "%" + escaped + "%");
|
||||||
|
ps.setString(i++, term);
|
||||||
|
ps.setString(i++, escaped + "%");
|
||||||
|
ps.setString(i++, escaped + "%");
|
||||||
|
ps.setInt(i, Math.min(50, Math.max(1, limit)));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
while (rs.next()) {
|
||||||
|
String publicName = (rs.getString("first_name") + " " + rs.getString("last_name")).trim();
|
||||||
|
users.add(new SearchUserCard(rs.getString("login"), publicName, rs.getString("ava_ar")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return users;
|
||||||
|
}
|
||||||
|
|
||||||
// -------------------- MAPPER --------------------
|
// -------------------- MAPPER --------------------
|
||||||
|
|
||||||
private CurrentUserEntry mapRow(ResultSet rs) throws SQLException {
|
private CurrentUserEntry mapRow(ResultSet rs) throws SQLException {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package shine.db.dao;
|
package shine.db.dao;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
import shine.db.MsgSubType;
|
import shine.db.MsgSubType;
|
||||||
import shine.db.entities.SignedMessageEntry;
|
import shine.db.entities.SignedMessageEntry;
|
||||||
|
|
||||||
@@ -17,6 +18,7 @@ import java.util.Map;
|
|||||||
|
|
||||||
public final class DmDialogStateDAO {
|
public final class DmDialogStateDAO {
|
||||||
private static volatile DmDialogStateDAO instance;
|
private static volatile DmDialogStateDAO instance;
|
||||||
|
private final DbController db = DbController.getInstance();
|
||||||
|
|
||||||
private DmDialogStateDAO() {}
|
private DmDialogStateDAO() {}
|
||||||
|
|
||||||
@@ -129,6 +131,26 @@ public final class DmDialogStateDAO {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Снимок счётчика после записи DM. Используется только сервером для push/WS, не отдаёт текст сообщения. */
|
||||||
|
public NotificationState getNotificationState(String ownerLogin, String peerLogin) throws SQLException {
|
||||||
|
try (Connection c = db.getConnection();
|
||||||
|
PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT unread_count, updated_at_ms
|
||||||
|
FROM dm_dialog_state
|
||||||
|
WHERE LOWER(owner_login) = LOWER(?) AND LOWER(peer_login) = LOWER(?)
|
||||||
|
LIMIT 1
|
||||||
|
""")) {
|
||||||
|
ps.setString(1, normalize(ownerLogin));
|
||||||
|
ps.setString(2, normalize(peerLogin));
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (!rs.next()) return null;
|
||||||
|
return new NotificationState(Math.max(0, rs.getInt("unread_count")), rs.getLong("updated_at_ms"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public record NotificationState(int unreadCount, long versionMs) {}
|
||||||
|
|
||||||
public void refreshFromEntry(Connection c, SignedMessageEntry entry) throws SQLException {
|
public void refreshFromEntry(Connection c, SignedMessageEntry entry) throws SQLException {
|
||||||
if (entry == null) return;
|
if (entry == null) return;
|
||||||
refreshConversationPair(c, entry.getFromLogin(), entry.getToLogin());
|
refreshConversationPair(c, entry.getFromLogin(), entry.getToLogin());
|
||||||
@@ -274,7 +296,7 @@ public final class DmDialogStateDAO {
|
|||||||
last_message_time_ms = EXCLUDED.last_message_time_ms,
|
last_message_time_ms = EXCLUDED.last_message_time_ms,
|
||||||
unread_count = EXCLUDED.unread_count,
|
unread_count = EXCLUDED.unread_count,
|
||||||
last_read_receipt_time_ms = EXCLUDED.last_read_receipt_time_ms,
|
last_read_receipt_time_ms = EXCLUDED.last_read_receipt_time_ms,
|
||||||
updated_at_ms = EXCLUDED.updated_at_ms
|
updated_at_ms = GREATEST(dm_dialog_state.updated_at_ms + 1, EXCLUDED.updated_at_ms)
|
||||||
""")) {
|
""")) {
|
||||||
ps.setString(1, summary.ownerLogin());
|
ps.setString(1, summary.ownerLogin());
|
||||||
ps.setString(2, summary.peerLogin());
|
ps.setString(2, summary.peerLogin());
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
package shine.db.dao;
|
||||||
|
|
||||||
|
import shine.db.DbController;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
|
/** Единая авторитетная проекция: FREE_CERT не притворяется Solana PDA. */
|
||||||
|
public final class RegistrationIdentityDAO {
|
||||||
|
public record ResolvedIdentity(String fullLogin, String rootKey, String blockchainKey,
|
||||||
|
String clientKey, String registrationSource, String registrationStatus,
|
||||||
|
String namespace, String accessServerLogin, boolean hasSolanaPda) {
|
||||||
|
public boolean isFree() { return "FREE_CERT".equals(registrationStatus); }
|
||||||
|
}
|
||||||
|
private static final RegistrationIdentityDAO INSTANCE = new RegistrationIdentityDAO();
|
||||||
|
public static RegistrationIdentityDAO getInstance() { return INSTANCE; }
|
||||||
|
private RegistrationIdentityDAO() {}
|
||||||
|
|
||||||
|
public ResolvedIdentity get(String login) throws SQLException {
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) { return get(c, login); }
|
||||||
|
}
|
||||||
|
public ResolvedIdentity get(Connection c, String login) throws SQLException {
|
||||||
|
if (login == null || login.isBlank()) return null;
|
||||||
|
try (PreparedStatement ps = c.prepareStatement("""
|
||||||
|
SELECT i.login, i.root_key, i.blockchain_key, i.client_key,
|
||||||
|
i.registration_source, i.registration_status, i.namespace,
|
||||||
|
i.solana_pda_address, n.default_server_login,
|
||||||
|
s.server_login AS actual_access_server
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN shine_namespace_current n ON n.namespace=i.namespace
|
||||||
|
LEFT JOIN user_access_servers_current s ON s.user_login=i.login
|
||||||
|
WHERE i.normalized_login=LOWER(BTRIM(?))
|
||||||
|
ORDER BY s.server_login ASC
|
||||||
|
LIMIT 1
|
||||||
|
""")) {
|
||||||
|
ps.setString(1, login);
|
||||||
|
try (ResultSet rs = ps.executeQuery()) {
|
||||||
|
if (!rs.next()) return null;
|
||||||
|
boolean hasPda = rs.getString("solana_pda_address") != null;
|
||||||
|
String status = rs.getString("registration_status");
|
||||||
|
String server = "FREE_CERT".equals(status) ? rs.getString("default_server_login")
|
||||||
|
: rs.getString("actual_access_server");
|
||||||
|
if ("FREE_CERT".equals(status) && hasPda)
|
||||||
|
throw new SQLException("Inconsistent free user: Solana PDA must be absent");
|
||||||
|
if (!"FREE_CERT".equals(status) && !hasPda)
|
||||||
|
throw new SQLException("Inconsistent paid user: Solana PDA is missing");
|
||||||
|
return new ResolvedIdentity(rs.getString("login"), rs.getString("root_key"),
|
||||||
|
rs.getString("blockchain_key"), rs.getString("client_key"),
|
||||||
|
rs.getString("registration_source"), status, rs.getString("namespace"), server, hasPda);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public boolean isFreeCertificate(String login) throws SQLException {
|
||||||
|
ResolvedIdentity identity = get(login);
|
||||||
|
return identity != null && identity.isFree();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -111,7 +111,7 @@ public final class SubscriptionsDAO {
|
|||||||
FROM connections_state cs
|
FROM connections_state cs
|
||||||
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
|
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
|
||||||
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
|
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
|
||||||
WHERE cs.login = ? AND cs.rel_type = ?
|
WHERE LOWER(cs.login) = LOWER(?) AND cs.rel_type = ?
|
||||||
|
|
||||||
UNION
|
UNION
|
||||||
|
|
||||||
|
|||||||
+12
-10
@@ -46,26 +46,28 @@ public final class UserAccessServersCurrentDAO {
|
|||||||
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
public UserAccessServerRouteEntry findPrimaryByUserLogin(String userLogin) throws SQLException {
|
||||||
String sql = """
|
String sql = """
|
||||||
SELECT
|
SELECT
|
||||||
u.login AS user_login,
|
i.login AS user_login,
|
||||||
s.login AS server_login,
|
s.login AS server_login,
|
||||||
s.server_address AS server_url,
|
s.server_address AS server_url,
|
||||||
s.client_key AS server_client_key
|
s.client_key AS server_client_key
|
||||||
FROM solana_user_pda_current u
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||||
CROSS JOIN LATERAL (
|
CROSS JOIN LATERAL (
|
||||||
SELECT BTRIM(a.login_value) AS server_login
|
SELECT CASE WHEN i.registration_status = 'FREE_CERT'
|
||||||
|
THEN ns.default_server_login
|
||||||
|
ELSE (SELECT BTRIM(a.login_value)
|
||||||
FROM jsonb_array_elements_text(
|
FROM jsonb_array_elements_text(
|
||||||
CASE
|
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||||
WHEN BTRIM(COALESCE(u.access_servers_json, '')) = '' THEN '[]'::jsonb
|
WITH ORDINALITY AS a(login_value, ord)
|
||||||
ELSE u.access_servers_json::jsonb
|
WHERE a.ord = 1)
|
||||||
END
|
END AS server_login
|
||||||
) WITH ORDINALITY AS a(login_value, ord)
|
|
||||||
WHERE a.ord = 1
|
|
||||||
) primary_access
|
) primary_access
|
||||||
JOIN solana_user_pda_current s
|
JOIN solana_user_pda_current s
|
||||||
ON s.normalized_login = LOWER(primary_access.server_login)
|
ON s.normalized_login = LOWER(primary_access.server_login)
|
||||||
AND s.is_server = TRUE
|
AND s.is_server = TRUE
|
||||||
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
AND BTRIM(COALESCE(s.server_address, '')) <> ''
|
||||||
WHERE u.normalized_login = LOWER(BTRIM(?))
|
WHERE i.normalized_login = LOWER(BTRIM(?))
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""";
|
""";
|
||||||
try (Connection c = db.getConnection();
|
try (Connection c = db.getConnection();
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ public final class CurrentUsersSql {
|
|||||||
current_users.blockchain_key AS blockchain_key,
|
current_users.blockchain_key AS blockchain_key,
|
||||||
current_users.client_key AS client_key,
|
current_users.client_key AS client_key,
|
||||||
current_users.is_server AS is_server
|
current_users.is_server AS is_server
|
||||||
FROM solana_user_pda_current current_users
|
FROM user_identity_current current_users
|
||||||
) %s
|
) %s
|
||||||
""".formatted(alias);
|
""".formatted(alias);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
-- Поиск публичных каналов и отображаемых имён (SHiNE DB v32).
|
||||||
|
BEGIN;
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_display
|
||||||
|
ON channel_names_state USING gin ((replace(lower(display_name), 'ё', 'е')) gin_trgm_ops)
|
||||||
|
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_slug
|
||||||
|
ON channel_names_state USING gin ((replace(lower(slug), 'ё', 'е')) gin_trgm_ops)
|
||||||
|
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_owner
|
||||||
|
ON channel_names_state USING gin ((replace(lower(owner_login), 'ё', 'е')) gin_trgm_ops)
|
||||||
|
WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name
|
||||||
|
ON user_profile_state USING gin ((replace(lower(coalesce(first_name, '') || ' ' || coalesce(last_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name_reverse
|
||||||
|
ON user_profile_state USING gin ((replace(lower(coalesce(last_name, '') || ' ' || coalesce(first_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||||
|
UPDATE db_schema_version SET schema_version = 32,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
-- SHiNE DB v33: общий индекс идентичностей, namespace и сертификаты.
|
||||||
|
-- ТОЛЬКО dev/test до проверки всей серверной авторизации.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE TABLE user_identity_current (
|
||||||
|
login TEXT PRIMARY KEY,
|
||||||
|
normalized_login TEXT NOT NULL UNIQUE,
|
||||||
|
namespace TEXT,
|
||||||
|
registration_source TEXT NOT NULL CHECK (registration_source IN ('SOLANA', 'ARWEAVE')),
|
||||||
|
registration_status TEXT NOT NULL CHECK (registration_status IN ('PAID_DIRECT', 'FREE_CERT', 'PAID_UPGRADED')),
|
||||||
|
solana_pda_address TEXT UNIQUE,
|
||||||
|
free_data_item_id TEXT UNIQUE,
|
||||||
|
root_key TEXT NOT NULL,
|
||||||
|
client_key TEXT NOT NULL,
|
||||||
|
blockchain_key TEXT NOT NULL,
|
||||||
|
blockchain_name TEXT NOT NULL,
|
||||||
|
is_server BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
registered_at_ms BIGINT NOT NULL,
|
||||||
|
updated_at_ms BIGINT NOT NULL,
|
||||||
|
CHECK ((registration_status = 'FREE_CERT' AND solana_pda_address IS NULL AND free_data_item_id IS NOT NULL)
|
||||||
|
OR (registration_status <> 'FREE_CERT' AND solana_pda_address IS NOT NULL))
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_user_identity_namespace ON user_identity_current(namespace);
|
||||||
|
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, root_key, client_key, blockchain_key, blockchain_name,
|
||||||
|
is_server, registered_at_ms, updated_at_ms
|
||||||
|
)
|
||||||
|
SELECT login, normalized_login,
|
||||||
|
CASE WHEN position('@' in login) > 0 THEN split_part(login, '@', 2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID_DIRECT', pda_address, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, created_at_ms, updated_at_ms
|
||||||
|
FROM solana_user_pda_current
|
||||||
|
ON CONFLICT (login) DO NOTHING;
|
||||||
|
|
||||||
|
CREATE TABLE shine_namespace_current (
|
||||||
|
namespace TEXT PRIMARY KEY,
|
||||||
|
pda_address TEXT NOT NULL UNIQUE,
|
||||||
|
namespace_type SMALLINT NOT NULL CHECK(namespace_type IN (1,2)),
|
||||||
|
min_localpart_len SMALLINT NOT NULL CHECK (min_localpart_len BETWEEN 1 AND 30),
|
||||||
|
registration_fee_lamports NUMERIC(20,0) NOT NULL CHECK (registration_fee_lamports >= 0),
|
||||||
|
registrar_pubkey TEXT,
|
||||||
|
default_server_login TEXT,
|
||||||
|
slot BIGINT NOT NULL,
|
||||||
|
last_tx_signature TEXT NOT NULL DEFAULT '',
|
||||||
|
raw_data_base64 TEXT NOT NULL,
|
||||||
|
CHECK ((namespace_type = 1 AND registrar_pubkey IS NULL AND default_server_login IS NULL)
|
||||||
|
OR (namespace_type = 2 AND registrar_pubkey IS NOT NULL AND default_server_login IS NOT NULL))
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE free_registration_certificate (
|
||||||
|
data_item_id TEXT PRIMARY KEY,
|
||||||
|
login TEXT NOT NULL UNIQUE REFERENCES user_identity_current(login),
|
||||||
|
namespace TEXT NOT NULL REFERENCES shine_namespace_current(namespace),
|
||||||
|
email_sha256 BYTEA NOT NULL UNIQUE CHECK (octet_length(email_sha256) = 32),
|
||||||
|
inner_signature BYTEA NOT NULL CHECK (octet_length(inner_signature) = 64),
|
||||||
|
raw_signed_data_item BYTEA NOT NULL,
|
||||||
|
publication_status TEXT NOT NULL CHECK (publication_status IN ('TURBO_ACCEPTED','ARWEAVE_SEEN','ARWEAVE_CONFIRMED')),
|
||||||
|
registered_at_ms BIGINT NOT NULL,
|
||||||
|
last_seen_at_ms BIGINT NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX idx_free_registration_namespace ON free_registration_certificate(namespace);
|
||||||
|
|
||||||
|
-- Существующие объекты (в том числе десятки FK) должны ссылаться на логическую
|
||||||
|
-- идентичность, иначе бесплатный пользователь не сможет иметь профиль/связи/каналы.
|
||||||
|
-- Воссоздаём существующие FK с теми же ON DELETE/UPDATE и deferrable-настройками.
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
item RECORD;
|
||||||
|
definition TEXT;
|
||||||
|
BEGIN
|
||||||
|
FOR item IN SELECT c.conname, c.conrelid::regclass AS child_table,
|
||||||
|
pg_get_constraintdef(c.oid) AS definition
|
||||||
|
FROM pg_constraint c
|
||||||
|
WHERE c.contype = 'f' AND c.confrelid = 'solana_user_pda_current'::regclass
|
||||||
|
LOOP
|
||||||
|
definition := replace(item.definition,
|
||||||
|
'REFERENCES solana_user_pda_current(', 'REFERENCES user_identity_current(');
|
||||||
|
IF definition = item.definition THEN
|
||||||
|
RAISE EXCEPTION 'Unexpected FK expression: %', item.definition;
|
||||||
|
END IF;
|
||||||
|
EXECUTE format('ALTER TABLE %s DROP CONSTRAINT %I', item.child_table, item.conname);
|
||||||
|
EXECUTE format('ALTER TABLE %s ADD CONSTRAINT %I %s', item.child_table, item.conname, definition);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Любое поступившее из Solana состояние дополняет существующую идентичность.
|
||||||
|
-- Бесплатный → платный допускается ТОЛЬКО при совпадении всех публичных ключей;
|
||||||
|
-- старые on-chain key rotations разрешены, если статус уже платный.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
|
||||||
|
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', CASE WHEN old_user.free_data_item_id IS NOT NULL THEN 'PAID_UPGRADED' ELSE 'PAID_DIRECT' END,
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER trg_sync_identity_from_solana
|
||||||
|
BEFORE INSERT OR UPDATE ON solana_user_pda_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_sync_identity_from_solana();
|
||||||
|
|
||||||
|
-- Free namespace: сервер доступа задаётся namespace, а не клиентским полем.
|
||||||
|
-- Реальный сервер должен иметь on-chain PDA и открытый адрес.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF p_user_login IS NULL OR btrim(p_user_login) = '' THEN RETURN; END IF;
|
||||||
|
DELETE FROM user_access_servers_current WHERE lower(user_login) = lower(p_user_login);
|
||||||
|
INSERT INTO user_access_servers_current (
|
||||||
|
user_login, server_login, server_url, server_client_key, user_record_number,
|
||||||
|
user_updated_at_ms, server_record_number, server_updated_at_ms, refreshed_at_ms)
|
||||||
|
SELECT i.login, srv.login, srv.server_address, srv.client_key,
|
||||||
|
COALESCE(u.record_number, 0), i.updated_at_ms,
|
||||||
|
srv.record_number, srv.updated_at_ms,
|
||||||
|
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current u ON u.login = i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace = i.namespace
|
||||||
|
CROSS JOIN LATERAL (
|
||||||
|
SELECT CASE WHEN i.registration_status = 'FREE_CERT' THEN ns.default_server_login
|
||||||
|
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||||
|
COALESCE(NULLIF(u.access_servers_json, ''), '[]')::jsonb)
|
||||||
|
WITH ORDINALITY AS a(value, position) WHERE position=1) END AS login
|
||||||
|
) effective
|
||||||
|
JOIN solana_user_pda_current srv
|
||||||
|
ON lower(srv.login) = lower(effective.login) AND srv.is_server = true
|
||||||
|
AND btrim(coalesce(srv.server_address, '')) <> ''
|
||||||
|
WHERE lower(i.login) = lower(p_user_login)
|
||||||
|
ON CONFLICT (user_login, server_login) DO UPDATE SET
|
||||||
|
server_url=EXCLUDED.server_url, server_client_key=EXCLUDED.server_client_key,
|
||||||
|
user_record_number=EXCLUDED.user_record_number,
|
||||||
|
user_updated_at_ms=EXCLUDED.user_updated_at_ms,
|
||||||
|
server_record_number=EXCLUDED.server_record_number,
|
||||||
|
server_updated_at_ms=EXCLUDED.server_updated_at_ms,
|
||||||
|
refreshed_at_ms=EXCLUDED.refreshed_at_ms;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_server(p_server_login TEXT)
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE u RECORD;
|
||||||
|
BEGIN
|
||||||
|
IF p_server_login IS NULL OR btrim(p_server_login) = '' THEN RETURN; END IF;
|
||||||
|
DELETE FROM user_access_servers_current WHERE lower(server_login) = lower(p_server_login);
|
||||||
|
FOR u IN
|
||||||
|
SELECT i.login FROM user_identity_current i
|
||||||
|
LEFT JOIN solana_user_pda_current p ON p.login=i.login
|
||||||
|
LEFT JOIN shine_namespace_current ns ON ns.namespace=i.namespace
|
||||||
|
WHERE lower(p_server_login) = lower(
|
||||||
|
CASE WHEN i.registration_status='FREE_CERT' THEN ns.default_server_login
|
||||||
|
ELSE (SELECT value FROM jsonb_array_elements_text(
|
||||||
|
COALESCE(NULLIF(p.access_servers_json,''),'[]')::jsonb)
|
||||||
|
WITH ORDINALITY AS a(value, position) WHERE position=1) END)
|
||||||
|
LOOP PERFORM shine_refresh_user_access_servers_for_user(u.login); END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_all()
|
||||||
|
RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE u RECORD;
|
||||||
|
BEGIN
|
||||||
|
TRUNCATE TABLE user_access_servers_current;
|
||||||
|
FOR u IN SELECT login FROM user_identity_current LOOP
|
||||||
|
PERFORM shine_refresh_user_access_servers_for_user(u.login);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_refresh_free_routing_from_identity()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF NEW.registration_status = 'FREE_CERT' THEN
|
||||||
|
PERFORM shine_refresh_user_access_servers_for_user(NEW.login);
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
CREATE TRIGGER trg_refresh_free_routing_from_identity
|
||||||
|
AFTER INSERT OR UPDATE ON user_identity_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_refresh_free_routing_from_identity();
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version=33,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT) WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
-- SHiNE v34. Отдельный checkpoint Arweave сертификатов, не смешивать с блоками.
|
||||||
|
BEGIN;
|
||||||
|
CREATE TABLE IF NOT EXISTS free_registration_arweave_sync_state (
|
||||||
|
id SMALLINT PRIMARY KEY CHECK (id=1),
|
||||||
|
last_block_height BIGINT NOT NULL DEFAULT 0 CHECK (last_block_height>=0),
|
||||||
|
updated_at_ms BIGINT NOT NULL DEFAULT 0
|
||||||
|
);
|
||||||
|
INSERT INTO free_registration_arweave_sync_state (id,last_block_height,updated_at_ms)
|
||||||
|
VALUES (1,0,0) ON CONFLICT (id) DO NOTHING;
|
||||||
|
UPDATE db_schema_version SET schema_version=34,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT) WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
-- v35: один полноценный статус для всех зарегистрированных в Solana.
|
||||||
|
-- Старые регистрационные сертификаты Arweave и дата исходной регистрации сохраняются.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
-- Сначала снимаем старое ограничение, затем переводим существующие строки.
|
||||||
|
ALTER TABLE user_identity_current
|
||||||
|
DROP CONSTRAINT user_identity_current_registration_status_check;
|
||||||
|
UPDATE user_identity_current
|
||||||
|
SET registration_status = 'PAID'
|
||||||
|
WHERE registration_status IN ('PAID_DIRECT', 'PAID_UPGRADED');
|
||||||
|
ALTER TABLE user_identity_current
|
||||||
|
ADD CONSTRAINT user_identity_current_registration_status_check
|
||||||
|
CHECK (registration_status IN ('FREE_CERT', 'PAID'));
|
||||||
|
|
||||||
|
-- Важнее миграции существующих строк: при следующих Solana sync/upsert
|
||||||
|
-- и обычный платный, и ранее бесплатный пользователь получают тот же PAID.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
-- Если PostgreSQL получил старую запись из replay, она не должна затереть
|
||||||
|
-- уже принятую более новую логическую идентичность в BEFORE INSERT.
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID',
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version
|
||||||
|
SET schema_version=35,
|
||||||
|
updated_at_ms=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)
|
||||||
|
WHERE id=1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
-- v36: регистрационная запись хранит исходный регистр; все ссылки FK
|
||||||
|
-- приводятся к её точному login. Исторические строки не мигрируются.
|
||||||
|
-- На новой базе исходные имена PDA/сертификатов и FK согласованы.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_canonicalize_identity_fk_login()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE
|
||||||
|
field_name TEXT := TG_ARGV[0];
|
||||||
|
requested_login TEXT;
|
||||||
|
canonical_login TEXT;
|
||||||
|
BEGIN
|
||||||
|
requested_login := to_jsonb(NEW)->>field_name;
|
||||||
|
IF requested_login IS NULL OR btrim(requested_login) = '' THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT i.login INTO canonical_login
|
||||||
|
FROM user_identity_current i
|
||||||
|
WHERE i.normalized_login = lower(btrim(requested_login))
|
||||||
|
LIMIT 1;
|
||||||
|
IF canonical_login IS NOT NULL THEN
|
||||||
|
-- Меняем только проекцию/связь в SQL, никогда не байты подписанного блока.
|
||||||
|
NEW := jsonb_populate_record(NEW, jsonb_build_object(field_name, canonical_login));
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
tab_name TEXT;
|
||||||
|
col_name TEXT;
|
||||||
|
spec TEXT;
|
||||||
|
trigger_name TEXT;
|
||||||
|
BEGIN
|
||||||
|
FOREACH spec IN ARRAY ARRAY[
|
||||||
|
'user_access_servers_current:user_login',
|
||||||
|
'user_access_servers_current:server_login',
|
||||||
|
'active_sessions:login',
|
||||||
|
'esp_pairing_settings:login',
|
||||||
|
'esp_pairing_requests:login',
|
||||||
|
'users_params:login',
|
||||||
|
'user_settings:login',
|
||||||
|
'channel_read_state:viewer_login',
|
||||||
|
'test_free_avatar_uploads:login',
|
||||||
|
-- blockchain_state — compatibility view; trigger может существовать
|
||||||
|
-- только на физической таблице хранения.
|
||||||
|
'blockchain_state_store:login',
|
||||||
|
'user_stats_state:login',
|
||||||
|
'user_push_tokens:login',
|
||||||
|
'key_rotation_sessions:login'
|
||||||
|
] LOOP
|
||||||
|
tab_name := split_part(spec, ':', 1);
|
||||||
|
col_name := split_part(spec, ':', 2);
|
||||||
|
trigger_name := 'trg_canonical_identity_' || tab_name || '_' || col_name;
|
||||||
|
EXECUTE format('DROP TRIGGER IF EXISTS %I ON %I', trigger_name, tab_name);
|
||||||
|
EXECUTE format(
|
||||||
|
'CREATE TRIGGER %I BEFORE INSERT OR UPDATE OF %I ON %I FOR EACH ROW EXECUTE FUNCTION shine_canonicalize_identity_fk_login(%L)',
|
||||||
|
trigger_name, col_name, tab_name, col_name
|
||||||
|
);
|
||||||
|
END LOOP;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version = 36,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
-- v37: оригинальный регистр имени фиксируется при первой регистрации.
|
||||||
|
-- Нормализованное имя остаётся единственным ключом уникальности.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
CREATE OR REPLACE FUNCTION shine_identity_login_immutable()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'UPDATE' AND (NEW.login IS DISTINCT FROM OLD.login
|
||||||
|
OR NEW.normalized_login IS DISTINCT FROM OLD.normalized_login) THEN
|
||||||
|
RAISE EXCEPTION 'Registered login spelling is immutable: %', OLD.login;
|
||||||
|
END IF;
|
||||||
|
IF NEW.normalized_login IS DISTINCT FROM lower(btrim(NEW.login)) THEN
|
||||||
|
RAISE EXCEPTION 'normalized_login must match registered login: %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS trg_identity_login_immutable ON user_identity_current;
|
||||||
|
CREATE TRIGGER trg_identity_login_immutable
|
||||||
|
BEFORE INSERT OR UPDATE ON user_identity_current
|
||||||
|
FOR EACH ROW EXECUTE FUNCTION shine_identity_login_immutable();
|
||||||
|
|
||||||
|
-- FREE_CERT -> Solana: имя должно совпадать побайтно, включая регистр.
|
||||||
|
-- Источником имени остаётся первая регистрация, а не очередная синхронизация.
|
||||||
|
CREATE OR REPLACE FUNCTION shine_sync_identity_from_solana()
|
||||||
|
RETURNS TRIGGER LANGUAGE plpgsql AS $$
|
||||||
|
DECLARE old_user user_identity_current%ROWTYPE;
|
||||||
|
BEGIN
|
||||||
|
IF TG_OP = 'INSERT' AND EXISTS (
|
||||||
|
SELECT 1 FROM solana_user_pda_current prior
|
||||||
|
WHERE prior.pda_address = NEW.pda_address AND prior.record_number > NEW.record_number
|
||||||
|
) THEN
|
||||||
|
RETURN NEW;
|
||||||
|
END IF;
|
||||||
|
SELECT * INTO old_user FROM user_identity_current
|
||||||
|
WHERE normalized_login = NEW.normalized_login FOR UPDATE;
|
||||||
|
IF FOUND AND old_user.login <> NEW.login THEN
|
||||||
|
RAISE EXCEPTION 'Registered login case mismatch: % vs %', old_user.login, NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.registration_status = 'FREE_CERT' AND
|
||||||
|
(old_user.root_key <> NEW.root_key OR old_user.client_key <> NEW.client_key OR old_user.blockchain_key <> NEW.blockchain_key) THEN
|
||||||
|
RAISE EXCEPTION 'Free certificate keys differ from Solana upgrade for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
IF FOUND AND old_user.solana_pda_address IS NOT NULL AND old_user.solana_pda_address <> NEW.pda_address THEN
|
||||||
|
RAISE EXCEPTION 'Duplicate on-chain identity for %', NEW.login;
|
||||||
|
END IF;
|
||||||
|
INSERT INTO user_identity_current (
|
||||||
|
login, normalized_login, namespace, registration_source, registration_status,
|
||||||
|
solana_pda_address, free_data_item_id, root_key, client_key, blockchain_key,
|
||||||
|
blockchain_name, is_server, registered_at_ms, updated_at_ms)
|
||||||
|
VALUES (NEW.login, NEW.normalized_login,
|
||||||
|
CASE WHEN position('@' in NEW.login) > 0 THEN split_part(NEW.login,'@',2) ELSE NULL END,
|
||||||
|
'SOLANA', 'PAID',
|
||||||
|
NEW.pda_address, old_user.free_data_item_id, NEW.root_key, NEW.client_key,
|
||||||
|
NEW.blockchain_key, NEW.blockchain_name, NEW.is_server,
|
||||||
|
COALESCE(old_user.registered_at_ms, NEW.created_at_ms), NEW.updated_at_ms)
|
||||||
|
ON CONFLICT (login) DO UPDATE SET
|
||||||
|
registration_source='SOLANA',
|
||||||
|
registration_status=EXCLUDED.registration_status,
|
||||||
|
solana_pda_address=EXCLUDED.solana_pda_address,
|
||||||
|
root_key=EXCLUDED.root_key, client_key=EXCLUDED.client_key,
|
||||||
|
blockchain_key=EXCLUDED.blockchain_key, blockchain_name=EXCLUDED.blockchain_name,
|
||||||
|
is_server=EXCLUDED.is_server, updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
RETURN NEW;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
UPDATE db_schema_version SET schema_version = 37,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
COMMIT;
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
-- v38: blockchain_state_store.blockchain_key — runtime Base64(32).
|
||||||
|
-- Исторические Base58-значения нормализуются Java bootstrapper-ом,
|
||||||
|
-- поскольку PostgreSQL не содержит встроенного корректного Base58 decoder.
|
||||||
|
BEGIN;
|
||||||
|
|
||||||
|
UPDATE db_schema_version
|
||||||
|
SET schema_version = 38,
|
||||||
|
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
|
||||||
|
WHERE id = 1;
|
||||||
|
|
||||||
|
COMMIT;
|
||||||
@@ -2334,11 +2334,15 @@ CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_blo
|
|||||||
|
|
||||||
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
|
||||||
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
|
||||||
|
v_canonical_login TEXT;
|
||||||
BEGIN
|
BEGIN
|
||||||
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
|
||||||
|
-- В FK остаётся исходный регистр владельца, но поиск/сопоставления регистронезависимы.
|
||||||
|
SELECT login INTO v_canonical_login FROM user_identity_current WHERE normalized_login=lower(btrim(p_login)) LIMIT 1;
|
||||||
|
IF v_canonical_login IS NULL THEN RETURN; END IF;
|
||||||
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
|
||||||
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
|
||||||
SELECT p_login,
|
SELECT v_canonical_login,
|
||||||
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||||
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
|
||||||
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
|
||||||
@@ -2485,15 +2489,15 @@ DECLARE positive_rel_type INTEGER; channel_bch TEXT;
|
|||||||
BEGIN
|
BEGIN
|
||||||
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
|
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
|
||||||
DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=NEW.msg_sub_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
|
INSERT INTO connections_state(login,rel_type,to_login,to_block_number,to_block_hash)
|
||||||
VALUES(NEW.login,NEW.msg_sub_type,NEW.to_login,NEW.to_block_number,NEW.to_block_hash);
|
VALUES(lower(NEW.login),NEW.msg_sub_type,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash);
|
||||||
ELSE
|
ELSE
|
||||||
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
|
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
|
||||||
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=lower(NEW.login) AND rel_type=positive_rel_type AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
|
||||||
END IF;
|
END IF;
|
||||||
PERFORM shine_refresh_user_stats(NEW.login);
|
PERFORM shine_refresh_user_stats(lower(NEW.login));
|
||||||
PERFORM shine_refresh_user_stats(NEW.to_login);
|
PERFORM shine_refresh_user_stats(lower(NEW.to_login));
|
||||||
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
|
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
|
||||||
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
|
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
|
||||||
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
|
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
|
||||||
@@ -2506,22 +2510,22 @@ DECLARE previous_sub_type INTEGER;
|
|||||||
BEGIN
|
BEGIN
|
||||||
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
|
||||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash)
|
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash)
|
||||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
|
ON CONFLICT(to_login,to_block_number,to_block_hash) DO NOTHING;
|
||||||
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=NEW.login AND reaction_type=1 AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
SELECT last_sub_type INTO previous_sub_type FROM reactions_state WHERE from_login=lower(NEW.login) AND reaction_type=1 AND to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash LIMIT 1;
|
||||||
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
|
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
|
||||||
UPDATE message_stats SET likes_count=likes_count+1,
|
UPDATE message_stats SET likes_count=likes_count+1,
|
||||||
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
|
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
|
||||||
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
|
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
|
||||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
|
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
|
||||||
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
|
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
|
||||||
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
|
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
|
||||||
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
|
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
|
||||||
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
WHERE to_login=lower(NEW.to_login) AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
|
||||||
END IF;
|
END IF;
|
||||||
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
|
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
|
||||||
VALUES(NEW.login,1,NEW.to_login,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
VALUES(lower(NEW.login),1,lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
|
||||||
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
|
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
|
||||||
RETURN NEW;
|
RETURN NEW;
|
||||||
END $$;
|
END $$;
|
||||||
@@ -2532,7 +2536,7 @@ BEGIN
|
|||||||
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
|
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
|
||||||
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
|
||||||
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
|
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
|
||||||
VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash,1)
|
VALUES(lower(NEW.to_login),NEW.to_block_number,NEW.to_block_hash,1)
|
||||||
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
|
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
|
||||||
RETURN NEW;
|
RETURN NEW;
|
||||||
END $$;
|
END $$;
|
||||||
@@ -2658,6 +2662,15 @@ CREATE TABLE IF NOT EXISTS canonical_rebuild_staging (
|
|||||||
);
|
);
|
||||||
CREATE INDEX IF NOT EXISTS idx_canonical_rebuild_staging_login ON canonical_rebuild_staging(login,logical_block_number);
|
CREATE INDEX IF NOT EXISTS idx_canonical_rebuild_staging_login ON canonical_rebuild_staging(login,logical_block_number);
|
||||||
|
|
||||||
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,31,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
|
|
||||||
|
-- v32: триграммные индексы публичного поиска.
|
||||||
|
CREATE EXTENSION IF NOT EXISTS pg_trgm;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_display ON channel_names_state USING gin ((replace(lower(display_name), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_slug ON channel_names_state USING gin ((replace(lower(slug), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_names_search_owner ON channel_names_state USING gin ((replace(lower(owner_login), 'ё', 'е')) gin_trgm_ops) WHERE channel_type_code = 1 AND NOT is_deleted;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name ON user_profile_state USING gin ((replace(lower(coalesce(first_name, '') || ' ' || coalesce(last_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_user_profile_search_name_reverse ON user_profile_state USING gin ((replace(lower(coalesce(last_name, '') || ' ' || coalesce(first_name, '')), 'ё', 'е')) gin_trgm_ops);
|
||||||
|
|
||||||
|
INSERT INTO db_schema_version(id,schema_version,updated_at_ms) VALUES(1,32,CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT)) ON CONFLICT(id) DO UPDATE SET schema_version=EXCLUDED.schema_version,updated_at_ms=EXCLUDED.updated_at_ms;
|
||||||
|
|
||||||
COMMIT;
|
COMMIT;
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ dependencies {
|
|||||||
|
|
||||||
implementation project(':shine-server-crypto') // модуль сервера для работы с криптографией
|
implementation project(':shine-server-crypto') // модуль сервера для работы с криптографией
|
||||||
implementation project(':shine-server-blockchain') // модуль для работы с блокчейном
|
implementation project(':shine-server-blockchain') // модуль для работы с блокчейном
|
||||||
|
implementation project(':shine-server-solana-users-sync') // Нормализованный адрес PDA
|
||||||
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
implementation project(':shine-server-db') // модуль для работы с БД содержит и сущности из БД и саму работу с БД
|
||||||
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
implementation project(':shine-server-geo') // модуль для определения геолокации по IP
|
||||||
|
|
||||||
|
|||||||
+22
@@ -96,6 +96,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.Net_GetGroupDialog_Handle
|
|||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetChannelsCounters_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListGroupChats200_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListGroupChats200_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListSubscriptionsFeed_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_ListSubscriptionsFeed_Handler;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_SearchChannels_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetUserCounters_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_GetUserCounters_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.Net_SetChannelReadState_Handler;
|
import server.logic.ws_protocol.JSON.handlers.channels.Net_SetChannelReadState_Handler;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelsCounters_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetChannelsCounters_Request;
|
||||||
@@ -106,6 +107,7 @@ import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetMessageLi
|
|||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetPersonalDiary_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetPersonalDiary_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListGroupChats200_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_ListSubscriptionsFeed_Request;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_GetUserCounters_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SetChannelReadState_Request;
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SetChannelReadState_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.connections.Net_GetUserConnectionsGraph_Handler;
|
import server.logic.ws_protocol.JSON.handlers.connections.Net_GetUserConnectionsGraph_Handler;
|
||||||
@@ -167,6 +169,8 @@ import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ListBlockchain
|
|||||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
|
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_Ping_Request;
|
||||||
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
|
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ServerHello_Request;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Handler;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.registration.Net_Registration_Request;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -182,6 +186,15 @@ public final class JsonHandlerRegistry {
|
|||||||
private static final Map<String, JsonMessageHandler> HANDLERS = Map.ofEntries(
|
private static final Map<String, JsonMessageHandler> HANDLERS = Map.ofEntries(
|
||||||
Map.entry("GetUser", new Net_GetUser_Handler()),
|
Map.entry("GetUser", new Net_GetUser_Handler()),
|
||||||
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
Map.entry("SearchUsers", new Net_SearchUsers_Handler()),
|
||||||
|
Map.entry("SearchChannels", new Net_SearchChannels_Handler()),
|
||||||
|
|
||||||
|
// --- Registration V2: 6 согласованных публичных операций ---
|
||||||
|
Map.entry("GetNamespaces", new Net_Registration_Handler("GetNamespaces")),
|
||||||
|
Map.entry("CheckRegistrationLogin", new Net_Registration_Handler("CheckRegistrationLogin")),
|
||||||
|
Map.entry("CheckRegistrationEmail", new Net_Registration_Handler("CheckRegistrationEmail")),
|
||||||
|
Map.entry("StartFreeRegistration", new Net_Registration_Handler("StartFreeRegistration")),
|
||||||
|
Map.entry("ConfirmFreeRegistration", new Net_Registration_Handler("ConfirmFreeRegistration")),
|
||||||
|
Map.entry("GetRegistrationStatus", new Net_Registration_Handler("GetRegistrationStatus")),
|
||||||
|
|
||||||
// --- auth ---
|
// --- auth ---
|
||||||
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
Map.entry("ResolveLoginForAuth", new Net_ResolveLoginForAuth_Handler()),
|
||||||
@@ -286,6 +299,15 @@ public final class JsonHandlerRegistry {
|
|||||||
private static final Map<String, Class<? extends Net_Request>> REQUEST_TYPES = Map.ofEntries(
|
private static final Map<String, Class<? extends Net_Request>> REQUEST_TYPES = Map.ofEntries(
|
||||||
Map.entry("GetUser", Net_GetUser_Request.class),
|
Map.entry("GetUser", Net_GetUser_Request.class),
|
||||||
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
Map.entry("SearchUsers", Net_SearchUsers_Request.class),
|
||||||
|
Map.entry("SearchChannels", Net_SearchChannels_Request.class),
|
||||||
|
|
||||||
|
// --- Registration V2 ---
|
||||||
|
Map.entry("GetNamespaces", Net_Registration_Request.class),
|
||||||
|
Map.entry("CheckRegistrationLogin", Net_Registration_Request.class),
|
||||||
|
Map.entry("CheckRegistrationEmail", Net_Registration_Request.class),
|
||||||
|
Map.entry("StartFreeRegistration", Net_Registration_Request.class),
|
||||||
|
Map.entry("ConfirmFreeRegistration", Net_Registration_Request.class),
|
||||||
|
Map.entry("GetRegistrationStatus", Net_Registration_Request.class),
|
||||||
|
|
||||||
// --- auth ---
|
// --- auth ---
|
||||||
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
Map.entry("ResolveLoginForAuth", Net_ResolveLoginForAuth_Request.class),
|
||||||
|
|||||||
+12
-4
@@ -76,9 +76,12 @@ public final class JsonInboundProcessor {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// DEBUG: сырой вход (обрезаем, чтобы не убить лог)
|
// Не писать email, challenge и ключи в лог даже на DEBUG.
|
||||||
if (log.isDebugEnabled()) {
|
if (log.isDebugEnabled()) {
|
||||||
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId, shorten(json, 1200));
|
log.debug("JSON IN (login={}, sessionId={}): {}", ctxLogin, ctxSessionId,
|
||||||
|
json.contains("FreeRegistration") || json.contains("RegistrationEmail")
|
||||||
|
|| json.contains("RegistrationLogin") || json.contains("GetNamespaces")
|
||||||
|
|| json.contains("GetRegistrationStatus") ? "<registration payload redacted>" : shorten(json, 1200));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1) Парсим общий пакет
|
// 1) Парсим общий пакет
|
||||||
@@ -178,7 +181,7 @@ public final class JsonInboundProcessor {
|
|||||||
} catch (Exception mapErr) {
|
} catch (Exception mapErr) {
|
||||||
// Важно: вот это часто “теряется”, если не логировать отдельно
|
// Важно: вот это часто “теряется”, если не логировать отдельно
|
||||||
log.error("❌ JSON map error (op={}, requestId={}, login={}, sessionId={}): merged={}",
|
log.error("❌ JSON map error (op={}, requestId={}, login={}, sessionId={}): merged={}",
|
||||||
op, safe(requestId), ctxLogin, ctxSessionId, shorten(merged.toString(), 1200), mapErr);
|
op, safe(requestId), ctxLogin, ctxSessionId, "<redacted>", mapErr);
|
||||||
|
|
||||||
Net_Exception_Response err = NetExceptionResponseFactory.error(
|
Net_Exception_Response err = NetExceptionResponseFactory.error(
|
||||||
op,
|
op,
|
||||||
@@ -202,7 +205,7 @@ public final class JsonInboundProcessor {
|
|||||||
// DEBUG: нормализованный запрос (уже распарсен)
|
// DEBUG: нормализованный запрос (уже распарсен)
|
||||||
if (log.isDebugEnabled()) {
|
if (log.isDebugEnabled()) {
|
||||||
log.debug("REQ OBJ (login={}, sessionId={}, op={}, requestId={}): {}",
|
log.debug("REQ OBJ (login={}, sessionId={}, op={}, requestId={}): {}",
|
||||||
ctxLogin, ctxSessionId, safe(op), safe(requestId), shorten(safeToString(request), 1200));
|
ctxLogin, ctxSessionId, safe(op), safe(requestId), isRegistrationOperation(op) ? "<registration payload redacted>" : shorten(safeToString(request), 1200));
|
||||||
}
|
}
|
||||||
|
|
||||||
// REMOTE-пользователь успешно авторизован, но этот сервер не является
|
// REMOTE-пользователь успешно авторизован, но этот сервер не является
|
||||||
@@ -372,6 +375,11 @@ public final class JsonInboundProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static boolean isRegistrationOperation(String op) {
|
||||||
|
return op != null && (op.endsWith("Registration") || op.startsWith("CheckRegistration")
|
||||||
|
|| op.equals("GetNamespaces") || op.equals("GetRegistrationStatus"));
|
||||||
|
}
|
||||||
|
|
||||||
private static String safe(String s) {
|
private static String safe(String s) {
|
||||||
return s != null ? s : "";
|
return s != null ? s : "";
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-1
@@ -20,7 +20,10 @@ public final class RemoteUserOperationPolicy {
|
|||||||
"ClientErrorLog",
|
"ClientErrorLog",
|
||||||
"ClientDebugLog",
|
"ClientDebugLog",
|
||||||
"CloseActiveSession",
|
"CloseActiveSession",
|
||||||
"ResolveLoginForAuth"
|
"ResolveLoginForAuth",
|
||||||
|
// Публичный read-only поиск доступен и REMOTE-сессии.
|
||||||
|
"SearchChannels",
|
||||||
|
"SearchUsers"
|
||||||
);
|
);
|
||||||
|
|
||||||
private RemoteUserOperationPolicy() {}
|
private RemoteUserOperationPolicy() {}
|
||||||
|
|||||||
+22
-37
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import utils.config.SolanaProgramsConfig;
|
import utils.config.SolanaProgramsConfig;
|
||||||
|
import shine.db.dao.RegistrationIdentityDAO;
|
||||||
|
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
import java.net.http.HttpClient;
|
import java.net.http.HttpClient;
|
||||||
@@ -34,6 +35,10 @@ public final class SolanaUserPdaImportService {
|
|||||||
public static SessionTypeCheckResult checkSessionTypeAgainstPda(String loginRaw, String sessionKeyApi, int requestedSessionType) throws Exception {
|
public static SessionTypeCheckResult checkSessionTypeAgainstPda(String loginRaw, String sessionKeyApi, int requestedSessionType) throws Exception {
|
||||||
String login = normalizeLogin(loginRaw);
|
String login = normalizeLogin(loginRaw);
|
||||||
if (login == null) return SessionTypeCheckResult.noRecord();
|
if (login == null) return SessionTypeCheckResult.noRecord();
|
||||||
|
// У FREE_CERT нет Solana PDA. Это НЕ означает отсутствие идентичности:
|
||||||
|
// AuthChallenge и подпись clientKey уже проверяются через общий индекс.
|
||||||
|
RegistrationIdentityDAO.ResolvedIdentity identity = RegistrationIdentityDAO.getInstance().get(login);
|
||||||
|
if (identity != null && identity.isFree()) return SessionTypeCheckResult.noRecord();
|
||||||
|
|
||||||
ParsedSolanaUser parsed = fetchFromSolana(login);
|
ParsedSolanaUser parsed = fetchFromSolana(login);
|
||||||
if (parsed == null) return SessionTypeCheckResult.noRecord();
|
if (parsed == null) return SessionTypeCheckResult.noRecord();
|
||||||
@@ -103,54 +108,34 @@ public final class SolanaUserPdaImportService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private static byte[] fetchRawUserPda(String login) throws Exception {
|
private static byte[] fetchRawUserPda(String login) throws Exception {
|
||||||
String loginB58 = toBase58(login.getBytes(StandardCharsets.UTF_8));
|
// Запись хранит исходный регистр, но адрес PDA зависит только от lowercase.
|
||||||
String lenB58 = toBase58(new byte[]{(byte) login.length()});
|
String address = sync.util.SolanaPdaUtil.findUserPdaV2(login, SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID);
|
||||||
|
String reqJson = MAPPER.writeValueAsString(Map.of(
|
||||||
String reqJson = """
|
"jsonrpc", "2.0", "id", 1,
|
||||||
{
|
"method", "getAccountInfo",
|
||||||
"jsonrpc":"2.0",
|
"params", List.of(address, Map.of("encoding", "base64", "commitment", "confirmed"))));
|
||||||
"id":1,
|
|
||||||
"method":"getProgramAccounts",
|
|
||||||
"params":[
|
|
||||||
"%s",
|
|
||||||
{
|
|
||||||
"encoding":"base64",
|
|
||||||
"filters":[
|
|
||||||
{"memcmp":{"offset":61,"bytes":"%s"}},
|
|
||||||
{"memcmp":{"offset":62,"bytes":"%s"}}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
""".formatted(SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID, lenB58, loginB58);
|
|
||||||
|
|
||||||
HttpRequest req = HttpRequest.newBuilder()
|
HttpRequest req = HttpRequest.newBuilder()
|
||||||
.uri(URI.create(SolanaProgramsConfig.SOLANA_RPC_URL))
|
.uri(URI.create(SolanaProgramsConfig.SOLANA_RPC_URL))
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.POST(HttpRequest.BodyPublishers.ofString(reqJson))
|
.POST(HttpRequest.BodyPublishers.ofString(reqJson))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
HttpResponse<String> resp = HTTP.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
|
||||||
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
|
||||||
throw new IllegalStateException("Solana RPC HTTP status=" + resp.statusCode());
|
throw new IllegalStateException("Solana RPC HTTP status=" + resp.statusCode());
|
||||||
}
|
}
|
||||||
|
|
||||||
JsonNode root = MAPPER.readTree(resp.body());
|
JsonNode root = MAPPER.readTree(resp.body());
|
||||||
if (root.hasNonNull("error")) {
|
if (root.hasNonNull("error")) {
|
||||||
throw new IllegalStateException("Solana RPC error: " + root.get("error").toString());
|
throw new IllegalStateException("Solana RPC error: " + root.get("error"));
|
||||||
}
|
}
|
||||||
|
JsonNode account = root.path("result").path("value");
|
||||||
JsonNode result = root.path("result");
|
if (account.isMissingNode() || account.isNull()) return null;
|
||||||
if (!result.isArray() || result.isEmpty()) return null;
|
if (!SolanaProgramsConfig.SHINE_USERS_PROGRAM_ID.equals(account.path("owner").asText())) {
|
||||||
|
throw new IllegalStateException("PDA принадлежит другой программе");
|
||||||
for (JsonNode item : result) {
|
|
||||||
JsonNode dataNode = item.path("account").path("data");
|
|
||||||
if (!dataNode.isArray() || dataNode.size() < 1) continue;
|
|
||||||
String b64 = dataNode.get(0).asText("");
|
|
||||||
if (b64.isBlank()) continue;
|
|
||||||
return Base64.getDecoder().decode(b64);
|
|
||||||
}
|
}
|
||||||
return null;
|
JsonNode data = account.path("data");
|
||||||
|
if (!data.isArray() || data.isEmpty()) return null;
|
||||||
|
String b64 = data.get(0).asText("");
|
||||||
|
return b64.isBlank() ? null : Base64.getDecoder().decode(b64);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ParsedSolanaUser parseUserPda(byte[] raw) {
|
private static ParsedSolanaUser parseUserPda(byte[] raw) {
|
||||||
@@ -253,7 +238,7 @@ public final class SolanaUserPdaImportService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
|
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
|
||||||
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
String blockchainName = normalizeLogin(login) + "-" + String.format(Locale.ROOT, "%03d", forkCount);
|
||||||
return new ParsedSolanaUser(
|
return new ParsedSolanaUser(
|
||||||
login,
|
login,
|
||||||
blockchainName,
|
blockchainName,
|
||||||
@@ -360,7 +345,7 @@ public final class SolanaUserPdaImportService {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Нужен для memcmp.bytes в Solana RPC.
|
// Вспомогательная base58-конверсия для других совместимых полей.
|
||||||
private static String toBase58(byte[] input) {
|
private static String toBase58(byte[] input) {
|
||||||
final char[] alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
final char[] alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
|
||||||
int zeros = 0;
|
int zeros = 0;
|
||||||
|
|||||||
+47
-2
@@ -37,11 +37,13 @@ import shine.db.dao.BlockchainStateDAO;
|
|||||||
import shine.db.dao.BlocksDAO;
|
import shine.db.dao.BlocksDAO;
|
||||||
import shine.db.dao.CanonicalChainResolver;
|
import shine.db.dao.CanonicalChainResolver;
|
||||||
import shine.db.dao.ChannelNameStateDAO;
|
import shine.db.dao.ChannelNameStateDAO;
|
||||||
|
import shine.db.dao.CurrentUsersDAO;
|
||||||
import shine.db.dao.UserNotificationsStateDAO;
|
import shine.db.dao.UserNotificationsStateDAO;
|
||||||
import shine.db.dao.UserParamsDAO;
|
import shine.db.dao.UserParamsDAO;
|
||||||
import shine.db.entities.BlockchainStateEntry;
|
import shine.db.entities.BlockchainStateEntry;
|
||||||
import shine.db.entities.BlockEntry;
|
import shine.db.entities.BlockEntry;
|
||||||
import shine.db.entities.ChannelNameStateEntry;
|
import shine.db.entities.ChannelNameStateEntry;
|
||||||
|
import shine.db.entities.CurrentUserEntry;
|
||||||
import shine.db.entities.UserNotificationEntry;
|
import shine.db.entities.UserNotificationEntry;
|
||||||
import shine.db.entities.UserParamEntry;
|
import shine.db.entities.UserParamEntry;
|
||||||
import utils.blockchain.BlockchainNameUtil;
|
import utils.blockchain.BlockchainNameUtil;
|
||||||
@@ -68,6 +70,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
|
||||||
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
|
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
|
||||||
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
|
||||||
|
private final CurrentUsersDAO currentUsersDAO = CurrentUsersDAO.getInstance();
|
||||||
private final UserParamsDAO userParamsDAO = UserParamsDAO.getInstance();
|
private final UserParamsDAO userParamsDAO = UserParamsDAO.getInstance();
|
||||||
private final ChannelNameStateDAO channelNameStateDAO = ChannelNameStateDAO.getInstance();
|
private final ChannelNameStateDAO channelNameStateDAO = ChannelNameStateDAO.getInstance();
|
||||||
|
|
||||||
@@ -202,6 +205,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
|
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
|
||||||
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
|
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
|
||||||
case "bad_block_body" -> "Некорректное тело блока";
|
case "bad_block_body" -> "Некорректное тело блока";
|
||||||
|
case "header_login_mismatch" -> "HEADER должен содержать имя точно в регистре регистрации";
|
||||||
|
case "header_identity_lookup_failed" -> "Не удалось проверить регистрационное имя HEADER";
|
||||||
case "bad_channel_name" -> "Некорректное название канала";
|
case "bad_channel_name" -> "Некорректное название канала";
|
||||||
case "bad_block_number" -> "Некорректный номер блока";
|
case "bad_block_number" -> "Некорректный номер блока";
|
||||||
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
|
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
|
||||||
@@ -255,7 +260,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 1) state обязателен
|
// 1) state обязателен
|
||||||
final BlockchainStateEntry st;
|
BlockchainStateEntry st;
|
||||||
try {
|
try {
|
||||||
st = stateDAO.getByBlockchainName(blockchainName);
|
st = stateDAO.getByBlockchainName(blockchainName);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -264,6 +269,37 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
|
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (st == null) {
|
||||||
|
// Runtime-проекция могла отсутствовать у пользователей, зарегистрированных
|
||||||
|
// ранней версией free-регистрации. Восстанавливаем только для точно
|
||||||
|
// существующего владельца этой цепочки; сам блок всё равно проходит
|
||||||
|
// полную проверку ключа и подписи ниже.
|
||||||
|
try {
|
||||||
|
CurrentUserEntry user = currentUsersDAO.getByBlockchainName(blockchainName);
|
||||||
|
if (user != null) {
|
||||||
|
BlockchainStateEntry recovered = new BlockchainStateEntry();
|
||||||
|
recovered.setBlockchainName(user.getBlockchainName());
|
||||||
|
recovered.setLogin(user.getLogin());
|
||||||
|
recovered.setBlockchainKey(user.getBlockchainKey());
|
||||||
|
recovered.setSizeLimit(100_000L);
|
||||||
|
recovered.setFileSizeBytes(0L);
|
||||||
|
recovered.setLastBlockNumber(-1);
|
||||||
|
recovered.setLastBlockHash(new byte[32]);
|
||||||
|
recovered.setUpdatedAtMs(System.currentTimeMillis());
|
||||||
|
stateDAO.insertIfMissing(recovered);
|
||||||
|
st = stateDAO.getByBlockchainName(blockchainName);
|
||||||
|
if (st != null) {
|
||||||
|
log.warn("AddBlock: восстановлена отсутствующая blockchain_state для login={}, blockchainName={}",
|
||||||
|
user.getLogin(), blockchainName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("AddBlock: не удалось восстановить blockchain_state (login={}, blockchainName={})",
|
||||||
|
login, blockchainName, e);
|
||||||
|
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error", 0, "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (st == null) {
|
if (st == null) {
|
||||||
log.warn("AddBlock: blockchain_state_not_found (login={}, blockchainName={}, reqGlobalNumber={})",
|
log.warn("AddBlock: blockchain_state_not_found (login={}, blockchainName={}, reqGlobalNumber={})",
|
||||||
login, blockchainName, globalNumberFromReq);
|
login, blockchainName, globalNumberFromReq);
|
||||||
@@ -351,9 +387,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
|
|||||||
if (!(block.body instanceof HeaderBody headerBody)) {
|
if (!(block.body instanceof HeaderBody headerBody)) {
|
||||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_required_as_block_zero", serverLastNum, serverLastHashHex);
|
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_required_as_block_zero", serverLastNum, serverLastHashHex);
|
||||||
}
|
}
|
||||||
if (!login.equals(headerBody.login)) {
|
// HEADER фиксирует написание из регистрационной записи, а не lower-case имя цепочки.
|
||||||
|
// Проверка точная: другой регистр не может создать альтернативное "официальное" имя.
|
||||||
|
try {
|
||||||
|
CurrentUserEntry registeredOwner = currentUsersDAO.getByLogin(login);
|
||||||
|
if (registeredOwner == null || !headerBody.login.equals(registeredOwner.getLogin())
|
||||||
|
|| !login.equalsIgnoreCase(registeredOwner.getLogin())) {
|
||||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
|
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
|
||||||
}
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("AddBlock: cannot verify registered HEADER login for {}", blockchainName, e);
|
||||||
|
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "header_identity_lookup_failed", serverLastNum, serverLastHashHex);
|
||||||
|
}
|
||||||
} else if (block.body instanceof HeaderBody) {
|
} else if (block.body instanceof HeaderBody) {
|
||||||
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_must_be_block_zero", serverLastNum, serverLastHashHex);
|
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_must_be_block_zero", serverLastNum, serverLastHashHex);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-4
@@ -13,10 +13,10 @@ import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
|||||||
import server.logic.ws_protocol.WireCodes;
|
import server.logic.ws_protocol.WireCodes;
|
||||||
import shine.db.dao.BlockchainStateDAO;
|
import shine.db.dao.BlockchainStateDAO;
|
||||||
import shine.db.dao.CanonicalChainResolver;
|
import shine.db.dao.CanonicalChainResolver;
|
||||||
import shine.db.dao.SolanaUserPdaCurrentDAO;
|
import shine.db.dao.CurrentUsersDAO;
|
||||||
import shine.db.entities.BlockEntry;
|
import shine.db.entities.BlockEntry;
|
||||||
import shine.db.entities.BlockchainStateEntry;
|
import shine.db.entities.BlockchainStateEntry;
|
||||||
import shine.db.entities.SolanaUserPdaCurrentEntry;
|
import shine.db.entities.CurrentUserEntry;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Collections;
|
import java.util.Collections;
|
||||||
@@ -26,7 +26,7 @@ import java.util.List;
|
|||||||
public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
|
public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
|
||||||
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
|
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
|
||||||
private final BlockchainStateDAO states = BlockchainStateDAO.getInstance();
|
private final BlockchainStateDAO states = BlockchainStateDAO.getInstance();
|
||||||
private final SolanaUserPdaCurrentDAO users = SolanaUserPdaCurrentDAO.getInstance();
|
private final CurrentUsersDAO users = CurrentUsersDAO.getInstance();
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
|
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
|
||||||
@@ -36,7 +36,7 @@ public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
SolanaUserPdaCurrentEntry user = users.getByLogin(login);
|
CurrentUserEntry user = users.getByLogin(login);
|
||||||
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
|
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 404, "BLOCKCHAIN_NOT_FOUND", "Текущий блокчейн пользователя не найден");
|
return NetExceptionResponseFactory.error(req, 404, "BLOCKCHAIN_NOT_FOUND", "Текущий блокчейн пользователя не найден");
|
||||||
}
|
}
|
||||||
|
|||||||
+15
@@ -16,6 +16,8 @@ import java.sql.SQLException;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
final class ChannelsReadSupport {
|
final class ChannelsReadSupport {
|
||||||
static final int MSG_TYPE_TEXT = 1;
|
static final int MSG_TYPE_TEXT = 1;
|
||||||
@@ -39,6 +41,19 @@ final class ChannelsReadSupport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Пользовательское отображение — из реестра, не из normalized blocks.login.
|
||||||
|
// Кэш ограничен временем одного ответа и не требует дополнительных запросов на каждый пост.
|
||||||
|
static String officialLogin(Connection c, Map<String, String> cache, String raw) throws SQLException {
|
||||||
|
if (raw == null || raw.isBlank()) return raw;
|
||||||
|
String key = raw.trim().toLowerCase(Locale.ROOT);
|
||||||
|
String value = cache.get(key);
|
||||||
|
if (value != null) return value;
|
||||||
|
value = canonicalLogin(c, raw);
|
||||||
|
if (value == null || value.isBlank()) value = raw;
|
||||||
|
cache.put(key, value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException {
|
static ChannelMeta detectChannelMeta(Connection c, String ownerBch, int rootNumber) throws SQLException {
|
||||||
ChannelMeta meta = new ChannelMeta();
|
ChannelMeta meta = new ChannelMeta();
|
||||||
meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF;
|
meta.channelTypeVersion = CreateChannelBody.CHANNEL_TYPE_VERSION_DEFAULT & 0xFFFF;
|
||||||
|
|||||||
+6
-3
@@ -20,6 +20,8 @@ import java.sql.PreparedStatement;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
||||||
private static final Logger log = LoggerFactory.getLogger(Net_GetChannelMessages_Handler.class);
|
private static final Logger log = LoggerFactory.getLogger(Net_GetChannelMessages_Handler.class);
|
||||||
@@ -44,6 +46,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
boolean asc = req.getSort() == null || !"desc".equalsIgnoreCase(req.getSort());
|
boolean asc = req.getSort() == null || !"desc".equalsIgnoreCase(req.getSort());
|
||||||
|
|
||||||
try (Connection c = DbController.getInstance().getConnection()) {
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
Map<String, String> officialLogins = new HashMap<>();
|
||||||
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
||||||
if (viewerLogin == null || viewerLogin.isBlank()) {
|
if (viewerLogin == null || viewerLogin.isBlank()) {
|
||||||
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
||||||
@@ -58,7 +61,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
Net_GetChannelMessages_Response.Channel channel = new Net_GetChannelMessages_Response.Channel();
|
Net_GetChannelMessages_Response.Channel channel = new Net_GetChannelMessages_Response.Channel();
|
||||||
channel.setOwnerBlockchainName(ownerBch);
|
channel.setOwnerBlockchainName(ownerBch);
|
||||||
channel.setOwnerLogin(BlockchainNameUtil.loginFromBlockchainName(ownerBch));
|
channel.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, BlockchainNameUtil.loginFromBlockchainName(ownerBch)));
|
||||||
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, ownerBch, lineCode);
|
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, ownerBch, lineCode);
|
||||||
channel.setChannelName(meta.channelName);
|
channel.setChannelName(meta.channelName);
|
||||||
channel.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
channel.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
||||||
@@ -88,7 +91,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
eventRef.setBlockNumber(event.blockNumber);
|
eventRef.setBlockNumber(event.blockNumber);
|
||||||
eventRef.setBlockHash(ChannelsReadSupport.toHex(event.blockHash));
|
eventRef.setBlockHash(ChannelsReadSupport.toHex(event.blockHash));
|
||||||
outEvent.setMessageRef(eventRef);
|
outEvent.setMessageRef(eventRef);
|
||||||
outEvent.setAuthorLogin(event.login);
|
outEvent.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, event.login));
|
||||||
outEvent.setAuthorBlockchainName(event.bchName);
|
outEvent.setAuthorBlockchainName(event.bchName);
|
||||||
outEvent.setLineStep(event.lineStep);
|
outEvent.setLineStep(event.lineStep);
|
||||||
outEvent.setCreatedAtMs(event.createdAtMs);
|
outEvent.setCreatedAtMs(event.createdAtMs);
|
||||||
@@ -133,7 +136,7 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
|
|||||||
msgRef.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
msgRef.setBlockHash(ChannelsReadSupport.toHex(post.blockHash));
|
||||||
item.setMessageRef(msgRef);
|
item.setMessageRef(msgRef);
|
||||||
item.setMsgSubType(post.msgSubType);
|
item.setMsgSubType(post.msgSubType);
|
||||||
item.setAuthorLogin(post.login);
|
item.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, post.login));
|
||||||
item.setAuthorBlockchainName(post.bchName);
|
item.setAuthorBlockchainName(post.bchName);
|
||||||
item.setLineStep(post.thisLineNumber);
|
item.setLineStep(post.thisLineNumber);
|
||||||
item.setTargetBlockchainName(post.toBchName);
|
item.setTargetBlockchainName(post.toBchName);
|
||||||
|
|||||||
+11
-8
@@ -21,6 +21,8 @@ import java.util.Comparator;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.Base64;
|
import java.util.Base64;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.HashMap;
|
||||||
|
|
||||||
public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
||||||
private static final Logger log = LoggerFactory.getLogger(Net_GetMessageThread_Handler.class);
|
private static final Logger log = LoggerFactory.getLogger(Net_GetMessageThread_Handler.class);
|
||||||
@@ -37,6 +39,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
int childLimit = req.getLimitChildrenPerNode() == null ? 50 : Math.max(1, req.getLimitChildrenPerNode());
|
int childLimit = req.getLimitChildrenPerNode() == null ? 50 : Math.max(1, req.getLimitChildrenPerNode());
|
||||||
|
|
||||||
try (Connection c = DbController.getInstance().getConnection()) {
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
Map<String, String> officialLogins = new HashMap<>();
|
||||||
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
String viewerLogin = ctx != null ? ctx.getLogin() : null;
|
||||||
if (viewerLogin == null || viewerLogin.isBlank()) {
|
if (viewerLogin == null || viewerLogin.isBlank()) {
|
||||||
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
viewerLogin = ChannelsReadSupport.canonicalLogin(c, req.getLogin());
|
||||||
@@ -51,7 +54,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
resp.setRequestId(req.getRequestId());
|
resp.setRequestId(req.getRequestId());
|
||||||
resp.setStatus(WireCodes.Status.OK);
|
resp.setStatus(WireCodes.Status.OK);
|
||||||
|
|
||||||
resp.setFocus(toNode(c, focusRow, viewerLogin));
|
resp.setFocus(toNode(c, focusRow, viewerLogin, officialLogins));
|
||||||
|
|
||||||
List<Net_GetMessageThread_Response.MessageNode> ancestors = new ArrayList<>();
|
List<Net_GetMessageThread_Response.MessageNode> ancestors = new ArrayList<>();
|
||||||
PostRow cur = focusRow;
|
PostRow cur = focusRow;
|
||||||
@@ -68,12 +71,12 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
|
parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
|
||||||
}
|
}
|
||||||
if (parent == null) break;
|
if (parent == null) break;
|
||||||
ancestors.add(0, toNode(c, parent, viewerLogin));
|
ancestors.add(0, toNode(c, parent, viewerLogin, officialLogins));
|
||||||
cur = parent;
|
cur = parent;
|
||||||
}
|
}
|
||||||
resp.setAncestors(ancestors);
|
resp.setAncestors(ancestors);
|
||||||
|
|
||||||
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin));
|
resp.setDescendants(loadChildren(c, focusRow, depthDown, childLimit, viewerLogin, officialLogins));
|
||||||
return resp;
|
return resp;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("GetMessageThread failed", e);
|
log.error("GetMessageThread failed", e);
|
||||||
@@ -97,14 +100,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin) throws Exception {
|
private List<Net_GetMessageThread_Response.MessageNodeTree> loadChildren(Connection c, PostRow parent, int depthDown, int childLimit, String viewerLogin, Map<String, String> officialLogins) throws Exception {
|
||||||
if (depthDown <= 0) return List.of();
|
if (depthDown <= 0) return List.of();
|
||||||
List<PostRow> replies = findRepliesAndRatings(c, parent.bchName, parent.blockNumber, parent.blockHash, childLimit);
|
List<PostRow> replies = findRepliesAndRatings(c, parent.bchName, parent.blockNumber, parent.blockHash, childLimit);
|
||||||
List<Net_GetMessageThread_Response.MessageNodeTree> out = new ArrayList<>();
|
List<Net_GetMessageThread_Response.MessageNodeTree> out = new ArrayList<>();
|
||||||
for (PostRow row : replies) {
|
for (PostRow row : replies) {
|
||||||
Net_GetMessageThread_Response.MessageNodeTree t = new Net_GetMessageThread_Response.MessageNodeTree();
|
Net_GetMessageThread_Response.MessageNodeTree t = new Net_GetMessageThread_Response.MessageNodeTree();
|
||||||
t.setNode(toNode(c, row, viewerLogin));
|
t.setNode(toNode(c, row, viewerLogin, officialLogins));
|
||||||
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin));
|
t.setChildren(loadChildren(c, row, depthDown - 1, childLimit, viewerLogin, officialLogins));
|
||||||
out.add(t);
|
out.add(t);
|
||||||
}
|
}
|
||||||
return out;
|
return out;
|
||||||
@@ -233,14 +236,14 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
|
|||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin) throws Exception {
|
private Net_GetMessageThread_Response.MessageNode toNode(Connection c, PostRow row, String viewerLogin, Map<String, String> officialLogins) throws Exception {
|
||||||
Net_GetMessageThread_Response.MessageNode node = new Net_GetMessageThread_Response.MessageNode();
|
Net_GetMessageThread_Response.MessageNode node = new Net_GetMessageThread_Response.MessageNode();
|
||||||
Net_GetChannelMessages_Response.BlockRef ref = new Net_GetChannelMessages_Response.BlockRef();
|
Net_GetChannelMessages_Response.BlockRef ref = new Net_GetChannelMessages_Response.BlockRef();
|
||||||
ref.setBlockNumber(row.blockNumber);
|
ref.setBlockNumber(row.blockNumber);
|
||||||
ref.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
ref.setBlockHash(ChannelsReadSupport.toHex(row.blockHash));
|
||||||
node.setMessageRef(ref);
|
node.setMessageRef(ref);
|
||||||
node.setMsgSubType(row.msgSubType);
|
node.setMsgSubType(row.msgSubType);
|
||||||
node.setAuthorLogin(row.login);
|
node.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, row.login));
|
||||||
node.setAuthorBlockchainName(row.bchName);
|
node.setAuthorBlockchainName(row.bchName);
|
||||||
node.setLineStep(row.thisLineNumber);
|
node.setLineStep(row.thisLineNumber);
|
||||||
node.setTargetBlockchainName(row.toBchName);
|
node.setTargetBlockchainName(row.toBchName);
|
||||||
|
|||||||
+5
-2
@@ -19,6 +19,8 @@ import java.sql.PreparedStatement;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
||||||
private static final Logger log = LoggerFactory.getLogger(Net_ListSubscriptionsFeed_Handler.class);
|
private static final Logger log = LoggerFactory.getLogger(Net_ListSubscriptionsFeed_Handler.class);
|
||||||
@@ -59,11 +61,12 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
private List<Net_ListSubscriptionsFeed_Response.ChannelSummary> buildSummaries(Connection c, String viewerLogin, List<ChannelKey> keys) throws Exception {
|
private List<Net_ListSubscriptionsFeed_Response.ChannelSummary> buildSummaries(Connection c, String viewerLogin, List<ChannelKey> keys) throws Exception {
|
||||||
List<Net_ListSubscriptionsFeed_Response.ChannelSummary> out = new ArrayList<>();
|
List<Net_ListSubscriptionsFeed_Response.ChannelSummary> out = new ArrayList<>();
|
||||||
|
Map<String, String> officialLogins = new HashMap<>();
|
||||||
for (ChannelKey key : keys) {
|
for (ChannelKey key : keys) {
|
||||||
Net_ListSubscriptionsFeed_Response.ChannelSummary row = new Net_ListSubscriptionsFeed_Response.ChannelSummary();
|
Net_ListSubscriptionsFeed_Response.ChannelSummary row = new Net_ListSubscriptionsFeed_Response.ChannelSummary();
|
||||||
Net_ListSubscriptionsFeed_Response.ChannelRef channelRef = new Net_ListSubscriptionsFeed_Response.ChannelRef();
|
Net_ListSubscriptionsFeed_Response.ChannelRef channelRef = new Net_ListSubscriptionsFeed_Response.ChannelRef();
|
||||||
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, key.ownerBch, key.rootNumber);
|
ChannelsReadSupport.ChannelMeta meta = ChannelsReadSupport.detectChannelMeta(c, key.ownerBch, key.rootNumber);
|
||||||
channelRef.setOwnerLogin(key.ownerLogin);
|
channelRef.setOwnerLogin(ChannelsReadSupport.officialLogin(c, officialLogins, key.ownerLogin));
|
||||||
channelRef.setOwnerBlockchainName(key.ownerBch);
|
channelRef.setOwnerBlockchainName(key.ownerBch);
|
||||||
channelRef.setChannelName(meta.channelName);
|
channelRef.setChannelName(meta.channelName);
|
||||||
channelRef.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
channelRef.setDisplayName(meta.displayName == null || meta.displayName.isBlank() ? meta.channelName : meta.displayName);
|
||||||
@@ -108,7 +111,7 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
|
|||||||
lm.setMessageRef(msgRef);
|
lm.setMessageRef(msgRef);
|
||||||
lm.setText(textInfo.text);
|
lm.setText(textInfo.text);
|
||||||
lm.setCreatedAtMs(textInfo.createdAtMs);
|
lm.setCreatedAtMs(textInfo.createdAtMs);
|
||||||
lm.setAuthorLogin(actual.login);
|
lm.setAuthorLogin(ChannelsReadSupport.officialLogin(c, officialLogins, actual.login));
|
||||||
lm.setAuthorBlockchainName(actual.bchName);
|
lm.setAuthorBlockchainName(actual.bchName);
|
||||||
row.setLastMessage(lm);
|
row.setLastMessage(lm);
|
||||||
}
|
}
|
||||||
|
|||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.channels;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Request;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.channels.entyties.Net_SearchChannels_Response;
|
||||||
|
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||||
|
import server.logic.ws_protocol.WireCodes;
|
||||||
|
import shine.db.DbController;
|
||||||
|
import shine.db.dao.ChannelSearchDAO;
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Net_SearchChannels_Handler implements JsonMessageHandler {
|
||||||
|
@Override
|
||||||
|
public Net_Response handle(Net_Request base, ConnectionContext ctx) {
|
||||||
|
Net_SearchChannels_Request req = (Net_SearchChannels_Request) base;
|
||||||
|
String query = req.getQuery() == null ? "" : req.getQuery().trim();
|
||||||
|
String owner = req.getOwnerLogin() == null ? "" : req.getOwnerLogin().trim();
|
||||||
|
if ((query.isEmpty() && owner.isEmpty()) || query.equals("@") || query.startsWith("/")
|
||||||
|
|| query.startsWith("@/") || query.length() > 120 || owner.length() > 80
|
||||||
|
|| (req.getLimit() != null && (req.getLimit() < 1 || req.getLimit() > 50))) {
|
||||||
|
return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST,
|
||||||
|
"BAD_FIELDS", "Нужен query или ownerLogin; limit от 1 до 50; длина query до 120 символов.");
|
||||||
|
}
|
||||||
|
int limit = req.getLimit() == null ? 10 : req.getLimit();
|
||||||
|
try (Connection c = DbController.getInstance().getConnection()) {
|
||||||
|
List<Net_SearchChannels_Response.ChannelItem> channels = new ArrayList<>();
|
||||||
|
for (var match : ChannelSearchDAO.search(c, query, owner, limit)) {
|
||||||
|
var item = new Net_SearchChannels_Response.ChannelItem();
|
||||||
|
item.setOwnerLogin(match.ownerLogin()); item.setSlug(match.slug());
|
||||||
|
item.setDisplayName(match.displayName()); item.setDescription(match.description());
|
||||||
|
item.setAvatarAr(match.avatarAr()); item.setAvatarSha256(match.avatarSha256());
|
||||||
|
item.setOwnerBlockchainName(match.ownerBlockchainName());
|
||||||
|
item.setRootBlockNumber(match.rootBlockNumber()); item.setRootBlockHashHex(match.rootBlockHashHex());
|
||||||
|
item.setSubscribersCount(match.subscribersCount());
|
||||||
|
channels.add(item);
|
||||||
|
}
|
||||||
|
var resp = new Net_SearchChannels_Response();
|
||||||
|
resp.setOp(req.getOp()); resp.setRequestId(req.getRequestId());
|
||||||
|
resp.setStatus(WireCodes.Status.OK); resp.setChannels(channels);
|
||||||
|
return resp;
|
||||||
|
} catch (SQLException e) {
|
||||||
|
return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR,
|
||||||
|
"DB_ERROR", "Ошибка БД при поиске каналов");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||||
|
|
||||||
|
/** Поиск публичных каналов по названию, slug и логину владельца. */
|
||||||
|
public class Net_SearchChannels_Request extends Net_Request {
|
||||||
|
private String query;
|
||||||
|
private String ownerLogin;
|
||||||
|
private Integer limit;
|
||||||
|
|
||||||
|
public String getQuery() { return query; }
|
||||||
|
public void setQuery(String query) { this.query = query; }
|
||||||
|
public String getOwnerLogin() { return ownerLogin; }
|
||||||
|
public void setOwnerLogin(String ownerLogin) { this.ownerLogin = ownerLogin; }
|
||||||
|
public Integer getLimit() { return limit; }
|
||||||
|
public void setLimit(Integer limit) { this.limit = limit; }
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.channels.entyties;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class Net_SearchChannels_Response extends Net_Response {
|
||||||
|
private List<ChannelItem> channels = new ArrayList<>();
|
||||||
|
public List<ChannelItem> getChannels() { return channels; }
|
||||||
|
public void setChannels(List<ChannelItem> channels) { this.channels = channels; }
|
||||||
|
|
||||||
|
public static class ChannelItem {
|
||||||
|
private String ownerLogin, slug, displayName, description, avatarAr, avatarSha256,
|
||||||
|
ownerBlockchainName, rootBlockHashHex;
|
||||||
|
private int rootBlockNumber, subscribersCount;
|
||||||
|
public String getOwnerLogin() { return ownerLogin; }
|
||||||
|
public void setOwnerLogin(String v) { ownerLogin = v; }
|
||||||
|
public String getSlug() { return slug; }
|
||||||
|
public void setSlug(String v) { slug = v; }
|
||||||
|
public String getDisplayName() { return displayName; }
|
||||||
|
public void setDisplayName(String v) { displayName = v; }
|
||||||
|
public String getDescription() { return description; }
|
||||||
|
public void setDescription(String v) { description = v; }
|
||||||
|
public String getAvatarAr() { return avatarAr; }
|
||||||
|
public void setAvatarAr(String v) { avatarAr = v; }
|
||||||
|
public String getAvatarSha256() { return avatarSha256; }
|
||||||
|
public void setAvatarSha256(String v) { avatarSha256 = v; }
|
||||||
|
public String getOwnerBlockchainName() { return ownerBlockchainName; }
|
||||||
|
public void setOwnerBlockchainName(String v) { ownerBlockchainName = v; }
|
||||||
|
public int getRootBlockNumber() { return rootBlockNumber; }
|
||||||
|
public void setRootBlockNumber(int v) { rootBlockNumber = v; }
|
||||||
|
public String getRootBlockHashHex() { return rootBlockHashHex; }
|
||||||
|
public void setRootBlockHashHex(String v) { rootBlockHashHex = v; }
|
||||||
|
public int getSubscribersCount() { return subscribersCount; }
|
||||||
|
public void setSubscribersCount(int v) { subscribersCount = v; }
|
||||||
|
}
|
||||||
|
}
|
||||||
+17
@@ -11,6 +11,23 @@ import java.util.Base64;
|
|||||||
final class KeyRotationApiSupport {
|
final class KeyRotationApiSupport {
|
||||||
private KeyRotationApiSupport() {}
|
private KeyRotationApiSupport() {}
|
||||||
|
|
||||||
|
/** Free identity не имеет Solana PDA и не вправе менять ключи/форки. */
|
||||||
|
static server.logic.ws_protocol.JSON.entyties.Net_Response denyFreeRotation(
|
||||||
|
server.logic.ws_protocol.JSON.entyties.Net_Request req, String login) {
|
||||||
|
try {
|
||||||
|
var identity = shine.db.dao.RegistrationIdentityDAO.getInstance().get(login);
|
||||||
|
if (identity == null) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||||
|
req, 404, "KEY_ROTATION_USER_NOT_FOUND", "Пользователь не найден");
|
||||||
|
if (identity.isFree()) return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||||
|
req, 403, "KEY_ROTATION_PAID_ONLY", "Для смены ключей необходима регистрация в Solana");
|
||||||
|
return null;
|
||||||
|
} catch (java.sql.SQLException e) {
|
||||||
|
// fail closed при неготовой миграции / ошибке БД
|
||||||
|
return server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory.error(
|
||||||
|
req, 503, "KEY_ROTATION_IDENTITY_UNAVAILABLE", "Невозможно проверить полномочия пользователя");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static String normalizePublicKey32(String raw) {
|
static String normalizePublicKey32(String raw) {
|
||||||
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
|
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
|
||||||
if (normalized == null || normalized.isBlank()) {
|
if (normalized == null || normalized.isBlank()) {
|
||||||
|
|||||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationAbort_Handler implements JsonMessageHandler {
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
try {
|
try {
|
||||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
|
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
|
||||||
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
|
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
|
||||||
|
|||||||
+2
@@ -44,6 +44,8 @@ public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
|
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
|
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
|
||||||
}
|
}
|
||||||
|
|||||||
+2
@@ -22,6 +22,8 @@ public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
try {
|
try {
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||||
|
|||||||
+2
@@ -47,6 +47,8 @@ public final class Net_KeyRotationFinishChain_Handler implements JsonMessageHand
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
|
|
||||||
KeyRotationSessionEntry initial;
|
KeyRotationSessionEntry initial;
|
||||||
|
|||||||
+14
-1
@@ -24,6 +24,8 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
|
|
||||||
final String signature;
|
final String signature;
|
||||||
@@ -39,7 +41,18 @@ public final class Net_KeyRotationRotatePda_Handler implements JsonMessageHandle
|
|||||||
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_ACTIVE", "Активная ротация отсутствует");
|
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_ACTIVE", "Активная ротация отсутствует");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED) {
|
// Solana sync и rebuild работают независимо от уведомления клиента.
|
||||||
|
// При повторе после подтверждённой PDA возвращаем реальный этап, а не 409.
|
||||||
|
if (current.getStatus() == KeyRotationStatus.PDA_ROTATED
|
||||||
|
|| current.getStatus() == KeyRotationStatus.REBUILDING_SERVER
|
||||||
|
|| current.getStatus() == KeyRotationStatus.WALLET_MIGRATION
|
||||||
|
|| current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION
|
||||||
|
|| current.getStatus() == KeyRotationStatus.FINALIZING) {
|
||||||
|
String stored = current.getPdaRotationSignature();
|
||||||
|
if (stored != null && !stored.isBlank() && !stored.equals(signature)) {
|
||||||
|
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_PDA_SIGNATURE_CONFLICT",
|
||||||
|
"Для этой ротации уже сохранена другая Solana transaction signature");
|
||||||
|
}
|
||||||
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
|
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
|
||||||
if (fresh != null) ctx.setCurrentUser(fresh);
|
if (fresh != null) ctx.setCurrentUser(fresh);
|
||||||
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
|
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
|
||||||
|
|||||||
+2
@@ -39,6 +39,8 @@ public final class Net_KeyRotationStart_Handler implements JsonMessageHandler {
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
|
String currentSessionId = ctx.getSessionId() == null ? "" : ctx.getSessionId().trim();
|
||||||
if (currentSessionId.isEmpty()) {
|
if (currentSessionId.isEmpty()) {
|
||||||
|
|||||||
+2
@@ -20,6 +20,8 @@ public final class Net_KeyRotationStatus_Handler implements JsonMessageHandler {
|
|||||||
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
|
||||||
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
|
||||||
}
|
}
|
||||||
|
var freeCheck = KeyRotationApiSupport.denyFreeRotation(req, ctx.getLogin());
|
||||||
|
if (freeCheck != null) return freeCheck;
|
||||||
try {
|
try {
|
||||||
String login = ctx.getLogin().trim();
|
String login = ctx.getLogin().trim();
|
||||||
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
|
||||||
|
|||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.ConnectionContext;
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||||
|
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
|
||||||
|
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
|
||||||
|
import server.logic.ws_protocol.WireCodes;
|
||||||
|
|
||||||
|
/** API доступно анонимному клиенту, но без разрешения приватных операций. */
|
||||||
|
public final class Net_Registration_Handler implements JsonMessageHandler {
|
||||||
|
private final String operation;
|
||||||
|
private static final java.util.Map<ConnectionContext, long[]> LIMITS =
|
||||||
|
java.util.Collections.synchronizedMap(new java.util.WeakHashMap<>());
|
||||||
|
private static long globalMinute=-1;
|
||||||
|
private static int globalHits=0;
|
||||||
|
private static boolean throttled(ConnectionContext ctx) {
|
||||||
|
long minute=System.currentTimeMillis()/60000L;
|
||||||
|
synchronized (LIMITS) {
|
||||||
|
if(globalMinute!=minute){globalMinute=minute;globalHits=0;}
|
||||||
|
if(++globalHits>1200) return true;
|
||||||
|
if(ctx==null) return false;
|
||||||
|
long[] bucket=LIMITS.computeIfAbsent(ctx, c->new long[]{minute,0});
|
||||||
|
if(bucket[0]!=minute){bucket[0]=minute;bucket[1]=0;}
|
||||||
|
return ++bucket[1]>30;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public Net_Registration_Handler(String operation) { this.operation=operation; }
|
||||||
|
@Override public Net_Response handle(Net_Request base, ConnectionContext ctx) throws Exception {
|
||||||
|
Net_Registration_Request request=(Net_Registration_Request)base;
|
||||||
|
if (throttled(ctx)) return NetExceptionResponseFactory.error(request,429,"RATE_LIMITED","Слишком много запросов регистрации");
|
||||||
|
RegistrationApiBridge.Service service=RegistrationApiBridge.get();
|
||||||
|
if (service==null) return NetExceptionResponseFactory.error(request,503,"REGISTRATION_UNAVAILABLE","Регистрация на сервере пока не настроена");
|
||||||
|
try {
|
||||||
|
java.util.Map<String,Object> values=service.execute(operation,request);
|
||||||
|
Net_Registration_Response out=new Net_Registration_Response();
|
||||||
|
out.setOp(request.getOp()); out.setRequestId(request.getRequestId());
|
||||||
|
out.setStatus(WireCodes.Status.OK); out.setValues(values);
|
||||||
|
return out;
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
// Без echo исходного email, чтобы не публиковать PII в ответе/логе.
|
||||||
|
return NetExceptionResponseFactory.error(request,400,"INVALID_REGISTRATION_INPUT","Данные регистрации не прошли проверку");
|
||||||
|
} catch (IllegalStateException e) {
|
||||||
|
return NetExceptionResponseFactory.error(request,409,"REGISTRATION_CONFLICT","Регистрация недоступна или данные уже заняты");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Request;
|
||||||
|
|
||||||
|
/** JSON payload; публичные данные пользователя, пароли/приватные ключи не принимаются. */
|
||||||
|
public final class Net_Registration_Request extends Net_Request {
|
||||||
|
private String fullLogin;
|
||||||
|
private String email;
|
||||||
|
private String rootPublicKeyB64;
|
||||||
|
private String blockchainPublicKeyB64;
|
||||||
|
private String clientPublicKeyB64;
|
||||||
|
private String challengeId;
|
||||||
|
private String code;
|
||||||
|
public String getFullLogin() { return fullLogin; }
|
||||||
|
public void setFullLogin(String v) { fullLogin = v; }
|
||||||
|
public String getEmail() { return email; }
|
||||||
|
public void setEmail(String v) { email = v; }
|
||||||
|
public String getRootPublicKeyB64() { return rootPublicKeyB64; }
|
||||||
|
public void setRootPublicKeyB64(String v) { rootPublicKeyB64 = v; }
|
||||||
|
public String getBlockchainPublicKeyB64() { return blockchainPublicKeyB64; }
|
||||||
|
public void setBlockchainPublicKeyB64(String v) { blockchainPublicKeyB64 = v; }
|
||||||
|
public String getClientPublicKeyB64() { return clientPublicKeyB64; }
|
||||||
|
public void setClientPublicKeyB64(String v) { clientPublicKeyB64 = v; }
|
||||||
|
public String getChallengeId() { return challengeId; }
|
||||||
|
public void setChallengeId(String v) { challengeId = v; }
|
||||||
|
public String getCode() { return code; }
|
||||||
|
public void setCode(String v) { code = v; }
|
||||||
|
}
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||||
|
|
||||||
|
import server.logic.ws_protocol.JSON.entyties.Net_Response;
|
||||||
|
import java.util.Map;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonAnyGetter;
|
||||||
|
|
||||||
|
/** Значения результата помещаются на верхний уровень объекта перед стандартной WS-обёрткой. */
|
||||||
|
public final class Net_Registration_Response extends Net_Response {
|
||||||
|
private Map<String, Object> values = Map.of();
|
||||||
|
public void setValues(Map<String,Object> values) { this.values = Map.copyOf(values); }
|
||||||
|
@JsonAnyGetter public Map<String,Object> getValues() { return values; }
|
||||||
|
}
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package server.logic.ws_protocol.JSON.handlers.registration;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/** SPI: HTTP/WS модуль не зависит от archive-модуля, устраняя циклический Gradle dependency. */
|
||||||
|
public final class RegistrationApiBridge {
|
||||||
|
@FunctionalInterface public interface Service {
|
||||||
|
Map<String, Object> execute(String operation, Net_Registration_Request request) throws Exception;
|
||||||
|
}
|
||||||
|
private static volatile Service service;
|
||||||
|
private RegistrationApiBridge() {}
|
||||||
|
public static void install(Service implementation) { service = java.util.Objects.requireNonNull(implementation); }
|
||||||
|
public static void uninstall() { service = null; }
|
||||||
|
public static Service get() { return service; }
|
||||||
|
}
|
||||||
+1
@@ -32,6 +32,7 @@ public class Net_GetServerInfo_Handler implements JsonMessageHandler {
|
|||||||
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
|
resp.setDescription(CONFIG.getStringOrEmpty("server.info.description"));
|
||||||
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
|
resp.setOrigin(CONFIG.getStringOrEmpty("server.info.origin"));
|
||||||
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
|
resp.setExtraInfo(CONFIG.getStringOrEmpty("server.info.extraInfo"));
|
||||||
|
resp.setSolanaCluster(CONFIG.getStringOrEmpty("solana.cluster"));
|
||||||
|
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|||||||
+4
@@ -26,6 +26,10 @@ public class Net_GetServerInfo_Response extends Net_Response {
|
|||||||
private String description;
|
private String description;
|
||||||
private String origin;
|
private String origin;
|
||||||
private String extraInfo;
|
private String extraInfo;
|
||||||
|
private String solanaCluster;
|
||||||
|
|
||||||
|
public String getSolanaCluster() { return solanaCluster; }
|
||||||
|
public void setSolanaCluster(String cluster) { this.solanaCluster = cluster; }
|
||||||
|
|
||||||
public String getUrl() { return url; }
|
public String getUrl() { return url; }
|
||||||
public void setUrl(String url) { this.url = url; }
|
public void setUrl(String url) { this.url = url; }
|
||||||
|
|||||||
+14
-7
@@ -25,7 +25,8 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
|||||||
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
|
||||||
Net_SearchUsers_Request req = (Net_SearchUsers_Request) baseRequest;
|
Net_SearchUsers_Request req = (Net_SearchUsers_Request) baseRequest;
|
||||||
|
|
||||||
if (req.getPrefix() == null || req.getPrefix().isBlank()) {
|
if (req.getPrefix() == null || req.getPrefix().isBlank() || req.getPrefix().length() > 120
|
||||||
|
|| (req.getLimit() != null && (req.getLimit() < 1 || req.getLimit() > 50))) {
|
||||||
return NetExceptionResponseFactory.error(
|
return NetExceptionResponseFactory.error(
|
||||||
req,
|
req,
|
||||||
WireCodes.Status.BAD_REQUEST,
|
WireCodes.Status.BAD_REQUEST,
|
||||||
@@ -39,13 +40,18 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
CurrentUsersDAO dao = CurrentUsersDAO.getInstance();
|
CurrentUsersDAO dao = CurrentUsersDAO.getInstance();
|
||||||
List<CurrentUserEntry> users = dao.searchByLoginPrefix(prefix, isServer); // case-insensitive + LIMIT 5
|
// Старые клиенты по-прежнему получают массив строк logins.
|
||||||
|
// Новый поиск дополнительно учитывает человекочитаемое имя.
|
||||||
|
var cards = dao.searchDirectory(prefix, isServer, req.getLimit() == null ? 5 : req.getLimit());
|
||||||
List<String> logins = new ArrayList<>();
|
List<String> logins = new ArrayList<>();
|
||||||
for (CurrentUserEntry u : users) {
|
List<Net_SearchUsers_Response.UserItem> users = new ArrayList<>();
|
||||||
if (u != null && u.getLogin() != null) {
|
for (var card : cards) {
|
||||||
logins.add(u.getLogin()); // регистр как в БД
|
logins.add(card.login());
|
||||||
}
|
var item = new Net_SearchUsers_Response.UserItem();
|
||||||
|
item.setLogin(card.login());
|
||||||
|
item.setDisplayName(card.displayName());
|
||||||
|
item.setAvatarAr(card.avatarAr());
|
||||||
|
users.add(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
Net_SearchUsers_Response resp = new Net_SearchUsers_Response();
|
Net_SearchUsers_Response resp = new Net_SearchUsers_Response();
|
||||||
@@ -53,6 +59,7 @@ public class Net_SearchUsers_Handler implements JsonMessageHandler {
|
|||||||
resp.setRequestId(req.getRequestId());
|
resp.setRequestId(req.getRequestId());
|
||||||
resp.setStatus(WireCodes.Status.OK);
|
resp.setStatus(WireCodes.Status.OK);
|
||||||
resp.setLogins(logins);
|
resp.setLogins(logins);
|
||||||
|
resp.setUsers(users);
|
||||||
|
|
||||||
log.info("✅ SearchUsers ok: prefix='{}', isServer={} -> {}", prefix, isServer, logins.size());
|
log.info("✅ SearchUsers ok: prefix='{}', isServer={} -> {}", prefix, isServer, logins.size());
|
||||||
return resp;
|
return resp;
|
||||||
|
|||||||
+3
@@ -19,7 +19,10 @@ public class Net_SearchUsers_Request extends Net_Request {
|
|||||||
|
|
||||||
private String prefix;
|
private String prefix;
|
||||||
private Boolean isServer;
|
private Boolean isServer;
|
||||||
|
private Integer limit;
|
||||||
|
|
||||||
|
public Integer getLimit() { return limit; }
|
||||||
|
public void setLimit(Integer value) { limit = value; }
|
||||||
public String getPrefix() { return prefix; }
|
public String getPrefix() { return prefix; }
|
||||||
public void setPrefix(String prefix) { this.prefix = prefix; }
|
public void setPrefix(String prefix) { this.prefix = prefix; }
|
||||||
public Boolean getIsServer() { return isServer; }
|
public Boolean getIsServer() { return isServer; }
|
||||||
|
|||||||
+14
@@ -23,6 +23,20 @@ import java.util.List;
|
|||||||
public class Net_SearchUsers_Response extends Net_Response {
|
public class Net_SearchUsers_Response extends Net_Response {
|
||||||
|
|
||||||
private List<String> logins = new ArrayList<>();
|
private List<String> logins = new ArrayList<>();
|
||||||
|
private List<UserItem> users = new ArrayList<>();
|
||||||
|
public List<UserItem> getUsers() { return users; }
|
||||||
|
public void setUsers(List<UserItem> users) { this.users = users; }
|
||||||
|
|
||||||
|
public static class UserItem {
|
||||||
|
private String login, displayName, avatarAr;
|
||||||
|
public String getLogin() { return login; }
|
||||||
|
public void setLogin(String value) { login = value; }
|
||||||
|
public String getDisplayName() { return displayName; }
|
||||||
|
public void setDisplayName(String value) { displayName = value; }
|
||||||
|
public String getAvatarAr() { return avatarAr; }
|
||||||
|
public void setAvatarAr(String value) { avatarAr = value; }
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
public List<String> getLogins() { return logins; }
|
public List<String> getLogins() { return logins; }
|
||||||
public void setLogins(List<String> logins) { this.logins = logins; }
|
public void setLogins(List<String> logins) { this.logins = logins; }
|
||||||
|
|||||||
+38
-24
@@ -9,6 +9,7 @@ import server.logic.ws_protocol.JSON.ConnectionContext;
|
|||||||
import server.logic.ws_protocol.JSON.push.WebPushSender;
|
import server.logic.ws_protocol.JSON.push.WebPushSender;
|
||||||
import server.logic.ws_protocol.JSON.push.WsEventSender;
|
import server.logic.ws_protocol.JSON.push.WsEventSender;
|
||||||
import shine.db.dao.ActiveSessionsDAO;
|
import shine.db.dao.ActiveSessionsDAO;
|
||||||
|
import shine.db.dao.DmDialogStateDAO;
|
||||||
import shine.db.dao.SignedMessagesDAO;
|
import shine.db.dao.SignedMessagesDAO;
|
||||||
import shine.db.entities.ActiveSessionEntry;
|
import shine.db.entities.ActiveSessionEntry;
|
||||||
import shine.db.entities.SignedMessageEntry;
|
import shine.db.entities.SignedMessageEntry;
|
||||||
@@ -49,6 +50,9 @@ public final class SignedMessagesRealtime {
|
|||||||
DeliveryCounters counters = new DeliveryCounters();
|
DeliveryCounters counters = new DeliveryCounters();
|
||||||
long now = System.currentTimeMillis();
|
long now = System.currentTimeMillis();
|
||||||
for (String targetLogin : targetLoginsForMessage(message)) {
|
for (String targetLogin : targetLoginsForMessage(message)) {
|
||||||
|
boolean incomingNotification = shouldPushNewIncomingMessage(targetLogin, message, block);
|
||||||
|
DmDialogStateDAO.NotificationState notificationState = incomingNotification
|
||||||
|
? loadNotificationState(targetLogin, message.getFromLogin()) : null;
|
||||||
List<ActiveSessionEntry> sessions = ActiveSessionsDAO.getInstance().getByLogin(targetLogin);
|
List<ActiveSessionEntry> sessions = ActiveSessionsDAO.getInstance().getByLogin(targetLogin);
|
||||||
List<String> sessionIdsToTrack = new ArrayList<>();
|
List<String> sessionIdsToTrack = new ArrayList<>();
|
||||||
for (ActiveSessionEntry s : sessions) {
|
for (ActiveSessionEntry s : sessions) {
|
||||||
@@ -64,13 +68,13 @@ public final class SignedMessagesRealtime {
|
|||||||
if (excludeSessionId != null && excludeSessionId.equals(sessionId)) {
|
if (excludeSessionId != null && excludeSessionId.equals(sessionId)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false);
|
boolean deliveredOnline = sendEventToSessionIfOnline(sessionId, targetLogin, message, false, notificationState);
|
||||||
if (deliveredOnline) {
|
if (deliveredOnline) {
|
||||||
counters.wsDelivered++;
|
counters.wsDelivered++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (shouldPushNewIncomingMessage(targetLogin, message, block)) {
|
if (incomingNotification) {
|
||||||
boolean pushed = pushNewMessageNotification(s, message);
|
boolean pushed = pushNewMessageNotification(s, message, notificationState);
|
||||||
if (pushed) counters.pushDelivered++;
|
if (pushed) counters.pushDelivered++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -100,7 +104,7 @@ public final class SignedMessagesRealtime {
|
|||||||
List<SignedMessageEntry> pending = SignedMessagesDAO.getInstance()
|
List<SignedMessageEntry> pending = SignedMessagesDAO.getInstance()
|
||||||
.listPendingForSession(login, sessionId);
|
.listPendingForSession(login, sessionId);
|
||||||
for (SignedMessageEntry e : pending) {
|
for (SignedMessageEntry e : pending) {
|
||||||
sendEventToSessionIfOnline(sessionId, login, e, true);
|
sendEventToSessionIfOnline(sessionId, login, e, true, null);
|
||||||
}
|
}
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("Failed to dispatch pending messages for sessionId={}", sessionId, e);
|
log.warn("Failed to dispatch pending messages for sessionId={}", sessionId, e);
|
||||||
@@ -111,7 +115,8 @@ public final class SignedMessagesRealtime {
|
|||||||
String sessionId,
|
String sessionId,
|
||||||
String actualTargetLogin,
|
String actualTargetLogin,
|
||||||
SignedMessageEntry message,
|
SignedMessageEntry message,
|
||||||
boolean backlog
|
boolean backlog,
|
||||||
|
DmDialogStateDAO.NotificationState notificationState
|
||||||
) {
|
) {
|
||||||
ConnectionContext targetCtx = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
|
ConnectionContext targetCtx = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
|
||||||
if (targetCtx == null) return false;
|
if (targetCtx == null) return false;
|
||||||
@@ -128,6 +133,10 @@ public final class SignedMessagesRealtime {
|
|||||||
payload.put("nonce", message.getNonce());
|
payload.put("nonce", message.getNonce());
|
||||||
payload.put("blobB64", blobB64);
|
payload.put("blobB64", blobB64);
|
||||||
payload.put("backlog", backlog);
|
payload.put("backlog", backlog);
|
||||||
|
if (message.getMessageType() == SignedMessageBlock.TYPE_INCOMING_TEXT && notificationState != null) {
|
||||||
|
payload.put("unreadCount", notificationState.unreadCount());
|
||||||
|
payload.put("notificationVersionMs", notificationState.versionMs());
|
||||||
|
}
|
||||||
if (message.getReceiptRefBaseKey() != null) {
|
if (message.getReceiptRefBaseKey() != null) {
|
||||||
payload.put("receiptRefBaseKey", message.getReceiptRefBaseKey());
|
payload.put("receiptRefBaseKey", message.getReceiptRefBaseKey());
|
||||||
}
|
}
|
||||||
@@ -141,21 +150,41 @@ public final class SignedMessagesRealtime {
|
|||||||
return block.revisionTimeMs == 0;
|
return block.revisionTimeMs == 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static boolean pushNewMessageNotification(ActiveSessionEntry session, SignedMessageEntry message) {
|
private static DmDialogStateDAO.NotificationState loadNotificationState(String ownerLogin, String peerLogin) {
|
||||||
|
try {
|
||||||
|
return DmDialogStateDAO.getInstance().getNotificationState(ownerLogin, peerLogin);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Не удалось получить счётчик непрочитанных DM для {} / {}", ownerLogin, peerLogin, e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean pushNewMessageNotification(
|
||||||
|
ActiveSessionEntry session, SignedMessageEntry message, DmDialogStateDAO.NotificationState notificationState
|
||||||
|
) {
|
||||||
try {
|
try {
|
||||||
if (session == null) return false;
|
if (session == null) return false;
|
||||||
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
|
if (isBlank(session.getPushEndpoint()) || isBlank(session.getPushP256dhKey()) || isBlank(session.getPushAuthKey())) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
String text = "Новое сообщение от " + message.getFromLogin();
|
ObjectNode payload = MAPPER.createObjectNode();
|
||||||
String payload = "{\"kind\":\"new_message\",\"fromLogin\":\"" + jsonEscape(message.getFromLogin()) + "\",\"text\":\"" + jsonEscape(text) + "\"}";
|
payload.put("kind", "new_message");
|
||||||
|
payload.put("toLogin", session.getLogin());
|
||||||
|
payload.put("fromLogin", message.getFromLogin());
|
||||||
|
payload.put("messageKey", message.getMessageKey());
|
||||||
|
payload.put("text", "Новое сообщение от " + message.getFromLogin());
|
||||||
|
if (notificationState != null) {
|
||||||
|
payload.put("unreadCount", notificationState.unreadCount());
|
||||||
|
payload.put("notificationVersionMs", notificationState.versionMs());
|
||||||
|
}
|
||||||
return WebPushSender.sendBase64Payload(
|
return WebPushSender.sendBase64Payload(
|
||||||
session.getPushEndpoint(),
|
session.getPushEndpoint(),
|
||||||
session.getPushP256dhKey(),
|
session.getPushP256dhKey(),
|
||||||
session.getPushAuthKey(),
|
session.getPushAuthKey(),
|
||||||
payload
|
payload.toString()
|
||||||
);
|
);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
|
log.warn("Не удалось подготовить Web Push для DM {}", message.getMessageKey(), e);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,21 +211,6 @@ public final class SignedMessagesRealtime {
|
|||||||
return s == null ? "" : s.trim().toLowerCase();
|
return s == null ? "" : s.trim().toLowerCase();
|
||||||
}
|
}
|
||||||
|
|
||||||
private static String jsonEscape(String s) {
|
|
||||||
if (s == null) return "";
|
|
||||||
StringBuilder out = new StringBuilder();
|
|
||||||
for (int i = 0; i < s.length(); i++) {
|
|
||||||
char c = s.charAt(i);
|
|
||||||
if (c == '\\') out.append("\\\\");
|
|
||||||
else if (c == '"') out.append("\\\"");
|
|
||||||
else if (c == '\n') out.append("\\n");
|
|
||||||
else if (c == '\r') out.append("\\r");
|
|
||||||
else if (c == '\t') out.append("\\t");
|
|
||||||
else out.append(c);
|
|
||||||
}
|
|
||||||
return out.toString();
|
|
||||||
}
|
|
||||||
|
|
||||||
private static boolean isBlank(String s) {
|
private static boolean isBlank(String s) {
|
||||||
return s == null || s.isBlank();
|
return s == null || s.isBlank();
|
||||||
}
|
}
|
||||||
|
|||||||
+58
@@ -2,6 +2,7 @@ package sync.codec;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.databind.JsonNode;
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
import sync.util.Base58Util;
|
import sync.util.Base58Util;
|
||||||
|
import sync.util.SolanaPdaUtil;
|
||||||
|
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@@ -29,6 +30,8 @@ public final class ShineUsersCodec {
|
|||||||
public static final int IX_CLOSE_LEGACY_USER_PDA =
|
public static final int IX_CLOSE_LEGACY_USER_PDA =
|
||||||
6;
|
6;
|
||||||
|
|
||||||
|
public static final int IX_CREATE_NAMESPACE = 7;
|
||||||
|
|
||||||
public static final long START_REGISTRATION_FEE_LAMPORTS =
|
public static final long START_REGISTRATION_FEE_LAMPORTS =
|
||||||
10_000_000L;
|
10_000_000L;
|
||||||
|
|
||||||
@@ -151,6 +154,16 @@ public final class ShineUsersCodec {
|
|||||||
null
|
null
|
||||||
);
|
);
|
||||||
|
|
||||||
|
case IX_CREATE_NAMESPACE ->
|
||||||
|
new ParsedInstruction(
|
||||||
|
TxKind.CREATE_NAMESPACE,
|
||||||
|
true,
|
||||||
|
accountAt(accounts, 1),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
case IX_CREATE_USER_PDA ->
|
case IX_CREATE_USER_PDA ->
|
||||||
parseV12PdaMutationInstruction(
|
parseV12PdaMutationInstruction(
|
||||||
TxKind.CREATE_USER_PDA, reader, accounts
|
TxKind.CREATE_USER_PDA, reader, accounts
|
||||||
@@ -731,10 +744,55 @@ public final class ShineUsersCodec {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Строгий декодер бинарного namespace 1.0 с on-chain PDA address check. */
|
||||||
|
public static NamespaceSnapshot parseNamespaceAccount(
|
||||||
|
String pdaAddress, long slot, String rawDataBase64,
|
||||||
|
String lastTxSignature, String programId
|
||||||
|
) {
|
||||||
|
byte[] bytes = Base64.getDecoder().decode(rawDataBase64);
|
||||||
|
if (bytes.length < 13 || bytes[0] != 1 || bytes[1] != 0) {
|
||||||
|
throw new IllegalArgumentException("Not a namespace PDA 1.0");
|
||||||
|
}
|
||||||
|
Reader r = new Reader(bytes);
|
||||||
|
r.readU8(); r.readU8();
|
||||||
|
int type = r.readU8();
|
||||||
|
if (type != 1 && type != 2) throw new IllegalArgumentException("Invalid namespace type");
|
||||||
|
int minLen = r.readU8();
|
||||||
|
String namespace = r.readStringU8();
|
||||||
|
if (!namespace.matches("[a-z0-9_]+") || minLen < 1 || namespace.length() + minLen + 1 > 30) {
|
||||||
|
throw new IllegalArgumentException("Invalid namespace");
|
||||||
|
}
|
||||||
|
byte[] feeLittleEndian = r.readFixed(8);
|
||||||
|
byte[] feeBigEndian = new byte[9];
|
||||||
|
for (int n = 0; n < 8; n++) feeBigEndian[8 - n] = feeLittleEndian[n];
|
||||||
|
java.math.BigInteger fee = new java.math.BigInteger(feeBigEndian);
|
||||||
|
String registrarKey = null, serverLogin = null;
|
||||||
|
if (type == 2) {
|
||||||
|
registrarKey = Base58Util.encode(r.readFixed(32));
|
||||||
|
serverLogin = r.readStringU8();
|
||||||
|
if (!serverLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || serverLogin.length() > 30) {
|
||||||
|
throw new IllegalArgumentException("Invalid access server login");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (r.remaining() != 0 || !pdaAddress.equals(SolanaPdaUtil.findNamespacePda(namespace, programId))) {
|
||||||
|
throw new IllegalArgumentException("Invalid namespace bytes or PDA address");
|
||||||
|
}
|
||||||
|
return new NamespaceSnapshot(namespace, pdaAddress, type, minLen,
|
||||||
|
fee, registrarKey, serverLogin, slot, lastTxSignature, rawDataBase64);
|
||||||
|
}
|
||||||
|
|
||||||
|
public record NamespaceSnapshot(
|
||||||
|
String namespace, String pdaAddress, int type, int minLocalpartLength,
|
||||||
|
java.math.BigInteger registrationFeeLamports, String registrarPublicKey,
|
||||||
|
String defaultServerLogin, long slot, String lastTxSignature,
|
||||||
|
String rawDataBase64
|
||||||
|
) {}
|
||||||
|
|
||||||
public enum TxKind {
|
public enum TxKind {
|
||||||
INIT_USERS_ECONOMY_CONFIG,
|
INIT_USERS_ECONOMY_CONFIG,
|
||||||
UPDATE_USERS_ECONOMY_CONFIG,
|
UPDATE_USERS_ECONOMY_CONFIG,
|
||||||
CREATE_USER_PDA,
|
CREATE_USER_PDA,
|
||||||
|
CREATE_NAMESPACE,
|
||||||
UPDATE_USER_PDA,
|
UPDATE_USER_PDA,
|
||||||
CLOSE_LEGACY_USER_PDA,
|
CLOSE_LEGACY_USER_PDA,
|
||||||
OTHER
|
OTHER
|
||||||
|
|||||||
+24
-15
@@ -386,6 +386,7 @@ public final class SolanaUsersSyncService
|
|||||||
);
|
);
|
||||||
|
|
||||||
storage.applyHistoryBatch(
|
storage.applyHistoryBatch(
|
||||||
|
List.of(),
|
||||||
List.of(),
|
List.of(),
|
||||||
List.of(),
|
List.of(),
|
||||||
newState
|
newState
|
||||||
@@ -452,6 +453,7 @@ public final class SolanaUsersSyncService
|
|||||||
|
|
||||||
List<ShineUsersCodec.UserPdaSnapshot> snapshotsToPersist =
|
List<ShineUsersCodec.UserPdaSnapshot> snapshotsToPersist =
|
||||||
new ArrayList<>();
|
new ArrayList<>();
|
||||||
|
List<ShineUsersCodec.NamespaceSnapshot> namespacesToPersist = new ArrayList<>();
|
||||||
|
|
||||||
ShineUsersCodec.EconomyConfigState economyState =
|
ShineUsersCodec.EconomyConfigState economyState =
|
||||||
state.economyConfigState();
|
state.economyConfigState();
|
||||||
@@ -528,17 +530,21 @@ public final class SolanaUsersSyncService
|
|||||||
SolanaRpcClient.AccountBatchResult exactAccounts =
|
SolanaRpcClient.AccountBatchResult exactAccounts =
|
||||||
rpcClient.getCurrentAccounts(exactFetchPdaAddresses, newestSeen.slot());
|
rpcClient.getCurrentAccounts(exactFetchPdaAddresses, newestSeen.slot());
|
||||||
for (ProgramAccountUpdate account : exactAccounts.updates()) {
|
for (ProgramAccountUpdate account : exactAccounts.updates()) {
|
||||||
ShineUsersCodec.UserPdaSnapshot snapshot =
|
String lastSignature = latestRelevantSignatureByPda.getOrDefault(account.address(), "");
|
||||||
ShineUsersCodec.parseUserPdaAccount(
|
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
|
||||||
account.address(),
|
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
|
||||||
account.slot(),
|
var ns = ShineUsersCodec.parseNamespaceAccount(account.address(),
|
||||||
account.dataBase64(),
|
account.slot(), account.dataBase64(), lastSignature, config.programId());
|
||||||
latestRelevantSignatureByPda.getOrDefault(account.address(), "")
|
namespacesToPersist.removeIf(existing -> existing.pdaAddress().equals(ns.pdaAddress()));
|
||||||
);
|
namespacesToPersist.add(ns);
|
||||||
|
} else {
|
||||||
|
var snapshot = ShineUsersCodec.parseUserPdaAccount(account.address(),
|
||||||
|
account.slot(), account.dataBase64(), lastSignature);
|
||||||
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
|
snapshotsToPersist.removeIf(existing -> existing.pdaAddress().equals(snapshot.pdaAddress()));
|
||||||
snapshotsToPersist.add(snapshot);
|
snapshotsToPersist.add(snapshot);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
PostgresStorageRepository.SyncStateSnapshot newState =
|
PostgresStorageRepository.SyncStateSnapshot newState =
|
||||||
new PostgresStorageRepository.SyncStateSnapshot(
|
new PostgresStorageRepository.SyncStateSnapshot(
|
||||||
@@ -558,6 +564,7 @@ public final class SolanaUsersSyncService
|
|||||||
storage.applyHistoryBatch(
|
storage.applyHistoryBatch(
|
||||||
txEntries,
|
txEntries,
|
||||||
snapshotsToPersist,
|
snapshotsToPersist,
|
||||||
|
namespacesToPersist,
|
||||||
newState
|
newState
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -595,6 +602,7 @@ public final class SolanaUsersSyncService
|
|||||||
|
|
||||||
List<ShineUsersCodec.UserPdaSnapshot> currentSnapshots =
|
List<ShineUsersCodec.UserPdaSnapshot> currentSnapshots =
|
||||||
new ArrayList<>();
|
new ArrayList<>();
|
||||||
|
List<ShineUsersCodec.NamespaceSnapshot> currentNamespaces = new ArrayList<>();
|
||||||
|
|
||||||
int processedAccounts =
|
int processedAccounts =
|
||||||
0;
|
0;
|
||||||
@@ -604,14 +612,14 @@ public final class SolanaUsersSyncService
|
|||||||
processedAccounts++;
|
processedAccounts++;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
currentSnapshots.add(
|
byte[] firstBytes = Base64.getDecoder().decode(account.dataBase64());
|
||||||
ShineUsersCodec.parseUserPdaAccount(
|
if (firstBytes.length > 2 && firstBytes[0] == 1 && firstBytes[1] == 0) {
|
||||||
account.address(),
|
currentNamespaces.add(ShineUsersCodec.parseNamespaceAccount(
|
||||||
account.slot(),
|
account.address(), account.slot(), account.dataBase64(), "", config.programId()));
|
||||||
account.dataBase64(),
|
} else {
|
||||||
""
|
currentSnapshots.add(ShineUsersCodec.parseUserPdaAccount(
|
||||||
)
|
account.address(), account.slot(), account.dataBase64(), ""));
|
||||||
);
|
}
|
||||||
} catch (Exception ignored) {
|
} catch (Exception ignored) {
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -654,6 +662,7 @@ public final class SolanaUsersSyncService
|
|||||||
|
|
||||||
storage.replaceCurrentFromFullSnapshot(
|
storage.replaceCurrentFromFullSnapshot(
|
||||||
currentSnapshots,
|
currentSnapshots,
|
||||||
|
currentNamespaces,
|
||||||
newState
|
newState
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
+49
@@ -248,6 +248,7 @@ public final class PostgresStorageRepository
|
|||||||
public synchronized void applyHistoryBatch(
|
public synchronized void applyHistoryBatch(
|
||||||
List<TxHistoryEntry> txEntries,
|
List<TxHistoryEntry> txEntries,
|
||||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
||||||
|
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
|
||||||
SyncStateSnapshot newState
|
SyncStateSnapshot newState
|
||||||
) throws Exception {
|
) throws Exception {
|
||||||
|
|
||||||
@@ -268,6 +269,7 @@ public final class PostgresStorageRepository
|
|||||||
snapshots
|
snapshots
|
||||||
);
|
);
|
||||||
|
|
||||||
|
upsertNamespaceSnapshots(connection, namespaces);
|
||||||
upsertCurrentSnapshots(
|
upsertCurrentSnapshots(
|
||||||
connection,
|
connection,
|
||||||
snapshots
|
snapshots
|
||||||
@@ -297,6 +299,7 @@ public final class PostgresStorageRepository
|
|||||||
|
|
||||||
public synchronized void replaceCurrentFromFullSnapshot(
|
public synchronized void replaceCurrentFromFullSnapshot(
|
||||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
List<ShineUsersCodec.UserPdaSnapshot> snapshots,
|
||||||
|
List<ShineUsersCodec.NamespaceSnapshot> namespaces,
|
||||||
SyncStateSnapshot newState
|
SyncStateSnapshot newState
|
||||||
) throws Exception {
|
) throws Exception {
|
||||||
|
|
||||||
@@ -306,6 +309,7 @@ public final class PostgresStorageRepository
|
|||||||
connection.setAutoCommit(false);
|
connection.setAutoCommit(false);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
upsertNamespaceSnapshots(connection, namespaces);
|
||||||
upsertCurrentSnapshots(
|
upsertCurrentSnapshots(
|
||||||
connection,
|
connection,
|
||||||
snapshots
|
snapshots
|
||||||
@@ -459,6 +463,39 @@ public final class PostgresStorageRepository
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private void upsertNamespaceSnapshots(Connection connection,
|
||||||
|
List<ShineUsersCodec.NamespaceSnapshot> namespaces) throws Exception {
|
||||||
|
if (namespaces == null || namespaces.isEmpty()) return;
|
||||||
|
String sql = """
|
||||||
|
INSERT INTO shine_namespace_current (
|
||||||
|
namespace, pda_address, namespace_type, min_localpart_len,
|
||||||
|
registration_fee_lamports, registrar_pubkey, default_server_login,
|
||||||
|
slot, last_tx_signature, raw_data_base64
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
ON CONFLICT (namespace) DO UPDATE SET
|
||||||
|
slot=EXCLUDED.slot, last_tx_signature=EXCLUDED.last_tx_signature,
|
||||||
|
raw_data_base64=EXCLUDED.raw_data_base64
|
||||||
|
WHERE shine_namespace_current.pda_address=EXCLUDED.pda_address
|
||||||
|
AND shine_namespace_current.raw_data_base64=EXCLUDED.raw_data_base64
|
||||||
|
""";
|
||||||
|
try (PreparedStatement ps = connection.prepareStatement(sql)) {
|
||||||
|
for (ShineUsersCodec.NamespaceSnapshot ns : namespaces) {
|
||||||
|
ps.setString(1, ns.namespace()); ps.setString(2, ns.pdaAddress());
|
||||||
|
ps.setInt(3, ns.type()); ps.setInt(4, ns.minLocalpartLength());
|
||||||
|
ps.setBigDecimal(5, new java.math.BigDecimal(ns.registrationFeeLamports()));
|
||||||
|
ps.setString(6, ns.registrarPublicKey());
|
||||||
|
ps.setString(7, ns.defaultServerLogin()); ps.setLong(8, ns.slot());
|
||||||
|
ps.setString(9, ns.lastTxSignature()); ps.setString(10, ns.rawDataBase64());
|
||||||
|
ps.addBatch();
|
||||||
|
}
|
||||||
|
ps.executeBatch();
|
||||||
|
}
|
||||||
|
// Namespace появляется после сервера, пересчитываем маршруты free пользователей.
|
||||||
|
try (Statement st = connection.createStatement()) {
|
||||||
|
st.execute("SELECT shine_refresh_user_access_servers_all()");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void upsertCurrentSnapshots(
|
private void upsertCurrentSnapshots(
|
||||||
Connection connection,
|
Connection connection,
|
||||||
List<ShineUsersCodec.UserPdaSnapshot> snapshots
|
List<ShineUsersCodec.UserPdaSnapshot> snapshots
|
||||||
@@ -1076,6 +1113,16 @@ public final class PostgresStorageRepository
|
|||||||
"ON user_access_servers_current(server_login)"
|
"ON user_access_servers_current(server_login)"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// После PostgreSQL migration_v33 функции маршрутизации принадлежат
|
||||||
|
// общему реестру логических identity, их нельзя перезаписывать
|
||||||
|
// legacy Solana-only вариантом при старте sync.
|
||||||
|
boolean hasIdentityTable;
|
||||||
|
try (ResultSet check = statement.executeQuery(
|
||||||
|
"SELECT to_regclass('user_identity_current') IS NOT NULL")) {
|
||||||
|
check.next();
|
||||||
|
hasIdentityTable = check.getBoolean(1);
|
||||||
|
}
|
||||||
|
if (!hasIdentityTable) {
|
||||||
statement.execute(
|
statement.execute(
|
||||||
"""
|
"""
|
||||||
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
CREATE OR REPLACE FUNCTION shine_refresh_user_access_servers_for_user(p_user_login TEXT)
|
||||||
@@ -1260,6 +1307,8 @@ public final class PostgresStorageRepository
|
|||||||
"EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate()"
|
"EXECUTE FUNCTION trg_refresh_user_access_servers_from_user_pda_truncate()"
|
||||||
);
|
);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
statement.execute("SELECT shine_refresh_user_access_servers_all()");
|
statement.execute("SELECT shine_refresh_user_access_servers_all()");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+21
@@ -61,6 +61,27 @@ public final class SolanaPdaUtil {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Новый v2 PDA. Старый двух-seed вариант оставлен только для legacy accounts. */
|
||||||
|
public static String findUserPdaV2(String fullLogin, String programId) {
|
||||||
|
if (fullLogin == null || !fullLogin.matches("[A-Za-z0-9_]+@[a-z0-9_]+") || fullLogin.length() > 30) {
|
||||||
|
throw new IllegalArgumentException("Invalid full login");
|
||||||
|
}
|
||||||
|
return findHashedPda("user_login=" + fullLogin.toLowerCase(java.util.Locale.ROOT), programId);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static String findNamespacePda(String namespace, String programId) {
|
||||||
|
if (namespace == null || !namespace.matches("[a-z0-9_]+")) {
|
||||||
|
throw new IllegalArgumentException("Invalid namespace");
|
||||||
|
}
|
||||||
|
return findHashedPda("namespace=" + namespace, programId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String findHashedPda(String preimage, String programId) {
|
||||||
|
SHA256.Digest digest = new SHA256.Digest();
|
||||||
|
byte[] seed = digest.digest(preimage.getBytes(StandardCharsets.UTF_8));
|
||||||
|
return findProgramAddress(List.of(seed), programId);
|
||||||
|
}
|
||||||
|
|
||||||
private static byte[] createProgramAddress(
|
private static byte[] createProgramAddress(
|
||||||
List<byte[]> seeds,
|
List<byte[]> seeds,
|
||||||
byte[] programId
|
byte[] programId
|
||||||
|
|||||||
+35
@@ -0,0 +1,35 @@
|
|||||||
|
package sync.codec;
|
||||||
|
|
||||||
|
import sync.util.SolanaPdaUtil;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.HexFormat;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
/** Отдельная offline-проверка, без RPC/DB; запуск через main(). */
|
||||||
|
public final class NamespaceV2VectorCheck {
|
||||||
|
public static void main(String[] args) throws Exception {
|
||||||
|
Properties p = new Properties();
|
||||||
|
try (var stream = Files.newInputStream(Path.of(args[0]))) { p.load(stream); }
|
||||||
|
String program = p.getProperty("program_id");
|
||||||
|
if (!p.getProperty("namespace_free_pda").equals(SolanaPdaUtil.findNamespacePda("free", program)))
|
||||||
|
throw new AssertionError("Namespace seed/PDA mismatch");
|
||||||
|
if (!p.getProperty("user_bob_free_pda").equals(SolanaPdaUtil.findUserPdaV2("bob@free", program)))
|
||||||
|
throw new AssertionError("User v2 seed/PDA mismatch");
|
||||||
|
byte[] raw = HexFormat.of().parseHex(p.getProperty("namespace_free_bytes_hex"));
|
||||||
|
var ns = ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
|
||||||
|
42, Base64.getEncoder().encodeToString(raw), "test-signature", program);
|
||||||
|
if (!"free".equals(ns.namespace()) || ns.type() != 2 ||
|
||||||
|
ns.registrationFeeLamports().longValueExact() != 5_000_000L ||
|
||||||
|
!"registrar@shine".equals(ns.defaultServerLogin()))
|
||||||
|
throw new AssertionError("Namespace value mismatch");
|
||||||
|
byte[] corrupt = raw.clone(); corrupt[6] ^= 1;
|
||||||
|
try {
|
||||||
|
ShineUsersCodec.parseNamespaceAccount(p.getProperty("namespace_free_pda"),
|
||||||
|
42, Base64.getEncoder().encodeToString(corrupt), "test-signature", program);
|
||||||
|
throw new AssertionError("Wrong PDA accepted");
|
||||||
|
} catch (IllegalArgumentException expected) { }
|
||||||
|
System.out.println("PASS: Java namespace decoder & SHA256 PDA test vectors");
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -24,4 +24,13 @@ class SolanaPdaUtilTest {
|
|||||||
pda
|
pda
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@Test
|
||||||
|
void mixedCaseUsesSamePdaButNamespaceMustRemainLowercase() {
|
||||||
|
String program = "SHiNEPr1APdAgNBteUyBXcNovaHctpSjUu8oH2ZJdN6";
|
||||||
|
String lower = SolanaPdaUtil.findUserPdaV2("superman@free", program);
|
||||||
|
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SuperMan@free", program));
|
||||||
|
assertEquals(lower, SolanaPdaUtil.findUserPdaV2("SUPERMAN@free", program));
|
||||||
|
org.junit.jupiter.api.Assertions.assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> SolanaPdaUtil.findUserPdaV2("SuperMan@FREE", program));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,11 +14,15 @@ import utils.crypto.Ed25519Util;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.io.InputStream;
|
import java.io.InputStream;
|
||||||
|
import java.nio.ByteBuffer;
|
||||||
|
import java.nio.channels.FileChannel;
|
||||||
import java.io.OutputStream;
|
import java.io.OutputStream;
|
||||||
import java.nio.charset.StandardCharsets;
|
import java.nio.charset.StandardCharsets;
|
||||||
import java.nio.file.AtomicMoveNotSupportedException;
|
import java.nio.file.AtomicMoveNotSupportedException;
|
||||||
import java.nio.file.FileAlreadyExistsException;
|
import java.nio.file.FileAlreadyExistsException;
|
||||||
import java.nio.file.Files;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.LinkOption;
|
||||||
|
import java.nio.file.StandardOpenOption;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
import java.nio.file.StandardCopyOption;
|
import java.nio.file.StandardCopyOption;
|
||||||
import java.nio.file.attribute.PosixFilePermission;
|
import java.nio.file.attribute.PosixFilePermission;
|
||||||
@@ -37,10 +41,10 @@ import java.util.regex.Pattern;
|
|||||||
* имя, расширение, MIME или владельца внутри пути файла. Одинаковые байты всех
|
* имя, расширение, MIME или владельца внутри пути файла. Одинаковые байты всех
|
||||||
* пользователей дедуплицируются в один объект: data/public-files/<sha256>.
|
* пользователей дедуплицируются в один объект: data/public-files/<sha256>.
|
||||||
*
|
*
|
||||||
* В production GET/HEAD /files/<sha256> рекомендуется отдавать Caddy напрямую с
|
* GET поддерживает HTTP Range для потокового просмотра видео без полной загрузки.
|
||||||
* того же каталога и кэшировать Cloudflare. Этот servlet оставляет GET/HEAD как
|
* Проверка SHA-256 выполняется при PUT; GET/HEAD читают метаданные файла без
|
||||||
* рабочий fallback; PUT всегда проходит через Java, с проверкой session-signature
|
* повторного хеширования всего содержимого. Caddy также может отдавать immutable
|
||||||
* и повторным вычислением SHA-256 полученных байтов.
|
* файлы напрямую, если настроен на корректную выдачу байтовых диапазонов и MIME.
|
||||||
*/
|
*/
|
||||||
public final class PublicFileServlet extends HttpServlet {
|
public final class PublicFileServlet extends HttpServlet {
|
||||||
|
|
||||||
@@ -202,29 +206,118 @@ public final class PublicFileServlet extends HttpServlet {
|
|||||||
|
|
||||||
String fileId = extractFileId(req);
|
String fileId = extractFileId(req);
|
||||||
Path target = fileId == null ? null : safeTarget(fileId);
|
Path target = fileId == null ? null : safeTarget(fileId);
|
||||||
if (target == null || !Files.isRegularFile(target)) {
|
// Не следуем по символическим ссылкам: без повторной проверки хеша GET не должен
|
||||||
|
// иметь возможность прочитать посторонний файл из-за подмены пути.
|
||||||
|
if (target == null || !Files.isRegularFile(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
StoredObjectCheck stored = verifyStoredObject(target, fileId);
|
long size = Files.size(target);
|
||||||
if (!stored.valid()) {
|
String etag = "\"" + fileId + "\"";
|
||||||
Files.deleteIfExists(target);
|
resp.setHeader("ETag", etag);
|
||||||
writeError(resp, HttpServletResponse.SC_NOT_FOUND, "FILE_NOT_FOUND", "Файл не найден");
|
resp.setHeader("Accept-Ranges", "bytes");
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
resp.setStatus(HttpServletResponse.SC_OK);
|
|
||||||
resp.setContentType("application/octet-stream");
|
|
||||||
resp.setHeader("Content-Length", Long.toString(stored.size()));
|
|
||||||
resp.setHeader("ETag", "\"" + fileId + "\"");
|
|
||||||
resp.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
resp.setHeader("Cache-Control", "public, max-age=31536000, immutable");
|
||||||
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
|
resp.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
|
||||||
if (!headOnly) {
|
resp.setContentType(detectContentType(target));
|
||||||
try (InputStream in = Files.newInputStream(target); OutputStream out = resp.getOutputStream()) {
|
|
||||||
in.transferTo(out);
|
// По HTTP заголовок Range относится к GET. Для HEAD отдаём обычные
|
||||||
|
// метаданные целого объекта, что нужно в том числе проверке вложений в UI.
|
||||||
|
String rangeHeader = headOnly ? null : req.getHeader("Range");
|
||||||
|
String ifRange = req.getHeader("If-Range");
|
||||||
|
if (rangeHeader != null && ifRange != null && !ifRange.trim().equals(etag)) {
|
||||||
|
rangeHeader = null; // неподтверждённая версия: отправляем обычный 200
|
||||||
|
}
|
||||||
|
ByteRange range = null;
|
||||||
|
if (rangeHeader != null) {
|
||||||
|
range = parseSingleRange(rangeHeader, size);
|
||||||
|
if (range == null) {
|
||||||
|
resp.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
|
||||||
|
resp.setHeader("Content-Range", "bytes */" + size);
|
||||||
|
resp.setHeader("Content-Length", "0");
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
long firstByte = range == null ? 0L : range.start();
|
||||||
|
long byteCount = range == null ? size : range.length();
|
||||||
|
resp.setStatus(range == null ? HttpServletResponse.SC_OK : HttpServletResponse.SC_PARTIAL_CONTENT);
|
||||||
|
resp.setHeader("Content-Length", Long.toString(byteCount));
|
||||||
|
if (range != null) resp.setHeader("Content-Range", "bytes " + range.start() + "-" + range.end() + "/" + size);
|
||||||
|
if (headOnly || byteCount == 0) return;
|
||||||
|
|
||||||
|
// Файловый канал позиционируется в начале запрошенного участка — не читаем
|
||||||
|
// все предыдущие байты и не буферизуем видео целиком в памяти.
|
||||||
|
try (FileChannel channel = FileChannel.open(target, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
channel.position(firstByte);
|
||||||
|
OutputStream out = resp.getOutputStream();
|
||||||
|
byte[] buffer = new byte[64 * 1024];
|
||||||
|
long remaining = byteCount;
|
||||||
|
while (remaining > 0) {
|
||||||
|
ByteBuffer chunk = ByteBuffer.wrap(buffer, 0, (int) Math.min(buffer.length, remaining));
|
||||||
|
int read = channel.read(chunk);
|
||||||
|
if (read < 0) break; // файл мог быть удалён/усечён во время чтения
|
||||||
|
if (read == 0) continue;
|
||||||
|
out.write(buffer, 0, read);
|
||||||
|
remaining -= read;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Поддерживается один диапазон (стандартные запросы браузерных <video>).
|
||||||
|
// Некорректные, составные или не удовлетворяемые диапазоны отвечают 416.
|
||||||
|
static ByteRange parseSingleRange(String header, long size) {
|
||||||
|
if (header == null || !header.startsWith("bytes=") || size <= 0) return null;
|
||||||
|
String value = header.substring("bytes=".length()).trim();
|
||||||
|
if (value.indexOf(',') >= 0) return null;
|
||||||
|
int dash = value.indexOf('-');
|
||||||
|
if (dash < 0 || dash != value.lastIndexOf('-')) return null;
|
||||||
|
String first = value.substring(0, dash).trim();
|
||||||
|
String last = value.substring(dash + 1).trim();
|
||||||
|
if (first.isEmpty() && last.isEmpty()) return null;
|
||||||
|
try {
|
||||||
|
if (first.isEmpty()) {
|
||||||
|
long suffixBytes = Long.parseLong(last);
|
||||||
|
if (suffixBytes <= 0) return null;
|
||||||
|
return new ByteRange(size - Math.min(suffixBytes, size), size - 1);
|
||||||
|
}
|
||||||
|
long start = Long.parseLong(first);
|
||||||
|
if (start < 0 || start >= size) return null;
|
||||||
|
long end = last.isEmpty() ? size - 1 : Long.parseLong(last);
|
||||||
|
if (end < start) return null;
|
||||||
|
return new ByteRange(start, Math.min(end, size - 1));
|
||||||
|
} catch (NumberFormatException ignored) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Объекты на диске не имеют расширений. Тип распознаём по сигнатуре первых
|
||||||
|
// байтов; обычные файлы по-прежнему отдаются как application/octet-stream.
|
||||||
|
private static String detectContentType(Path target) throws IOException {
|
||||||
|
byte[] signature = new byte[16];
|
||||||
|
int count;
|
||||||
|
try (InputStream in = Files.newInputStream(target, LinkOption.NOFOLLOW_LINKS)) {
|
||||||
|
count = in.read(signature);
|
||||||
|
}
|
||||||
|
if (count >= 12 && signature[4] == 'f' && signature[5] == 't'
|
||||||
|
&& signature[6] == 'y' && signature[7] == 'p') {
|
||||||
|
return "video/mp4";
|
||||||
|
}
|
||||||
|
if (count >= 4 && (signature[0] & 0xff) == 0x1a && (signature[1] & 0xff) == 0x45
|
||||||
|
&& (signature[2] & 0xff) == 0xdf && (signature[3] & 0xff) == 0xa3) {
|
||||||
|
return "video/webm";
|
||||||
|
}
|
||||||
|
if (count >= 4 && signature[0] == 'O' && signature[1] == 'g'
|
||||||
|
&& signature[2] == 'g' && signature[3] == 'S') return "video/ogg";
|
||||||
|
if (count >= 12 && signature[0] == 'R' && signature[1] == 'I'
|
||||||
|
&& signature[2] == 'F' && signature[3] == 'F'
|
||||||
|
&& signature[8] == 'A' && signature[9] == 'V'
|
||||||
|
&& signature[10] == 'I' && signature[11] == ' ') return "video/x-msvideo";
|
||||||
|
return "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
record ByteRange(long start, long end) {
|
||||||
|
long length() { return end - start + 1; }
|
||||||
}
|
}
|
||||||
|
|
||||||
private static StoredObjectCheck verifyStoredObject(Path target, String expectedFileId) throws IOException {
|
private static StoredObjectCheck verifyStoredObject(Path target, String expectedFileId) throws IOException {
|
||||||
@@ -361,8 +454,8 @@ public final class PublicFileServlet extends HttpServlet {
|
|||||||
resp.setHeader("Access-Control-Allow-Origin", "*");
|
resp.setHeader("Access-Control-Allow-Origin", "*");
|
||||||
resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, PUT, OPTIONS");
|
resp.setHeader("Access-Control-Allow-Methods", "GET, HEAD, PUT, OPTIONS");
|
||||||
resp.setHeader("Access-Control-Allow-Headers",
|
resp.setHeader("Access-Control-Allow-Headers",
|
||||||
"Content-Type, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Content-Length, X-Shine-Signature");
|
"Content-Type, Range, If-Range, X-Shine-Session-Id, X-Shine-Time-Ms, X-Shine-Content-Length, X-Shine-Signature");
|
||||||
resp.setHeader("Access-Control-Expose-Headers", "Content-Length, ETag");
|
resp.setHeader("Access-Control-Expose-Headers", "Content-Length, ETag, Accept-Ranges, Content-Range, Content-Type");
|
||||||
resp.setHeader("Vary", "Origin");
|
resp.setHeader("Vary", "Origin");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
package server.ws;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import jakarta.servlet.http.HttpServlet;
|
||||||
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.URI;
|
||||||
|
import java.net.http.HttpClient;
|
||||||
|
import java.net.http.HttpRequest;
|
||||||
|
import java.net.http.HttpResponse;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.util.Set;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/** Single, provider-independent Solana HTTP JSON-RPC gateway. */
|
||||||
|
public final class SolanaRpcGateway extends HttpServlet {
|
||||||
|
private static final ObjectMapper JSON = new ObjectMapper();
|
||||||
|
private static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(8)).build();
|
||||||
|
private static final Set<String> METHODS = Set.of(
|
||||||
|
"getBalance", "getAccountInfo", "getMultipleAccounts", "getProgramAccounts",
|
||||||
|
"getLatestBlockhash", "getBlockHeight", "isBlockhashValid", "getFeeForMessage",
|
||||||
|
"getMinimumBalanceForRentExemption", "getSignatureStatuses", "getSignatureStatus",
|
||||||
|
"getTransaction", "getParsedTransaction", "getEpochInfo", "getSlot", "getVersion",
|
||||||
|
"getTokenAccountBalance", "getTokenAccountsByOwner", "getSignaturesForAddress",
|
||||||
|
"simulateTransaction", "getRecentPrioritizationFees", "sendTransaction"
|
||||||
|
);
|
||||||
|
private static final ConcurrentHashMap<String, Window> LIMITS = new ConcurrentHashMap<>();
|
||||||
|
private static final int MAX_BYTES = 256 * 1024;
|
||||||
|
private record Window(long minute, int count) {}
|
||||||
|
|
||||||
|
@Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) {
|
||||||
|
cors(req, resp);
|
||||||
|
resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
|
||||||
|
resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
||||||
|
resp.setStatus(204);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
|
||||||
|
cors(req, resp);
|
||||||
|
resp.setContentType("application/json; charset=utf-8");
|
||||||
|
if (req.getContentLengthLong() > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
|
||||||
|
byte[] bytes = req.getInputStream().readNBytes(MAX_BYTES + 1);
|
||||||
|
if (bytes.length > MAX_BYTES) { fail(resp, 413, "Request too large"); return; }
|
||||||
|
final JsonNode call;
|
||||||
|
try {
|
||||||
|
call = JSON.readTree(bytes);
|
||||||
|
if (call == null || !call.isObject() || !call.path("jsonrpc").asText().equals("2.0")
|
||||||
|
|| !call.has("id") || !call.path("params").isArray()
|
||||||
|
|| !METHODS.contains(call.path("method").asText())) {
|
||||||
|
fail(resp, 400, "Unsupported JSON-RPC request"); return;
|
||||||
|
}
|
||||||
|
} catch (Exception ex) { fail(resp, 400, "Invalid JSON"); return; }
|
||||||
|
boolean write = "sendTransaction".equals(call.path("method").asText());
|
||||||
|
String client = req.getRemoteAddr();
|
||||||
|
if ("127.0.0.1".equals(client) || "::1".equals(client)) {
|
||||||
|
String forwarded = req.getHeader("X-Forwarded-For");
|
||||||
|
if (forwarded != null && !forwarded.isBlank()) {
|
||||||
|
String first = forwarded.split(",", 2)[0].trim();
|
||||||
|
if (first.matches("[0-9a-fA-F:.]{3,48}")) client = first;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
long minute = System.currentTimeMillis() / 60_000L;
|
||||||
|
String key = client + (write ? ":write" : ":read");
|
||||||
|
Window window = LIMITS.compute(key, (k, old) -> old == null || old.minute != minute
|
||||||
|
? new Window(minute, 1) : new Window(minute, old.count + 1));
|
||||||
|
if (window.count > (write ? 6 : 180)) { fail(resp, 429, "RPC request limit exceeded"); return; }
|
||||||
|
String rpc = AppConfig.getInstance().getStringOrEmpty("solana.rpcUrl");
|
||||||
|
if (!rpc.startsWith("https://") && !rpc.startsWith("http://")) {
|
||||||
|
fail(resp, 503, "Solana RPC is not configured"); return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
HttpRequest upstream = HttpRequest.newBuilder(URI.create(rpc))
|
||||||
|
.timeout(Duration.ofSeconds(30)).header("Content-Type", "application/json")
|
||||||
|
.POST(HttpRequest.BodyPublishers.ofByteArray(bytes)).build();
|
||||||
|
HttpResponse<byte[]> answer = HTTP.send(upstream, HttpResponse.BodyHandlers.ofByteArray());
|
||||||
|
resp.setStatus(answer.statusCode());
|
||||||
|
resp.getOutputStream().write(answer.body());
|
||||||
|
} catch (InterruptedException ex) {
|
||||||
|
Thread.currentThread().interrupt(); fail(resp, 502, "RPC interrupted");
|
||||||
|
} catch (Exception ex) { fail(resp, 502, "RPC upstream unavailable"); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void cors(HttpServletRequest req, HttpServletResponse resp) {
|
||||||
|
String origin = req.getHeader("Origin");
|
||||||
|
if (origin == null) return;
|
||||||
|
try {
|
||||||
|
URI uri = URI.create(origin);
|
||||||
|
String host = uri.getHost();
|
||||||
|
if (host != null && (host.equals("shineup.me") || host.endsWith(".shineup.me")
|
||||||
|
|| host.equals("localhost") || host.equals("127.0.0.1"))) {
|
||||||
|
resp.setHeader("Access-Control-Allow-Origin", origin);
|
||||||
|
resp.setHeader("Vary", "Origin");
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException ignored) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void fail(HttpServletResponse response, int code, String message) throws IOException {
|
||||||
|
response.setStatus(code);
|
||||||
|
response.getWriter().write(JSON.createObjectNode().put("error", message).toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,10 +4,12 @@ import server.keyrotation.KeyRotationRebuildScheduler;
|
|||||||
|
|
||||||
import org.eclipse.jetty.server.Server;
|
import org.eclipse.jetty.server.Server;
|
||||||
import org.eclipse.jetty.servlet.ServletContextHandler;
|
import org.eclipse.jetty.servlet.ServletContextHandler;
|
||||||
|
import org.eclipse.jetty.servlet.ServletHolder;
|
||||||
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
import org.eclipse.jetty.websocket.server.config.JettyWebSocketServletContainerInitializer;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import server.archive.ArweaveBlockPublisherScheduler;
|
import server.archive.ArweaveBlockPublisherScheduler;
|
||||||
|
import server.archive.registration.FreeRegistrationApiBootstrap;
|
||||||
import server.archive.ArweaveBlockSyncScheduler;
|
import server.archive.ArweaveBlockSyncScheduler;
|
||||||
import server.debug.DebugApiConfigurator;
|
import server.debug.DebugApiConfigurator;
|
||||||
import server.files.DmFileApiConfigurator;
|
import server.files.DmFileApiConfigurator;
|
||||||
@@ -17,6 +19,7 @@ import server.sync.PeriodicDmDeliveryService;
|
|||||||
import server.sync.SolanaUsersSyncStartupService;
|
import server.sync.SolanaUsersSyncStartupService;
|
||||||
import server.sync.SyncServersBootstrapService;
|
import server.sync.SyncServersBootstrapService;
|
||||||
import server.sync.ServerConnectionPool;
|
import server.sync.ServerConnectionPool;
|
||||||
|
import shine.db.DbController;
|
||||||
import utils.config.AppConfig;
|
import utils.config.AppConfig;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -33,7 +36,14 @@ public final class WsServer {
|
|||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
|
|
||||||
// ============================================================
|
// ============================================================
|
||||||
// 1.0) Синхронизация пользовательских Solana PDA
|
// 1.0) Сначала создаём полную runtime-схему SHiNE.
|
||||||
|
// Solana sync использует ту же БД и создаёт собственные таблицы;
|
||||||
|
// без этого порядка чистая БД ошибочно выглядит для runtime как legacy.
|
||||||
|
// ============================================================
|
||||||
|
DbController.getInstance();
|
||||||
|
|
||||||
|
// ============================================================
|
||||||
|
// 1.1) Синхронизация пользовательских Solana PDA
|
||||||
// ============================================================
|
// ============================================================
|
||||||
SolanaUsersSyncStartupService.startOrThrow();
|
SolanaUsersSyncStartupService.startOrThrow();
|
||||||
|
|
||||||
@@ -64,6 +74,7 @@ public final class WsServer {
|
|||||||
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
|
// PeriodicBlockchainSyncService is retained only as deprecated historical code.
|
||||||
|
|
||||||
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
|
// ANS-104: publish locally-created signed user blocks and discover blocks published by other servers.
|
||||||
|
FreeRegistrationApiBootstrap.startOrThrow();
|
||||||
ArweaveBlockPublisherScheduler.startOrLog();
|
ArweaveBlockPublisherScheduler.startOrLog();
|
||||||
ArweaveBlockSyncScheduler.startOrLog();
|
ArweaveBlockSyncScheduler.startOrLog();
|
||||||
KeyRotationRebuildScheduler.startOrLog();
|
KeyRotationRebuildScheduler.startOrLog();
|
||||||
@@ -77,6 +88,9 @@ public final class WsServer {
|
|||||||
context.setContextPath("/");
|
context.setContextPath("/");
|
||||||
server.setHandler(context);
|
server.setHandler(context);
|
||||||
|
|
||||||
|
// Universal Solana HTTP JSON-RPC gateway
|
||||||
|
context.addServlet(new ServletHolder(new SolanaRpcGateway()), "/solana-rpc");
|
||||||
|
|
||||||
// HTTP debug API
|
// HTTP debug API
|
||||||
DebugApiConfigurator.register(context);
|
DebugApiConfigurator.register(context);
|
||||||
|
|
||||||
@@ -100,7 +114,7 @@ public final class WsServer {
|
|||||||
log.info("✅ WS сервер запущен на ws://localhost:{}/ws", port);
|
log.info("✅ WS сервер запущен на ws://localhost:{}/ws", port);
|
||||||
ServerConnectionPool.getInstance().startOrLog();
|
ServerConnectionPool.getInstance().startOrLog();
|
||||||
Runtime.getRuntime().addShutdownHook(new Thread(
|
Runtime.getRuntime().addShutdownHook(new Thread(
|
||||||
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); },
|
() -> { ServerConnectionPool.getInstance().close(); ArweaveBlockPublisherScheduler.close(); ArweaveBlockSyncScheduler.close(); FreeRegistrationApiBootstrap.close(); },
|
||||||
"server-connection-pool-shutdown"));
|
"server-connection-pool-shutdown"));
|
||||||
PeriodicDmDeliveryService.startOrLog();
|
PeriodicDmDeliveryService.startOrLog();
|
||||||
server.join();
|
server.join();
|
||||||
|
|||||||
@@ -146,7 +146,7 @@ test.freeAvatar.walletJwkPath=
|
|||||||
|
|
||||||
# ============================================================
|
# ============================================================
|
||||||
# Arweave per-user-block transport (ANS-104)
|
# Arweave per-user-block transport (ANS-104)
|
||||||
# Test namespace: each user DataItem is signed with App=test5591.
|
# Test namespace: each user DataItem is signed with App=test5592.
|
||||||
# Channel DataItems additionally contain c=<canonical-channel-slug>.
|
# Channel DataItems additionally contain c=<canonical-channel-slug>.
|
||||||
# ============================================================
|
# ============================================================
|
||||||
arweave.blocks.publish.enabled=false
|
arweave.blocks.publish.enabled=false
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package server.files;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class PublicFileRangeTest {
|
||||||
|
|
||||||
|
private static void assertRange(String header, long size, long start, long end) {
|
||||||
|
PublicFileServlet.ByteRange range = PublicFileServlet.parseSingleRange(header, size);
|
||||||
|
assertNotNull(range);
|
||||||
|
assertEquals(start, range.start());
|
||||||
|
assertEquals(end, range.end());
|
||||||
|
assertEquals(end - start + 1, range.length());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void readsExplicitOpenAndSuffixRanges() {
|
||||||
|
assertRange("bytes=0-1023", 2048, 0, 1023);
|
||||||
|
assertRange("bytes=1024-", 2048, 1024, 2047);
|
||||||
|
assertRange("bytes=-256", 2048, 1792, 2047);
|
||||||
|
assertRange("bytes=-4096", 2048, 0, 2047);
|
||||||
|
assertRange("bytes=2047-9999", 2048, 2047, 2047);
|
||||||
|
assertRange("bytes=0-0", 2048, 0, 0);
|
||||||
|
assertRange("bytes=0-0", 1, 0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void rejectsUnsatisfiableAndMalformedRanges() {
|
||||||
|
for (String header : new String[] {
|
||||||
|
"bytes=2048-", "bytes=2000-1999", "bytes=-0", "bytes=-", "bytes=0-1,10-20",
|
||||||
|
"bytes=a-b", "bytes=-9223372036854775808", "bytes=9223372036854775808-",
|
||||||
|
"items=0-1", "bytes=-1-2", "bytes=0--1"
|
||||||
|
}) {
|
||||||
|
assertNull(PublicFileServlet.parseSingleRange(header, 2048), header);
|
||||||
|
}
|
||||||
|
assertNull(PublicFileServlet.parseSingleRange("bytes=0-0", 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-2
@@ -1,2 +1,2 @@
|
|||||||
client.version=1.14.16
|
client.version=1.20.10
|
||||||
server.version=1.12.13
|
server.version=1.16.10
|
||||||
|
|||||||
@@ -37,6 +37,28 @@ chmod 755 /home/player/shine-public-files
|
|||||||
|
|
||||||
## 2. Caddyfile
|
## 2. Caddyfile
|
||||||
|
|
||||||
|
### Вариант A: GET/HEAD/PUT через Java (надежный MIME и HTTP Range)
|
||||||
|
|
||||||
|
Для запуска предпросмотра видео проще всего добавить **в каждый site block**
|
||||||
|
(`shineup.me`, `:80` и соответствующие тестовые домены) до общего SPA `handle`:
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
@shinePublicFiles path_regexp shine_public_file ^/files/[0-9a-f]{64}$
|
||||||
|
handle @shinePublicFiles {
|
||||||
|
reverse_proxy 127.0.0.1:7070
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Java проверяет подпись/хеш при PUT, а при GET поддерживает `206`, Range,
|
||||||
|
`Accept-Ranges`, `Content-Range`, узнаёт MP4/WebM по сигнатуре и отдаёт
|
||||||
|
байты потоково без SHA-256 проверки при каждом скачивании. Маршрут должен
|
||||||
|
располагаться раньше SPA fallback; иначе `/files/<sha256>` может получить HTML.
|
||||||
|
Проверьте порт Java-сервера (в примере `7070`). Для больших потоков это
|
||||||
|
проще в настройке, но нагружает Java больше, чем прямая раздача Caddy.
|
||||||
|
|
||||||
|
### Вариант B: прямая отдача Caddy (лучше для большого трафика)
|
||||||
|
|
||||||
|
|
||||||
Маршруты `/files/*` должны стоять **до SPA fallback**.
|
Маршруты `/files/*` должны стоять **до SPA fallback**.
|
||||||
|
|
||||||
```caddyfile
|
```caddyfile
|
||||||
@@ -92,7 +114,7 @@ shineup.me {
|
|||||||
|
|
||||||
Если используется отдельный `:80` site block, тот же `/files` routing нужно добавить и туда либо перенаправлять HTTP на HTTPS.
|
Если используется отдельный `:80` site block, тот же `/files` routing нужно добавить и туда либо перенаправлять HTTP на HTTPS.
|
||||||
|
|
||||||
После изменения:
|
После изменения любого варианта:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||||
@@ -142,6 +164,9 @@ UI дополнительно уже отправляет `Cache-Control: no-sto
|
|||||||
|
|
||||||
```bash
|
```bash
|
||||||
curl -I https://shineup.me/files/<sha256>
|
curl -I https://shineup.me/files/<sha256>
|
||||||
|
curl -i -H 'Range: bytes=0-1023' https://shineup.me/files/<sha256> -o /dev/null -D -
|
||||||
|
# Ожидается: HTTP 206, Content-Range: bytes 0-1023/<size>, Content-Length: 1024
|
||||||
|
# Без Range: 200; Range: bytes=999999999999- : 416 + Content-Range: bytes */<size>
|
||||||
```
|
```
|
||||||
|
|
||||||
Ожидается:
|
Ожидается:
|
||||||
|
|||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Caddy: проксирование SolanaRpcGateway
|
||||||
|
|
||||||
|
Добавьте перед общим `handle` с UI / SPA в **каждый** site block SHiNE:
|
||||||
|
|
||||||
|
```caddyfile
|
||||||
|
@solana_rpc path /solana-rpc
|
||||||
|
handle @solana_rpc {
|
||||||
|
reverse_proxy 127.0.0.1:7070
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Порт `7070` приведён для основного сервера из резервной конфигурации. У t1/t2/t3/t4 используйте фактический локальный Java-порт (например, 7102). Не заменяйте существующие настройки сервера целиком этой вставкой.
|
||||||
|
|
||||||
|
Далее: `caddy validate --config /etc/caddy/Caddyfile`, перезагрузите Caddy и проверьте `POST https://<ваш-сервер>/solana-rpc` с JSON-RPC `getVersion`.
|
||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
## Что уже есть
|
## Что уже есть
|
||||||
|
|
||||||
- основной сервер запускает `SolanaUsersSyncStartupService` до продолжения startup;
|
- основной сервер сначала инициализирует полную PostgreSQL runtime-схему SHiNE, затем запускает `SolanaUsersSyncStartupService` до продолжения startup;
|
||||||
- модуль синхронизации держит актуальными таблицы:
|
- модуль синхронизации держит актуальными таблицы:
|
||||||
- `solana_sync_state`
|
- `solana_sync_state`
|
||||||
- `solana_sync_tx_history`
|
- `solana_sync_tx_history`
|
||||||
@@ -56,7 +56,7 @@ psql \
|
|||||||
-f SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql
|
-f SHiNE-server/shine-server-db/src/main/resources/postgres/schema_v1.sql
|
||||||
```
|
```
|
||||||
|
|
||||||
Скрипт предназначен **только для полностью пустой PostgreSQL схемы**. На старой/непустой базе он завершится ошибкой и не выполняет in-place migration.
|
Скрипт предназначен **только для полностью пустой PostgreSQL схемы**. На старой/непустой базе он завершится ошибкой и не выполняет in-place migration. При обычном первом запуске вручную выполнять его не нужно: сервер сам первым создаёт полную runtime-схему, и только затем стартует Solana sync; это не даёт sync-таблицам ошибочно выглядеть как legacy-БД.
|
||||||
|
|
||||||
Скрипт:
|
Скрипт:
|
||||||
|
|
||||||
@@ -125,3 +125,43 @@ Migration v26 добавляет server-local поля `rotation_status` / `rota
|
|||||||
## Миграции key rotation
|
## Миграции key rotation
|
||||||
|
|
||||||
При обновлении сервера DatabaseInitializer последовательно применяет migration v26 (state machine смены ключей) и v27 (отдельные candidate-блоки будущего fork). Ручного создания таблиц не требуется. Candidate-блоки не входят в текущую таблицу `blocks` до финального переключения fork.
|
При обновлении сервера DatabaseInitializer последовательно применяет migration v26 (state machine смены ключей) и v27 (отдельные candidate-блоки будущего fork). Ручного создания таблиц не требуется. Candidate-блоки не входят в текущую таблицу `blocks` до финального переключения fork.
|
||||||
|
|
||||||
|
|
||||||
|
## Этапы регистрации V2 4–7: подготовка тестового окружения (23.10.2026)
|
||||||
|
|
||||||
|
Перед запуском новой синхронизации нужен тестовый `shine_users` (opcode 7, namespace accounts), применённая PostgreSQL v33, бэкап и отдельная БД. Только после этого разрешён импорт namespace в отдельный регистр `shine_namespace_current`. Не совмещать с существующим UI/production. `freeRegistration.enabled` по умолчанию false; `freeRegistration.registrarSeedFile` — локальный secret path (Base64 seed32) вне Git. При несоответствии регистратора публичному ключу on-chain namespace выдача сертификата прекращается. Нет Arweave importer до этапа 8, API/UI до этапов 9–10. Сначала прогоните чистый snapshot, историю, restart/replay, FK и ключевую ротацию на тестовом контуре.
|
||||||
|
|
||||||
|
|
||||||
|
## DB v35: единый платный статус (26.10.2026)
|
||||||
|
|
||||||
|
`DatabaseInitializer` при запуске сервера последовательно обновляет схему до v35. Старые
|
||||||
|
`PAID_DIRECT` и `PAID_UPGRADED` преобразуются в единый `PAID`; `FREE_CERT` не изменяется.
|
||||||
|
Любой новый пользователь с настоящей PDA Solana получает `PAID` независимо от способа регистрации.
|
||||||
|
Данные аккаунтов, Arweave-сертификаты, начальная дата регистрации и ключи не удаляются.
|
||||||
|
|
||||||
|
Порядок на тестовом контуре: резервная копия БД → обновление серверного кода с `migration_v35.sql`
|
||||||
|
→ перезапуск и проверка `db_schema_version=35` → обновление UI → пробная регистрация и upgrade.
|
||||||
|
До обновления сервера или при неудачной миграции оставьте существующий UI: новое значение `PAID`
|
||||||
|
должно приходить только от сервера с применённой v35. На production — отдельное согласование.
|
||||||
|
Для проверки статусов после миграции:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
SELECT registration_status, count(*) FROM user_identity_current GROUP BY registration_status;
|
||||||
|
SELECT schema_version FROM db_schema_version WHERE id=1;
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Регистронезависимый логин (2026-10-28)
|
||||||
|
Для новых баз важно совместное обновление программы `shine_users`, Java Solana sync/архива и UI. После обновления `login` внутри PDA сохраняет регистр, а адрес и `normalized_login` используют lowercase. Перед проверкой смешанного регистра заново инициализируйте **тестовую** БД и разверните обновлённую Solana-программу в devnet; сам ZIP её не разворачивает.
|
||||||
|
|
||||||
|
## 2026-10-28 — Неизменяемый регистр логина (PostgreSQL v37)
|
||||||
|
|
||||||
|
- В `user_identity_current.login` хранится **написание первой регистрации**, включая заглавные буквы. В `normalized_login` — его lowercase-форма для поиска и уникальности.
|
||||||
|
- v37 добавляет BEFORE INSERT/UPDATE-проверку: `normalized_login = lower(btrim(login))`, а после создания идентичности оба поля неизменяемы.
|
||||||
|
- `shine_sync_identity_from_solana()` отклоняет PDA, если для того же нормализованного имени его `login` не совпадает **точно** с Arweave-сертификатом или предыдущей регистрацией. При FREE_CERT → PAID нельзя изменять только регистр.
|
||||||
|
- Сервер перед первым `AddBlock` сверяет HEADER с точным `user_identity_current.login`; нормализованное имя цепочки этому не противоречит.
|
||||||
|
- Никакого преобразования существующих signed-блоков нет; новая тестовая эпоха создаётся с чистой БД и без старых HEADER.
|
||||||
|
|
||||||
|
## PostgreSQL v38: ключ blockchain state
|
||||||
|
|
||||||
|
После обновления сервера `DatabaseInitializer` автоматически применит migration v38 и при старте нормализует `blockchain_state_store.blockchain_key` из исторического Base58 в Base64(32). Ручной SQL-апдейт для free-пользователей не нужен. После запуска проверьте, что первый `AddBlock` нового free-пользователя проходит без `BAD_BLOCKCHAIN_KEY_LEN`.
|
||||||
|
|||||||
@@ -65,7 +65,8 @@ rsync -a "$SRC_DIR"/ "$TMP_DIR"/
|
|||||||
DEPLOY_CONFIG_FILE="$TMP_DIR/js/deploy-config.js"
|
DEPLOY_CONFIG_FILE="$TMP_DIR/js/deploy-config.js"
|
||||||
if [[ -f "$DEPLOY_CONFIG_FILE" ]]; then
|
if [[ -f "$DEPLOY_CONFIG_FILE" ]]; then
|
||||||
if [[ -n "$DEPLOY_SERVER_LOGIN" ]]; then
|
if [[ -n "$DEPLOY_SERVER_LOGIN" ]]; then
|
||||||
perl -0pi -e "s/export const defaultServerLogin = '.*?';/export const defaultServerLogin = '$DEPLOY_SERVER_LOGIN';/s" "$DEPLOY_CONFIG_FILE"
|
export DEPLOY_SERVER_LOGIN
|
||||||
|
perl -0pi -e 's/export const defaultServerLogin = '\''[^'\'']*'\'';/export const defaultServerLogin = '\''$ENV{DEPLOY_SERVER_LOGIN}'\'';/' "$DEPLOY_CONFIG_FILE"
|
||||||
fi
|
fi
|
||||||
if [[ -n "$DEPLOY_SERVER_ADDRESS" ]]; then
|
if [[ -n "$DEPLOY_SERVER_ADDRESS" ]]; then
|
||||||
perl -0pi -e "s/export const defaultServerAddress = '.*?';/export const defaultServerAddress = '$DEPLOY_SERVER_ADDRESS';/s" "$DEPLOY_CONFIG_FILE"
|
perl -0pi -e "s/export const defaultServerAddress = '.*?';/export const defaultServerAddress = '$DEPLOY_SERVER_ADDRESS';/s" "$DEPLOY_CONFIG_FILE"
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ REMOTE_HOST="player@t2.shineup.me" \
|
|||||||
REMOTE_UI_DIR="/home/player/t2/UI" \
|
REMOTE_UI_DIR="/home/player/t2/UI" \
|
||||||
EXPECTED_CADDY_UI_ROOT="/home/player/t2/UI" \
|
EXPECTED_CADDY_UI_ROOT="/home/player/t2/UI" \
|
||||||
EXPECTED_CADDY_SITE="t2.shineup.me" \
|
EXPECTED_CADDY_SITE="t2.shineup.me" \
|
||||||
DEPLOY_SERVER_LOGIN="server_t2" \
|
DEPLOY_SERVER_LOGIN="server_t2@shine" \
|
||||||
DEPLOY_SERVER_ADDRESS="t2.shineup.me" \
|
DEPLOY_SERVER_ADDRESS="t2.shineup.me" \
|
||||||
DEPLOY_SOLANA_CLUSTER="devnet" \
|
DEPLOY_SOLANA_CLUSTER="devnet" \
|
||||||
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
|
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ REMOTE_HOST="player@t3.shineup.me" \
|
|||||||
REMOTE_UI_DIR="/home/player/t3/UI" \
|
REMOTE_UI_DIR="/home/player/t3/UI" \
|
||||||
EXPECTED_CADDY_UI_ROOT="/home/player/t3/UI" \
|
EXPECTED_CADDY_UI_ROOT="/home/player/t3/UI" \
|
||||||
EXPECTED_CADDY_SITE="t3.shineup.me" \
|
EXPECTED_CADDY_SITE="t3.shineup.me" \
|
||||||
DEPLOY_SERVER_LOGIN="server_t3" \
|
DEPLOY_SERVER_LOGIN="server_t3@shine" \
|
||||||
DEPLOY_SERVER_ADDRESS="t3.shineup.me" \
|
DEPLOY_SERVER_ADDRESS="t3.shineup.me" \
|
||||||
DEPLOY_SOLANA_CLUSTER="devnet" \
|
DEPLOY_SOLANA_CLUSTER="devnet" \
|
||||||
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
|
DEPLOY_SOLANA_ENDPOINT="https://devnet.helius-rpc.com/?api-key=0614c894-52d8-4ddc-bbbc-0947ce5ec3a4" \
|
||||||
|
|||||||
@@ -118,7 +118,7 @@
|
|||||||
|
|
||||||
### Назначение
|
### Назначение
|
||||||
|
|
||||||
Поиск пользователей по префиксу логина. Операция зарегистрирована в серверном API и используется как вспомогательная dev/test операция.
|
Поиск пользователей по префиксу логина и фрагменту публичного имени (`first_name`, `last_name`) без учёта регистра и с нормализацией `ё/е`. Совместимый ответ — массив строк `logins`.
|
||||||
При необходимости можно включить фильтр только по server PDA.
|
При необходимости можно включить фильтр только по server PDA.
|
||||||
|
|
||||||
### Запрос
|
### Запрос
|
||||||
@@ -129,12 +129,14 @@
|
|||||||
"requestId": "search-001",
|
"requestId": "search-001",
|
||||||
"payload": {
|
"payload": {
|
||||||
"prefix": "an",
|
"prefix": "an",
|
||||||
"isServer": true
|
"isServer": true,
|
||||||
|
"limit": 10
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
- `prefix` — обязательный префикс логина.
|
- `prefix` — обязательный поисковый фрагмент (до 120 символов); логины ищутся по началу, публичные имена — по подстроке.
|
||||||
|
- `limit` — необязательное число результатов 1–50, по умолчанию **5** (совместимость с клиентами).
|
||||||
- `isServer` — необязательный boolean-флаг; если `true`, сервер вернёт только логины,
|
- `isServer` — необязательный boolean-флаг; если `true`, сервер вернёт только логины,
|
||||||
у которых в `solana_user_pda_current` стоит `is_server = true`.
|
у которых в `solana_user_pda_current` стоит `is_server = true`.
|
||||||
|
|
||||||
@@ -147,7 +149,11 @@
|
|||||||
"status": 200,
|
"status": 200,
|
||||||
"ok": true,
|
"ok": true,
|
||||||
"payload": {
|
"payload": {
|
||||||
"logins": ["anya", "andrey"]
|
"logins": ["anya", "andrey"],
|
||||||
|
"users": [
|
||||||
|
{ "login": "anya", "displayName": "Анна", "avatarAr": "" },
|
||||||
|
{ "login": "andrey", "displayName": "Андрей", "avatarAr": "" }
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -165,3 +171,11 @@
|
|||||||
- `GetUser` — проверка существования пользователя на сервере.
|
- `GetUser` — проверка существования пользователя на сервере.
|
||||||
- `SearchUsers` — временный поиск пользователей по префиксу.
|
- `SearchUsers` — временный поиск пользователей по префиксу.
|
||||||
- Регистрация выполняется только через Solana.
|
- Регистрация выполняется только через Solana.
|
||||||
|
|
||||||
|
|
||||||
|
## Регистрация V2: полные логины и независимые проверки
|
||||||
|
|
||||||
|
Публичные WS-операции нового протокола перечислены в `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md`.
|
||||||
|
Сначала `GetNamespaces` → `CheckRegistrationLogin` с полным `login@namespace`; затем **только для бесплатной регистрации** отдельное `CheckRegistrationEmail`. После проверки запускается `StartFreeRegistration`, затем `ConfirmFreeRegistration` с тестовым кодом `1111`. Состояние читается через `GetRegistrationStatus`.
|
||||||
|
|
||||||
|
Все бесплатные сертификаты подписаны ANS-104 и внутренней подписью Ed25519; успешный Turbo ACK не означает подтверждённую высоту Arweave. Клиент никогда не отправляет пароль или приватные ключи на сервер.
|
||||||
|
|||||||
@@ -32,14 +32,14 @@
|
|||||||
- generic Ed25519 signature type `2`;
|
- generic Ed25519 signature type `2`;
|
||||||
- Ed25519 signature 64 bytes;
|
- Ed25519 signature 64 bytes;
|
||||||
- owner 32 bytes и равен текущему blockchain public key;
|
- owner 32 bytes и равен текущему blockchain public key;
|
||||||
- обязательный тестовый tag `App=test5591`;
|
- обязательный тестовый tag `App=test5592`;
|
||||||
- для channel block — `c=<canonical_channel_slug>`;
|
- для channel block — `c=<canonical_channel_slug>`;
|
||||||
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
|
- `TEXT_CHANNEL_DELETE (type=1/subType=92/version=1)` является обычным line-based channel block с пустым text и тем же обязательным `c=<slug>`; отдельной операции API для удаления канала нет;
|
||||||
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
|
- `data` содержит SHiNE Frame v1 (`frameCode=1`).
|
||||||
|
|
||||||
## Основные ошибки
|
## Основные ошибки
|
||||||
|
|
||||||
- `bad_app_tag` — отсутствует/неверен `App=test5591`;
|
- `bad_app_tag` — отсутствует/неверен `App=test5592`;
|
||||||
- `bad_channel_tag` — `c` отсутствует, лишний или не совпадает с canonical slug;
|
- `bad_channel_tag` — `c` отсутствует, лишний или не совпадает с canonical slug;
|
||||||
- `bad_signature` / `signature_verify_failed` — DataItem не подписан текущим blockchain key;
|
- `bad_signature` / `signature_verify_failed` — DataItem не подписан текущим blockchain key;
|
||||||
- `bad_block_number` — нарушена последовательность;
|
- `bad_block_number` — нарушена последовательность;
|
||||||
|
|||||||
@@ -587,3 +587,62 @@ Channel/message responses expose three counters:
|
|||||||
- `shiningLikesCount` — likes from users who are currently both `primary` and `shining`.
|
- `shiningLikesCount` — likes from users who are currently both `primary` and `shining`.
|
||||||
|
|
||||||
Changing `account_role` or `shine` does not alter the raw reaction. The two qualified counters are recalculated from `reactions_state`; therefore old likes automatically enter or leave qualified counters when the actor's current status changes.
|
Changing `account_role` or `shine` does not alter the raw reaction. The two qualified counters are recalculated from `reactions_state`; therefore old likes automatically enter or leave qualified counters when the actor's current status changes.
|
||||||
|
|
||||||
|
|
||||||
|
## `SearchChannels` — публичный поиск каналов (v32)
|
||||||
|
|
||||||
|
Операция **без авторизации**, на текущем сервере (не федеративный поиск).
|
||||||
|
Результаты берутся из актуального состояния `channel_names_state`; публичные каналы — `channel_type_code = 1`, не удалённые (`is_deleted = false`).
|
||||||
|
|
||||||
|
Запрос:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"op": "SearchChannels",
|
||||||
|
"requestId": "search-ch-1",
|
||||||
|
"payload": { "query": "гриб", "limit": 10 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `query` — текст от 1 до 120 символов. Не обязателен, если указан `ownerLogin`.
|
||||||
|
- `ownerLogin` — дополнительное ограничение по началу логина владельца, до 80 символов.
|
||||||
|
- `limit` — число результатов, по умолчанию 10, допустимо 1–50. Курсора и пагинации нет.
|
||||||
|
- `@anna` — каналы владельцев, чьи логины содержат `anna`.
|
||||||
|
- `anna/art` — каналы владельца `anna`, у которых публичное либо техническое название содержит `art`.
|
||||||
|
- `anna/` — все доступные каналы владельца `anna`.
|
||||||
|
- В обычном запросе ищутся **подстроки** в публичном имени `display_name`, техническом `slug` и логине `owner_login`. Регистр не важен, `ё` приравнивается к `е`. Вводимые `%`, `_` и `!` не работают как SQL-маски.
|
||||||
|
- Сначала идут точные совпадения с названием или slug, затем префиксные, затем частичные, далее учитывается количество подписчиков.
|
||||||
|
|
||||||
|
Ответ:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"op": "SearchChannels",
|
||||||
|
"requestId": "search-ch-1",
|
||||||
|
"status": 200,
|
||||||
|
"ok": true,
|
||||||
|
"payload": {
|
||||||
|
"channels": [{
|
||||||
|
"ownerLogin": "anna",
|
||||||
|
"slug": "fungal-art",
|
||||||
|
"displayName": "Грибной мир",
|
||||||
|
"description": "Картины и грибы",
|
||||||
|
"avatarAr": "",
|
||||||
|
"avatarSha256": "",
|
||||||
|
"ownerBlockchainName": "anna-001",
|
||||||
|
"rootBlockNumber": 12,
|
||||||
|
"rootBlockHashHex": "<hex>",
|
||||||
|
"subscribersCount": 128
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Массив `channels` пустой при отсутствии совпадений; URL не возвращается.
|
||||||
|
`ownerBlockchainName` и корневой блок позволяют клиенту открыть канонический канал через существующую маршрутизацию.
|
||||||
|
Неверные поля: HTTP-подобный статус `400`, код `BAD_FIELDS`; ошибки чтения БД: `SERVER_DATA_ERROR`, `DB_ERROR`.
|
||||||
|
Структура блокчейна не меняется. Индексы поиска добавлены миграцией БД v32 (`pg_trgm`).
|
||||||
|
|
||||||
|
## 2026-10-28 — Официальный регистр логинов при чтении
|
||||||
|
|
||||||
|
В ответах `GetChannelMessages`, `GetMessageThread`, `ListSubscriptionsFeed` поля `authorLogin` и `ownerLogin` показывают **регистрационное написание** из `user_identity_current`, например `AlexSmith@shine`. В БД блока и в `blockchainName` по-прежнему возможен lowercase, используемый как нормализованный идентификатор. Это не меняет имена JSON-полей или типы значений, а уточняет их семантику. Для поиска и переходов разные варианты регистра по-прежнему ссылаются на одну идентичность; байты уже подписанных блоков не переписываются.
|
||||||
|
|||||||
@@ -13,7 +13,8 @@
|
|||||||
| Операция | Раздел документации | Кратко |
|
| Операция | Раздел документации | Кратко |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `GetUser` | `01_User_Registration_API.md` | чтение/проверка пользователя + server-состояние его блокчейна |
|
| `GetUser` | `01_User_Registration_API.md` | чтение/проверка пользователя + server-состояние его блокчейна |
|
||||||
| `SearchUsers` | `01_User_Registration_API.md` | поиск логинов по префиксу |
|
| `SearchUsers` | `01_User_Registration_API.md` | поиск логинов и публичных имён пользователей |
|
||||||
|
| `SearchChannels` | `06_Channels_Read_API.md` | поиск публичных каналов по названию, slug и логину владельца |
|
||||||
| `ResolveLoginForAuth` | `02_Authentication_API.md` | проверка login перед входом: LOCAL / REMOTE / NOT_FOUND / NO_ACCESS_SERVER + URL правильного access server |
|
| `ResolveLoginForAuth` | `02_Authentication_API.md` | проверка login перед входом: LOCAL / REMOTE / NOT_FOUND / NO_ACCESS_SERVER + URL правильного access server |
|
||||||
| `AuthChallenge` | `02_Authentication_API.md` | challenge для создания новой сессии |
|
| `AuthChallenge` | `02_Authentication_API.md` | challenge для создания новой сессии |
|
||||||
| `CreateAuthSession` | `02_Authentication_API.md` | создание новой авторизованной сессии |
|
| `CreateAuthSession` | `02_Authentication_API.md` | создание новой авторизованной сессии |
|
||||||
@@ -94,3 +95,25 @@
|
|||||||
- HTTP endpoints публичных content-addressed файлов (`PUT/GET/HEAD/OPTIONS /files/{sha256}`) также не являются WebSocket `op` и описаны отдельно в `21_Public_File_Storage_API.md`.
|
- HTTP endpoints публичных content-addressed файлов (`PUT/GET/HEAD/OPTIONS /files/{sha256}`) также не являются WebSocket `op` и описаны отдельно в `21_Public_File_Storage_API.md`.
|
||||||
- Классы `Net_MarkChannelMessagesSeen_*` существуют в коде, но операция `MarkChannelMessagesSeen` не зарегистрирована в `JsonHandlerRegistry`, поэтому в публичный список API не входит.
|
- Классы `Net_MarkChannelMessagesSeen_*` существуют в коде, но операция `MarkChannelMessagesSeen` не зарегистрирована в `JsonHandlerRegistry`, поэтому в публичный список API не входит.
|
||||||
- HTTP debug endpoints из `src/main/java/server/debug/` не входят в этот индекс WebSocket `op`; они описаны отдельно в `13_HTTP_Debug_API.md`.
|
- HTTP debug endpoints из `src/main/java/server/debug/` не входят в этот индекс WebSocket `op`; они описаны отдельно в `13_HTTP_Debug_API.md`.
|
||||||
|
|
||||||
|
|
||||||
|
## Registration V2 (добавлено 23.10.2026, test/dev only)
|
||||||
|
|
||||||
|
- `GetNamespaces` — список зарегистрированных namespace из Solana-синхронизации;
|
||||||
|
- `CheckRegistrationLogin` — отдельная проверка `login@namespace`;
|
||||||
|
- `CheckRegistrationEmail` — отдельная проверка email;
|
||||||
|
- `StartFreeRegistration` — запрос сертификата по трём публичным ключам;
|
||||||
|
- `ConfirmFreeRegistration` — подтверждение тестовым кодом и Turbo ACK;
|
||||||
|
- `GetRegistrationStatus` — статус и публичные поля сертификата для upgrade.
|
||||||
|
|
||||||
|
Точный JSON и ограничения: `docs/registration-v2/WS_REGISTRATION_V2_PROPOSED_NOT_ENABLED.md` (имя сохранено для обратных ссылок; внутри утверждённая версия).
|
||||||
|
|
||||||
|
### `GetRegistrationStatus` после DB v35
|
||||||
|
|
||||||
|
Для существующего пользователя `payload.registrationStatus` имеет одно из **двух** значений:
|
||||||
|
`FREE_CERT` (бесплатная регистрация Arweave) или `PAID` (подтверждённая PDA Solana).
|
||||||
|
`PAID` применяется и к первоначально платным, и к ранее бесплатным пользователям;
|
||||||
|
`NOT_FOUND` остаётся техническим ответом для отсутствующего логина.
|
||||||
|
Во время поэтапного развертывания старый сервер может ещё возвращать `PAID_DIRECT`
|
||||||
|
или `PAID_UPGRADED`; обновлённый UI понимает эти устаревшие ответы как платные.
|
||||||
|
Поля сертификата для `FREE_CERT` и остальные поля API не меняются.
|
||||||
|
|||||||
@@ -324,10 +324,16 @@ signed-блока проверяется всегда. Официальный UI
|
|||||||
"timeMs": 1774700000123,
|
"timeMs": 1774700000123,
|
||||||
"nonce": 123456789,
|
"nonce": 123456789,
|
||||||
"blobB64": "BASE64_SIGNED_BLOCK",
|
"blobB64": "BASE64_SIGNED_BLOCK",
|
||||||
"backlog": false
|
"backlog": false,
|
||||||
|
"unreadCount": 3,
|
||||||
|
"notificationVersionMs": 1774700000456
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
`unreadCount` и `notificationVersionMs` добавляются только для нового входящего type=1 при обычной realtime-доставке. Это серверный снимок `dm_dialog_state`; для backlog, read-receipts и других типов эти поля могут отсутствовать. `notificationVersionMs` монотонно увеличивается при обновлении состояния конкретной переписки; формат подписанного блока не меняется.
|
||||||
|
|
||||||
|
При отсутствии активного WebSocket сервер отправляет Web Push с полями `kind=new_message`, `toLogin`, `fromLogin`, `messageKey`, `unreadCount`, `notificationVersionMs`. Push не содержит расшифрованного текста. Service Worker показывает по одной карточке на пару (получатель, отправитель), обновляя счётчик с запросом нового звукового оповещения для каждого нового сообщения.
|
||||||
|
|
||||||
Если это новая ревизия того же письма, `messageKey` остаётся тем же, а `revisionTimeMs` меняется внутри бинарного блока.
|
Если это новая ревизия того же письма, `messageKey` остаётся тем же, а `revisionTimeMs` меняется внутри бинарного блока.
|
||||||
|
|
||||||
Для типов `5/6/7/8` событие тоже приходит в таком же конверте, но логика применения определяется `messageType` и бинарным `blobB64`.
|
Для типов `5/6/7/8` событие тоже приходит в таком же конверте, но логика применения определяется `messageType` и бинарным `blobB64`.
|
||||||
|
|||||||
@@ -248,7 +248,7 @@
|
|||||||
|
|
||||||
Если Solana sync успел увидеть новое PDA раньше вызова `KeyRotationRotatePda`, он умеет подтвердить ожидаемые ключи прямо из `CHAIN_READY`. Поэтому потеря клиентского запроса после уже подтверждённой Solana-транзакции не оставляет ротацию зависшей. Если API-вызов всё же приходит, handler идемпотентно возвращает текущее подтверждённое состояние.
|
Если Solana sync успел увидеть новое PDA раньше вызова `KeyRotationRotatePda`, он умеет подтвердить ожидаемые ключи прямо из `CHAIN_READY`. Поэтому потеря клиентского запроса после уже подтверждённой Solana-транзакции не оставляет ротацию зависшей. Если API-вызов всё же приходит, handler идемпотентно возвращает текущее подтверждённое состояние.
|
||||||
|
|
||||||
Повтор с той же signature идемпотентен. Другая signature для уже начатого `ROTATING_PDA` возвращает conflict.
|
Повтор с той же signature идемпотентен: при `PDA_ROTATED`, `REBUILDING_SERVER`, `WALLET_MIGRATION`, `MESSAGE_MIGRATION` и `FINALIZING` возвращается актуальное состояние без ошибки 409. Это закрывает гонку Solana sync с уведомлением UI. Если signature ранее сохранена, конфликтующая signature возвращает conflict.
|
||||||
|
|
||||||
### Основные ошибки
|
### Основные ошибки
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user