MVP: весь функционал сервера работает

Версия main, в которой по сути весь функционал сервера работает для MVP.
This commit is contained in:
AidarKC
2026-10-08 22:55:39 +03:00
350 changed files with 20879 additions and 25114 deletions
@@ -1,30 +0,0 @@
-proc:none
-d
/tmp/javac-check
-sourcepath
SHiNE-server/shine-server-geo/src/main/java:SHiNE-server/shine-server-log/src/main/java:SHiNE-server/shine-server-solana-users-sync/src/main/java:SHiNE-server/shine-server-db/src/main/java:SHiNE-server/src/main/java:SHiNE-server/shine-server-archive/src/main/java:SHiNE-server/shine-server-blockchain/src/main/java:SHiNE-server/shine-server-crypto/src/main/java:SHiNE-server/shine-server-net-protocol/src/main/java:SHiNE-server/shine-server-config/src/main/java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-net-protocol/src/main/java/server/sync/BlockchainResyncGuard.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/JsonHandlerRegistry.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-net-protocol/src/main/java/server/logic/ws_protocol/JSON/handlers/blockchain/Net_AddBlock_Handler_utils/BlockchainWriter.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-blockchain/src/main/java/blockchain/Ans104DataItem.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-blockchain/src/main/java/blockchain/BchCryptoVerifier.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-blockchain/src/main/java/blockchain/BchBlockEntry.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlocksConfig.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlockSyncScheduler.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveMerkle.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlockSyncService.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlockPublisherScheduler.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/Ans104Bundle.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveL1Uploader.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-archive/src/main/java/server/archive/ArweaveBlockPublisherService.java
/mnt/data/shine_patch_final_work/SHiNE-server/src/main/java/server/ws/WsServer.java
/mnt/data/shine_patch_final_work/SHiNE-server/src/main/java/server/sync/PeriodicBlockchainSyncService.java
/mnt/data/shine_patch_final_work/SHiNE-server/src/test/java/test/it/blockchain/AddBlockSender.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/DatabaseInitializer.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/entities/BlockEntry.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/ArweaveBlockImportDAO.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/BlockchainResyncCleanupDAO.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/BlocksDAO.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/ChannelNameStateDAO.java
/mnt/data/shine_patch_final_work/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/SolanaUserPdaCurrentDAO.java
+1
View File
@@ -78,6 +78,7 @@ shine-solana/shine/scripts/**/TEMP_*.md
# Локальные артефакты и внешние материалы ESP32-подпроекта
ESP32/esp32-config-tool/
ESP32/local-sketches/
ESP32/**/.git/
ESP32/**/.idea/
ESP32-wallet/.idea/
+4 -7
View File
@@ -138,11 +138,8 @@
- с какого сценария продолжать разработку;
- из какого коммита брать последнюю полную реализацию.
## Коммуникация по новым задачам (обязательно)
- При получении нового задания сначала кратко пересказать задачу своими словами.
- До начала реализации задать недостающие уточняющие вопросы (если они есть).
## Коммуникация по новым задачам
- При получении нового задания кратко подтвердить понимание задачи, если это помогает синхронизироваться.
- До начала реализации задавать уточняющие вопросы только когда без ответа есть риск сделать не то или затронуть опасную область.
- Если задача понятна и не требует отдельного подтверждения по другим правилам проекта, переходить к реализации сразу.
- Если есть уместные идеи/улучшения — кратко предложить их; если полезных идей нет, ничего дополнительно не предлагать.
- Добавлять краткую оценку фичи (насколько это полезно/удачно по мнению исполнителя).
- После этого обязательно запросить подтверждение от пользователя, что задача понята верно, и только после подтверждения переходить к реализации.
- Если вопросов нет, явно написать в формате: «Я всё понял, начинаю делать?» и ждать подтверждения.
- Без подтверждения пользователя реализацию не начинать.
@@ -47,10 +47,13 @@ case "${MODE}" in
lvgl-official-based-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_official_based_test" ;;
lvgl-subserver-touch-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_subserver_touch_test" ;;
lvgl-russian-font-test) SKETCH_DIR="${ROOT_DIR}/test_sketches/lvgl_russian_font_test" ;;
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-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" ;;
*)
echo "Unknown mode: ${MODE}" >&2
echo "Use one of: hello, widgets, audio, simple, argon2, homeserver-ui, shine-homeserver-main, shine-homeserver-ui-main, legacy-homeserver-ui, text-test, gfx-text-test, gfx-layout-test, lvgl-basic-test, lvgl-interaction-test, lvgl-touch-debug-test, lvgl-official-based-test, lvgl-subserver-touch-test, lvgl-russian-font-test" >&2
echo "Use one of: 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
exit 2
;;
esac
@@ -78,6 +81,7 @@ compile_args=(
--library "${DEMO_BASE}/libraries/XPowersLib"
--library "${DEMO_BASE}/libraries/lvgl"
--library "${DEMO_BASE}/libraries/Mylibrary"
--library "${ROOT_DIR}/simple_av_test"
"${SKETCH_DIR}"
)
@@ -15,6 +15,8 @@
- `lvgl_official_based_test/` - минимальный наш экран поверх максимально близкой к официальному `05_LVGL_Widgets` инициализации
- `lvgl_subserver_touch_test/` - старый гибридный тест: `LVGL`-экран с инициализацией дисплея и чтением touch из старого `shine_homeserver_ui`; подтверждён на реальном устройстве
- `lvgl_russian_font_test/` - тест кастомного кириллического `LVGL`-шрифта с русскими кнопками, длинными строками и рабочим touch
- `usb_contact_sensor_test/` - тест переключения нативных USB D-/D+ (`GPIO19/20`) в режим простого замыкаемого контакта после нажатия Start; после перезагрузки снова обычный USB
- `usb_contact_sensor_debug_test/` - debug-версия теста замыкания контакта: экранная кнопка проверяет touch, а переход в sensor mode выполняется физической кнопкой BOOT
- `lvgl_nav_minimal_test/` - старое тестовое имя, этот скетч перенесён в `shine_homeserver_main/` и теперь является основным
## Запуск
@@ -29,3 +31,5 @@
- `./burn.sh lvgl-official-based-test`
- `./burn.sh lvgl-subserver-touch-test`
- `./burn.sh lvgl-russian-font-test`
- `./burn.sh usb-contact-test`
- `./burn.sh usb-contact-debug-test`
@@ -0,0 +1,600 @@
#include <Arduino.h>
#include <Wire.h>
#include <math.h>
#include <Preferences.h>
#include <Arduino_GFX_Library.h>
#include <TouchDrvCSTXXX.hpp>
#include "ESP_I2S.h"
#include "es8311.h"
#define PIN_LCD_CS 12
#define PIN_LCD_SCLK 38
#define PIN_LCD_D0 4
#define PIN_LCD_D1 5
#define PIN_LCD_D2 6
#define PIN_LCD_D3 7
#define PIN_LCD_RST 2
#define PIN_I2C_SDA 15
#define PIN_I2C_SCL 14
#define PIN_TP_INT 11
#define PIN_USER_BTN 0
#define PIN_PA 46
#define PIN_I2S_BCLK 9
#define PIN_I2S_LRCK 45
#define PIN_I2S_DOUT 8
#define PIN_I2S_DIN 10
#define PIN_I2S_MCLK 42
#define DISP_W 480
#define DISP_H 480
static constexpr int kUsbDmPin = 19;
static constexpr int kUsbDpPin = 20;
static constexpr uint32_t kContactDebounceMs = 80;
static constexpr uint32_t kButtonDebounceMs = 45;
static constexpr uint32_t kUiPeriodMs = 200;
static constexpr uint32_t kSampleRate = 16000;
static constexpr uint32_t kMinCycleMs = 1500;
static constexpr uint32_t kPauseAfterMs = 60000;
#define C_BG 0x0841u
#define C_PANEL 0x1082u
#define C_CARD 0x18C3u
#define C_BORDER 0x39C7u
#define C_TEXT 0xFFFFu
#define C_MUTE 0xBDF7u
#define C_ACCENT 0x5D5Fu
#define C_OK 0x3666u
#define C_BAD 0xD145u
#define C_BUTTON 0x2145u
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
PIN_LCD_CS, PIN_LCD_SCLK, PIN_LCD_D0, PIN_LCD_D1, PIN_LCD_D2, PIN_LCD_D3);
Arduino_CO5300 *gfx = new Arduino_CO5300(
gBus, PIN_LCD_RST, 0, DISP_W, DISP_H, 0, 0, 0, 0);
TouchDrvCST92xx gTouch;
I2SClass gI2s;
Preferences gPrefs;
struct Rect {
int16_t x;
int16_t y;
int16_t w;
int16_t h;
};
static const Rect kStartButton = {96, 348, 288, 78};
static const Rect kLimitSlider = {42, 132, 396, 44};
static const Rect kTickSlider = {42, 246, 396, 44};
static const Rect kAlertSlider = {42, 360, 396, 44};
static const uint16_t kLimitsSec[] = {5, 7, 10, 15, 20};
static const int16_t kTickAmpByVolume[] = {0, 40, 80, 140, 220, 320, 440, 580, 720, 800, 1600};
static const int16_t kAlertAmpByVolume[] = {0, 150, 300, 500, 800, 12000, 12000, 12000, 12000, 12000, 12000};
static bool gStarted = false;
static bool gSettingsOpen = false;
static bool gAudioReady = false;
static bool gStableClosed = false;
static bool gLastRawClosed = false;
static bool gStaticDrawn = false;
static bool gNeedRedraw = true;
static bool gNeedStaticRedraw = true;
static bool gLastDrawnClosed = false;
static bool gLastDrawnPaused = false;
static bool gTouchDown = false;
static bool gUserButtonDown = false;
static int16_t gTouchStartX = 0;
static int16_t gTouchStartY = 0;
static int16_t gTouchLastX = 0;
static int16_t gTouchLastY = 0;
static uint32_t gLastRawChangeMs = 0;
static uint32_t gStartedMs = 0;
static uint32_t gLastCycleStartMs = 0;
static uint32_t gLastUiMs = 0;
static uint32_t gUserButtonChangeMs = 0;
static uint32_t gCycleMs[5] = {};
static uint8_t gCycleCount = 0;
static uint8_t gCycleNext = 0;
static uint8_t gLimitIndex = 2;
static uint8_t gTickVolume = 3;
static uint8_t gAlertVolume = 10;
static uint8_t gShortStreak = 0;
static char gLastTopLine[48] = "";
static char gLastStreakLine[48] = "";
static void drawPanel(int x, int y, int w, int h, uint16_t fill, uint16_t border, int radius = 10) {
gfx->fillRoundRect(x, y, w, h, radius, fill);
gfx->drawRoundRect(x, y, w, h, radius, border);
}
static void drawText(int x, int y, const char *text, uint16_t color, uint8_t size = 2) {
gfx->setFont();
gfx->setTextSize(size);
gfx->setTextColor(color);
gfx->setCursor(x, y);
gfx->print(text);
}
static void drawCenteredText(int x, int y, int w, const char *text, uint16_t color, uint8_t size = 2) {
int textW = strlen(text) * 6 * size;
int textX = x + (w - textW) / 2;
if (textX < x + 8) {
textX = x + 8;
}
drawText(textX, y, text, color, size);
}
static void drawButton(const Rect &rect, const char *label, uint8_t size = 2) {
drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12);
drawCenteredText(rect.x, rect.y + 18, rect.w, label, C_TEXT, size);
}
static bool contains(const Rect &rect, int16_t x, int16_t y) {
return x >= rect.x && x < rect.x + rect.w && y >= rect.y && y < rect.y + rect.h;
}
static void clearArea(int x, int y, int w, int h, uint16_t fill) {
gfx->fillRect(x, y, w, h, fill);
}
static void formatSec(char *out, size_t outSize, uint32_t ms) {
snprintf(out, outSize, "%lu.%01lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100));
}
static void formatClock(char *out, size_t outSize, uint32_t ms) {
uint32_t sec = ms / 1000;
snprintf(out, outSize, "%02lu:%02lu", (unsigned long)(sec / 60), (unsigned long)(sec % 60));
}
static uint32_t averageCycleMs() {
if (gCycleCount == 0) {
return 0;
}
uint32_t sum = 0;
for (uint8_t i = 0; i < gCycleCount; i++) {
sum += gCycleMs[i];
}
return sum / gCycleCount;
}
static void resetCachedUiText() {
gLastTopLine[0] = '\0';
gLastStreakLine[0] = '\0';
}
static void loadSettings() {
gPrefs.begin("breath-mon", false);
gLimitIndex = gPrefs.getUChar("limit", gLimitIndex);
gTickVolume = gPrefs.getUChar("tick", gTickVolume);
gAlertVolume = gPrefs.getUChar("alert", gAlertVolume);
if (gLimitIndex > 4) {
gLimitIndex = 2;
}
if (gTickVolume > 10) {
gTickVolume = 3;
}
if (gAlertVolume > 10) {
gAlertVolume = 10;
}
}
static void saveSettings() {
gPrefs.putUChar("limit", gLimitIndex);
gPrefs.putUChar("tick", gTickVolume);
gPrefs.putUChar("alert", gAlertVolume);
}
static bool isAutoPaused() {
return gStarted && gLastCycleStartMs != 0 && (millis() - gLastCycleStartMs) > kPauseAfterMs;
}
static esp_err_t codecInit() {
es8311_handle_t esHandle = es8311_create(0, ES8311_ADDRRES_0);
if (!esHandle) {
return ESP_FAIL;
}
const es8311_clock_config_t clk = {
.mclk_inverted = false,
.sclk_inverted = false,
.mclk_from_mclk_pin = true,
.mclk_frequency = (int)kSampleRate * 256,
.sample_frequency = (int)kSampleRate,
};
if (es8311_init(esHandle, &clk, ES8311_RESOLUTION_16, ES8311_RESOLUTION_16) != ESP_OK) {
return ESP_FAIL;
}
es8311_voice_volume_set(esHandle, 100, nullptr);
es8311_voice_mute(esHandle, false);
return ESP_OK;
}
static void initAudio() {
pinMode(PIN_PA, OUTPUT);
digitalWrite(PIN_PA, HIGH);
gI2s.setPins(PIN_I2S_BCLK, PIN_I2S_LRCK, PIN_I2S_DOUT, PIN_I2S_DIN, PIN_I2S_MCLK);
if (!gI2s.begin(I2S_MODE_STD, kSampleRate, I2S_DATA_BIT_WIDTH_16BIT, I2S_SLOT_MODE_STEREO, I2S_STD_SLOT_BOTH)) {
Serial.println("I2S init failed");
return;
}
gAudioReady = (codecInit() == ESP_OK);
Serial.println(gAudioReady ? "Audio init OK" : "Audio codec init failed");
}
static void playBeep(uint16_t freq, uint16_t samples, int16_t amp) {
if (!gAudioReady || amp <= 0) {
return;
}
static int16_t toneBuf[1600 * 2];
if (samples > 1600) {
samples = 1600;
}
for (int i = 0; i < samples; i++) {
float s = sinf(2.0f * 3.1415926f * (float)freq * ((float)i / (float)kSampleRate));
int16_t v = (int16_t)(s * amp);
toneBuf[i * 2] = v;
toneBuf[i * 2 + 1] = v;
}
gI2s.write((uint8_t *)toneBuf, samples * 2 * sizeof(int16_t));
}
static void playCycleTick() {
playBeep(880, 480, kTickAmpByVolume[gTickVolume]);
}
static void playAlertBeep() {
playBeep(1200, 1600, kAlertAmpByVolume[gAlertVolume]);
}
static void alertIfNeeded() {
if (gShortStreak == 0) {
return;
}
uint8_t count = min<uint8_t>(gShortStreak, 5);
for (uint8_t i = 0; i < count; i++) {
playAlertBeep();
delay(80);
}
}
static void addCycle(uint32_t cycleMs) {
gCycleMs[gCycleNext] = cycleMs;
gCycleNext = (gCycleNext + 1) % 5;
if (gCycleCount < 5) {
gCycleCount++;
}
uint32_t avgMs = averageCycleMs();
if (avgMs > 0 && avgMs < (uint32_t)kLimitsSec[gLimitIndex] * 1000UL) {
if (gShortStreak < 5) {
gShortStreak++;
}
} else {
gShortStreak = 0;
}
}
static void drawReadyScreen() {
gfx->fillScreen(C_BG);
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
drawText(28, 42, "BREATH MONITOR", C_TEXT, 3);
drawText(28, 78, "USB contact sensor", C_MUTE, 2);
drawPanel(34, 132, 412, 160, C_CARD, C_BORDER, 14);
drawCenteredText(34, 166, 412, "READY", C_ACCENT, 4);
drawCenteredText(34, 222, 412, "Closed = exhale", C_TEXT, 2);
drawCenteredText(34, 252, 412, "Open = inhale", C_MUTE, 2);
drawButton(kStartButton, "START", 3);
}
static void drawSlider(const Rect &rect, const char *title, const char *value, uint8_t pos, uint8_t maxPos) {
drawText(rect.x, rect.y - 28, title, C_TEXT, 2);
drawText(rect.x + 278, rect.y - 28, value, C_ACCENT, 2);
drawPanel(rect.x, rect.y, rect.w, rect.h, C_BUTTON, C_BORDER, 12);
int trackX = rect.x + 22;
int trackW = rect.w - 44;
int trackY = rect.y + rect.h / 2 - 3;
gfx->fillRect(trackX, trackY, trackW, 6, C_BORDER);
int knobX = trackX + (trackW * pos) / max<uint8_t>(1, maxPos);
gfx->fillRoundRect(knobX - 10, rect.y + 8, 20, rect.h - 16, 8, C_ACCENT);
}
static void drawSettingsScreen() {
char value[24];
gfx->fillScreen(C_BG);
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
drawText(28, 36, "SETTINGS", C_TEXT, 3);
drawText(28, 72, "Press top button to close", C_MUTE, 2);
snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]);
drawSlider(kLimitSlider, "Limit", value, gLimitIndex, 4);
snprintf(value, sizeof(value), "%u/10", gTickVolume);
drawSlider(kTickSlider, "Cycle tick volume", value, gTickVolume, 10);
snprintf(value, sizeof(value), "%u/10", gAlertVolume);
drawSlider(kAlertSlider, "Alert volume", value, gAlertVolume, 10);
gStaticDrawn = false;
gNeedStaticRedraw = true;
}
static void drawMonitorStatic() {
gfx->fillScreen(C_BG);
drawPanel(12, 12, 456, 456, C_PANEL, C_BORDER, 16);
drawText(28, 32, "BREATH MONITOR", C_TEXT, 2);
drawPanel(28, 96, 424, 104, C_CARD, C_BORDER, 14);
drawPanel(28, 216, 200, 72, C_CARD, C_BORDER, 10);
drawText(42, 236, "Current", C_MUTE, 1);
drawPanel(252, 216, 200, 72, C_CARD, C_BORDER, 10);
drawText(266, 236, "Average 5", C_MUTE, 1);
drawPanel(28, 304, 200, 64, C_CARD, C_BORDER, 10);
drawText(42, 322, "From start", C_MUTE, 1);
drawPanel(252, 304, 200, 64, C_CARD, C_BORDER, 10);
drawText(266, 322, "Limit", C_MUTE, 1);
gStaticDrawn = true;
gLastDrawnClosed = !gStableClosed;
gLastDrawnPaused = !isAutoPaused();
resetCachedUiText();
}
static void updateMonitorValues(bool force) {
char line[48];
char value[16];
uint32_t now = millis();
uint32_t runMs = now - gStartedMs;
uint32_t currentMs = (gLastCycleStartMs == 0) ? 0 : now - gLastCycleStartMs;
bool paused = isAutoPaused();
if (paused) {
currentMs = now - gLastCycleStartMs - kPauseAfterMs;
}
uint32_t avgMs = averageCycleMs();
if (force || gLastDrawnClosed != gStableClosed || gLastDrawnPaused != paused) {
clearArea(42, 118, 396, 68, C_CARD);
if (paused) {
drawCenteredText(28, 122, 424, "PAUSE", C_BAD, 4);
drawCenteredText(28, 172, 424, "no cycle for 60s", C_MUTE, 2);
} else {
drawCenteredText(28, 122, 424, gStableClosed ? "EXHALE" : "INHALE",
gStableClosed ? C_OK : C_ACCENT, 4);
drawCenteredText(28, 172, 424, gStableClosed ? "contact closed" : "contact open", C_MUTE, 2);
}
gLastDrawnClosed = gStableClosed;
gLastDrawnPaused = paused;
}
snprintf(line, sizeof(line), "Limit: %us top button: settings", kLimitsSec[gLimitIndex]);
if (strcmp(line, gLastTopLine) != 0) {
clearArea(28, 58, 424, 28, C_PANEL);
drawText(28, 60, line, C_MUTE, 2);
strncpy(gLastTopLine, line, sizeof(gLastTopLine) - 1);
gLastTopLine[sizeof(gLastTopLine) - 1] = '\0';
}
clearArea(42, 254, 160, 28, C_CARD);
formatSec(value, sizeof(value), currentMs);
drawText(42, 256, value, C_TEXT, 3);
clearArea(266, 254, 160, 28, C_CARD);
if (avgMs > 0) {
formatSec(value, sizeof(value), avgMs);
} else {
snprintf(value, sizeof(value), "--");
}
drawText(266, 256, value, C_TEXT, 3);
clearArea(42, 340, 160, 24, C_CARD);
formatClock(value, sizeof(value), runMs);
drawText(42, 342, value, C_TEXT, 2);
clearArea(266, 340, 160, 24, C_CARD);
snprintf(value, sizeof(value), "%us", kLimitsSec[gLimitIndex]);
drawText(266, 342, value, C_TEXT, 2);
snprintf(line, sizeof(line), "Short avg streak: %u", gShortStreak);
if (strcmp(line, gLastStreakLine) != 0) {
clearArea(28, 398, 280, 28, C_PANEL);
drawText(32, 402, line, gShortStreak > 0 ? C_BAD : C_MUTE, 2);
strncpy(gLastStreakLine, line, sizeof(gLastStreakLine) - 1);
gLastStreakLine[sizeof(gLastStreakLine) - 1] = '\0';
}
}
static void redrawScreen() {
if (gSettingsOpen) {
drawSettingsScreen();
} else if (gStarted) {
if (gNeedStaticRedraw || !gStaticDrawn) {
drawMonitorStatic();
gNeedStaticRedraw = false;
}
updateMonitorValues(true);
} else {
drawReadyScreen();
}
gNeedRedraw = false;
gLastUiMs = millis();
}
static void enterSensorMode() {
Serial.flush();
delay(30);
pinMode(kUsbDmPin, OUTPUT);
digitalWrite(kUsbDmPin, LOW);
pinMode(kUsbDpPin, INPUT_PULLUP);
uint32_t now = millis();
gStarted = true;
gStartedMs = now;
gLastCycleStartMs = 0;
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
gStableClosed = gLastRawClosed;
gLastRawChangeMs = now;
if (gStableClosed) {
gLastCycleStartMs = now;
playCycleTick();
}
gNeedStaticRedraw = true;
gNeedRedraw = true;
}
static void toggleSettings() {
gSettingsOpen = !gSettingsOpen;
gNeedStaticRedraw = true;
gNeedRedraw = true;
resetCachedUiText();
}
static void handleStableContact(bool closed) {
uint32_t now = millis();
gStableClosed = closed;
if (closed) {
if (gLastCycleStartMs != 0) {
uint32_t cycleMs = now - gLastCycleStartMs;
if (cycleMs >= kPauseAfterMs) {
gShortStreak = 0;
gLastCycleStartMs = now;
playCycleTick();
} else if (cycleMs >= kMinCycleMs) {
addCycle(cycleMs);
gLastCycleStartMs = now;
playCycleTick();
alertIfNeeded();
}
} else {
gLastCycleStartMs = now;
playCycleTick();
}
}
gNeedRedraw = !gSettingsOpen;
}
static void pollContact() {
if (!gStarted) {
return;
}
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
uint32_t now = millis();
if (rawClosed != gLastRawClosed) {
gLastRawClosed = rawClosed;
gLastRawChangeMs = now;
}
if ((now - gLastRawChangeMs) >= kContactDebounceMs && gStableClosed != gLastRawClosed) {
handleStableContact(gLastRawClosed);
}
}
static void pollUserButton() {
bool down = digitalRead(PIN_USER_BTN) == LOW;
uint32_t now = millis();
if (down != gUserButtonDown && (now - gUserButtonChangeMs) >= kButtonDebounceMs) {
gUserButtonDown = down;
gUserButtonChangeMs = now;
if (down) {
toggleSettings();
}
}
}
static uint8_t sliderValueFromX(const Rect &rect, int16_t x, uint8_t maxValue) {
int16_t left = rect.x + 22;
int16_t right = rect.x + rect.w - 22;
if (x < left) x = left;
if (x > right) x = right;
return (uint8_t)(((uint32_t)(x - left) * maxValue + (right - left) / 2) / (right - left));
}
static void handleSettingsTouch(int16_t x, int16_t y) {
if (contains(kLimitSlider, x, y)) {
uint8_t next = sliderValueFromX(kLimitSlider, x, 4);
if (next == gLimitIndex) {
return;
}
gLimitIndex = next;
} else if (contains(kTickSlider, x, y)) {
uint8_t next = sliderValueFromX(kTickSlider, x, 10);
if (next == gTickVolume) {
return;
}
gTickVolume = next;
playCycleTick();
} else if (contains(kAlertSlider, x, y)) {
uint8_t next = sliderValueFromX(kAlertSlider, x, 10);
if (next == gAlertVolume) {
return;
}
gAlertVolume = next;
playAlertBeep();
} else {
return;
}
saveSettings();
gNeedRedraw = true;
}
static void pollTouch() {
int16_t x = 0;
int16_t y = 0;
bool touching = gTouch.getPoint(&x, &y, 1) > 0;
if (touching && !gTouchDown) {
gTouchDown = true;
gTouchStartX = x;
gTouchStartY = y;
gTouchLastX = x;
gTouchLastY = y;
return;
}
if (touching && gTouchDown) {
gTouchLastX = x;
gTouchLastY = y;
return;
}
if (!touching && gTouchDown) {
gTouchDown = false;
int dx = abs(gTouchLastX - gTouchStartX);
int dy = abs(gTouchLastY - gTouchStartY);
if (dx >= 14 || dy >= 14) {
return;
}
if (gSettingsOpen) {
handleSettingsTouch(gTouchLastX, gTouchLastY);
} else if (!gStarted && contains(kStartButton, gTouchLastX, gTouchLastY)) {
enterSensorMode();
}
}
}
void setup() {
Serial.begin(115200);
Wire.begin(PIN_I2C_SDA, PIN_I2C_SCL);
pinMode(PIN_USER_BTN, INPUT_PULLUP);
loadSettings();
initAudio();
gfx->begin();
gBus->writeC8D8(0x36, 0xA0);
gfx->setBrightness(220);
gfx->fillScreen(C_BG);
gTouch.setPins(PIN_TP_INT, -1);
bool touchOk = gTouch.begin(Wire, CST92XX_SLAVE_ADDRESS, PIN_I2C_SDA, PIN_I2C_SCL);
gTouch.setMaxCoordinates(DISP_W, DISP_H);
gTouch.setSwapXY(true);
gTouch.setMirrorXY(true, false);
Serial.println("Breath monitor ready.");
Serial.println(touchOk ? "Touch init OK" : "Touch init failed");
gNeedRedraw = true;
}
void loop() {
pollUserButton();
pollTouch();
pollContact();
if (gStarted && !gSettingsOpen && millis() - gLastUiMs >= kUiPeriodMs) {
updateMonitorValues(false);
gLastUiMs = millis();
}
if (gNeedRedraw) {
redrawScreen();
}
delay(10);
}
@@ -0,0 +1,407 @@
#include <Arduino.h>
#include <Wire.h>
#include <lvgl.h>
#include <Arduino_GFX_Library.h>
#include "pin_config.h"
#include "TouchDrvCSTXXX.hpp"
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
// ESP32-S3 native USB data pins.
static constexpr int kUsbDmPin = 19; // USB D-
static constexpr int kUsbDpPin = 20; // USB D+
static constexpr int kUserButtonPin = 0; // BOOT/user button, active LOW.
static constexpr uint32_t kDebounceMs = 20;
static constexpr uint32_t kEnterDelayMs = 250;
static constexpr uint32_t kButtonDebounceMs = 35;
static lv_disp_draw_buf_t gDrawBuf;
static lv_color_t *gBuf1 = nullptr;
static lv_color_t *gBuf2 = nullptr;
static lv_obj_t *gRawLabel = nullptr;
static lv_obj_t *gEventLabel = nullptr;
static lv_obj_t *gModeLabel = nullptr;
static lv_obj_t *gStateLabel = nullptr;
static lv_obj_t *gActionButton = nullptr;
static lv_obj_t *gActionButtonLabel = nullptr;
static lv_obj_t *gMarker = nullptr;
static TouchDrvCST92xx gTouch;
static int16_t gTouchX[5];
static int16_t gTouchY[5];
static volatile bool gTouchPressed = false;
static volatile int16_t gLastTouchX = -1;
static volatile int16_t gLastTouchY = -1;
static volatile uint32_t gRawTouchCount = 0;
static uint32_t gButtonPressCount = 0;
static uint32_t gButtonClickCount = 0;
static bool gLastButtonRawPressed = false;
static bool gButtonStablePressed = false;
static uint32_t gLastButtonRawChangeMs = 0;
static bool gSensorMode = false;
static bool gEnterPending = false;
static uint32_t gEnterAtMs = 0;
static bool gStableClosed = false;
static bool gLastRawClosed = false;
static uint32_t gLastRawChangeMs = 0;
static uint32_t gLastUiRefreshMs = 0;
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
Arduino_CO5300 *gfx = new Arduino_CO5300(
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
uint32_t w = area->x2 - area->x1 + 1;
uint32_t h = area->y2 - area->y1 + 1;
#if (LV_COLOR_16_SWAP != 0)
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#else
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#endif
lv_disp_flush_ready(disp);
}
static void lvglTick(void *arg) {
LV_UNUSED(arg);
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
LV_UNUSED(indevDrv);
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
if (touched > 0) {
gTouchPressed = true;
gLastTouchX = gTouchX[0];
gLastTouchY = gTouchY[0];
gRawTouchCount++;
data->state = LV_INDEV_STATE_PR;
data->point.x = gTouchX[0];
data->point.y = gTouchY[0];
return;
}
gTouchPressed = false;
data->state = LV_INDEV_STATE_REL;
}
static void setStateUi(bool closed) {
if (closed) {
lv_label_set_text(gStateLabel, "CLOSED");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x6DFF8B), 0);
} else {
lv_label_set_text(gStateLabel, "OPEN");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFD166), 0);
}
}
static void updateTouchDiagnostics() {
uint32_t now = millis();
if (now - gLastUiRefreshMs < 40) return;
gLastUiRefreshMs = now;
String raw = gTouchPressed ? "RAW: PRESSED" : "RAW: released";
raw += "\nx=" + String((int)gLastTouchX) + " y=" + String((int)gLastTouchY);
raw += " n=" + String((uint32_t)gRawTouchCount);
lv_label_set_text(gRawLabel, raw.c_str());
if (gTouchPressed && gLastTouchX >= 0 && gLastTouchY >= 0) {
int markerX = gLastTouchX - 8;
int markerY = gLastTouchY - 8;
if (markerX < 0) markerX = 0;
if (markerY < 0) markerY = 0;
lv_obj_set_pos(gMarker, markerX, markerY);
lv_obj_clear_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
}
}
static void actuallyEnterSensorMode() {
gEnterPending = false;
// Make the visual transition happen BEFORE the USB data pins are repurposed.
lv_label_set_text(gModeLabel, "SENSOR MODE");
lv_label_set_text(gActionButtonLabel, "Restart to USB");
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0xA33D4F), LV_PART_MAIN | LV_STATE_DEFAULT);
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0xC94F65), LV_PART_MAIN | LV_STATE_PRESSED);
lv_label_set_text(gEventLabel, "GPIO19=D- LOW GPIO20=D+ INPUT_PULLUP");
lv_label_set_text(gStateLabel, "SWITCHING...");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
lv_refr_now(nullptr);
delay(60);
// Intentionally repurpose only USB D-/D+. These are not LCD or touch pins.
// Do NOT call Serial.flush() here: USB CDC may already be disappearing.
pinMode(kUsbDmPin, OUTPUT);
digitalWrite(kUsbDmPin, LOW);
pinMode(kUsbDpPin, INPUT_PULLUP);
gSensorMode = true;
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
gStableClosed = gLastRawClosed;
gLastRawChangeMs = millis();
setStateUi(gStableClosed);
}
static void actionButtonEventCb(lv_event_t *event) {
lv_event_code_t code = lv_event_get_code(event);
if (code == LV_EVENT_PRESSED) {
gButtonPressCount++;
String text = "BUTTON PRESSED #" + String(gButtonPressCount);
lv_label_set_text(gEventLabel, text.c_str());
if (!gSensorMode && !gEnterPending) {
lv_label_set_text(gActionButtonLabel, "Starting...");
lv_label_set_text(gStateLabel, "TOUCH OK");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
}
return;
}
if (code != LV_EVENT_CLICKED) return;
gButtonClickCount++;
if (!gSensorMode) {
lv_label_set_text(gModeLabel, "USB MODE");
lv_label_set_text(gActionButtonLabel, "TOUCH OK");
lv_label_set_text(gStateLabel, "PRESS BOOT");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFD166), 0);
String text = "TOUCH CLICK OK #" + String(gButtonClickCount) + " use BOOT button";
lv_label_set_text(gEventLabel, text.c_str());
lv_refr_now(nullptr);
return;
}
lv_label_set_text(gModeLabel, "RESTARTING TO USB...");
lv_label_set_text(gActionButtonLabel, "Restarting...");
lv_label_set_text(gStateLabel, "USB NEXT BOOT");
lv_refr_now(nullptr);
delay(180);
ESP.restart();
}
static void requestEnterSensorMode(const char *source) {
if (gSensorMode || gEnterPending) {
return;
}
gEnterPending = true;
gEnterAtMs = millis() + kEnterDelayMs;
lv_label_set_text(gModeLabel, "START RECEIVED");
lv_label_set_text(gActionButtonLabel, "Starting sensor...");
String text = String(source) + " OK waiting 250 ms";
lv_label_set_text(gEventLabel, text.c_str());
lv_label_set_text(gStateLabel, "STARTING...");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
lv_refr_now(nullptr);
}
static void pollUserButton() {
bool rawPressed = (digitalRead(kUserButtonPin) == LOW);
uint32_t now = millis();
if (rawPressed != gLastButtonRawPressed) {
gLastButtonRawPressed = rawPressed;
gLastButtonRawChangeMs = now;
}
if ((now - gLastButtonRawChangeMs) < kButtonDebounceMs || rawPressed == gButtonStablePressed) {
return;
}
gButtonStablePressed = rawPressed;
if (!gButtonStablePressed) {
return;
}
gButtonClickCount++;
if (!gSensorMode) {
requestEnterSensorMode("BOOT BUTTON");
return;
}
lv_label_set_text(gModeLabel, "RESTARTING TO USB...");
lv_label_set_text(gActionButtonLabel, "Restarting...");
lv_label_set_text(gStateLabel, "USB NEXT BOOT");
lv_refr_now(nullptr);
delay(180);
ESP.restart();
}
static void createUi() {
lv_obj_t *screen = lv_scr_act();
lv_obj_set_style_bg_color(screen, lv_color_hex(0x000000), 0);
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
lv_obj_t *title = lv_label_create(screen);
lv_label_set_text(title, "USB CONTACT DEBUG");
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 10);
gRawLabel = lv_label_create(screen);
lv_label_set_text(gRawLabel, "RAW: released\nx=-1 y=-1 n=0");
lv_obj_set_style_text_font(gRawLabel, &lv_font_montserrat_16, 0);
lv_obj_set_style_text_color(gRawLabel, lv_color_hex(0x9EE493), 0);
lv_obj_align(gRawLabel, LV_ALIGN_TOP_LEFT, 14, 48);
gModeLabel = lv_label_create(screen);
lv_label_set_text(gModeLabel, "USB MODE");
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0x72D6FF), 0);
lv_obj_align(gModeLabel, LV_ALIGN_TOP_RIGHT, -14, 50);
gEventLabel = lv_label_create(screen);
lv_label_set_text(gEventLabel, "Button events: waiting");
lv_obj_set_width(gEventLabel, 440);
lv_label_set_long_mode(gEventLabel, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(gEventLabel, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_font(gEventLabel, &lv_font_montserrat_16, 0);
lv_obj_set_style_text_color(gEventLabel, lv_color_hex(0xFFD166), 0);
lv_obj_align(gEventLabel, LV_ALIGN_TOP_MID, 0, 102);
gStateLabel = lv_label_create(screen);
lv_label_set_text(gStateLabel, "READY");
lv_obj_set_style_text_font(gStateLabel, &lv_font_montserrat_40, 0);
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
lv_obj_align(gStateLabel, LV_ALIGN_CENTER, 0, -52);
// Put the button in almost the same position/size as the known-working touch debug sketch.
gActionButton = lv_btn_create(screen);
lv_obj_set_size(gActionButton, 360, 110);
lv_obj_align(gActionButton, LV_ALIGN_CENTER, 0, 52);
lv_obj_set_style_radius(gActionButton, 18, 0);
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), LV_PART_MAIN | LV_STATE_DEFAULT);
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x47C7B6), LV_PART_MAIN | LV_STATE_PRESSED);
lv_obj_set_style_border_width(gActionButton, 3, 0);
lv_obj_set_style_border_color(gActionButton, lv_color_hex(0xBDE0FE), 0);
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_ALL, nullptr);
gActionButtonLabel = lv_label_create(gActionButton);
lv_label_set_text(gActionButtonLabel, "START");
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_28, 0);
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
lv_obj_center(gActionButtonLabel);
lv_obj_t *hint = lv_label_create(screen);
lv_label_set_text(hint, "Press BOOT button to START. Touch button only checks touch UI.");
lv_obj_set_width(hint, 440);
lv_label_set_long_mode(hint, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(hint, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_font(hint, &lv_font_montserrat_14, 0);
lv_obj_set_style_text_color(hint, lv_color_hex(0xD9D9D9), 0);
lv_obj_align(hint, LV_ALIGN_BOTTOM_MID, 0, -18);
gMarker = lv_obj_create(screen);
lv_obj_set_size(gMarker, 16, 16);
lv_obj_set_style_radius(gMarker, LV_RADIUS_CIRCLE, 0);
lv_obj_set_style_bg_color(gMarker, lv_color_hex(0xFF4D6D), 0);
lv_obj_set_style_border_width(gMarker, 2, 0);
lv_obj_set_style_border_color(gMarker, lv_color_hex(0xFFFFFF), 0);
lv_obj_add_flag(gMarker, LV_OBJ_FLAG_HIDDEN);
}
static void pollContact() {
if (!gSensorMode) return;
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
uint32_t now = millis();
if (rawClosed != gLastRawClosed) {
gLastRawClosed = rawClosed;
gLastRawChangeMs = now;
}
if ((now - gLastRawChangeMs) >= kDebounceMs && gStableClosed != gLastRawClosed) {
gStableClosed = gLastRawClosed;
setStateUi(gStableClosed);
}
}
void setup() {
Serial.begin(115200);
pinMode(kUserButtonPin, INPUT_PULLUP);
Wire.begin(IIC_SDA, IIC_SCL);
pinMode(TP_RST, OUTPUT);
pinMode(TP_INT, INPUT);
digitalWrite(TP_RST, LOW);
delay(30);
digitalWrite(TP_RST, HIGH);
delay(50);
delay(1000);
gTouch.setPins(TP_RST, TP_INT);
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
if (!touchOk) {
Serial.println("Touch init failed");
} else {
Serial.print("Touch model: ");
Serial.println(gTouch.getModelName());
gTouch.sleep();
gTouch.reset();
gTouch.setMaxCoordinates(480, 480);
gTouch.setSwapXY(true);
gTouch.setMirrorXY(true, false);
}
gfx->begin();
gBus->writeC8D8(0x36, 0xA0);
gfx->setBrightness(220);
gfx->fillScreen(0x0000);
lv_init();
uint32_t screenWidth = gfx->width();
uint32_t screenHeight = gfx->height();
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
static lv_disp_drv_t dispDrv;
lv_disp_drv_init(&dispDrv);
dispDrv.hor_res = screenWidth;
dispDrv.ver_res = screenHeight;
dispDrv.flush_cb = lvglFlushCb;
dispDrv.draw_buf = &gDrawBuf;
lv_disp_drv_register(&dispDrv);
static lv_indev_drv_t indevDrv;
lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = lvglTouchRead;
lv_indev_drv_register(&indevDrv);
const esp_timer_create_args_t lvglTickTimerArgs = {
.callback = &lvglTick,
.name = "lvgl_tick"};
esp_timer_handle_t lvglTickTimer = nullptr;
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
createUi();
Serial.println("USB contact sensor DEBUG ready. USB pins remain untouched until START click.");
}
void loop() {
updateTouchDiagnostics();
pollUserButton();
pollContact();
if (gEnterPending && (int32_t)(millis() - gEnterAtMs) >= 0) {
actuallyEnterSensorMode();
}
lv_timer_handler();
delay(5);
}
@@ -0,0 +1,250 @@
#include <Arduino.h>
#include <Wire.h>
#include <lvgl.h>
#include <Arduino_GFX_Library.h>
#include "pin_config.h"
#include "TouchDrvCSTXXX.hpp"
#define EXAMPLE_LVGL_TICK_PERIOD_MS 2
// ESP32-S3 native USB pins.
static constexpr int kUsbDmPin = 19; // USB D-
static constexpr int kUsbDpPin = 20; // USB D+
static constexpr uint32_t kDebounceMs = 20;
static lv_disp_draw_buf_t gDrawBuf;
static lv_color_t *gBuf1 = nullptr;
static lv_color_t *gBuf2 = nullptr;
static lv_obj_t *gModeLabel = nullptr;
static lv_obj_t *gStateLabel = nullptr;
static lv_obj_t *gHintLabel = nullptr;
static lv_obj_t *gActionButton = nullptr;
static lv_obj_t *gActionButtonLabel = nullptr;
static TouchDrvCST92xx gTouch;
static int16_t gTouchX[5];
static int16_t gTouchY[5];
static bool gSensorMode = false;
static bool gStableClosed = false;
static bool gLastRawClosed = false;
static uint32_t gLastRawChangeMs = 0;
Arduino_DataBus *gBus = new Arduino_ESP32QSPI(
LCD_CS, LCD_SCLK, LCD_SDIO0, LCD_SDIO1, LCD_SDIO2, LCD_SDIO3);
Arduino_CO5300 *gfx = new Arduino_CO5300(
gBus, LCD_RESET, 0, LCD_WIDTH, LCD_HEIGHT, 0, 0, 0, 0);
static void lvglFlushCb(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *colorP) {
uint32_t w = area->x2 - area->x1 + 1;
uint32_t h = area->y2 - area->y1 + 1;
#if (LV_COLOR_16_SWAP != 0)
gfx->draw16bitBeRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#else
gfx->draw16bitRGBBitmap(area->x1, area->y1, (uint16_t *)&colorP->full, w, h);
#endif
lv_disp_flush_ready(disp);
}
static void lvglTick(void *arg) {
LV_UNUSED(arg);
lv_tick_inc(EXAMPLE_LVGL_TICK_PERIOD_MS);
}
static void lvglTouchRead(lv_indev_drv_t *indevDrv, lv_indev_data_t *data) {
LV_UNUSED(indevDrv);
uint8_t touched = gTouch.getPoint(gTouchX, gTouchY, gTouch.getSupportTouchPoint());
if (touched > 0) {
data->state = LV_INDEV_STATE_PR;
data->point.x = gTouchX[0];
data->point.y = gTouchY[0];
return;
}
data->state = LV_INDEV_STATE_REL;
}
static void setStateUi(bool closed) {
if (closed) {
lv_label_set_text(gStateLabel, "CLOSED");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x7CFF8A), 0);
} else {
lv_label_set_text(gStateLabel, "OPEN");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0xFFCC66), 0);
}
}
static void enterSensorMode() {
// From this moment the native USB data pair is no longer USB.
// D- is held LOW, D+ is read with the ESP32-S3 internal pull-up.
// A passive switch between D- and D+ therefore reads LOW when closed.
Serial.flush();
delay(30);
pinMode(kUsbDmPin, OUTPUT);
digitalWrite(kUsbDmPin, LOW);
pinMode(kUsbDpPin, INPUT_PULLUP);
gSensorMode = true;
gLastRawClosed = (digitalRead(kUsbDpPin) == LOW);
gStableClosed = gLastRawClosed;
gLastRawChangeMs = millis();
lv_label_set_text(gModeLabel, "Sensor mode");
lv_label_set_text(gHintLabel, "USB D- / D+ are now the contact input.\nDo not connect this port to a computer.");
lv_label_set_text(gActionButtonLabel, "Restart to USB");
setStateUi(gStableClosed);
}
static void actionButtonEventCb(lv_event_t *event) {
if (lv_event_get_code(event) != LV_EVENT_CLICKED) {
return;
}
if (!gSensorMode) {
enterSensorMode();
return;
}
lv_label_set_text(gModeLabel, "Restarting...");
lv_label_set_text(gHintLabel, "USB mode will return after reboot.");
lv_timer_handler();
delay(150);
ESP.restart();
}
static void createUi() {
lv_obj_t *screen = lv_scr_act();
lv_obj_set_style_bg_color(screen, lv_color_hex(0x0B1320), 0);
lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0);
lv_obj_t *title = lv_label_create(screen);
lv_label_set_text(title, "USB CONTACT TEST");
lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_text_font(title, &lv_font_montserrat_22, 0);
lv_obj_align(title, LV_ALIGN_TOP_MID, 0, 26);
gModeLabel = lv_label_create(screen);
lv_label_set_text(gModeLabel, "USB mode");
lv_obj_set_style_text_color(gModeLabel, lv_color_hex(0xB8C8DC), 0);
lv_obj_set_style_text_font(gModeLabel, &lv_font_montserrat_18, 0);
lv_obj_align(gModeLabel, LV_ALIGN_TOP_MID, 0, 72);
gStateLabel = lv_label_create(screen);
lv_label_set_text(gStateLabel, "READY");
lv_obj_set_style_text_color(gStateLabel, lv_color_hex(0x72D6FF), 0);
lv_obj_set_style_text_font(gStateLabel, &lv_font_montserrat_40, 0);
lv_obj_align(gStateLabel, LV_ALIGN_CENTER, 0, -56);
gHintLabel = lv_label_create(screen);
lv_label_set_text(gHintLabel, "USB is normal now.\nTap Start to use D- / D+ as a contact sensor.");
lv_obj_set_width(gHintLabel, 390);
lv_label_set_long_mode(gHintLabel, LV_LABEL_LONG_WRAP);
lv_obj_set_style_text_align(gHintLabel, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(gHintLabel, lv_color_hex(0xD5DCE5), 0);
lv_obj_set_style_text_font(gHintLabel, &lv_font_montserrat_16, 0);
lv_obj_align(gHintLabel, LV_ALIGN_CENTER, 0, 18);
gActionButton = lv_btn_create(screen);
lv_obj_set_size(gActionButton, 260, 72);
lv_obj_align(gActionButton, LV_ALIGN_BOTTOM_MID, 0, -48);
lv_obj_set_style_radius(gActionButton, 18, 0);
lv_obj_set_style_bg_color(gActionButton, lv_color_hex(0x2A9D8F), 0);
lv_obj_set_style_border_width(gActionButton, 0, 0);
lv_obj_add_event_cb(gActionButton, actionButtonEventCb, LV_EVENT_CLICKED, nullptr);
gActionButtonLabel = lv_label_create(gActionButton);
lv_label_set_text(gActionButtonLabel, "Start");
lv_obj_set_style_text_color(gActionButtonLabel, lv_color_hex(0xFFFFFF), 0);
lv_obj_set_style_text_font(gActionButtonLabel, &lv_font_montserrat_22, 0);
lv_obj_center(gActionButtonLabel);
}
static void pollContact() {
if (!gSensorMode) {
return;
}
bool rawClosed = (digitalRead(kUsbDpPin) == LOW);
uint32_t now = millis();
if (rawClosed != gLastRawClosed) {
gLastRawClosed = rawClosed;
gLastRawChangeMs = now;
}
if ((now - gLastRawChangeMs) >= kDebounceMs && gStableClosed != gLastRawClosed) {
gStableClosed = gLastRawClosed;
setStateUi(gStableClosed);
}
}
void setup() {
// With the project's FQBN this is the normal ESP32-S3 native USB serial mode.
// No sensor mode is persisted: every reset starts here with normal USB again.
Serial.begin(115200);
Wire.begin(IIC_SDA, IIC_SCL);
pinMode(TP_RST, OUTPUT);
pinMode(TP_INT, INPUT);
digitalWrite(TP_RST, LOW);
delay(30);
digitalWrite(TP_RST, HIGH);
delay(50);
delay(1000);
gTouch.setPins(TP_RST, TP_INT);
bool touchOk = gTouch.begin(Wire, 0x5A, IIC_SDA, IIC_SCL);
if (!touchOk) {
Serial.println("Touch init failed");
} else {
gTouch.sleep();
gTouch.reset();
gTouch.setMaxCoordinates(480, 480);
gTouch.setSwapXY(true);
gTouch.setMirrorXY(true, false);
}
gfx->begin();
gBus->writeC8D8(0x36, 0xA0);
gfx->setBrightness(220);
gfx->fillScreen(0x0000);
lv_init();
uint32_t screenWidth = gfx->width();
uint32_t screenHeight = gfx->height();
gBuf1 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
gBuf2 = (lv_color_t *)heap_caps_malloc(screenWidth * screenHeight / 4 * sizeof(lv_color_t), MALLOC_CAP_DMA);
lv_disp_draw_buf_init(&gDrawBuf, gBuf1, gBuf2, screenWidth * screenHeight / 4);
static lv_disp_drv_t dispDrv;
lv_disp_drv_init(&dispDrv);
dispDrv.hor_res = screenWidth;
dispDrv.ver_res = screenHeight;
dispDrv.flush_cb = lvglFlushCb;
dispDrv.draw_buf = &gDrawBuf;
lv_disp_drv_register(&dispDrv);
static lv_indev_drv_t indevDrv;
lv_indev_drv_init(&indevDrv);
indevDrv.type = LV_INDEV_TYPE_POINTER;
indevDrv.read_cb = lvglTouchRead;
lv_indev_drv_register(&indevDrv);
const esp_timer_create_args_t lvglTickTimerArgs = {
.callback = &lvglTick,
.name = "lvgl_tick"};
esp_timer_handle_t lvglTickTimer = nullptr;
esp_timer_create(&lvglTickTimerArgs, &lvglTickTimer);
esp_timer_start_periodic(lvglTickTimer, EXAMPLE_LVGL_TICK_PERIOD_MS * 1000);
createUi();
Serial.println("USB contact sensor test ready; native USB remains active until Start is tapped.");
}
void loop() {
pollContact();
lv_timer_handler();
delay(5);
}
@@ -0,0 +1,88 @@
# USB contact sensor test
Diagnostic sketches:
- `main-device/test_sketches/usb_contact_sensor_test/usb_contact_sensor_test.ino`
- `main-device/test_sketches/usb_contact_sensor_debug_test/usb_contact_sensor_debug_test.ino`
- `main-device/test_sketches/usb_contact_screen_start_stub/usb_contact_screen_start_stub.ino`
## Purpose
Use the ESP32-S3 native USB data pair as a removable two-wire dry-contact input without making this mode persistent.
- `GPIO19` = native USB `D-`
- `GPIO20` = native USB `D+`
## Boot behavior
Every normal reset starts in ordinary native USB mode. The sketch does not save sensor mode in NVS or any other persistent storage.
Initial screen:
- title: `USB CONTACT TEST`
- mode: `USB mode`
- state: `READY`
- action button: `Start`
Until `Start` is pressed, the sketch does not reconfigure GPIO19/20.
## Sensor mode
After `Start`:
- GPIO19 is configured as `OUTPUT LOW`
- GPIO20 is configured as `INPUT_PULLUP`
- a passive switch/contact is connected between USB `D-` and `D+`
- open contact => GPIO20 reads HIGH => UI shows `OPEN`
- closed contact => GPIO20 reads LOW => UI shows `CLOSED`
- contact changes use a 20 ms debounce
Native USB data is intentionally unavailable while sensor mode owns GPIO19/20. The UI warns not to connect the port to a computer in this state.
The action button changes to `Restart to USB`. Pressing it calls `ESP.restart()`; after reboot normal USB mode is restored.
A physical reset/power cycle has the same effect. The ESP32-S3 ROM download mode remains available through the board's BOOT procedure if recovery is needed.
## Debug version
The debug sketch starts in normal USB mode and shows raw touch diagnostics on screen. The on-screen `START` button is intentionally diagnostic only: it confirms touch/LVGL button events and does not reconfigure GPIO19/20.
Sensor mode starts from the physical BOOT/user button on GPIO0, active LOW. The button is debounced for 35 ms, then the UI shows `START RECEIVED` / `STARTING...`, waits 250 ms so the visual transition is rendered, and only then reconfigures USB D-/D+ as the contact input.
While in sensor mode, pressing the BOOT/user button again restarts the device and returns normal USB mode on the next boot.
## GFX breath monitor version
The `usb_contact_screen_start_stub` sketch is a breath monitor firmware based on the production `Arduino_GFX` display path instead of LVGL.
Initial screen:
- title: `USB CONTACT`
- title in the current version: `BREATH MONITOR`
- state: `READY`
- action button: `START`
After tapping `START`:
- GPIO19 is configured as `OUTPUT LOW`
- GPIO20 is configured as `INPUT_PULLUP`
- closed contact is treated as `EXHALE`
- open contact is treated as `INHALE`
- one breathing cycle is measured from one stable `EXHALE` start to the next stable `EXHALE` start
- contact changes use an 80 ms debounce
- UI shows current cycle duration, arithmetic average duration over the last 5 completed cycles, and elapsed time from start
- the physical user/BOOT button opens and closes the settings screen
- settings screen has three touch sliders: limit `5/7/10/15/20` seconds, quiet cycle tick volume `0..10`, and alert volume `0..10`
- settings are persisted in NVS and restored after power off/on
- quiet cycle tick volume uses a compressed quiet scale: previous low audible levels are moved near `9..10`
- alert volume uses a gentler low range; level `5` equals the previous maximum alert level
- the working screen uses a static frame and only updates value regions to avoid display flicker
- the main screen header/status line and the bottom short-average streak line redraw only when their text changes
- the `START` button is a flat rounded rectangle with a border; there is no pause button in this version
- every new cycle start plays one quiet confirmation beep
- if the arithmetic average of the last up to 5 completed cycles is shorter than the selected limit, the device plays warning beeps: 1 beep for the first short average in a row, 2 beeps for the second, up to 5 beeps
- completed cycles shorter than 1.5 seconds are ignored as contact bounce
- if the current cycle exceeds 60 seconds, the main screen shows `PAUSE`; that long cycle is skipped and the next `EXHALE` start begins a fresh cycle from zero
- reset/power cycle restores ordinary native USB boot
This version is intended to monitor breathing cadence from a dry-contact USB D-/D+ sensor.
@@ -2,17 +2,32 @@ package server.archive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.sync.ArweavePublishSignal;
import java.util.Base64;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/** Fixed-delay publisher. Empty cycles are no-ops. */
/**
* Publisher с двумя путями доставки:
* 1) Turbo — немедленная неблокирующая попытка для только что принятого блока;
* 2) плановый fixed-delay цикл — страховочная добивка только зависших pending-записей.
*/
public final class ArweaveBlockPublisherScheduler {
private static final Logger log = LoggerFactory.getLogger(ArweaveBlockPublisherScheduler.class);
private static final long RETRY_MIN_PENDING_AGE_MS = 60_000L;
private static final AtomicBoolean STARTED = new AtomicBoolean(false);
private static final AtomicBoolean IMMEDIATE_DRAIN_SCHEDULED = new AtomicBoolean(false);
private static final ConcurrentLinkedQueue<ArweavePublishSignal.PendingRef> IMMEDIATE_QUEUE = new ConcurrentLinkedQueue<>();
private static final ConcurrentHashMap<String, Long> PENDING_SINCE_MS = new ConcurrentHashMap<>();
private static ScheduledExecutorService executor;
private static ArweaveBlockPublisherService service;
private static ArweaveBlocksConfig config;
private ArweaveBlockPublisherScheduler() {}
@@ -23,15 +38,105 @@ public final class ArweaveBlockPublisherScheduler {
if (!cfg.publishEnabled()) { log.info("Arweave user-block publisher disabled (mode=none)"); return; }
if (!STARTED.compareAndSet(false,true)) return;
try {
ArweaveBlockPublisherService service = new ArweaveBlockPublisherService(cfg);
config = cfg;
service = new ArweaveBlockPublisherService(cfg);
executor = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "shine-arweave-block-publisher"); t.setDaemon(true); return t;
});
Runnable task = () -> { try { service.runCycle(); } catch (Exception e) { log.error("Arweave block publish cycle failed", e); } };
executor.scheduleWithFixedDelay(task, 0, cfg.publishIntervalMinutes(), TimeUnit.MINUTES);
log.info("Arweave user-block publisher enabled: mode={} interval={}m", cfg.publishMode(), cfg.publishIntervalMinutes());
} catch (Exception e) { STARTED.set(false); log.error("Arweave user-block publisher failed to start", e); }
if (cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO) {
ArweavePublishSignal.setListener(ArweaveBlockPublisherScheduler::enqueueImmediateTurboPublish);
}
Runnable retryTask = () -> {
try {
if (config.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO) {
long nowMs = System.currentTimeMillis();
service.runRetryCycle(
id -> isOldEnoughForRetry(id, nowMs),
id -> PENDING_SINCE_MS.remove(idKey(id))
);
} else {
service.runCycle();
}
} catch (Exception e) {
log.error("Arweave block publish retry cycle failed", e);
}
};
long retryInitialDelayMinutes = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO
? cfg.publishIntervalMinutes()
: 0L;
executor.scheduleWithFixedDelay(retryTask, retryInitialDelayMinutes, cfg.publishIntervalMinutes(), TimeUnit.MINUTES);
log.info("Arweave user-block publisher enabled: mode={} immediateTurbo={} retryInterval={}m retryMinAge={}s",
cfg.publishMode(), cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO,
cfg.publishIntervalMinutes(), RETRY_MIN_PENDING_AGE_MS / 1000L);
} catch (Exception e) {
ArweavePublishSignal.clearListener();
STARTED.set(false);
log.error("Arweave user-block publisher failed to start", e);
}
}
public static void close() { ScheduledExecutorService e=executor; if(e!=null)e.shutdownNow(); }
private static void enqueueImmediateTurboPublish(ArweavePublishSignal.PendingRef item) {
if (!STARTED.get() || config == null || config.publishMode() != ArweaveBlocksConfig.PublishMode.TURBO) return;
PENDING_SINCE_MS.putIfAbsent(idKey(item.dataItemId()), System.currentTimeMillis());
IMMEDIATE_QUEUE.offer(item);
scheduleImmediateDrain();
}
private static boolean isOldEnoughForRetry(byte[] dataItemId, long nowMs) {
Long pendingSince = PENDING_SINCE_MS.get(idKey(dataItemId));
// Нет записи в памяти => pending пережил старт процесса и уже считается зависшим.
return pendingSince == null || nowMs - pendingSince >= RETRY_MIN_PENDING_AGE_MS;
}
private static String idKey(byte[] dataItemId) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(dataItemId);
}
private static void scheduleImmediateDrain() {
ScheduledExecutorService currentExecutor = executor;
if (currentExecutor == null || currentExecutor.isShutdown()) return;
if (!IMMEDIATE_DRAIN_SCHEDULED.compareAndSet(false, true)) return;
try {
currentExecutor.execute(ArweaveBlockPublisherScheduler::drainImmediateQueue);
} catch (RuntimeException e) {
IMMEDIATE_DRAIN_SCHEDULED.set(false);
throw e;
}
}
private static void drainImmediateQueue() {
try {
ArweavePublishSignal.PendingRef item;
while ((item = IMMEDIATE_QUEUE.poll()) != null) {
try {
boolean resolved = service.publishAcceptedNow(item);
if (resolved) PENDING_SINCE_MS.remove(idKey(item.dataItemId()));
} catch (Exception e) {
// Turbo недоступен: не держим поток клиента и не молотим всю очередь одной и той же ошибкой.
// Все элементы уже надёжно лежат в БД с pending=TRUE; плановый цикл подберёт их после min-age.
log.warn("Immediate Turbo publish failed; pending blocks will be retried by the periodic cycle: {}", e.getMessage());
IMMEDIATE_QUEUE.clear();
break;
}
}
} finally {
IMMEDIATE_DRAIN_SCHEDULED.set(false);
if (!IMMEDIATE_QUEUE.isEmpty()) scheduleImmediateDrain();
}
}
public static void close() {
ArweavePublishSignal.clearListener();
IMMEDIATE_QUEUE.clear();
PENDING_SINCE_MS.clear();
IMMEDIATE_DRAIN_SCHEDULED.set(false);
ScheduledExecutorService e = executor;
executor = null;
service = null;
config = null;
STARTED.set(false);
if (e != null) e.shutdownNow();
}
}
@@ -3,10 +3,15 @@ package server.archive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import shine.db.dao.BlocksDAO;
import shine.db.dao.KeyRotationCandidateBlocksDAO;
import shine.db.entities.BlockEntry;
import shine.db.entities.KeyRotationCandidateBlockEntry;
import server.sync.ArweavePublishSignal;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
/** Publishes locally-created signed user DataItems through the configured transport. */
public final class ArweaveBlockPublisherService {
@@ -14,6 +19,7 @@ public final class ArweaveBlockPublisherService {
private final ArweaveBlocksConfig cfg;
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final KeyRotationCandidateBlocksDAO candidateBlocksDAO = KeyRotationCandidateBlocksDAO.getInstance();
private final ArweaveL1Uploader arweaveUploader;
private final TurboDataItemUploader turboUploader;
@@ -23,18 +29,105 @@ public final class ArweaveBlockPublisherService {
this.turboUploader = cfg.publishMode() == ArweaveBlocksConfig.PublishMode.TURBO ? new TurboDataItemUploader(cfg) : null;
}
/**
* Мгновенная попытка для только что принятого DataItem. Вызывается только из фонового executor-а:
* сетевой запрос AddBlock не ждёт результат Turbo. Если запись уже успел обработать другой цикл, это no-op.
* При ошибке pending-флаг в БД не меняется, поэтому обычный runCycle() повторит публикацию позже.
*/
public boolean publishAcceptedNow(ArweavePublishSignal.PendingRef pending) throws Exception {
if (cfg.publishMode() != ArweaveBlocksConfig.PublishMode.TURBO) return false;
byte[] id = pending.dataItemId();
if (pending.kind() == ArweavePublishSignal.Kind.KEY_ROTATION_CANDIDATE) {
KeyRotationCandidateBlockEntry entry = candidateBlocksDAO.getPendingArweaveByDataItemId(id);
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published key-rotation DataItem {} chain={} block={}",
result.dataItemId(), entry.getCandidateBlockchainName(), entry.getBlockNumber());
return true;
}
BlockEntry entry = blocksDAO.getPendingArweaveByDataItemId(id);
if (entry == null) return true;
byte[] raw = entry.getBlockBytes();
if (raw == null || raw.length == 0) return false;
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
log.debug("Turbo immediately published SHiNE DataItem {} chain={} block={}",
result.dataItemId(), entry.getBchName(), entry.getBlockNumber());
return true;
}
public int runCycle() throws Exception {
return runCycle(id -> true, id -> {});
}
/** Плановый retry может отфильтровать слишком свежие pending-записи и получить callback успешных id. */
public int runRetryCycle(Predicate<byte[]> eligible, Consumer<byte[]> onPublished) throws Exception {
return runCycle(eligible == null ? id -> true : eligible, onPublished == null ? id -> {} : onPublished);
}
private int runCycle(Predicate<byte[]> eligible, Consumer<byte[]> onPublished) throws Exception {
if (cfg.publishMode() == ArweaveBlocksConfig.PublishMode.NONE) return 0;
List<BlockEntry> candidates = blocksDAO.listPendingArweave(cfg.publishMaxItems());
if (candidates.isEmpty()) return 0;
return switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates);
int maxItems = cfg.publishMaxItems();
int attempted = 0;
int published = 0;
// Ротация приоритетна: пользователь уже заблокирован для обычной записи и ждёт завершения копирования.
List<KeyRotationCandidateBlockEntry> rotationCandidates = candidateBlocksDAO.listPendingArweave(maxItems);
rotationCandidates = rotationCandidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
if (!rotationCandidates.isEmpty()) {
attempted += rotationCandidates.size();
published += switch (cfg.publishMode()) {
case TURBO -> publishTurboRotation(rotationCandidates, onPublished);
case ARWEAVE -> publishDirectArweaveRotation(rotationCandidates);
case NONE -> 0;
};
}
int remaining = Math.max(0, maxItems - attempted);
if (remaining == 0) return published;
List<BlockEntry> candidates = blocksDAO.listPendingArweave(remaining);
candidates = candidates.stream().filter(e -> eligible.test(e.getDataItemId())).toList();
if (candidates.isEmpty()) return published;
published += switch (cfg.publishMode()) {
case TURBO -> publishTurbo(candidates, onPublished);
case ARWEAVE -> publishDirectArweave(candidates);
case NONE -> 0;
};
return published;
}
private int publishTurbo(List<BlockEntry> candidates) throws Exception {
private int publishTurboRotation(List<KeyRotationCandidateBlockEntry> candidates, Consumer<byte[]> onPublished) throws Exception {
int published = 0;
Exception firstFailure = null;
for (KeyRotationCandidateBlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
candidateBlocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id);
published++;
log.debug("Turbo published key-rotation DataItem {} chain={} block={}",
result.dataItemId(), e.getCandidateBlockchainName(), e.getBlockNumber());
} catch (Exception ex) {
if (firstFailure == null) firstFailure = ex;
log.warn("Turbo key-rotation publish failed: chain={} block={} bytes={} error={}",
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length, ex.getMessage());
}
}
if (published > 0) log.info("Published {} SHiNE key-rotation DataItems through Turbo", published);
if (published == 0 && firstFailure != null) throw firstFailure;
return published;
}
private int publishTurbo(List<BlockEntry> candidates, Consumer<byte[]> onPublished) throws Exception {
int published = 0;
Exception firstFailure = null;
for (BlockEntry e : candidates) {
@@ -44,6 +137,7 @@ public final class ArweaveBlockPublisherService {
try {
TurboDataItemUploader.UploadResult result = turboUploader.upload(raw, id);
blocksDAO.markArweavePublished(List.of(id), System.currentTimeMillis());
onPublished.accept(id);
published++;
log.debug("Turbo published SHiNE DataItem {} chain={} block={}", result.dataItemId(), e.getBchName(), e.getBlockNumber());
} catch (Exception ex) {
@@ -57,6 +151,40 @@ public final class ArweaveBlockPublisherService {
return published;
}
private int publishDirectArweaveRotation(List<KeyRotationCandidateBlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
long estimated = 32;
for (KeyRotationCandidateBlockEntry e : candidates) {
byte[] raw = e.getBlockBytes();
byte[] id = e.getDataItemId();
if (raw == null || raw.length == 0 || id == null || id.length != 32) continue;
long next = estimated + 64L + raw.length;
if (!items.isEmpty() && next > cfg.publishMaxBundleBytes()) break;
if (next > cfg.publishMaxBundleBytes()) {
log.error("One key-rotation DataItem exceeds arweave.blocks.publish.maxBundleBytes: chain={} block={} bytes={}",
e.getCandidateBlockchainName(), e.getBlockNumber(), raw.length);
continue;
}
items.add(raw);
ids.add(id);
estimated = next;
}
if (items.isEmpty()) return 0;
byte[] bundle = Ans104Bundle.write(items);
List<ArweaveL1Uploader.Tag> rootTags = List.of(
new ArweaveL1Uploader.Tag("Content-Type", "application/octet-stream"),
new ArweaveL1Uploader.Tag("Bundle-Format", "binary"),
new ArweaveL1Uploader.Tag("Bundle-Version", "2.0.0")
);
ArweaveL1Uploader.UploadResult result = arweaveUploader.upload(bundle, rootTags);
candidateBlocksDAO.markArweavePublished(ids, System.currentTimeMillis());
log.info("Published {} SHiNE key-rotation DataItems in direct Arweave root tx {} (bundle={} bytes)",
items.size(), result.txId(), bundle.length);
return items.size();
}
private int publishDirectArweave(List<BlockEntry> candidates) throws Exception {
List<byte[]> items = new ArrayList<>();
List<byte[]> ids = new ArrayList<>();
@@ -22,10 +22,14 @@ public final class ArweaveBlockSyncScheduler {
if (!STARTED.compareAndSet(false,true)) return;
try {
ArweaveBlockSyncService service = new ArweaveBlockSyncService(cfg);
// Один поток намеренно сериализует полный discovery и быстрые retry уже найденных DataItem.
executor = Executors.newSingleThreadScheduledExecutor(r -> { Thread t=new Thread(r,"shine-arweave-block-sync");t.setDaemon(true);return t; });
Runnable task=()->{try{service.runCycle();}catch(Exception e){log.error("Arweave block sync cycle failed",e);}};
Runnable retryTask=()->{try{service.runRetryCycle();}catch(Exception e){log.error("Arweave block fast retry failed",e);}};
executor.scheduleWithFixedDelay(task,0,cfg.syncIntervalMinutes(),TimeUnit.MINUTES);
log.info("Arweave user-block sync enabled: interval={}m gateway={}",cfg.syncIntervalMinutes(),cfg.syncGateway());
executor.scheduleWithFixedDelay(retryTask,cfg.syncLocationRetrySeconds(),cfg.syncLocationRetrySeconds(),TimeUnit.SECONDS);
log.info("Arweave user-block sync enabled: interval={}m locationRetry={}s gateway={} turboApi={}",
cfg.syncIntervalMinutes(),cfg.syncLocationRetrySeconds(),cfg.syncGateway(),cfg.syncTurboApiBase());
} catch (Exception e) { STARTED.set(false); log.error("Arweave user-block sync failed to start",e); }
}
public static void close(){ScheduledExecutorService e=executor;if(e!=null)e.shutdownNow();}
@@ -7,9 +7,15 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.sync.BlockchainResyncGuard;
import shine.db.DbController;
import shine.db.dao.ArweaveBlockImportDAO;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.dao.BlockchainForkSegmentsDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelReadStateDAO;
import shine.db.dao.BlockchainResyncCleanupDAO;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
@@ -22,11 +28,15 @@ import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.Duration;
import java.util.*;
/**
* Discovers individual App=test5590 DataItems and imports the exact signed ANS-104 bytes.
* Discovers individual App=test5591 DataItems and imports the exact signed ANS-104 bytes.
* The importer is transport-agnostic: a DataItem may have reached Arweave through Turbo
* or inside a direct server-created ANS-104 bundle.
*/
@@ -45,14 +55,28 @@ public final class ArweaveBlockSyncService {
private final SolanaUserPdaCurrentDAO usersDAO = SolanaUserPdaCurrentDAO.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
private final Net_AddBlock_Handler addBlock = new Net_AddBlock_Handler();
private final BlockchainForkSegmentsDAO segmentsDAO = BlockchainForkSegmentsDAO.getInstance();
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
private final BlockchainResyncCleanupDAO cleanupDAO = BlockchainResyncCleanupDAO.getInstance();
// DataItem уже виден через GraphQL, но его физические координаты внутри ANS-104 bundle
// ещё не появились у индексатора. Полный discovery остаётся редким, а эти ID ретраятся часто.
private final Map<String, PendingDownload> unresolvedDownloads = new LinkedHashMap<>();
public ArweaveBlockSyncService(ArweaveBlocksConfig cfg) { this.cfg = cfg; }
public void runCycle() throws Exception {
recoverInterruptedCanonicalRebuilds();
discover();
drainQueue();
}
/** Быстрый retry только для уже обнаруженных DataItem, без повторного полного GraphQL discovery. */
public void runRetryCycle() throws Exception {
int queued = retryPendingDownloads();
if (queued > 0) drainQueue();
}
private void discover() throws Exception {
long stored = importDAO.getLastBlockHeight();
long minHeight = Math.max(cfg.syncStartBlockHeight(), stored);
@@ -85,11 +109,20 @@ public final class ArweaveBlockSyncService {
log.warn("Ignoring malformed Arweave DataItem id {}: {}", dataItemId, e.getMessage());
continue;
}
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) continue;
if (blocksDAO.existsByDataItemId(id32) || importDAO.exists(id32)) {
unresolvedDownloads.remove(dataItemId);
continue;
}
try {
byte[] rawDataItem = downloadSignedDataItem(dataItemId);
if (importDAO.enqueueIfMissing(id32, height, rawDataItem, System.currentTimeMillis())) discovered++;
DownloadedDataItem downloaded = downloadSignedDataItem(dataItemId);
unresolvedDownloads.remove(dataItemId);
if (importDAO.enqueueIfMissing(id32, downloaded.rootTxId(), height, downloaded.rawDataItem(), System.currentTimeMillis())) discovered++;
} catch (RetryableDataItemDownloadException e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
unresolvedDownloads.put(dataItemId, new PendingDownload(dataItemId, id32, height));
log.info("Signed DataItem {} visible at height {} but raw ANS-104 bytes are not ready yet; queued for fast retry: {}",
dataItemId, height, e.getMessage());
} catch (Exception e) {
lowestRetryHeight = Math.min(lowestRetryHeight, height);
log.warn("Cannot retrieve signed DataItem {} at height {} yet: {}", dataItemId, height, e.getMessage());
@@ -108,37 +141,117 @@ public final class ArweaveBlockSyncService {
}
}
private int retryPendingDownloads() throws Exception {
if (unresolvedDownloads.isEmpty()) return 0;
int queued = 0;
int attempted = 0;
List<PendingDownload> snapshot = new ArrayList<>(unresolvedDownloads.values());
for (PendingDownload pending : snapshot) {
if (attempted >= cfg.syncPageSize()) break;
attempted++;
if (blocksDAO.existsByDataItemId(pending.id32()) || importDAO.exists(pending.id32())) {
unresolvedDownloads.remove(pending.dataItemId());
continue;
}
DownloadedDataItem downloaded;
try {
downloaded = downloadSignedDataItem(pending.dataItemId());
} catch (RetryableDataItemDownloadException e) {
// Переносим в конец LinkedHashMap, чтобы первые 100 зависших ID не блокировали retry следующих.
unresolvedDownloads.remove(pending.dataItemId());
unresolvedDownloads.put(pending.dataItemId(), pending);
log.debug("ANS-104 DataItem {} still waits for location/raw bytes: {}", pending.dataItemId(), e.getMessage());
continue;
} catch (Exception e) {
// Не долбим явно плохой ответ каждые 30 секунд. Полный discovery попробует его снова позднее.
unresolvedDownloads.remove(pending.dataItemId());
log.warn("Fast retry stopped for signed DataItem {} until next discovery: {}", pending.dataItemId(), e.getMessage());
continue;
}
if (importDAO.enqueueIfMissing(pending.id32(), downloaded.rootTxId(), pending.height(),
downloaded.rawDataItem(), System.currentTimeMillis())) {
queued++;
}
unresolvedDownloads.remove(pending.dataItemId());
}
if (queued > 0) {
log.info("Fast Arweave retry queued {} signed DataItems; {} still unresolved", queued, unresolvedDownloads.size());
}
return queued;
}
private void drainQueue() throws Exception {
int passes = 0;
int importedTotal = 0;
boolean progress;
Set<String> replayedLogins = new HashSet<>();
do {
progress = false;
List<ArweaveBlockImportDAO.QueueItem> pending = importDAO.listPending(cfg.syncQueueBatchSize());
// Phase 1 is global: validate every pending DataItem and discover all signed segment
// ancestry before any canonical/orphan decision is made.
prepareAllSegmentMetadata();
// Phase 2 is deterministic logical replay order, never Arweave height/order.
List<ArweaveBlockImportDAO.QueueItem> pending = importDAO.listPendingValidated(cfg.syncQueueBatchSize());
if (pending.isEmpty()) break;
for (ArweaveBlockImportDAO.QueueItem q : pending) {
Ans104DataItem item;
try {
item = new Ans104DataItem(q.rawDataItem());
if (!Arrays.equals(item.id32(), q.dataItemId())) throw new IllegalArgumentException("data_item_id mismatch");
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE)) throw new IllegalArgumentException("bad App tag");
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
new BchBlockEntry(q.rawDataItem());
} catch (Exception e) {
importDAO.reject(q.dataItemId(), "invalid_data_item: " + e.getMessage(), System.currentTimeMillis());
if (q.parsedLogin() == null || q.parsedForkNumber() == null || q.parsedBlockNumber() == null) continue;
SolanaUserPdaCurrentEntry activeUser = usersDAO.getByLogin(q.parsedLogin());
if (activeUser == null || activeUser.getBlockchainName() == null || activeUser.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "active_user_missing", System.currentTimeMillis());
continue;
}
int activeFork = forkOf(activeUser.getBlockchainName());
if (!isAncestryComplete(q.parsedLogin(), activeFork)) {
importDAO.setPendingError(q.dataItemId(), "ancestry_incomplete", System.currentTimeMillis());
continue;
}
SolanaUserPdaCurrentEntry user = usersDAO.getByBlockchainKey(item.owner32());
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
importDAO.setPendingError(q.dataItemId(), "unknown_owner", System.currentTimeMillis());
int canonicalFork;
try (Connection cc = DbController.getInstance().getConnection()) {
canonicalFork = canonical.resolveFork(cc, q.parsedLogin(), activeFork, q.parsedBlockNumber());
}
if (canonicalFork != q.parsedForkNumber()) {
importDAO.reject(q.dataItemId(), "orphan_noncanonical", System.currentTimeMillis());
progress = true;
continue;
}
ensureState(user);
Net_AddBlock_Handler.ArweaveImportResult result = addBlock.addBlockFromArweave(user.getBlockchainName(), q.rawDataItem());
Ans104DataItem item;
BchBlockEntry parsedBlock;
try {
item = new Ans104DataItem(q.rawDataItem());
parsedBlock = new BchBlockEntry(q.rawDataItem());
} catch (Exception e) {
// Should be impossible after metadata validation, but never trust persisted bytes blindly.
importDAO.reject(q.dataItemId(), "validated_item_reparse_failed: " + e.getMessage(), System.currentTimeMillis());
progress = true;
continue;
}
SolanaUserPdaCurrentEntry physicalUser = usersDAO.getByBlockchainKey(item.owner32());
if (physicalUser == null || physicalUser.getBlockchainName() == null
|| !q.parsedLogin().equalsIgnoreCase(physicalUser.getLogin())
|| forkOf(physicalUser.getBlockchainName()) != q.parsedForkNumber()) {
importDAO.reject(q.dataItemId(), "validated_owner_mapping_changed", System.currentTimeMillis());
progress = true;
continue;
}
ensureState(physicalUser, parsedBlock);
Net_AddBlock_Handler.ArweaveImportResult result = addBlock.addBlockFromReplay(
physicalUser.getBlockchainName(), q.rawDataItem());
if (result.ok()) {
importDAO.delete(q.dataItemId());
importedTotal++; progress = true;
importedTotal++;
replayedLogins.add(q.parsedLogin());
progress = true;
rebuildIfLocalOrphansExist(q.parsedLogin(), activeFork);
continue;
}
String reason = result.reasonCode();
@@ -148,21 +261,217 @@ public final class ArweaveBlockSyncService {
importDAO.setPendingError(q.dataItemId(), reason, System.currentTimeMillis());
} else {
importDAO.reject(q.dataItemId(), reason, System.currentTimeMillis());
progress = true;
}
}
passes++;
} while (progress && passes < 8);
} while (progress && passes < 1000);
// Replay deliberately suppresses live unread/push side effects. Recompute the server-owned
// unread projection from final canonical channel contents and preserved signed read_count.
if (!replayedLogins.isEmpty()) {
try (Connection c = DbController.getInstance().getConnection()) {
boolean ac = c.getAutoCommit(); c.setAutoCommit(false);
try {
for (String login : replayedLogins) {
ChannelReadStateDAO.getInstance().recalculateUnreadForOwnedChannels(c, login, System.currentTimeMillis());
}
c.commit();
} catch (Exception e) {
c.rollback(); throw e;
} finally { c.setAutoCommit(ac); }
}
}
if (importedTotal > 0) log.info("Imported {} SHiNE test DataItems from Arweave", importedTotal);
}
private void ensureState(SolanaUserPdaCurrentEntry user) throws Exception {
BlockchainStateEntry existing = stateDAO.getByBlockchainName(user.getBlockchainName());
if (existing != null) return;
BlockchainStateEntry s = new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName()); s.setLogin(user.getLogin()); s.setBlockchainKey(user.getBlockchainKey());
s.setSizeLimit(user.getPaidLimitBytes() > 0 ? user.getPaidLimitBytes() : 100_000L);
s.setFileSizeBytes(0L); s.setLastBlockNumber(-1); s.setLastBlockHash(null); s.setUpdatedAtMs(System.currentTimeMillis());
stateDAO.insertIfMissing(s);
/**
* Phase 1 of Arweave recovery: scan the complete persistent PENDING queue and register only
* immutable segment ancestry metadata. No block is applied or rejected here.
*/
private void prepareAllSegmentMetadata() throws Exception {
String sql = "SELECT data_item_id,raw_data_item FROM arweave_block_import_queue WHERE status=? AND metadata_validated=FALSE ORDER BY block_height DESC, first_seen_at_ms DESC";
try (Connection c = DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ArweaveBlockImportDAO.STATUS_PENDING);
ps.setFetchSize(Math.max(100, cfg.syncQueueBatchSize()));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
byte[] id = rs.getBytes(1);
byte[] raw = rs.getBytes(2);
if (raw == null || raw.length == 0) {
importDAO.reject(id, "empty_data_item", System.currentTimeMillis());
continue;
}
try {
// Metadata is trusted only after complete ANS-104 validation.
Ans104DataItem item = new Ans104DataItem(raw);
if (!Arrays.equals(item.id32(), id)) throw new IllegalArgumentException("data_item_id mismatch");
if (!item.hasTag(ArweaveBlocksConfig.TEST_TAG_NAME, ArweaveBlocksConfig.TEST_TAG_VALUE))
throw new IllegalArgumentException("bad App tag");
if (!item.verifySignature()) throw new IllegalArgumentException("bad ANS-104 signature");
BchBlockEntry b = new BchBlockEntry(raw);
SolanaUserPdaCurrentEntry owner = usersDAO.getByBlockchainKey(item.owner32());
if (owner == null || owner.getBlockchainName() == null || owner.getLogin() == null) {
importDAO.setPendingError(id, "unknown_owner", System.currentTimeMillis());
continue;
}
int fork = forkOf(owner.getBlockchainName());
// Only signed structural anchor blocks can create/modify ancestry metadata.
if (fork == 1 && b.blockNumber == 0) {
if (!(b.body instanceof blockchain.body.HeaderBody))
throw new IllegalArgumentException("fork1 block #0 is not HEADER");
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
owner.getLogin(), 1, null, -1, null, 0, System.currentTimeMillis()));
} else if (b.body instanceof blockchain.body.ForkBody fb) {
if (fork <= 1) throw new IllegalArgumentException("TECH_FORK cannot belong to fork1");
if (b.blockNumber != fb.forkPointBlockNumber + 1)
throw new IllegalArgumentException("TECH_FORK block number/fork point mismatch");
SolanaUserPdaCurrentEntry parent = usersDAO.getByBlockchainKey(fb.parentBlockchainKey32);
if (parent == null || parent.getBlockchainName() == null
|| !owner.getLogin().equalsIgnoreCase(parent.getLogin()))
throw new IllegalArgumentException("TECH_FORK parent owner mismatch");
int parentFork = forkOf(parent.getBlockchainName());
if (parentFork >= fork) throw new IllegalArgumentException("TECH_FORK parent fork is not older");
segmentsDAO.upsert(c, new BlockchainForkSegmentsDAO.Segment(
owner.getLogin(), fork, parentFork,
fb.forkPointBlockNumber, fb.forkPointBlockHash32,
fb.forkPointBlockNumber + 1, System.currentTimeMillis()));
}
importDAO.markMetadataValidated(id, owner.getLogin(), fork, b.blockNumber, b.getHash32(), System.currentTimeMillis());
} catch (Exception e) {
importDAO.reject(id, "invalid_data_item: " + e.getMessage(), System.currentTimeMillis());
}
}
}
}
}
/** True only when rotation ancestry is known all the way back to fork1. */
private boolean isAncestryComplete(String login, int activeFork) throws Exception {
int f = activeFork;
Set<Integer> seen = new HashSet<>();
while (true) {
if (f < 1 || !seen.add(f)) return false;
BlockchainForkSegmentsDAO.Segment seg = segmentsDAO.get(login, f);
if (seg == null) return false;
if (seg.parentForkNumber() == null) {
return f == 1 && seg.firstPhysicalBlockNumber() == 0;
}
f = seg.parentForkNumber();
}
}
private void ensureState(SolanaUserPdaCurrentEntry user, BchBlockEntry firstSeen) throws Exception {
int fork=forkOf(user.getBlockchainName()); BlockchainStateEntry s=new BlockchainStateEntry();
s.setBlockchainName(user.getBlockchainName());s.setLogin(user.getLogin());s.setBlockchainKey(user.getBlockchainKey());s.setSizeLimit(user.getPaidLimitBytes()>0?user.getPaidLimitBytes():100_000L);s.setFileSizeBytes(0L);
BlockchainForkSegmentsDAO.Segment seg=segmentsDAO.get(user.getLogin(),fork);
BlockchainStateEntry existing=stateDAO.getByBlockchainName(user.getBlockchainName());
if(existing!=null && (seg==null || seg.parentForkNumber()==null || existing.getLastBlockNumber()>=seg.forkPointBlockNumber()))return;
if(seg!=null&&seg.parentForkNumber()!=null){
s.setLastBlockNumber(seg.forkPointBlockNumber());s.setLastBlockHash(seg.forkPointBlockHash());
try(var c=shine.db.DbController.getInstance().getConnection();var ps=c.prepareStatement("SELECT COALESCE(SUM(octet_length(block_bytes)),0) FROM blocks_store WHERE LOWER(login)=LOWER(?) AND block_number<=? AND fork_number=shine_canonical_fork(?,?,block_number)")){
ps.setString(1,user.getLogin());ps.setInt(2,seg.forkPointBlockNumber());ps.setString(3,user.getLogin());ps.setInt(4,seg.parentForkNumber());try(var rs=ps.executeQuery()){if(rs.next())s.setFileSizeBytes(rs.getLong(1));}
}
} else{s.setLastBlockNumber(-1);s.setLastBlockHash(null);}
s.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(s);
if(existing!=null)stateDAO.upsert(s);
}
private static int forkOf(String n){int d=n.lastIndexOf('-');return Integer.parseInt(n.substring(d+1));}
/** Resume a durable canonical rebuild that was interrupted after staging/cleanup/replay. */
private void recoverInterruptedCanonicalRebuilds() throws Exception {
List<String> logins=new ArrayList<>();
try(Connection c=DbController.getInstance().getConnection();
PreparedStatement ps=c.prepareStatement("SELECT DISTINCT login FROM canonical_rebuild_staging ORDER BY login");
ResultSet rs=ps.executeQuery()){
while(rs.next())logins.add(rs.getString(1));
}
for(String login:logins){
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);
if(u==null||u.getBlockchainName()==null)continue;
replayDurableCanonicalStaging(login,forkOf(u.getBlockchainName()));
}
}
/**
* A server may learn a deep fork only through Arweave after already materializing the old branch.
* If any local raw block is non-canonical under the current PDA fork, stage the canonical raw set
* and rebuild projections exactly like local key rotation does.
*/
private void rebuildIfLocalOrphansExist(String login,int activeFork)throws Exception{
if(!hasNonCanonicalLocalBlocks(login,activeFork))return;
if(!hasGenericStaging(login))stageLocalCanonicalBlocks(login,activeFork);
validateGenericStaging(login);
replayDurableCanonicalStaging(login,activeFork);
}
private boolean hasNonCanonicalLocalBlocks(String login,int activeFork)throws SQLException{
String sql="SELECT 1 FROM blocks_store b WHERE LOWER(b.login)=LOWER(?) AND b.fork_number<>shine_canonical_fork(?,?,b.block_number) LIMIT 1";
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);try(ResultSet rs=ps.executeQuery()){return rs.next();}
}
}
private boolean hasGenericStaging(String login)throws SQLException{
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT 1 FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) LIMIT 1")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){return rs.next();}
}
}
private void stageLocalCanonicalBlocks(String login,int activeFork)throws Exception{
try(Connection c=DbController.getInstance().getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
try(PreparedStatement d=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){d.setString(1,login);d.executeUpdate();}
String q="""
SELECT block_number,fork_number,block_bytes,block_hash
FROM blocks_store b
WHERE LOWER(login)=LOWER(?) AND fork_number=shine_canonical_fork(?,?,block_number)
ORDER BY block_number ASC
""";
String ins="INSERT INTO canonical_rebuild_staging(login,logical_block_number,physical_fork_number,block_bytes,block_hash) VALUES(?,?,?,?,?)";
try(PreparedStatement ps=c.prepareStatement(q);PreparedStatement out=c.prepareStatement(ins)){
ps.setString(1,login);ps.setString(2,login);ps.setInt(3,activeFork);
try(ResultSet rs=ps.executeQuery()){while(rs.next()){
out.setString(1,login);out.setInt(2,rs.getInt(1));out.setInt(3,rs.getInt(2));out.setBytes(4,rs.getBytes(3));out.setBytes(5,rs.getBytes(4));out.addBatch();
}}out.executeBatch();
}
c.commit();
}catch(Exception e){c.rollback();throw e;}finally{c.setAutoCommit(ac);}}
}
private void validateGenericStaging(String login)throws Exception{
int expected=0,last=-1;byte[] previous=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1);byte[] raw=rs.getBytes(2),hash=rs.getBytes(3);if(n!=expected)throw new IllegalStateException("canonical staging gap for "+login+": expected #"+expected+" got #"+n);
BchBlockEntry b=new BchBlockEntry(raw);if(b.blockNumber!=n)throw new IllegalStateException("canonical staging block mismatch #"+n);
if(n==0&&!(b.body instanceof blockchain.body.HeaderBody))throw new IllegalStateException("canonical staging must start HEADER #0");
if(n>0&&(previous==null||!Arrays.equals(b.prevHash32,previous)))throw new IllegalStateException("canonical staging prevHash mismatch #"+n);
if(hash==null||hash.length!=32||!Arrays.equals(hash,b.getHash32()))throw new IllegalStateException("canonical staging hash mismatch #"+n);
previous=hash;last=n;expected++;
}}
}
if(last<0)throw new IllegalStateException("canonical staging is empty for "+login);
}
private void replayDurableCanonicalStaging(String login,int activeFork)throws Exception{
SolanaUserPdaCurrentEntry u=usersDAO.getByLogin(login);if(u==null)throw new IllegalStateException("user missing for canonical rebuild: "+login);
String activeName=u.getBlockchainName();boolean guard=BlockchainResyncGuard.tryBegin(activeName);if(!guard)throw new IllegalStateException("canonical rebuild already active: "+login);
try{
validateGenericStaging(login);
cleanupDAO.cleanupLoginForCanonicalReplay(login);
long limit=u.getPaidLimitBytes()>0?u.getPaidLimitBytes():100_000L,cumulative=0;int currentFork=-1,prevNumber=-1;byte[] prevHash=null;
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("SELECT logical_block_number,physical_fork_number,block_bytes,block_hash FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?) ORDER BY logical_block_number ASC")){
ps.setString(1,login);try(ResultSet rs=ps.executeQuery()){while(rs.next()){
int n=rs.getInt(1),f=rs.getInt(2);byte[] raw=rs.getBytes(3),hash=rs.getBytes(4);BchBlockEntry b=new BchBlockEntry(raw);
String bch=login+"-"+String.format("%03d",f);
if(f!=currentFork){BlockchainStateEntry st=new BlockchainStateEntry();st.setBlockchainName(bch);st.setLogin(login);st.setBlockchainKey(Base64.getEncoder().encodeToString(b.getOwner32()));st.setSizeLimit(limit);st.setFileSizeBytes(cumulative);st.setLastBlockNumber(prevNumber);st.setLastBlockHash(prevHash);st.setUpdatedAtMs(System.currentTimeMillis());stateDAO.insertIfMissing(st);currentFork=f;}
Net_AddBlock_Handler.ArweaveImportResult r=addBlock.addBlockFromReplay(bch,raw);if(!r.ok())throw new IllegalStateException("canonical Arweave rebuild rejected #"+n+": "+r.reasonCode());
cumulative+=raw.length;prevNumber=n;prevHash=hash;
}}
}
cleanupDAO.finalizeCanonicalReplay(login);
try(Connection c=DbController.getInstance().getConnection();PreparedStatement ps=c.prepareStatement("DELETE FROM canonical_rebuild_staging WHERE LOWER(login)=LOWER(?)")){ps.setString(1,login);ps.executeUpdate();}
}finally{BlockchainResyncGuard.end(activeName);}
}
private JsonNode graphQlPage(long minHeight, String cursor) throws Exception {
@@ -181,53 +490,186 @@ public final class ArweaveBlockSyncService {
}
/**
* Gateways normally expose only the payload at /{dataItemId}. SHiNE needs the complete signed
* DataItem, so obtain its exact offset/size inside the root L1 transaction and range-read it.
* Gateway по /{dataItemId} обычно отдаёт только payload. Для импорта SHiNE нужен полный
* подписанный ANS-104 DataItem, поэтому сначала резолвим rootTx + offset + size, а затем
* читаем точный range из root L1 transaction.
*/
private byte[] downloadSignedDataItem(String dataItemId) throws Exception {
JsonNode offsets = getOffsets(dataItemId);
String rootTxId = offsets.path("rootTxId").asText("").trim();
long rootOffset = offsets.path("rootOffset").asLong(-1L);
long size = offsets.path("size").asLong(-1L);
if (rootTxId.isBlank() || rootOffset < 0 || size <= 0) {
throw new IOException("Bad AR.IO offsets for " + dataItemId + ": " + offsets);
}
if (size > cfg.syncMaxDataItemBytes()) {
throw new IOException("DataItem exceeds syncMaxDataItemBytes: " + size);
}
if (rootOffset > Long.MAX_VALUE - size) throw new IOException("DataItem offset overflow");
long endInclusive = rootOffset + size - 1;
private DownloadedDataItem downloadSignedDataItem(String dataItemId) throws Exception {
DataItemLocation location = resolveDataItemLocation(dataItemId);
long endInclusive = location.rootOffset() + location.size() - 1;
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/raw/" + rootTxId))
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/raw/" + location.rootTxId()))
.timeout(Duration.ofMinutes(2))
.header("Range", "bytes=" + rootOffset + "-" + endInclusive)
.header("Range", "bytes=" + location.rootOffset() + "-" + endInclusive)
.header("Accept", "application/octet-stream")
.GET().build();
HttpResponse<InputStream> resp = http.send(req, HttpResponse.BodyHandlers.ofInputStream());
try (InputStream in = resp.body()) {
if (resp.statusCode() != 206) {
if (isRetryableHttpStatus(resp.statusCode())) {
throw new RetryableDataItemDownloadException(
"root range is temporarily unavailable via " + location.source() + ": HTTP " + resp.statusCode());
}
throw new IOException("Gateway ignored root range for DataItem " + dataItemId + ": HTTP " + resp.statusCode());
}
byte[] bytes = readExactlyBounded(in, (int) size);
if (bytes.length != size) throw new IOException("Truncated DataItem range: expected=" + size + " got=" + bytes.length);
byte[] bytes = readExactlyBounded(in, Math.toIntExact(location.size()));
if (bytes.length != location.size()) {
throw new RetryableDataItemDownloadException(
"truncated DataItem range: expected=" + location.size() + " got=" + bytes.length);
}
Ans104DataItem parsed = new Ans104DataItem(bytes);
byte[] expectedId = B64URL.decode(dataItemId);
if (!Arrays.equals(parsed.id32(), expectedId)) {
throw new IOException("Range returned another ANS-104 DataItem for " + dataItemId);
}
return bytes;
return new DownloadedDataItem(location.rootTxId(), bytes);
}
}
private JsonNode getOffsets(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/ar-io/offsets/" + dataItemId))
.timeout(Duration.ofSeconds(30)).header("Accept","application/json").GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() == 404) throw new IOException("AR.IO offsets not indexed yet");
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("AR.IO offsets HTTP " + resp.statusCode() + ": " + safe(resp.body()));
/**
* Координаты считаются только подсказкой транспорта: источник может ошибиться, поэтому после
* range-read всё равно обязательно сверяется настоящий ANS-104 DataItem ID и затем подпись.
*/
private DataItemLocation resolveDataItemLocation(String dataItemId) throws Exception {
List<String> misses = new ArrayList<>(3);
try {
DataItemLocation location = getArIoIndexedLocation(dataItemId);
if (location != null) return location;
misses.add("ar-io=404");
} catch (Exception e) {
misses.add("ar-io=" + shortError(e));
}
return MAPPER.readTree(resp.body());
try {
DataItemLocation location = getTurboLocation(dataItemId);
if (location != null) return location;
misses.add("turbo=404");
} catch (Exception e) {
misses.add("turbo=" + shortError(e));
}
try {
DataItemLocation location = getHeadLocation(dataItemId);
if (location != null) return location;
misses.add("head=no-location");
} catch (Exception e) {
misses.add("head=" + shortError(e));
}
throw new RetryableDataItemDownloadException(
"ANS-104 location not available yet (" + String.join(", ", misses) + ")");
}
/** Самый дешёвый путь: локальный индекс AR.IO gateway. */
private DataItemLocation getArIoIndexedLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/ar-io/offsets/" + dataItemId))
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
}
JsonNode offsets = MAPPER.readTree(resp.body());
return validateLocation("ar-io", dataItemId,
offsets.path("rootTxId").asText("").trim(),
offsets.path("rootOffset").asLong(-1L),
offsets.path("size").asLong(-1L));
}
/** Turbo часто знает координаты раньше общего gateway index. */
private DataItemLocation getTurboLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncTurboApiBase()) + "/tx/" + dataItemId + "/offsets"))
.timeout(Duration.ofSeconds(30)).header("Accept", "application/json").GET().build();
HttpResponse<String> resp = http.send(req, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode() + ": " + safe(resp.body()));
}
JsonNode offsets = MAPPER.readTree(resp.body());
return validateLocation("turbo", dataItemId,
offsets.path("rootBundleId").asText("").trim(),
offsets.path("startOffsetInRootBundle").asLong(-1L),
offsets.path("rawContentLength").asLong(-1L));
}
/**
* Последний fallback: успешный HEAD/GET AR.IO может вернуть координаты DataItem в headers.
* Поддерживаем несколько имён headers, чтобы пережить различия версий gateway.
*/
private DataItemLocation getHeadLocation(String dataItemId) throws Exception {
HttpRequest req = HttpRequest.newBuilder(URI.create(trim(cfg.syncGateway()) + "/" + dataItemId))
.timeout(Duration.ofSeconds(45))
.header("Accept", "application/octet-stream")
.method("HEAD", HttpRequest.BodyPublishers.noBody())
.build();
HttpResponse<Void> resp = http.send(req, HttpResponse.BodyHandlers.discarding());
if (resp.statusCode() == 404) return null;
if (resp.statusCode() < 200 || resp.statusCode() >= 300) {
throw new IOException("HTTP " + resp.statusCode());
}
String rootTxId = firstHeader(resp, "X-AR-IO-Root-Transaction-Id");
long offset = firstLongHeader(resp,
"X-AR-IO-Root-Item-Offset",
"X-AR-IO-Root-Data-Item-Offset",
"X-AR-IO-Data-Item-Offset");
long size = firstLongHeader(resp,
"X-AR-IO-Root-Item-Size",
"X-AR-IO-Data-Item-Size");
if (rootTxId == null || offset < 0 || size <= 0) return null;
return validateLocation("head", dataItemId, rootTxId, offset, size);
}
private DataItemLocation validateLocation(String source, String dataItemId, String rootTxId, long rootOffset, long size)
throws IOException {
if (!isArweaveId(rootTxId) || rootOffset < 0 || size <= 0) {
throw new IOException("bad location for " + dataItemId + ": rootTxId=" + rootTxId
+ " offset=" + rootOffset + " size=" + size);
}
if (size > cfg.syncMaxDataItemBytes()) {
throw new IOException("DataItem exceeds syncMaxDataItemBytes: " + size);
}
if (size > Integer.MAX_VALUE) throw new IOException("DataItem is too large for in-memory import: " + size);
if (rootOffset > Long.MAX_VALUE - size) throw new IOException("DataItem offset overflow");
return new DataItemLocation(rootTxId, rootOffset, size, source);
}
private static String firstHeader(HttpResponse<?> response, String name) {
return response.headers().firstValue(name).map(String::trim).filter(v -> !v.isEmpty()).orElse(null);
}
private static long firstLongHeader(HttpResponse<?> response, String... names) {
for (String name : names) {
String value = firstHeader(response, name);
if (value == null) continue;
try { return Long.parseLong(value); }
catch (NumberFormatException ignored) { }
}
return -1L;
}
private static boolean isArweaveId(String value) {
if (value == null || value.length() != 43) return false;
try { return B64URL.decode(value).length == 32; }
catch (IllegalArgumentException e) { return false; }
}
private static boolean isRetryableHttpStatus(int status) {
return status == 404 || status == 408 || status == 425 || status == 429 || status >= 500;
}
private static String shortError(Exception e) {
String message = e.getMessage();
return safe(message == null || message.isBlank() ? e.getClass().getSimpleName() : message);
}
private record PendingDownload(String dataItemId, byte[] id32, long height) {}
private record DownloadedDataItem(String rootTxId, byte[] rawDataItem) {}
private record DataItemLocation(String rootTxId, long rootOffset, long size, String source) {}
private static final class RetryableDataItemDownloadException extends IOException {
private RetryableDataItemDownloadException(String message) { super(message); }
}
private static byte[] readExactlyBounded(InputStream in, int expected) throws IOException {
@@ -1,6 +1,7 @@
package server.archive;
import blockchain.Ans104DataItem;
import blockchain.ShineProtocolTags;
import utils.config.AppConfig;
import java.nio.file.Path;
@@ -26,7 +27,9 @@ public record ArweaveBlocksConfig(
int syncQueueBatchSize,
long syncStartBlockHeight,
long syncMaxDataItemBytes,
String syncGateway
String syncGateway,
String syncTurboApiBase,
int syncLocationRetrySeconds
) {
public enum PublishMode {
TURBO,
@@ -45,9 +48,9 @@ public record ArweaveBlocksConfig(
}
}
public static final String TEST_TAG_NAME = "App";
public static final String TEST_TAG_VALUE = "test5590";
public static final String CHANNEL_TAG_NAME = "c_test5590";
public static final String TEST_TAG_NAME = ShineProtocolTags.APP_TAG_NAME;
public static final String TEST_TAG_VALUE = ShineProtocolTags.APP_TAG_VALUE;
public static final String CHANNEL_TAG_NAME = ShineProtocolTags.CHANNEL_TAG_NAME;
public static ArweaveBlocksConfig load() {
AppConfig c = AppConfig.getInstance();
@@ -72,7 +75,9 @@ public record ArweaveBlocksConfig(
positive(c.getInt("arweave.blocks.sync.queueBatchSize", 10_000), "sync.queueBatchSize"),
nonNegativeLong(parseLong(c.getParam("arweave.blocks.sync.startBlockHeight"), 0L), "sync.startBlockHeight"),
positiveLong(maxDataItemBytes, "sync.maxDataItemBytes"),
orDefault(c.getParam("arweave.blocks.sync.gateway"), "https://turbo-gateway.com")
orDefault(c.getParam("arweave.blocks.sync.gateway"), "https://turbo-gateway.com"),
orDefault(c.getParam("arweave.blocks.sync.turboApiBase"), "https://turbo.ardrive.io"),
positive(c.getInt("arweave.blocks.sync.locationRetrySeconds", 30), "sync.locationRetrySeconds")
);
}
@@ -29,7 +29,7 @@ final class Ans104BundleTest {
byte[] privateKey = Ed25519Util.generatePrivateKeyFromString("bundle-" + payload);
byte[] owner = Ed25519Util.derivePublicKey(privateKey);
byte[] data = payload.getBytes(StandardCharsets.UTF_8);
List<Ans104DataItem.Tag> tags = List.of(new Ans104DataItem.Tag("App", "test5590"));
List<Ans104DataItem.Tag> tags = List.of(new Ans104DataItem.Tag(blockchain.ShineProtocolTags.APP_TAG_NAME, blockchain.ShineProtocolTags.APP_TAG_VALUE));
byte[] signature = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, data), privateKey);
return Ans104DataItem.serializeEd25519(signature, owner, tags, data);
}
@@ -17,6 +17,7 @@ import java.util.Objects;
* SHiNE Frame v1 (all integer fields BigEndian):
* [2] frameCode = 0x0001
* [32] prevHash32 = SHA-256(Frame v1 bytes of previous SHiNE block)
* [32] back32Hash32 = SHA-256(Frame v1 bytes of block N-32), or zero for N<32
* [4] blockSize = exact Frame v1 byte length
* [4] blockNumber
* [8] timestamp unix seconds
@@ -33,10 +34,11 @@ public final class BchBlockEntry {
public static final int FRAME_CODE_V1 = 0x0001;
public static final int MAX_BLOCK_FULL_BYTES = Ans104DataItem.MAX_DATA_ITEM_BYTES;
public static final long MAX_FUTURE_SECONDS = 60;
public static final int FRAME_HEADER_SIZE = 2 + 32 + 4 + 4 + 8 + 2 + 2 + 2;
public static final int FRAME_HEADER_SIZE = 2 + 32 + 32 + 4 + 4 + 8 + 2 + 2 + 2;
public final int frameCode;
public final byte[] prevHash32;
public final byte[] back32Hash32;
public final int blockSize;
public final int blockNumber;
public final long timestamp;
@@ -66,6 +68,8 @@ public final class BchBlockEntry {
}
this.prevHash32 = new byte[32];
bb.get(prevHash32);
this.back32Hash32 = new byte[32];
bb.get(back32Hash32);
this.blockSize = bb.getInt();
if (blockSize != frameBytes.length || blockSize < FRAME_HEADER_SIZE) {
throw new IllegalArgumentException("SHiNE blockSize mismatch: declared=" + blockSize + " actual=" + frameBytes.length);
@@ -25,6 +25,10 @@ public final class BodyRecordParser {
&& (v == (CreateChannelBody.VER & 0xFFFF))) {
return new CreateChannelBody(subType, version, bodyBytes).check();
}
if (st == (ForkBody.SUBTYPE & 0xFFFF)
&& (v == (ForkBody.VER & 0xFFFF))) {
return new ForkBody(subType, version, bodyBytes).check();
}
throw new IllegalArgumentException(
String.format("Unknown TECH body type/version/subType: type=%d ver=%d subType=%d", t, v, st)
);
@@ -33,7 +37,7 @@ public final class BodyRecordParser {
int key = (t << 16) | v;
BodyRecord r = switch (key) {
case TextBody.KEY -> {
case TextLineBody.KEY -> {
if (st == (MsgSubType.TEXT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
@@ -41,7 +45,8 @@ public final class BodyRecordParser {
|| st == (MsgSubType.TEXT_COURSE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
|| st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
yield new TextLineBody(subType, version, bodyBytes);
}
@@ -13,5 +13,5 @@
// public static final short TEXT = 1; // сообщения да надо
// public static final short REACTION = 2; // реакции не надо
// public static final short CONNECTION = 3; // связи (friend/contact/follow) да надо
// public static final short USER_PARAM = 4; // параметры профиля да надо
// public static final short USER_PROFILE= 4; // профиль пользователя да надо
//}
@@ -35,6 +35,8 @@ public final class MsgSubType {
/** HeaderBody: subType всегда 0 (compat). */
public static final short HEADER_COMPAT = 0;
public static final short TECH_CREATE_CHANNEL = 1;
/** Новый fork/ротация ключей: ссылка на родительскую цепочку и точку отката. */
public static final short TECH_FORK = 2;
/* ===================== TEXT (msg_type=1) ===================== */
@@ -53,7 +55,7 @@ public final class MsgSubType {
/**
* REPLY — ответ на сообщение.
* НЕ в линии. Имеет target (toBlockchainName + blockNumber + hash32).
* НЕ в линии. Имеет target (toLogin + blockNumber + hash32).
* Может указывать на чужой блокчейн/чужую линию/чужой канал.
*/
public static final short TEXT_REPLY = 20;
@@ -69,7 +71,7 @@ public final class MsgSubType {
/**
* REPOST — отложенная будущая заготовка репоста сообщения в линии канала.
* Имеет hasLine + target (toBlockchainName + toBlockGlobalNumber + toBlockHash32) + текст комментария.
* Имеет hasLine + target (toLogin + toBlockGlobalNumber + toBlockHash32) + текст комментария.
*/
public static final short TEXT_REPOST = 50;
@@ -79,6 +81,9 @@ public final class MsgSubType {
*/
public static final short TEXT_CHANNEL_META = 90;
/** CHANNEL_DELETE — soft-delete marker for a channel line. */
public static final short TEXT_CHANNEL_DELETE = 92;
/** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100;
/** EXERCISE — упражнение/комплекс (line-based). */
@@ -0,0 +1,17 @@
package blockchain;
/**
* Канонические ANS-104 tag names/value текущего SHiNE transport namespace на сервере.
*
* При смене тестовой эпохи namespace меняется отдельно в трёх рабочих местах:
* сервер, UI и актуальный Arweave Viewer.
*/
public final class ShineProtocolTags {
private ShineProtocolTags() {}
public static final String NAMESPACE = "test5591";
public static final String APP_TAG_NAME = "App";
public static final String APP_TAG_VALUE = NAMESPACE;
public static final String CHANNEL_TAG_NAME = "c";
public static final String TYPE_TAG_NAME = "t";
}
@@ -1,21 +1,23 @@
package blockchain.body;
/**
* BodyHasLine — для типов, которые имеют линейные поля в body.
* BodyHasLine — типы блоков, которые входят в проверяемую логическую линию.
*
* Line-prefix (BigEndian) в НАЧАЛЕ bodyBytes:
* [4] lineCode код линии (root-идентификатор):
* - 0 для дефолтной линии/канала "0" (root = HEADER, blockNumber=0)
* - для канала "X": blockNumber root-блока канала (CREATE_CHANNEL)
* Общая семантика:
* prevLineBlockGlobalNumber — GLOBAL blockNumber предыдущего блока этой линии;
* prevLineBlockHash32 — hash32 предыдущего блока этой линии;
* lineSeq — порядковый номер шага линии.
*
* [4] prevLineBlockGlobalNumber глобальный номер предыдущего блока в этой линии
* [32] prevLineBlockHash32 hash32 предыдущего блока в этой линии
* lineCode — логический идентификатор линии:
* - 0 для фиксированных системных линий (TECH, CONNECTION, USER_PROFILE)
* и для дефолтного канала, корнем которого является HEADER #0;
* - для пользовательского канала: GLOBAL blockNumber его CREATE_CHANNEL root.
*
* [4] lineSeq порядковый номер сообщения внутри линии (1..N)
* Важно: lineCode не обязан физически присутствовать в body. Для фиксированных
* USER_PROFILE и CONNECTION он выводится из msg_type и метод lineCode() возвращает 0.
* Для TEXT-каналов и TECH-блоков lineCode хранится в body явно.
*
* Важно:
* - Проверка связности линии (prevLineBlockGlobalNumber ↔ prevLineBlockHash32) и корректности lineSeq
* выполняется на сервере/в БД при вставке (а не в body.check()).
* Полная проверка хвоста линии, prev hash и lineSeq выполняется сервером при AddBlock.
*/
public interface BodyHasLine {
@@ -26,4 +28,4 @@ public interface BodyHasLine {
byte[] prevLineBlockHash32();
int lineSeq();
}
}
@@ -1,31 +1,25 @@
package blockchain.body;
import utils.blockchain.BlockchainNameUtil;
/**
* BodyHasTarget — дополнительный интерфейс для body, которые "ссылаются" на цель (to-поля).
* Body that refers to a logical block target.
*
* Новое правило:
* - toLogin НЕ храним в байтах блока.
* - toLogin всегда вычисляется из toBchName по стандарту login+"-NNN".
*
* Все методы могут возвращать null.
* Canonical rules:
* - external target: login + forkNumber + blockNumber + blockHash;
* - own EDIT target: blockNumber + blockHash only;
* - logical identity NEVER includes forkNumber: login + blockNumber + blockHash;
* - forkNumber is informational/historical only and must be in 1..999.
*/
public interface BodyHasTarget {
/** Target login; null for own-chain compact EDIT targets. */
default String toLogin() { return null; }
/** login цели (nullable). Вычисляется из toBchName(). */
default String toLogin() {
String bch = toBchName();
if (bch == null) return null;
return BlockchainNameUtil.loginFromBlockchainName(bch);
}
/** Historical fork number recorded by the author; null for compact EDIT targets. */
default Integer toForkNumber() { return null; }
/** blockchainName цели (nullable). */
String toBchName();
/** Runtime-only physical blockchain cache; never serialized in canonical targets. */
@Deprecated
default String toBchName() { return null; }
/** globalNumber цели (nullable). */
Integer toBlockGlobalNumber();
/** hash целевого блока (обычно 32 байта). Может быть null, если ссылки нет. */
byte[] toBlockHashBytes();
}
}
@@ -0,0 +1,115 @@
package blockchain.body;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/** Shared codec/validation for canonical SHiNE target formats. */
final class BodyTargetSupport {
private BodyTargetSupport() {}
record ExternalTarget(String login, int forkNumber, int blockNumber, byte[] blockHash32) {}
static ExternalTarget readExternal(ByteBuffer bb, String ctx, int bytesRequiredAfterTarget) {
ensureMin(bb, 1 + 1 + 2 + 4 + 32 + bytesRequiredAfterTarget, ctx + " target too short");
int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0) throw new IllegalArgumentException(ctx + " toLoginLen is 0");
ensureMin(bb, loginLen + 2 + 4 + 32 + bytesRequiredAfterTarget, ctx + " target payload too short");
byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes);
String login = decodeStrictUtf8(loginBytes, ctx + " toLogin");
if (login.isBlank()) throw new IllegalArgumentException(ctx + " toLogin is blank");
int forkNumber = Short.toUnsignedInt(bb.getShort());
validateForkNumber(forkNumber, ctx);
int blockNumber = bb.getInt();
if (blockNumber < 0) throw new IllegalArgumentException(ctx + " toBlockGlobalNumber < 0");
byte[] hash = new byte[32];
bb.get(hash);
requireNonZeroHash32(hash, ctx + " toBlockHash32");
return new ExternalTarget(login, forkNumber, blockNumber, hash);
}
static int externalSize(String login) {
return 1 + loginBytes(login).length + 2 + 4 + 32;
}
static void writeExternal(ByteBuffer bb, String login, int forkNumber, int blockNumber, byte[] hash32, String ctx) {
byte[] loginBytes = loginBytes(login);
validateForkNumber(forkNumber, ctx);
if (blockNumber < 0) throw new IllegalArgumentException(ctx + " toBlockGlobalNumber < 0");
requireNonZeroHash32(hash32, ctx + " toBlockHash32");
bb.put((byte) loginBytes.length);
bb.put(loginBytes);
bb.putShort((short) forkNumber);
bb.putInt(blockNumber);
bb.put(hash32);
}
static void validateExternal(String login, Integer forkNumber, Integer blockNumber, byte[] hash32, String ctx) {
loginBytes(login);
if (forkNumber == null) throw new IllegalArgumentException(ctx + " toForkNumber is null");
validateForkNumber(forkNumber, ctx);
if (blockNumber == null || blockNumber < 0) throw new IllegalArgumentException(ctx + " toBlockGlobalNumber invalid");
requireNonZeroHash32(hash32, ctx + " toBlockHash32");
}
static void validateCompact(Integer blockNumber, byte[] hash32, String ctx) {
if (blockNumber == null || blockNumber < 0) throw new IllegalArgumentException(ctx + " toBlockGlobalNumber invalid");
requireNonZeroHash32(hash32, ctx + " toBlockHash32");
}
static byte[] readCompactHash(ByteBuffer bb, String ctx) {
ensureMin(bb, 4 + 32, ctx + " target too short");
int blockNumber = bb.getInt();
if (blockNumber < 0) throw new IllegalArgumentException(ctx + " toBlockGlobalNumber < 0");
byte[] hash = new byte[32];
bb.get(hash);
requireNonZeroHash32(hash, ctx + " toBlockHash32");
return hash;
}
static byte[] loginBytes(String login) {
if (login == null || login.isBlank()) throw new IllegalArgumentException("toLogin is blank");
byte[] bytes = login.getBytes(StandardCharsets.UTF_8);
if (bytes.length == 0 || bytes.length > 255) throw new IllegalArgumentException("toLogin utf8 len must be 1..255");
return bytes;
}
static void validateForkNumber(int forkNumber, String ctx) {
if (forkNumber < 1 || forkNumber > 999) {
throw new IllegalArgumentException(ctx + " toForkNumber must be 1..999");
}
}
static void requireNonZeroHash32(byte[] hash32, String field) {
if (hash32 == null || hash32.length != 32) throw new IllegalArgumentException(field + " must be 32 bytes");
boolean any = false;
for (byte b : hash32) any |= b != 0;
if (!any) throw new IllegalArgumentException(field + " must not be zero hash");
}
static byte[] copyHash(byte[] hash32) {
return hash32 == null ? null : Arrays.copyOf(hash32, 32);
}
static String decodeStrictUtf8(byte[] bytes, String field) {
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return decoder.decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(field + " is not valid UTF-8", e);
}
}
static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
}
@@ -1,286 +1,104 @@
package blockchain.body;
import blockchain.MsgSubType;
import utils.blockchain.BlockchainNameUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* ConnectionBody — type=3, ver=1 (в заголовке блока).
*
* subType (в заголовке блока) как MsgSubType:
* FRIEND=10, UNFRIEND=11
* CONTACT=20, UNCONTACT=21
* FOLLOW=30, UNFOLLOW=31
* SPOUSE=40, UNSPOUSE=41
* PARENT=50, UNPARENT=51
* CHILD=52, UNCHILD=53
* SIBLING=54, UNSIBLING=55
* FRIEND=14, UNFRIEND=15
* KNOWN_PERSON=60, UNKNOWN_PERSON=61 (legacy; accepted but not used by current UI)
* SHINE_CONFIRMED=70, SHINE_UNCONFIRMED=71
* SHINE_SEEN=74, SHINE_UNSEEN=75 (currently not used by UI)
* OFFICIAL_ACCOUNT_CONFIRMED=80, OFFICIAL_ACCOUNT_UNCONFIRMED=81
*
* bodyBytes (BigEndian), новый формат (toLogin НЕ ХРАНИМ):
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
*
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber (int32)
* [32] toBlockHash32 (raw 32 bytes)
*
* toLogin вычисляется автоматически из toBlockchainName:
* toLogin = BlockchainNameUtil.loginFromBlockchainName(toBlockchainName)
* CONNECTION with one fixed connection-history line and canonical external target.
* lineCode is not stored in body: the logical connection line always has code 0.
*/
/**
* =========================================================================
* ПРАВИЛО TARGET/ROOT ДЛЯ КАНАЛОВ И СВЯЗЕЙ (важно для подписок/друзей/контактов)
* =========================================================================
*
* Термины:
* - ROOT линии/канала = блок, который "начинает" линию:
* * для канала "0" root = HEADER (blockNumber=0)
* * для канала "X" root = CREATE_CHANNEL (blockNumber этого блока)
*
* 1) СВЯЗИ МЕЖДУ ПОЛЬЗОВАТЕЛЯМИ (CONNECTION_*):
* FRIEND / CONTACT -> цель ВСЕГДА HEADER пользователя:
* toBlockNumber = 0
* toBlockHash32 = hash32(HEADER цели)
*
* 2) ПОДПИСКИ НА КОНТЕНТ (FOLLOW/SUBSCRIBE):
* FOLLOW пользователя (в целом) -> цель = ROOT дефолтного канала "0" (то есть HEADER):
* toBlockNumber = 0
* toBlockHash32 = hash32(HEADER цели)
*
* FOLLOW/подписка на конкретный канал пользователя ->
* цель = ROOT этого канала:
* - канал "0": toBlockNumber=0, toBlockHash32=hash32(HEADER)
* - канал "X": toBlockNumber=blockNumber(CREATE_CHANNEL),
* toBlockHash32=hash32(CREATE_CHANNEL)
*
* 3) ЗАПРЕТЫ ВАЛИДАЦИИ (желательно на сервере/в БД):
* - CONNECTION_CLOSE_FRIEND/CONTACT не могут ссылаться на не-HEADER (toBlockNumber != 0 запрещено).
* - FOLLOW на канал "X" не может ссылаться на произвольный пост внутри канала:
* разрешено ТОЛЬКО на ROOT (HEADER или CREATE_CHANNEL).
*
* Зачем так:
* - связи и подписки всегда стабильны и не ломаются при новых постах,
* - один понятный инвариант: "подписка всегда указывает на root линии".
* =========================================================================
*/
public final class ConnectionBody implements BodyRecord, BodyHasTarget, BodyHasLine {
public static final short TYPE = 3;
public static final short VER = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // из header
// line
public final int lineCode;
public final int prevLineNumber;
public final byte[] prevLineHash32;
public final int thisLineNumber;
// payload
public final String toBlockchainName;
public final short subType;
public final short version;
public final int prevConnectionBlockNumber;
public final byte[] prevConnectionBlockHash32;
public final int connectionSequence;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public ConnectionBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ConnectionBody version must be 1, got=" + (this.version & 0xFFFF));
}
if (!isValidSubType(this.subType)) {
throw new IllegalArgumentException("Bad connection subType: " + (this.subType & 0xFFFF));
}
// минимум:
// lineCode(4) + line(4+32+4) + toBchLen[1]+toBch[1] + global[4] + hash[32]
if (bodyBytes.length < 4 + (4 + 32 + 4) + 1 + 1 + 4 + 32) {
throw new IllegalArgumentException("ConnectionBody too short");
}
if ((version & 0xFFFF) != 1 || !isValidSubType(subType)) throw new IllegalArgumentException("Bad Connection header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
int bchLen = Byte.toUnsignedInt(bb.get());
if (bchLen <= 0) throw new IllegalArgumentException("toBlockchainNameLen is 0");
if (bb.remaining() < bchLen + 4 + 32) throw new IllegalArgumentException("Connection payload too short");
byte[] bchBytes = new byte[bchLen];
bb.get(bchBytes);
this.toBlockchainName = new String(bchBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
BodyTargetSupport.ensureMin(bb, 4 + 32 + 4 + 1 + 1 + 2 + 4 + 32, "ConnectionBody too short");
this.prevConnectionBlockNumber = bb.getInt();
this.prevConnectionBlockHash32 = new byte[32];
bb.get(this.prevConnectionBlockHash32);
this.connectionSequence = bb.getInt();
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "CONNECTION", 0);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected ConnectionBody tail");
}
public ConnectionBody(int lineCode,
int prevLineNumber,
byte[] prevLineHash32,
int thisLineNumber,
short subType,
String toBlockchainName,
int toBlockGlobalNumber,
byte[] toBlockHash32) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection subType: " + (subType & 0xFFFF));
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
// Железное правило формата: bchName -> login + "-NNN"
if (BlockchainNameUtil.loginFromBlockchainName(toBlockchainName) == null) {
throw new IllegalArgumentException("toBlockchainName must match login+\"-NNN\": " + toBlockchainName);
}
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.lineCode = lineCode;
this.prevLineNumber = prevLineNumber;
this.prevLineHash32 = (prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
this.thisLineNumber = thisLineNumber;
public ConnectionBody(int prevConnectionBlockNumber, byte[] prevConnectionBlockHash32, int connectionSequence, short subType,
String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
this.prevConnectionBlockNumber = prevConnectionBlockNumber;
this.prevConnectionBlockHash32 = prevConnectionBlockHash32 == null ? new byte[32] : Arrays.copyOf(prevConnectionBlockHash32, 32);
this.connectionSequence = connectionSequence;
this.subType = subType;
this.version = VER;
this.toBlockchainName = toBlockchainName;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
}
private static boolean isValidSubType(short st) {
int v = st & 0xFFFF;
return v == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNCLOSE_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNFRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CONTACT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNCONTACT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FOLLOW & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SPOUSE & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNSPOUSE & 0xFFFF)
|| v == (MsgSubType.CONNECTION_PARENT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNPARENT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CHILD & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNCHILD & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SIBLING & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNSIBLING & 0xFFFF)
|| v == (MsgSubType.CONNECTION_KNOWN_PERSON & 0xFFFF)
|| v == (MsgSubType.CONNECTION_UNKNOWN_PERSON & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_UNCONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_SEEN & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_UNSEEN & 0xFFFF)
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
}
@Override
public ConnectionBody check() {
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection subType: " + (subType & 0xFFFF));
// line rule (как было)
if (prevLineNumber == -1) {
if (!isAllZero32(prevLineHash32)) throw new IllegalArgumentException("prevLineHash32 must be zero when prevLineNumber=-1");
if (thisLineNumber != -1) throw new IllegalArgumentException("thisLineNumber must be -1 when prevLineNumber=-1");
} else {
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
}
if (toBlockchainName == null || toBlockchainName.isBlank())
throw new IllegalArgumentException("toBlockchainName is blank");
// гарантируем вычислимый toLogin (иначе target “битый” по стандарту)
if (BlockchainNameUtil.loginFromBlockchainName(toBlockchainName) == null)
throw new IllegalArgumentException("toBlockchainName must match login+\"-NNN\": " + toBlockchainName);
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 invalid");
@Override public ConnectionBody check() {
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad connection fields");
if (prevConnectionBlockNumber < 0) throw new IllegalArgumentException("prevConnectionBlockNumber must be >=0");
if (prevConnectionBlockHash32 == null || prevConnectionBlockHash32.length != 32) throw new IllegalArgumentException("prevConnectionBlockHash32 invalid");
if (connectionSequence <= 0) throw new IllegalArgumentException("connectionSequence must be >=1");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return this;
}
@Override
public byte[] toBytes() {
byte[] bchBytes = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (bchBytes.length == 0 || bchBytes.length > 255)
throw new IllegalArgumentException("toBlockchainName utf8 len must be 1..255");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("toBlockHash32 != 32");
int cap = 4 + (4 + 32 + 4)
+ 1 + bchBytes.length
+ 4 + 32;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
bb.put((byte) bchBytes.length);
bb.put(bchBytes);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
@Override public byte[] toBytes() {
check();
ByteBuffer bb = ByteBuffer.allocate(4 + 32 + 4 + BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
bb.putInt(prevConnectionBlockNumber).put(prevConnectionBlockHash32).putInt(connectionSequence);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "CONNECTION");
return bb.array();
}
private static boolean isAllZero32(byte[] b) {
if (b == null || b.length != 32) return true;
for (int i = 0; i < 32; i++) if (b[i] != 0) return false;
return true;
}
/* ====================== BodyHasLine ====================== */
@Override public int lineCode() { return lineCode; }
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
@Override public byte[] prevLineBlockHash32() { return prevLineHash32 == null ? null : Arrays.copyOf(prevLineHash32, 32); }
@Override public int lineSeq() { return thisLineNumber; }
/* ====================== BodyHasTarget ===================== */
@Override public String toBchName() { return toBlockchainName; }
@Override public int lineCode() { return 0; }
@Override public int prevLineBlockGlobalNumber() { return prevConnectionBlockNumber; }
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevConnectionBlockHash32, 32); }
@Override public int lineSeq() { return connectionSequence; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static boolean isValidSubType(short st) {
int v = st & 0xFFFF;
return v == (MsgSubType.CONNECTION_CLOSE_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCLOSE_FRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FRIEND & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFRIEND & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CONTACT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCONTACT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_FOLLOW & 0xFFFF) || v == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SPOUSE & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSPOUSE & 0xFFFF)
|| v == (MsgSubType.CONNECTION_PARENT & 0xFFFF) || v == (MsgSubType.CONNECTION_UNPARENT & 0xFFFF)
|| v == (MsgSubType.CONNECTION_CHILD & 0xFFFF) || v == (MsgSubType.CONNECTION_UNCHILD & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SIBLING & 0xFFFF) || v == (MsgSubType.CONNECTION_UNSIBLING & 0xFFFF)
|| v == (MsgSubType.CONNECTION_KNOWN_PERSON & 0xFFFF) || v == (MsgSubType.CONNECTION_UNKNOWN_PERSON & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNCONFIRMED & 0xFFFF)
|| v == (MsgSubType.CONNECTION_SHINE_SEEN & 0xFFFF) || v == (MsgSubType.CONNECTION_SHINE_UNSEEN & 0xFFFF)
|| v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_CONFIRMED & 0xFFFF) || v == (MsgSubType.CONNECTION_OFFICIAL_ACCOUNT_UNCONFIRMED & 0xFFFF);
}
}
@@ -0,0 +1,235 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* TECH_FORK body (type=0, subType=2, version=1).
*
* TECH_FORK является обычным шагом общей TECH-линии. Поэтому body начинается
* тем же line-prefix, что и TECH_CREATE_CHANNEL.
*
* body bytes (BigEndian):
* [4] lineCode (=0 для TECH-линии)
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
*
* [32] parentBlockchainKey
* [4] forkPointBlockNumber
* [32] forkPointBlockHash32
* [8] forkPointTimestampMs
* [4] parentTipBlockNumber
* [32] parentTipBlockHash32
* [8] parentTipTimestampMs
* [4] discardedBlocksCount
* [1] reasonCode
* [2] commentUtf8Length
* [N] comment UTF-8 (0..1024 bytes)
*/
public final class ForkBody implements BodyRecord, BodyHasLine {
public static final short TYPE = 0;
public static final short VER = 1;
public static final short SUBTYPE = MsgSubType.TECH_FORK;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public static final int REASON_ROUTINE_ROTATION = 1;
public static final int REASON_POSSIBLE_COMPROMISE = 2;
public static final int REASON_CONFIRMED_COMPROMISE_ROLLBACK = 3;
public static final int REASON_RECOVERY = 4;
public static final int MAX_COMMENT_UTF8_LEN = 1024;
private static final int LINE_PREFIX_LEN = 4 + 4 + 32 + 4;
private static final int FIXED_PAYLOAD_LEN = 32 + 4 + 32 + 8 + 4 + 32 + 8 + 4 + 1 + 2;
private static final int FIXED_LEN = LINE_PREFIX_LEN + FIXED_PAYLOAD_LEN;
public final short subType;
public final short version;
public final int lineCode;
public final int prevLineNumber;
public final byte[] prevLineHash32;
public final int thisLineNumber;
public final byte[] parentBlockchainKey32;
public final int forkPointBlockNumber;
public final byte[] forkPointBlockHash32;
public final long forkPointTimestampMs;
public final int parentTipBlockNumber;
public final byte[] parentTipBlockHash32;
public final long parentTipTimestampMs;
public final int discardedBlocksCount;
public final int reasonCode;
public final String comment;
public ForkBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody version must be 1");
}
if (bodyBytes.length < FIXED_LEN) {
throw new IllegalArgumentException("ForkBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
this.parentBlockchainKey32 = new byte[32];
bb.get(this.parentBlockchainKey32);
this.forkPointBlockNumber = bb.getInt();
this.forkPointBlockHash32 = new byte[32];
bb.get(this.forkPointBlockHash32);
this.forkPointTimestampMs = bb.getLong();
this.parentTipBlockNumber = bb.getInt();
this.parentTipBlockHash32 = new byte[32];
bb.get(this.parentTipBlockHash32);
this.parentTipTimestampMs = bb.getLong();
this.discardedBlocksCount = bb.getInt();
this.reasonCode = Byte.toUnsignedInt(bb.get());
int commentLen = Short.toUnsignedInt(bb.getShort());
if (commentLen > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkBody comment utf8 len must be <=1024");
}
if (bb.remaining() != commentLen) {
throw new IllegalArgumentException("ForkBody tail mismatch: remaining=" + bb.remaining() + " commentLen=" + commentLen);
}
byte[] commentBytes = new byte[commentLen];
bb.get(commentBytes);
this.comment = new String(commentBytes, StandardCharsets.UTF_8);
}
public ForkBody(int lineCode,
int prevLineNumber,
byte[] prevLineHash32,
int thisLineNumber,
byte[] parentBlockchainKey32,
int forkPointBlockNumber,
byte[] forkPointBlockHash32,
long forkPointTimestampMs,
int parentTipBlockNumber,
byte[] parentTipBlockHash32,
long parentTipTimestampMs,
int discardedBlocksCount,
int reasonCode,
String comment) {
this.subType = SUBTYPE;
this.version = VER;
this.lineCode = lineCode;
this.prevLineNumber = prevLineNumber;
this.prevLineHash32 = copy32(prevLineHash32, "prevLineHash32");
this.thisLineNumber = thisLineNumber;
this.parentBlockchainKey32 = copy32(parentBlockchainKey32, "parentBlockchainKey32");
this.forkPointBlockNumber = forkPointBlockNumber;
this.forkPointBlockHash32 = copy32(forkPointBlockHash32, "forkPointBlockHash32");
this.forkPointTimestampMs = forkPointTimestampMs;
this.parentTipBlockNumber = parentTipBlockNumber;
this.parentTipBlockHash32 = copy32(parentTipBlockHash32, "parentTipBlockHash32");
this.parentTipTimestampMs = parentTipTimestampMs;
this.discardedBlocksCount = discardedBlocksCount;
this.reasonCode = reasonCode;
this.comment = normalizeComment(comment);
}
@Override
public ForkBody check() {
if ((subType & 0xFFFF) != (SUBTYPE & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody subType must be TECH_FORK(2)");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ForkBody version must be 1");
}
if (lineCode != 0) throw new IllegalArgumentException("ForkBody lineCode must be 0");
if (prevLineNumber < 0) throw new IllegalArgumentException("prevLineNumber must be >=0");
require32(prevLineHash32, "prevLineHash32");
if (thisLineNumber <= 0) throw new IllegalArgumentException("thisLineNumber must be >=1");
require32(parentBlockchainKey32, "parentBlockchainKey32");
require32(forkPointBlockHash32, "forkPointBlockHash32");
require32(parentTipBlockHash32, "parentTipBlockHash32");
if (forkPointBlockNumber < 0) throw new IllegalArgumentException("forkPointBlockNumber < 0");
if (parentTipBlockNumber < forkPointBlockNumber) {
throw new IllegalArgumentException("parentTipBlockNumber < forkPointBlockNumber");
}
if (forkPointTimestampMs < 0) throw new IllegalArgumentException("forkPointTimestampMs < 0");
if (parentTipTimestampMs < 0) throw new IllegalArgumentException("parentTipTimestampMs < 0");
int expectedDiscarded = parentTipBlockNumber - forkPointBlockNumber;
if (discardedBlocksCount != expectedDiscarded) {
throw new IllegalArgumentException("discardedBlocksCount must equal parentTipBlockNumber - forkPointBlockNumber");
}
if (!isReasonSupported(reasonCode)) {
throw new IllegalArgumentException("Unsupported fork reasonCode=" + reasonCode);
}
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
if (commentUtf8.length > MAX_COMMENT_UTF8_LEN) {
throw new IllegalArgumentException("ForkBody comment utf8 len must be <=1024");
}
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] commentUtf8 = normalizeComment(comment).getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(FIXED_LEN + commentUtf8.length).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32);
bb.putInt(thisLineNumber);
bb.put(parentBlockchainKey32);
bb.putInt(forkPointBlockNumber);
bb.put(forkPointBlockHash32);
bb.putLong(forkPointTimestampMs);
bb.putInt(parentTipBlockNumber);
bb.put(parentTipBlockHash32);
bb.putLong(parentTipTimestampMs);
bb.putInt(discardedBlocksCount);
bb.put((byte) reasonCode);
bb.putShort((short) commentUtf8.length);
bb.put(commentUtf8);
return bb.array();
}
@Override public int lineCode() { return lineCode; }
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevLineHash32, 32); }
@Override public int lineSeq() { return thisLineNumber; }
public static boolean isReasonSupported(int code) {
return code == REASON_ROUTINE_ROTATION
|| code == REASON_POSSIBLE_COMPROMISE
|| code == REASON_CONFIRMED_COMPROMISE_ROLLBACK
|| code == REASON_RECOVERY;
}
private static byte[] copy32(byte[] value, String name) {
require32(value, name);
return Arrays.copyOf(value, 32);
}
private static void require32(byte[] value, String name) {
if (value == null || value.length != 32) {
throw new IllegalArgumentException(name + " must be 32 bytes");
}
}
private static String normalizeComment(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
}
@@ -5,123 +5,107 @@ import utils.config.ShineSignatureConstants;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* HeaderBody — type=0, version=1.
*
* В новом формате type/subType/version живут в HEADER блока,
* поэтому bodyBytes для HeaderBody содержат только payload:
* HeaderBody — type=0, subType=0, version=1.
*
* bodyBytes (BigEndian):
* [TAG_LEN] tag ASCII "SHiNE"
* [1] loginLength=N (uint8)
* [N] login UTF-8
* [TAG_LEN] tag ASCII
* [1] loginLength (uint8)
* [N] login UTF-8
* [32] initialBlockchainKey32
*
* initialBlockchainKey32 is the public blockchain-signing key that created fork #1.
* It is historical identity metadata and MUST remain byte-for-byte unchanged when a
* preserved prefix (including block #0) is republished into later forks.
*/
public final class HeaderBody implements BodyRecord {
public static final short TYPE = 0;
public static final short VER = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
/** Для header subType всегда 0 (служебная совместимость). */
public static final short SUBTYPE_COMPAT = 0;
/** TAG формата (ASCII). */
public static final String TAG = ShineSignatureConstants.BLOCKCHAIN_HEADER_TAG;
private static final byte[] TAG_ASCII = TAG.getBytes(StandardCharsets.US_ASCII);
private static final int TAG_LEN = TAG_ASCII.length;
public final short subType; // всегда 0 (из заголовка блока)
public final short version; // из заголовка блока
public final String tag; // "SHiNE"
public final short subType;
public final short version;
public final String tag;
public final String login;
public final byte[] initialBlockchainKey32;
/** Десериализация из payload bodyBytes (без type/subType/version). */
public HeaderBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.subType & 0xFFFF) != (SUBTYPE_COMPAT & 0xFFFF)) {
throw new IllegalArgumentException("HeaderBody subType must be 0, got=" + (this.subType & 0xFFFF));
}
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("HeaderBody version must be 1, got=" + (this.version & 0xFFFF));
}
// минимум: tag[TAG_LEN] + loginLen[1]
if (bodyBytes.length < TAG_LEN + 1) throw new IllegalArgumentException("HeaderBody too short");
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("HeaderBody version must be 1");
if (bodyBytes.length < TAG_LEN + 1 + 1 + 32) throw new IllegalArgumentException("HeaderBody too short");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
byte[] tagBytes = new byte[TAG_LEN];
bb.get(tagBytes);
String t = new String(tagBytes, StandardCharsets.US_ASCII);
if (!TAG.equals(t)) throw new IllegalArgumentException("Bad tag: " + t);
this.tag = t;
String parsedTag = new String(tagBytes, StandardCharsets.US_ASCII);
if (!TAG.equals(parsedTag)) throw new IllegalArgumentException("Bad tag: " + parsedTag);
this.tag = parsedTag;
int loginLen = Byte.toUnsignedInt(bb.get());
if (loginLen <= 0 || bb.remaining() < loginLen)
throw new IllegalArgumentException("Bad login length");
if (loginLen <= 0 || bb.remaining() != loginLen + 32) throw new IllegalArgumentException("Bad HeaderBody login/key length");
byte[] loginBytes = new byte[loginLen];
bb.get(loginBytes);
this.login = new String(loginBytes, StandardCharsets.UTF_8);
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
this.login = BodyTargetSupport.decodeStrictUtf8(loginBytes, "HeaderBody login");
this.initialBlockchainKey32 = new byte[32];
bb.get(this.initialBlockchainKey32);
requireNonZeroKey(this.initialBlockchainKey32);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected HeaderBody tail");
}
/** Создание “вручную”. */
public HeaderBody(String login) {
public HeaderBody(String login, byte[] initialBlockchainKey32) {
Objects.requireNonNull(login, "login == null");
Objects.requireNonNull(initialBlockchainKey32, "initialBlockchainKey32 == null");
this.subType = SUBTYPE_COMPAT;
this.version = VER;
this.tag = TAG;
this.login = login;
this.initialBlockchainKey32 = Arrays.copyOf(initialBlockchainKey32, initialBlockchainKey32.length);
check();
}
@Override
public HeaderBody check() {
if ((subType & 0xFFFF) != (SUBTYPE_COMPAT & 0xFFFF))
throw new IllegalArgumentException("HeaderBody subType must be 0");
if (login == null || login.isBlank())
throw new IllegalArgumentException("Login is blank");
if (!login.matches("^[A-Za-z0-9_]+$"))
throw new IllegalArgumentException("Login must match ^[A-Za-z0-9_]+$");
if ((subType & 0xFFFF) != 0) throw new IllegalArgumentException("HeaderBody subType must be 0");
if (login == null || login.isBlank()) throw new IllegalArgumentException("Login is blank");
if (!login.matches("^[A-Za-z0-9_]+$")) throw new IllegalArgumentException("Login must match ^[A-Za-z0-9_]+$");
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
if (loginUtf8.length == 0 || loginUtf8.length > 255) throw new IllegalArgumentException("Login utf8 len must be 1..255");
requireNonZeroKey(initialBlockchainKey32);
return this;
}
@Override
public byte[] toBytes() {
check();
byte[] loginUtf8 = login.getBytes(StandardCharsets.UTF_8);
if (loginUtf8.length == 0 || loginUtf8.length > 255)
throw new IllegalArgumentException("Login utf8 len must be 1..255");
int cap = TAG_LEN + 1 + loginUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
ByteBuffer bb = ByteBuffer.allocate(TAG_LEN + 1 + loginUtf8.length + 32).order(ByteOrder.BIG_ENDIAN);
bb.put(TAG_ASCII);
bb.put((byte) loginUtf8.length);
bb.put(loginUtf8);
bb.put(initialBlockchainKey32);
return bb.array();
}
private static void requireNonZeroKey(byte[] key) {
if (key == null || key.length != 32) throw new IllegalArgumentException("initialBlockchainKey32 must be 32 bytes");
boolean any = false;
for (byte b : key) any |= b != 0;
if (!any) throw new IllegalArgumentException("initialBlockchainKey32 must not be zero");
}
@Override
public String toString() {
return """
HeaderBody {
тип записи : HEADER (type=0, ver=1) [в заголовке блока]
subType : 0 (compat)
тег формата : "%s"
login владельца : "%s"
}
""".formatted(tag, login);
return "HeaderBody{login='" + login + "', initialBlockchainKey32=<32 bytes>}";
}
}
}
@@ -4,130 +4,68 @@ import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* ReactionBody — type=2, version=1 (в заголовке блока).
*
* subType (в заголовке блока):
* 1 = LIKE
* 2 = UNLIKE
*
* bodyBytes (BigEndian), новый формат:
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber (int32)
* [32] toBlockHash32 (raw 32 bytes)
*
* ЛИНИИ НЕТ.
*/
/** REACTION LIKE/UNLIKE. External target = login + forkNumber + blockNumber + hash32. */
public final class ReactionBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 2;
public static final short VER = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // из header
public final String toBlockchainName;
public final short subType;
public final short version;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public ReactionBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("ReactionBody version must be 1, got=" + (this.version & 0xFFFF));
}
if (!isSupportedSubType(this.subType)) {
throw new IllegalArgumentException("Bad reaction subType: " + (this.subType & 0xFFFF));
}
// минимум: nameLen[1]+name[1]+global[4]+hash[32]
if (bodyBytes.length < 1 + 1 + 4 + 32) throw new IllegalArgumentException("ReactionBody too short");
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("ReactionBody version must be 1");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad reaction subType: " + (subType & 0xFFFF));
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("toBlockchainNameLen is 0");
if (bb.remaining() < nameLen + 4 + 32) throw new IllegalArgumentException("ReactionBody payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes, remaining=" + bb.remaining());
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "REACTION", 0);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected REACTION tail");
}
public ReactionBody(String toBlockchainName, int toBlockGlobalNumber, byte[] toBlockHash32) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
this.subType = MsgSubType.REACTION_LIKE;
public ReactionBody(short subType, String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32) {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad reaction subType");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REACTION");
this.subType = subType;
this.version = VER;
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = toBlockchainName;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
}
@Override
public ReactionBody check() {
if (!isSupportedSubType(subType))
throw new IllegalArgumentException("Bad reaction subType: " + (subType & 0xFFFF));
if (toBlockchainName == null || toBlockchainName.isBlank())
throw new IllegalArgumentException("toBlockchainName is blank");
if (toBlockGlobalNumber < 0)
throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("toBlockHash32 invalid");
@Override public ReactionBody check() {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad reaction subType");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REACTION");
return this;
}
@Override
public byte[] toBytes() {
byte[] nameBytes = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameBytes.length == 0 || nameBytes.length > 255)
throw new IllegalArgumentException("toBlockchainName utf8 len must be 1..255");
int cap = 1 + nameBytes.length + 4 + 32;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameBytes.length);
bb.put(nameBytes);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
@Override public byte[] toBytes() {
check();
ByteBuffer bb = ByteBuffer.allocate(BodyTargetSupport.externalSize(toLogin)).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REACTION");
return bb.array();
}
/* ====================== BodyHasTarget ====================== */
@Override public String toBchName() { return toBlockchainName; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static boolean isSupportedSubType(short subType) {
int st = subType & 0xFFFF;
return st == (MsgSubType.REACTION_LIKE & 0xFFFF)
|| st == (MsgSubType.REACTION_UNLIKE & 0xFFFF);
return st == (MsgSubType.REACTION_LIKE & 0xFFFF) || st == (MsgSubType.REACTION_UNLIKE & 0xFFFF);
}
}
@@ -10,157 +10,78 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* StatusActionBody — type=5, ver=1.
*
* Все STATUS_ACTION имеют target на конкретный блок и опциональный текст-пояснение.
*
* Формат bodyBytes (BigEndian):
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [M] text UTF-8
*/
/** STATUS_ACTION. External target = login + forkNumber + blockNumber + hash32. */
public final class StatusActionBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 5;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toBlockchainName;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public final String message;
public StatusActionBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("StatusActionBody version must be 1, got=" + (version & 0xFFFF));
}
if (!isSupportedSubType(subType)) {
throw new IllegalArgumentException("Unsupported STATUS_ACTION subType: " + (subType & 0xFFFF));
}
this.subType = subType; this.version = version;
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad STATUS_ACTION header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
ensureMin(bb, 1 + 1 + 4 + 32 + 2, "STATUS_ACTION too short");
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("STATUS_ACTION toBlockchainNameLen is 0");
ensureMin(bb, nameLen + 4 + 32 + 2, "STATUS_ACTION payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
this.message = readStrictUtf8Len16AllowEmpty(bb, "StatusActionBody text");
ensureNoTail(bb, "StatusActionBody");
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "STATUS_ACTION", 2);
this.toLogin = t.login(); this.toForkNumber = t.forkNumber(); this.toBlockGlobalNumber = t.blockNumber(); this.toBlockHash32 = t.blockHash32();
this.message = readText(bb);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected STATUS_ACTION tail");
}
public StatusActionBody(short subType, String toBlockchainName, int toBlockGlobalNumber, byte[] toBlockHash32, String message) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
public StatusActionBody(short subType, String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32, String message) {
Objects.requireNonNull(message, "message == null");
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Unsupported STATUS_ACTION subType");
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.subType = subType;
this.version = VER;
this.toBlockchainName = toBlockchainName;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
this.message = message;
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "STATUS_ACTION");
this.subType = subType; this.version = VER; this.toLogin = toLogin; this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber; this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32); this.message = message;
}
@Override
public StatusActionBody check() {
if (!isSupportedSubType(subType)) {
throw new IllegalArgumentException("Bad STATUS_ACTION subType: " + (subType & 0xFFFF));
}
if (toBlockchainName == null || toBlockchainName.isBlank()) {
throw new IllegalArgumentException("STATUS_ACTION toBlockchainName is blank");
}
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32 == null || toBlockHash32.length != 32) {
throw new IllegalArgumentException("toBlockHash32 invalid");
}
@Override public StatusActionBody check() {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad STATUS_ACTION subType");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "STATUS_ACTION");
if (message == null) throw new IllegalArgumentException("message is null");
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override
public byte[] toBytes() {
byte[] msgUtf8 = message.getBytes(StandardCharsets.UTF_8);
if (msgUtf8.length > 65535) throw new IllegalArgumentException("Text too long (>65535 bytes)");
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("STATUS_ACTION toBlockchainName utf8 len must be 1..255");
}
ByteBuffer bb = ByteBuffer.allocate(1 + nameUtf8.length + 4 + 32 + 2 + msgUtf8.length)
.order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(BodyTargetSupport.externalSize(toLogin) + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "STATUS_ACTION");
bb.putShort((short) text.length).put(text);
return bb.array();
}
@Override public String toBchName() { return toBlockchainName; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static boolean isSupportedSubType(short subType) {
int st = subType & 0xFFFF;
return st == (MsgSubType.STATUS_DONE_ONCE & 0xFFFF)
|| st == (MsgSubType.STATUS_LEARNED & 0xFFFF)
|| st == (MsgSubType.STATUS_SERVICE_PASSED & 0xFFFF)
|| st == (MsgSubType.STATUS_CONFIRMED & 0xFFFF)
|| st == (MsgSubType.STATUS_INTERESTED & 0xFFFF)
|| st == (MsgSubType.STATUS_STARTED & 0xFFFF)
|| st == (MsgSubType.STATUS_IN_STUDY & 0xFFFF)
|| st == (MsgSubType.STATUS_ABANDONED & 0xFFFF)
return st == (MsgSubType.STATUS_DONE_ONCE & 0xFFFF) || st == (MsgSubType.STATUS_LEARNED & 0xFFFF)
|| st == (MsgSubType.STATUS_SERVICE_PASSED & 0xFFFF) || st == (MsgSubType.STATUS_CONFIRMED & 0xFFFF)
|| st == (MsgSubType.STATUS_INTERESTED & 0xFFFF) || st == (MsgSubType.STATUS_STARTED & 0xFFFF)
|| st == (MsgSubType.STATUS_IN_STUDY & 0xFFFF) || st == (MsgSubType.STATUS_ABANDONED & 0xFFFF)
|| st == (MsgSubType.STATUS_COMPLETED & 0xFFFF);
}
private static String readStrictUtf8Len16AllowEmpty(ByteBuffer bb, String fieldName) {
private static String readText(ByteBuffer bb) {
if (bb.remaining() < 2) throw new IllegalArgumentException("STATUS_ACTION text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (bb.remaining() < len) throw new IllegalArgumentException("STATUS_ACTION text payload too short");
if (len == 0) return "";
if (bb.remaining() < len) throw new IllegalArgumentException(fieldName + " payload too short (len=" + len + ")");
byte[] bytes = new byte[len];
bb.get(bytes);
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
return decoder.decode(ByteBuffer.wrap(bytes)).toString();
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
private static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
private static void ensureNoTail(ByteBuffer bb, String ctx) {
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes for " + ctx + ", remaining=" + bb.remaining());
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { return dec.decode(ByteBuffer.wrap(bytes)).toString(); }
catch (CharacterCodingException e) { throw new IllegalArgumentException("STATUS_ACTION text invalid UTF-8", e); }
}
}
@@ -1,544 +0,0 @@
package blockchain.body;
import blockchain.MsgSubType;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* TextBody — type=1, ver=1 (в заголовке блока).
*
* subType (в заголовке блока):
* 10 = POST
* 11 = EDIT_POST
* 20 = REPLY
* 21 = EDIT_REPLY
*
* =========================================================================
* КОНЦЕПЦИЯ ЛИНИЙ ДЛЯ ТЕКСТОВЫХ СООБЩЕНИЙ:
*
* POST и EDIT_POST принадлежат ЛИНИИ КАНАЛА и имеют hasLine.
* В новом формате добавлен lineCode:
* lineCode = 0 для канала "0"
* lineCode = blockNumber "заглавия линии/канала" (например CREATE_CHANNEL)
*
* REPLY и EDIT_REPLY НЕ имеют линии (нет hasLine в байтах).
*
* =========================================================================
* ФОРМАТЫ bodyBytes (BigEndian):
*
* 1) POST (subType=10):
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
* [2] textLenBytes (uint16)
* [N] text UTF-8
*
* 2) EDIT_POST (subType=11):
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
*
* hasTarget (на ОРИГИНАЛЬНЫЙ POST, toBchName НЕ хранить):
* [4] toBlockGlobalNumber
* [32] toBlockHash32
*
* [2] textLenBytes (uint16)
* [N] text UTF-8
*
* 3) REPLY (subType=20) — НЕ в линии:
* hasTarget:
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber
* [32] toBlockHash32
*
* [2] textLenBytes (uint16)
* [M] text UTF-8
*
* 4) EDIT_REPLY (subType=21) — НЕ в линии:
* hasTarget (на ОРИГИНАЛЬНЫЙ REPLY, toBchName НЕ хранить):
* [4] toBlockGlobalNumber
* [32] toBlockHash32
*
* [2] textLenBytes (uint16)
* [N] text UTF-8
*/
public final class TextBody implements BodyRecord, BodyHasTarget, BodyHasLine {
public static final short TYPE = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // из header
// ===== line fields (только для POST/EDIT_POST) =====
// Для REPLY/EDIT_REPLY эти поля НЕ сериализуются; значения держим как "пустые".
public final int lineCode; // только для line-message; иначе -1
public final int prevLineNumber;
public final byte[] prevLineHash32; // 32 or null
public final int thisLineNumber;
// ===== message text =====
public final String message;
// ===== target fields =====
// REPLY: toBlockchainName + globalNumber + hash32
// EDIT_POST / EDIT_REPLY: только globalNumber + hash32 (без toBlockchainName)
public final String toBlockchainName; // nullable
public final Integer toBlockGlobalNumber; // nullable
public final byte[] toBlockHash32; // nullable (но если target есть -> 32)
/* ===================================================================== */
/* ====================== Конструктор из байт ========================== */
/* ===================================================================== */
public TextBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("TextBody version must be 1, got=" + (this.version & 0xFFFF));
}
if (!isValidSubType(this.subType)) {
throw new IllegalArgumentException("Bad Text subType: " + (this.subType & 0xFFFF));
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
int st = this.subType & 0xFFFF;
if (st == (MsgSubType.TEXT_POST & 0xFFFF)) {
// POST: hasLine(lineCode+line) + text
ensureMin(bb, (4 + 4 + 32 + 4) + 2, "POST too short");
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
this.message = readStrictUtf8Len16(bb, "POST text");
this.toBlockchainName = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
ensureNoTail(bb, "POST");
} else if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
// EDIT_POST: hasLine(lineCode+line) + target(no bch) + text
ensureMin(bb, (4 + 4 + 32 + 4) + (4 + 32) + 2, "EDIT_POST too short");
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
int tgtNum = bb.getInt();
byte[] tgtHash = new byte[32];
bb.get(tgtHash);
this.toBlockchainName = null;
this.toBlockGlobalNumber = tgtNum;
this.toBlockHash32 = tgtHash;
this.message = readStrictUtf8Len16(bb, "EDIT_POST text");
ensureNoTail(bb, "EDIT_POST");
} else if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
// REPLY: target(with bch) + text (без line)
ensureMin(bb, 1 + 1 + 4 + 32 + 2, "REPLY too short");
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("REPLY toBlockchainNameLen is 0");
ensureMin(bb, nameLen + 4 + 32 + 2, "REPLY payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
this.message = readStrictUtf8Len16(bb, "REPLY text");
// line fields отсутствуют в байтах
this.lineCode = -1;
this.prevLineNumber = -1;
this.prevLineHash32 = null;
this.thisLineNumber = -1;
ensureNoTail(bb, "REPLY");
} else if (st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
// EDIT_REPLY: target(no bch) + text (без line)
ensureMin(bb, (4 + 32) + 2, "EDIT_REPLY too short");
int tgtNum = bb.getInt();
byte[] tgtHash = new byte[32];
bb.get(tgtHash);
this.toBlockchainName = null;
this.toBlockGlobalNumber = tgtNum;
this.toBlockHash32 = tgtHash;
this.message = readStrictUtf8Len16(bb, "EDIT_REPLY text");
// line fields отсутствуют в байтах
this.lineCode = -1;
this.prevLineNumber = -1;
this.prevLineHash32 = null;
this.thisLineNumber = -1;
ensureNoTail(bb, "EDIT_REPLY");
} else {
throw new IllegalArgumentException("Unsupported Text subType: " + st);
}
}
/* ===================================================================== */
/* ====================== Фабрики (удобно) ============================= */
/* ===================================================================== */
public static TextBody newPost(int lineCode, int prevLineNumber, byte[] prevLineHash32, int thisLineNumber, String message) {
return new TextBody(MsgSubType.TEXT_POST, lineCode, prevLineNumber, prevLineHash32, thisLineNumber,
message, null, null, null);
}
public static TextBody newEditPost(int lineCode, int prevLineNumber, byte[] prevLineHash32, int thisLineNumber,
int targetBlockNumber, byte[] targetHash32,
String message) {
return new TextBody(MsgSubType.TEXT_EDIT_POST, lineCode, prevLineNumber, prevLineHash32, thisLineNumber,
message, null, targetBlockNumber, targetHash32);
}
public static TextBody newReply(String toBlockchainName, int targetBlockNumber, byte[] targetHash32, String message) {
return new TextBody(MsgSubType.TEXT_REPLY, -1, -1, null, -1,
message, toBlockchainName, targetBlockNumber, targetHash32);
}
public static TextBody newEditReply(int targetBlockNumber, byte[] targetHash32, String message) {
return new TextBody(MsgSubType.TEXT_EDIT_REPLY, -1, -1, null, -1,
message, null, targetBlockNumber, targetHash32);
}
/**
* Универсальный конструктор “вручную”.
* Для REPLY/EDIT_REPLY line поля игнорируются при сериализации (их в формате нет).
*/
public TextBody(short subType,
int lineCode,
int prevLineNumber,
byte[] prevLineHash32,
int thisLineNumber,
String message,
String toBlockchainName,
Integer toBlockGlobalNumber,
byte[] toBlockHash32) {
Objects.requireNonNull(message, "message == null");
if (!isValidSubType(subType)) throw new IllegalArgumentException("Bad Text subType: " + (subType & 0xFFFF));
if (message.isBlank()) throw new IllegalArgumentException("message is blank");
this.subType = subType;
this.version = VER;
int st = subType & 0xFFFF;
// line применима только к POST/EDIT_POST
if (st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0 for line message");
this.lineCode = lineCode;
this.prevLineNumber = prevLineNumber;
this.prevLineHash32 = (prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
this.thisLineNumber = thisLineNumber;
} else {
this.lineCode = -1;
this.prevLineNumber = -1;
this.prevLineHash32 = null;
this.thisLineNumber = -1;
}
this.message = message;
// target правила
if (st == (MsgSubType.TEXT_POST & 0xFFFF)) {
this.toBlockchainName = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
} else if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
Objects.requireNonNull(toBlockGlobalNumber, "toBlockGlobalNumber == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = null; // по ТЗ: не хранить
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
} else if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
Objects.requireNonNull(toBlockGlobalNumber, "toBlockGlobalNumber == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = toBlockchainName;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
} else if (st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
Objects.requireNonNull(toBlockGlobalNumber, "toBlockGlobalNumber == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = null; // по ТЗ: не хранить
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
} else {
this.toBlockchainName = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
}
}
private static boolean isValidSubType(short st) {
int v = st & 0xFFFF;
return v == (MsgSubType.TEXT_POST & 0xFFFF)
|| v == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| v == (MsgSubType.TEXT_REPLY & 0xFFFF)
|| v == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF);
}
@Override
public TextBody check() {
if (!isValidSubType(subType))
throw new IllegalArgumentException("Bad Text subType: " + (subType & 0xFFFF));
if (message == null || message.isBlank())
throw new IllegalArgumentException("Text message is blank");
int st = subType & 0xFFFF;
// локальные проверки line (БД не трогаем)
if (st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0 for line message");
if (prevLineHash32 == null || prevLineHash32.length != 32)
throw new IllegalArgumentException("prevLineHash32 invalid");
} else {
// reply/edit_reply: line отсутствует
if (prevLineHash32 != null)
throw new IllegalArgumentException("REPLY/EDIT_REPLY must not contain line hash");
}
// target rules
if (st == (MsgSubType.TEXT_POST & 0xFFFF)) {
if (toBlockchainName != null || toBlockGlobalNumber != null || toBlockHash32 != null)
throw new IllegalArgumentException("POST must not contain target fields");
} else if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (toBlockchainName != null)
throw new IllegalArgumentException("EDIT_POST must not contain toBlockchainName in target");
if (toBlockGlobalNumber == null || toBlockGlobalNumber < 0)
throw new IllegalArgumentException("EDIT_POST toBlockGlobalNumber invalid");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("EDIT_POST toBlockHash32 invalid");
} else if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
if (toBlockchainName == null || toBlockchainName.isBlank())
throw new IllegalArgumentException("REPLY toBlockchainName is blank");
if (toBlockGlobalNumber == null || toBlockGlobalNumber < 0)
throw new IllegalArgumentException("REPLY toBlockGlobalNumber invalid");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("REPLY toBlockHash32 invalid");
} else if (st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
if (toBlockchainName != null)
throw new IllegalArgumentException("EDIT_REPLY must not contain toBlockchainName in target");
if (toBlockGlobalNumber == null || toBlockGlobalNumber < 0)
throw new IllegalArgumentException("EDIT_REPLY toBlockGlobalNumber invalid");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("EDIT_REPLY toBlockHash32 invalid");
}
return this;
}
@Override
public byte[] toBytes() {
byte[] msgUtf8 = message.getBytes(StandardCharsets.UTF_8);
if (msgUtf8.length == 0) throw new IllegalArgumentException("Text payload is empty");
if (msgUtf8.length > 65535) throw new IllegalArgumentException("Text too long (>65535 bytes)");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_POST & 0xFFFF)) {
// hasLine(lineCode+line) + text
int cap = (4 + 4 + 32 + 4) + 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
return bb.array();
} else if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
// hasLine(lineCode+line) + target(no bch) + text
if (toBlockGlobalNumber == null) throw new IllegalArgumentException("EDIT_POST missing toBlockGlobalNumber");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("EDIT_POST toBlockHash32 != 32");
int cap = (4 + 4 + 32 + 4) + (4 + 32) + 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
return bb.array();
} else if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
// target(with bch) + text
if (toBlockchainName == null) throw new IllegalArgumentException("REPLY missing toBlockchainName");
if (toBlockGlobalNumber == null) throw new IllegalArgumentException("REPLY missing toBlockGlobalNumber");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("REPLY toBlockHash32 != 32");
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255)
throw new IllegalArgumentException("REPLY toBlockchainName utf8 len must be 1..255");
int cap = 1 + nameUtf8.length + 4 + 32
+ 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
return bb.array();
} else if (st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
// target(no bch) + text
if (toBlockGlobalNumber == null) throw new IllegalArgumentException("EDIT_REPLY missing toBlockGlobalNumber");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("EDIT_REPLY toBlockHash32 != 32");
int cap = (4 + 32) + 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
return bb.array();
} else {
throw new IllegalStateException("Unsupported Text subType: " + st);
}
}
/* ===================================================================== */
/* ========================== Helpers ================================== */
/* ===================================================================== */
private static String readStrictUtf8Len16(ByteBuffer bb, String fieldName) {
int len = Short.toUnsignedInt(bb.getShort());
if (len <= 0) throw new IllegalArgumentException(fieldName + " is empty");
if (bb.remaining() < len) throw new IllegalArgumentException(fieldName + " payload too short (len=" + len + ")");
byte[] bytes = new byte[len];
bb.get(bytes);
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
String s = decoder.decode(ByteBuffer.wrap(bytes)).toString();
if (s.isBlank()) throw new IllegalArgumentException(fieldName + " is blank");
return s;
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
private static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
private static void ensureNoTail(ByteBuffer bb, String ctx) {
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes for " + ctx + ", remaining=" + bb.remaining());
}
/* ====================== BodyHasLine ====================== */
@Override public int lineCode() { return lineCode; }
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
@Override public byte[] prevLineBlockHash32() {
if (prevLineHash32 == null) return null;
return Arrays.copyOf(prevLineHash32, 32);
}
@Override public int lineSeq() { return thisLineNumber; }
/* ====================== BodyHasTarget ===================== */
@Override public String toBchName() { return toBlockchainName; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
/* ===================================================================== */
/* ===================== Удобные хелперы (для ChainState) =============== */
/* ===================================================================== */
/** true только для POST / EDIT_POST (т.е. это сообщение в линии канала). */
public boolean isLineMessage() {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF);
}
/** true только для EDIT_POST / EDIT_REPLY. */
public boolean isEditMessage() {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF);
}
/** true только для REPLY / EDIT_REPLY (т.е. “не в линии”). */
public boolean isReplyFamily() {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_REPLY & 0xFFFF)
|| st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF);
}
}
@@ -11,374 +11,177 @@ import java.util.Arrays;
import java.util.Objects;
/**
* TextLineBody — type=1, ver=1.
*
* subType:
* - POST (10)
* - EDIT_POST (11)
* - REPOST (50)
* - CHANNEL_META (90)
* - ENTRYPOINT (100)
* - EXERCISE (110)
* - SERVICE (120)
* - COURSE (130)
*
* Формат bodyBytes (BigEndian):
* Line-based TEXT body.
*
* POST / CHANNEL_META / ENTRYPOINT / EXERCISE / SERVICE / COURSE:
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
* [2] textLenBytes (uint16)
* [N] text UTF-8
* line fields + text
*
* EDIT_POST:
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
* [4] toBlockGlobalNumber (int32)
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [N] text UTF-8
* EDIT_POST (own-chain compact target):
* line fields + [4] targetBlockNumber + [32] targetHash + text
*
* REPOST:
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber (int32)
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [N] text UTF-8
* REPOST (external target):
* line fields + [1]loginLen + login + [2]forkNumber + [4]blockNumber + [32]hash + text
*/
public final class TextLineBody implements BodyRecord, BodyHasLine, BodyHasTarget {
public static final short TYPE = 1;
public static final short VER = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // из header (=1)
// line
public final short subType;
public final short version;
public final int lineCode;
public final int prevLineNumber;
public final byte[] prevLineHash32; // 32 (может быть нули)
public final byte[] prevLineHash32;
public final int thisLineNumber;
// target (для EDIT_POST / REPOST)
public final String toBlockchainName; // nullable для POST/EDIT_POST
public final Integer toBlockGlobalNumber; // nullable для POST
public final byte[] toBlockHash32; // nullable для POST
// text
public final String toLogin;
public final Integer toForkNumber;
public final Integer toBlockGlobalNumber;
public final byte[] toBlockHash32;
public final String message;
/* ====================== parse from bytes ====================== */
public TextLineBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("TextLineBody version must be 1, got=" + (this.version & 0xFFFF));
}
int st = this.subType & 0xFFFF;
if (st != (MsgSubType.TEXT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_REPOST & 0xFFFF)
&& st != (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
&& st != (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
&& st != (MsgSubType.TEXT_EXERCISE & 0xFFFF)
&& st != (MsgSubType.TEXT_SERVICE & 0xFFFF)
&& st != (MsgSubType.TEXT_COURSE & 0xFFFF)) {
throw new IllegalArgumentException("TextLineBody supports only POST/EDIT_POST/REPOST/CHANNEL_META, got subType=" + st);
}
if ((version & 0xFFFF) != 1 || !isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody header");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
// минимум line + textLen(2)
ensureMin(bb, (4 + 4 + 32 + 4) + 2, "TextLineBody too short");
BodyTargetSupport.ensureMin(bb, 4 + 4 + 32 + 4 + 2, "TextLineBody too short");
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.prevLineHash32 = new byte[32]; bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
// нужен target
ensureMin(bb, (4 + 32) + 2, "EDIT_POST missing target");
int tgtNum = bb.getInt();
byte[] tgtHash = new byte[32];
bb.get(tgtHash);
this.toBlockchainName = null;
this.toBlockGlobalNumber = tgtNum;
this.toBlockHash32 = tgtHash;
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
ensureMin(bb, 1 + 1 + 4 + 32 + 2, "REPOST missing target");
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("REPOST toBlockchainNameLen is 0");
ensureMin(bb, nameLen + 4 + 32 + 2, "REPOST payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
BodyTargetSupport.ensureMin(bb, 4 + 32 + 2, "EDIT_POST target missing");
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
this.toBlockHash32 = new byte[32]; bb.get(this.toBlockHash32);
BodyTargetSupport.validateCompact(this.toBlockGlobalNumber, this.toBlockHash32, "EDIT_POST");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "REPOST", 2);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
} else {
this.toBlockchainName = null;
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
}
this.message = readStrictUtf8Len16(bb, "TextLineBody text",
st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF));
ensureNoTail(bb, "TextLineBody");
boolean allowEmpty = st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
this.message = readText(bb, allowEmpty);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextLineBody tail");
}
/* ====================== manual ctor ====================== */
public TextLineBody(int lineCode,
int prevLineNumber,
byte[] prevLineHash32,
int thisLineNumber,
short subType,
String toLogin,
Integer toForkNumber,
Integer toBlockGlobalNumber,
byte[] toBlockHash32,
String toBlockchainName,
String message) {
Objects.requireNonNull(message, "message == null");
int st = subType & 0xFFFF;
if (st != (MsgSubType.TEXT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_REPOST & 0xFFFF)
&& st != (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
&& st != (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
&& st != (MsgSubType.TEXT_EXERCISE & 0xFFFF)
&& st != (MsgSubType.TEXT_SERVICE & 0xFFFF)
&& st != (MsgSubType.TEXT_COURSE & 0xFFFF)) {
throw new IllegalArgumentException("TextLineBody supports only POST/EDIT_POST/REPOST/CHANNEL_META");
}
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
if (requiresNonBlankMessage(st) && message.isBlank()) {
throw new IllegalArgumentException("message is blank");
}
this.subType = subType;
this.version = VER;
this.lineCode = lineCode;
this.prevLineNumber = prevLineNumber;
this.prevLineHash32 = (prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
this.prevLineHash32 = prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32);
this.thisLineNumber = thisLineNumber;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
Objects.requireNonNull(toBlockGlobalNumber, "toBlockGlobalNumber == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = null;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
Objects.requireNonNull(toBlockGlobalNumber, "toBlockGlobalNumber == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
this.toBlockchainName = toBlockchainName;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
} else {
this.toBlockchainName = null;
this.toBlockGlobalNumber = null;
this.toBlockHash32 = null;
}
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = toBlockHash32 == null ? null : Arrays.copyOf(toBlockHash32, 32);
this.message = message;
check();
}
@Override
public TextLineBody check() {
int st = subType & 0xFFFF;
if (st != (MsgSubType.TEXT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
&& st != (MsgSubType.TEXT_REPOST & 0xFFFF)
&& st != (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
&& st != (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
&& st != (MsgSubType.TEXT_EXERCISE & 0xFFFF)
&& st != (MsgSubType.TEXT_SERVICE & 0xFFFF)
&& st != (MsgSubType.TEXT_COURSE & 0xFFFF))
throw new IllegalArgumentException("Bad TextLineBody subType: " + st);
@Override public TextLineBody check() {
if (!isSupportedSubType(subType)) throw new IllegalArgumentException("Bad TextLineBody subtype");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
if (prevLineHash32 == null || prevLineHash32.length != 32)
throw new IllegalArgumentException("prevLineHash32 invalid");
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
if (toLogin != null || toForkNumber != null) throw new IllegalArgumentException("EDIT_POST must not contain login/fork target");
BodyTargetSupport.validateCompact(toBlockGlobalNumber, toBlockHash32, "EDIT_POST");
if (message == null) throw new IllegalArgumentException("EDIT_POST message is null");
if (toBlockGlobalNumber == null || toBlockGlobalNumber < 0)
throw new IllegalArgumentException("EDIT_POST toBlockGlobalNumber invalid");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("EDIT_POST toBlockHash32 invalid");
if (toBlockchainName != null)
throw new IllegalArgumentException("EDIT_POST must not contain toBlockchainName");
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
if (message == null || message.isBlank())
throw new IllegalArgumentException("REPOST message is blank");
if (toBlockchainName == null || toBlockchainName.isBlank())
throw new IllegalArgumentException("REPOST toBlockchainName is blank");
if (toBlockGlobalNumber == null || toBlockGlobalNumber < 0)
throw new IllegalArgumentException("REPOST toBlockGlobalNumber invalid");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("REPOST toBlockHash32 invalid");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
if (message == null || message.isBlank()) throw new IllegalArgumentException("REPOST message is blank");
} else {
if (toLogin != null || toForkNumber != null || toBlockGlobalNumber != null || toBlockHash32 != null) {
throw new IllegalArgumentException("Non-target text body must not contain target fields");
}
if (st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)) {
if (message == null) throw new IllegalArgumentException("CHANNEL_META message is null");
} else if (requiresNonBlankMessage(st) && (message == null || message.isBlank())) {
} else if (st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
if (message == null || !message.isEmpty()) throw new IllegalArgumentException("CHANNEL_DELETE message must be empty");
} else if (message == null || message.isBlank()) {
throw new IllegalArgumentException("Text message is blank");
} else if (message == null) {
throw new IllegalArgumentException("Text message is null");
}
if (toBlockchainName != null || toBlockGlobalNumber != null || toBlockHash32 != null)
throw new IllegalArgumentException("POST/CHANNEL_META must not contain target fields");
}
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override
public byte[] toBytes() {
byte[] msgUtf8 = message.getBytes(StandardCharsets.UTF_8);
if (msgUtf8.length > 65535) throw new IllegalArgumentException("Text too long (>65535 bytes)");
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
int st = subType & 0xFFFF;
if (requiresNonBlankMessage(st) && msgUtf8.length == 0) {
throw new IllegalArgumentException("Text payload is empty");
}
int cap;
if (st == (MsgSubType.TEXT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
|| st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF)
|| st == (MsgSubType.TEXT_COURSE & 0xFFFF)) {
cap = (4 + 4 + 32 + 4) + 2 + msgUtf8.length;
} else if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
// EDIT_POST
if (toBlockGlobalNumber == null) throw new IllegalArgumentException("EDIT_POST missing toBlockGlobalNumber");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("EDIT_POST toBlockHash32 != 32");
cap = (4 + 4 + 32 + 4) + (4 + 32) + 2 + msgUtf8.length;
} else {
if (toBlockchainName == null) throw new IllegalArgumentException("REPOST missing toBlockchainName");
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("REPOST toBlockchainName utf8 len must be 1..255");
}
if (toBlockGlobalNumber == null) throw new IllegalArgumentException("REPOST missing toBlockGlobalNumber");
if (toBlockHash32 == null || toBlockHash32.length != 32) throw new IllegalArgumentException("REPOST toBlockHash32 != 32");
cap = (4 + 4 + 32 + 4) + (1 + nameUtf8.length + 4 + 32) + 2 + msgUtf8.length;
}
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
int targetSize = 0;
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) targetSize = 4 + 32;
else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) targetSize = BodyTargetSupport.externalSize(toLogin);
ByteBuffer bb = ByteBuffer.allocate(4 + 4 + 32 + 4 + targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode).putInt(prevLineNumber).put(prevLineHash32).putInt(thisLineNumber);
if (st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)) {
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
} else if (st == (MsgSubType.TEXT_REPOST & 0xFFFF)) {
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPOST");
}
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
bb.putShort((short) text.length).put(text);
return bb.array();
}
/* ====================== BodyHasLine ====================== */
@Override public int lineCode() { return lineCode; }
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevLineHash32, 32); }
@Override public int lineSeq() { return thisLineNumber; }
/* ====================== BodyHasTarget ===================== */
@Override public String toBchName() { return toBlockchainName; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32 == null ? null : Arrays.copyOf(toBlockHash32, 32); }
public boolean isEditPost() { return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_POST & 0xFFFF); }
/* ====================== helpers ====================== */
public boolean isEditPost() {
return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_POST & 0xFFFF);
private static boolean isSupportedSubType(short subType) {
int st = subType & 0xFFFF;
return st == (MsgSubType.TEXT_POST & 0xFFFF) || st == (MsgSubType.TEXT_EDIT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF) || st == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
|| st == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF) || st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF) || st == (MsgSubType.TEXT_COURSE & 0xFFFF);
}
private static boolean requiresNonBlankMessage(int st) {
return st == (MsgSubType.TEXT_POST & 0xFFFF)
|| st == (MsgSubType.TEXT_REPOST & 0xFFFF)
|| st == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)
|| st == (MsgSubType.TEXT_EXERCISE & 0xFFFF)
|| st == (MsgSubType.TEXT_SERVICE & 0xFFFF)
|| st == (MsgSubType.TEXT_COURSE & 0xFFFF);
}
private static String readStrictUtf8Len16(ByteBuffer bb, String fieldName, boolean allowEmpty) {
private static String readText(ByteBuffer bb, boolean allowEmpty) {
if (bb.remaining() < 2) throw new IllegalArgumentException("Text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (len == 0) {
if (allowEmpty) return "";
throw new IllegalArgumentException(fieldName + " is empty");
}
if (bb.remaining() < len) throw new IllegalArgumentException(fieldName + " payload too short (len=" + len + ")");
byte[] bytes = new byte[len];
bb.get(bytes);
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
String s = decoder.decode(ByteBuffer.wrap(bytes)).toString();
if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException(fieldName + " is blank");
return s;
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
private static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
private static void ensureNoTail(ByteBuffer bb, String ctx) {
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes for " + ctx + ", remaining=" + bb.remaining());
if (len == 0) { if (allowEmpty) return ""; throw new IllegalArgumentException("Text is empty"); }
if (bb.remaining() < len) throw new IllegalArgumentException("Text payload too short");
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { String s = dec.decode(ByteBuffer.wrap(bytes)).toString(); if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException("Text blank"); return s; }
catch (CharacterCodingException e) { throw new IllegalArgumentException("Text invalid UTF-8", e); }
}
}
@@ -10,29 +10,16 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
/**
* TextRatingBody — type=1, ver=1.
*
* subType:
* - RATING (30)
*
* Формат bodyBytes (BigEndian):
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [M] text UTF-8
*/
/** TEXT_RATING. External target = login + forkNumber + blockNumber + hash32. */
public final class TextRatingBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType;
public final short version;
public final String toBlockchainName;
public final String toLogin;
public final int toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32;
public final String message;
@@ -41,117 +28,60 @@ public final class TextRatingBody implements BodyRecord, BodyHasTarget {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("TextRatingBody version must be 1, got=" + (version & 0xFFFF));
}
if ((subType & 0xFFFF) != (MsgSubType.TEXT_RATING & 0xFFFF)) {
throw new IllegalArgumentException("TextRatingBody supports only TEXT_RATING");
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("TextRatingBody version must be 1");
if ((subType & 0xFFFF) != (MsgSubType.TEXT_RATING & 0xFFFF)) throw new IllegalArgumentException("TextRatingBody supports only TEXT_RATING");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
ensureMin(bb, 1 + 1 + 4 + 32 + 2, "RATING too short");
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("RATING toBlockchainNameLen is 0");
ensureMin(bb, nameLen + 4 + 32 + 2, "RATING payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
this.message = readStrictUtf8Len16(bb, "TextRatingBody text");
ensureNoTail(bb, "TextRatingBody");
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "RATING", 2);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
this.message = readText(bb);
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected RATING tail");
}
public TextRatingBody(String toBlockchainName, int toBlockGlobalNumber, byte[] toBlockHash32, String message) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
public TextRatingBody(String toLogin, int toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32, String message) {
Objects.requireNonNull(message, "message == null");
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
if (message.isBlank()) throw new IllegalArgumentException("message is blank");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "RATING");
this.subType = MsgSubType.TEXT_RATING;
this.version = VER;
this.toBlockchainName = toBlockchainName;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
this.message = message;
}
@Override
public TextRatingBody check() {
if ((subType & 0xFFFF) != (MsgSubType.TEXT_RATING & 0xFFFF)) {
throw new IllegalArgumentException("Bad TextRatingBody subType: " + (subType & 0xFFFF));
}
if (toBlockchainName == null || toBlockchainName.isBlank()) {
throw new IllegalArgumentException("RATING toBlockchainName is blank");
}
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32 == null || toBlockHash32.length != 32) {
throw new IllegalArgumentException("toBlockHash32 invalid");
}
@Override public TextRatingBody check() {
if ((subType & 0xFFFF) != (MsgSubType.TEXT_RATING & 0xFFFF)) throw new IllegalArgumentException("Bad RATING subType");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "RATING");
if (message == null || message.isBlank()) throw new IllegalArgumentException("message is blank");
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override
public byte[] toBytes() {
byte[] msgUtf8 = message.getBytes(StandardCharsets.UTF_8);
if (msgUtf8.length == 0) throw new IllegalArgumentException("Text payload is empty");
if (msgUtf8.length > 65535) throw new IllegalArgumentException("Text too long (>65535 bytes)");
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255) {
throw new IllegalArgumentException("RATING toBlockchainName utf8 len must be 1..255");
}
ByteBuffer bb = ByteBuffer.allocate(1 + nameUtf8.length + 4 + 32 + 2 + msgUtf8.length)
.order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
ByteBuffer bb = ByteBuffer.allocate(BodyTargetSupport.externalSize(toLogin) + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "RATING");
bb.putShort((short) text.length).put(text);
return bb.array();
}
@Override public String toBchName() { return toBlockchainName; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
private static String readStrictUtf8Len16(ByteBuffer bb, String fieldName) {
private static String readText(ByteBuffer bb) {
if (bb.remaining() < 2) throw new IllegalArgumentException("RATING text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (len == 0) throw new IllegalArgumentException(fieldName + " is empty");
if (bb.remaining() < len) throw new IllegalArgumentException(fieldName + " payload too short (len=" + len + ")");
byte[] bytes = new byte[len];
bb.get(bytes);
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
String s = decoder.decode(ByteBuffer.wrap(bytes)).toString();
if (s.isBlank()) throw new IllegalArgumentException(fieldName + " is blank");
return s;
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
private static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
private static void ensureNoTail(ByteBuffer bb, String ctx) {
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes for " + ctx + ", remaining=" + bb.remaining());
if (len <= 0 || bb.remaining() < len) throw new IllegalArgumentException("RATING text invalid");
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { String s = dec.decode(ByteBuffer.wrap(bytes)).toString(); if (s.isBlank()) throw new IllegalArgumentException("RATING text blank"); return s; }
catch (CharacterCodingException e) { throw new IllegalArgumentException("RATING text invalid UTF-8", e); }
}
}
@@ -11,241 +11,111 @@ import java.util.Arrays;
import java.util.Objects;
/**
* TextReplyBody — type=1, ver=1.
*
* subType:
* - REPLY (20)
* - EDIT_REPLY (21)
*
* Форматы bodyBytes (BigEndian):
*
* REPLY:
* [1] toBlockchainNameLen (uint8)
* [N] toBlockchainName UTF-8
* [4] toBlockGlobalNumber
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [M] text UTF-8
*
* EDIT_REPLY:
* [4] toBlockGlobalNumber
* [32] toBlockHash32
* [2] textLenBytes (uint16)
* [N] text UTF-8
* TEXT_REPLY / TEXT_EDIT_REPLY.
* REPLY external target: login + forkNumber + blockNumber + hash32.
* EDIT_REPLY compact own-chain target: blockNumber + hash32.
*/
public final class TextReplyBody implements BodyRecord, BodyHasTarget {
public static final short TYPE = 1;
public static final short VER = 1;
public static final short VER = 1;
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // (=1)
// target
public final String toBlockchainName; // nullable для EDIT_REPLY
public final short subType;
public final short version;
public final String toLogin;
public final Integer toForkNumber;
public final int toBlockGlobalNumber;
public final byte[] toBlockHash32; // 32
// text
public final byte[] toBlockHash32;
public final String message;
public TextReplyBody(short subType, short version, byte[] bodyBytes) {
Objects.requireNonNull(bodyBytes, "bodyBytes == null");
this.subType = subType;
this.version = version;
if ((this.version & 0xFFFF) != (VER & 0xFFFF)) {
throw new IllegalArgumentException("TextReplyBody version must be 1, got=" + (this.version & 0xFFFF));
}
int st = this.subType & 0xFFFF;
if (st != (MsgSubType.TEXT_REPLY & 0xFFFF) && st != (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
throw new IllegalArgumentException("TextReplyBody supports only REPLY/EDIT_REPLY, got subType=" + st);
}
if ((version & 0xFFFF) != (VER & 0xFFFF)) throw new IllegalArgumentException("TextReplyBody version must be 1");
int st = subType & 0xFFFF;
if (st != (MsgSubType.TEXT_REPLY & 0xFFFF) && st != (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) throw new IllegalArgumentException("Bad reply subtype");
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
// минимум: nameLen[1]+name[1]+global[4]+hash[32]+textLen[2]
ensureMin(bb, 1 + 1 + 4 + 32 + 2, "REPLY too short");
int nameLen = Byte.toUnsignedInt(bb.get());
if (nameLen <= 0) throw new IllegalArgumentException("REPLY toBlockchainNameLen is 0");
ensureMin(bb, nameLen + 4 + 32 + 2, "REPLY payload too short");
byte[] nameBytes = new byte[nameLen];
bb.get(nameBytes);
this.toBlockchainName = new String(nameBytes, StandardCharsets.UTF_8);
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
BodyTargetSupport.ExternalTarget t = BodyTargetSupport.readExternal(bb, "REPLY", 2);
this.toLogin = t.login();
this.toForkNumber = t.forkNumber();
this.toBlockGlobalNumber = t.blockNumber();
this.toBlockHash32 = t.blockHash32();
} else {
// EDIT_REPLY: target без имени
ensureMin(bb, (4 + 32) + 2, "EDIT_REPLY too short");
this.toBlockchainName = null;
BodyTargetSupport.ensureMin(bb, 4 + 32 + 2, "EDIT_REPLY too short");
this.toLogin = null;
this.toForkNumber = null;
this.toBlockGlobalNumber = bb.getInt();
this.toBlockHash32 = new byte[32];
bb.get(this.toBlockHash32);
BodyTargetSupport.validateCompact(this.toBlockGlobalNumber, this.toBlockHash32, "EDIT_REPLY");
}
this.message = readStrictUtf8Len16(bb, "TextReplyBody text", st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF));
ensureNoTail(bb, "TextReplyBody");
this.message = readText(bb, st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF));
if (bb.hasRemaining()) throw new IllegalArgumentException("Unexpected TextReplyBody tail");
}
public TextReplyBody(short subType,
int toBlockGlobalNumber,
byte[] toBlockHash32,
String toBlockchainName,
String message) {
public TextReplyBody(short subType, String toLogin, Integer toForkNumber, int toBlockGlobalNumber, byte[] toBlockHash32, String message) {
Objects.requireNonNull(message, "message == null");
Objects.requireNonNull(toBlockHash32, "toBlockHash32 == null");
int st = subType & 0xFFFF;
if (st != (MsgSubType.TEXT_REPLY & 0xFFFF) && st != (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
throw new IllegalArgumentException("TextReplyBody supports only REPLY/EDIT_REPLY");
}
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF) && message.isBlank()) {
throw new IllegalArgumentException("message is blank");
}
if (toBlockGlobalNumber < 0) throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32.length != 32) throw new IllegalArgumentException("toBlockHash32 != 32");
if (st != (MsgSubType.TEXT_REPLY & 0xFFFF) && st != (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) throw new IllegalArgumentException("Bad reply subtype");
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
Objects.requireNonNull(toBlockchainName, "toBlockchainName == null");
if (toBlockchainName.isBlank()) throw new IllegalArgumentException("toBlockchainName is blank");
this.toBlockchainName = toBlockchainName;
if (message.isBlank()) throw new IllegalArgumentException("REPLY message is blank");
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPLY");
} else {
// EDIT_REPLY: имя не хранить
this.toBlockchainName = null;
if (toLogin != null || toForkNumber != null) throw new IllegalArgumentException("EDIT_REPLY must not contain login/fork target");
BodyTargetSupport.validateCompact(toBlockGlobalNumber, toBlockHash32, "EDIT_REPLY");
}
this.subType = subType;
this.version = VER;
this.toLogin = toLogin;
this.toForkNumber = toForkNumber;
this.toBlockGlobalNumber = toBlockGlobalNumber;
this.toBlockHash32 = Arrays.copyOf(toBlockHash32, 32);
this.message = message;
}
@Override
public TextReplyBody check() {
@Override public TextReplyBody check() {
int st = subType & 0xFFFF;
if (st != (MsgSubType.TEXT_REPLY & 0xFFFF) && st != (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF))
throw new IllegalArgumentException("Bad TextReplyBody subType: " + st);
if (toBlockGlobalNumber < 0)
throw new IllegalArgumentException("toBlockGlobalNumber < 0");
if (toBlockHash32 == null || toBlockHash32.length != 32)
throw new IllegalArgumentException("toBlockHash32 invalid");
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
if (message == null || message.isBlank())
throw new IllegalArgumentException("Text message is blank");
if (toBlockchainName == null || toBlockchainName.isBlank())
throw new IllegalArgumentException("REPLY toBlockchainName is blank");
} else {
BodyTargetSupport.validateExternal(toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPLY");
if (message == null || message.isBlank()) throw new IllegalArgumentException("REPLY message is blank");
} else if (st == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
if (toLogin != null || toForkNumber != null) throw new IllegalArgumentException("EDIT_REPLY must not contain login/fork target");
BodyTargetSupport.validateCompact(toBlockGlobalNumber, toBlockHash32, "EDIT_REPLY");
if (message == null) throw new IllegalArgumentException("EDIT_REPLY message is null");
if (toBlockchainName != null)
throw new IllegalArgumentException("EDIT_REPLY must not contain toBlockchainName");
}
} else throw new IllegalArgumentException("Bad reply subtype");
if (message.getBytes(StandardCharsets.UTF_8).length > 65535) throw new IllegalArgumentException("Text too long");
return this;
}
@Override
public byte[] toBytes() {
byte[] msgUtf8 = message.getBytes(StandardCharsets.UTF_8);
if (msgUtf8.length > 65535) throw new IllegalArgumentException("Text too long (>65535 bytes)");
int st = subType & 0xFFFF;
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF) && msgUtf8.length == 0) {
throw new IllegalArgumentException("Text payload is empty");
}
if (st == (MsgSubType.TEXT_REPLY & 0xFFFF)) {
if (toBlockchainName == null) throw new IllegalArgumentException("REPLY missing toBlockchainName");
byte[] nameUtf8 = toBlockchainName.getBytes(StandardCharsets.UTF_8);
if (nameUtf8.length == 0 || nameUtf8.length > 255)
throw new IllegalArgumentException("REPLY toBlockchainName utf8 len must be 1..255");
int cap = 1 + nameUtf8.length + 4 + 32 + 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.put((byte) nameUtf8.length);
bb.put(nameUtf8);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
return bb.array();
}
// EDIT_REPLY
int cap = (4 + 32) + 2 + msgUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(toBlockGlobalNumber);
bb.put(toBlockHash32);
bb.putShort((short) msgUtf8.length);
bb.put(msgUtf8);
@Override public byte[] toBytes() {
check();
byte[] text = message.getBytes(StandardCharsets.UTF_8);
boolean reply = (subType & 0xFFFF) == (MsgSubType.TEXT_REPLY & 0xFFFF);
int targetSize = reply ? BodyTargetSupport.externalSize(toLogin) : 4 + 32;
ByteBuffer bb = ByteBuffer.allocate(targetSize + 2 + text.length).order(ByteOrder.BIG_ENDIAN);
if (reply) BodyTargetSupport.writeExternal(bb, toLogin, toForkNumber, toBlockGlobalNumber, toBlockHash32, "REPLY");
else bb.putInt(toBlockGlobalNumber).put(toBlockHash32);
bb.putShort((short) text.length).put(text);
return bb.array();
}
/* ====================== BodyHasTarget ====================== */
@Override public String toBchName() { return toBlockchainName; }
@Override public String toLogin() { return toLogin; }
@Override public Integer toForkNumber() { return toForkNumber; }
@Override public Integer toBlockGlobalNumber() { return toBlockGlobalNumber; }
@Override public byte[] toBlockHashBytes() { return toBlockHash32; }
@Override public byte[] toBlockHashBytes() { return Arrays.copyOf(toBlockHash32, 32); }
public boolean isEditReply() { return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF); }
public boolean isEditReply() {
return (subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF);
}
/* ====================== helpers ====================== */
private static String readStrictUtf8Len16(ByteBuffer bb, String fieldName, boolean allowEmpty) {
private static String readText(ByteBuffer bb, boolean allowEmpty) {
if (bb.remaining() < 2) throw new IllegalArgumentException("Text length missing");
int len = Short.toUnsignedInt(bb.getShort());
if (len == 0) {
if (allowEmpty) return "";
throw new IllegalArgumentException(fieldName + " is empty");
}
if (bb.remaining() < len) throw new IllegalArgumentException(fieldName + " payload too short (len=" + len + ")");
byte[] bytes = new byte[len];
bb.get(bytes);
var decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT);
try {
String s = decoder.decode(ByteBuffer.wrap(bytes)).toString();
if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException(fieldName + " is blank");
return s;
} catch (CharacterCodingException e) {
throw new IllegalArgumentException(fieldName + " is not valid UTF-8", e);
}
}
private static void ensureMin(ByteBuffer bb, int need, String msg) {
if (bb.remaining() < need) throw new IllegalArgumentException(msg + " (need=" + need + ", remaining=" + bb.remaining() + ")");
}
private static void ensureNoTail(ByteBuffer bb, String ctx) {
if (bb.remaining() != 0) throw new IllegalArgumentException("Unexpected tail bytes for " + ctx + ", remaining=" + bb.remaining());
if (len == 0) { if (allowEmpty) return ""; throw new IllegalArgumentException("Text is empty"); }
if (bb.remaining() < len) throw new IllegalArgumentException("Text payload too short");
byte[] bytes = new byte[len]; bb.get(bytes);
var dec = StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);
try { String s = dec.decode(ByteBuffer.wrap(bytes)).toString(); if (!allowEmpty && s.isBlank()) throw new IllegalArgumentException("Text is blank"); return s; }
catch (CharacterCodingException e) { throw new IllegalArgumentException("Text invalid UTF-8", e); }
}
}
@@ -11,16 +11,16 @@ import java.util.Arrays;
import java.util.Objects;
/**
* UserParamBody — type=4, ver=1 (в заголовке блока).
* UserParamBody — type=4, ver=1 (в документации: USER_PROFILE).
*
* subType (в заголовке блока):
* 1 = TEXT_TEXT
*
* bodyBytes (BigEndian), новый формат:
* [4] lineCode
* [4] prevLineNumber
* [32] prevLineHash32
* [4] thisLineNumber
* USER_PROFILE имеет единственную фиксированную линию, поэтому lineCode в body не хранится.
* bodyBytes (BigEndian):
* [4] prevProfileBlockNumber — GLOBAL blockNumber предыдущего USER_PROFILE-блока
* [32] prevProfileBlockHash32 — hash32 предыдущего USER_PROFILE-блока
* [4] profileSequence — порядковый номер изменения профиля (1..N)
*
* [2] keyLenBytes (uint16)
* [N] keyUtf8
@@ -35,14 +35,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
public static final int KEY = ((TYPE & 0xFFFF) << 16) | (VER & 0xFFFF);
public final short subType; // из header
public final short version; // из header
public final short subType;
public final short version;
// line
public final int lineCode;
public final int prevLineNumber;
public final byte[] prevLineHash32;
public final int thisLineNumber;
public final int prevProfileBlockNumber;
public final byte[] prevProfileBlockHash32;
public final int profileSequence;
public final String paramKey;
public final String paramValue;
@@ -60,21 +58,17 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
throw new IllegalArgumentException("Bad UserParam subType: " + (this.subType & 0xFFFF));
}
// минимум: lineCode(4)+line(4+32+4) + keyLen(2)+key(1) + valLen(2)+val(1)
if (bodyBytes.length < 4 + (4 + 32 + 4) + 2 + 1 + 2 + 1) {
// prevGlobal(4)+prevHash(32)+seq(4) + keyLen(2)+key(1) + valLen(2)+val(1)
if (bodyBytes.length < 4 + 32 + 4 + 2 + 1 + 2 + 1) {
throw new IllegalArgumentException("UserParamBody too short");
}
ByteBuffer bb = ByteBuffer.wrap(bodyBytes).order(ByteOrder.BIG_ENDIAN);
this.lineCode = bb.getInt();
this.prevLineNumber = bb.getInt();
this.prevLineHash32 = new byte[32];
bb.get(this.prevLineHash32);
this.thisLineNumber = bb.getInt();
this.prevProfileBlockNumber = bb.getInt();
this.prevProfileBlockHash32 = new byte[32];
bb.get(this.prevProfileBlockHash32);
this.profileSequence = bb.getInt();
int keyLen = Short.toUnsignedInt(bb.getShort());
if (keyLen <= 0) throw new IllegalArgumentException("paramKeyLen is 0");
@@ -99,25 +93,21 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
if (this.paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
}
public UserParamBody(int lineCode,
int prevLineNumber,
byte[] prevLineHash32,
int thisLineNumber,
public UserParamBody(int prevProfileBlockNumber,
byte[] prevProfileBlockHash32,
int profileSequence,
String paramKey,
String paramValue) {
Objects.requireNonNull(paramKey, "paramKey == null");
Objects.requireNonNull(paramValue, "paramValue == null");
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
this.subType = MsgSubType.USER_PARAM_TEXT_TEXT;
this.version = VER;
this.lineCode = lineCode;
this.prevLineNumber = prevLineNumber;
this.prevLineHash32 = (prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
this.thisLineNumber = thisLineNumber;
this.prevProfileBlockNumber = prevProfileBlockNumber;
this.prevProfileBlockHash32 = (prevProfileBlockHash32 == null ? new byte[32] : Arrays.copyOf(prevProfileBlockHash32, 32));
this.profileSequence = profileSequence;
if (paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
@@ -128,17 +118,12 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
@Override
public UserParamBody check() {
if (lineCode < 0) throw new IllegalArgumentException("lineCode < 0");
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF))
if ((subType & 0xFFFF) != (MsgSubType.USER_PARAM_TEXT_TEXT & 0xFFFF)) {
throw new IllegalArgumentException("Bad UserParam subType: " + (subType & 0xFFFF));
if (prevLineNumber == -1) {
if (!isAllZero32(prevLineHash32)) throw new IllegalArgumentException("prevLineHash32 must be zero when prevLineNumber=-1");
if (thisLineNumber != -1) throw new IllegalArgumentException("thisLineNumber must be -1 when prevLineNumber=-1");
} else {
if (prevLineHash32 == null || prevLineHash32.length != 32) throw new IllegalArgumentException("prevLineHash32 invalid");
}
if (prevProfileBlockNumber < 0) throw new IllegalArgumentException("prevProfileBlockNumber must be >=0");
if (prevProfileBlockHash32 == null || prevProfileBlockHash32.length != 32) throw new IllegalArgumentException("prevProfileBlockHash32 invalid");
if (profileSequence <= 0) throw new IllegalArgumentException("profileSequence must be >=1");
if (paramKey == null || paramKey.isBlank()) throw new IllegalArgumentException("paramKey is blank");
if (paramValue == null || paramValue.isBlank()) throw new IllegalArgumentException("paramValue is blank");
@@ -148,30 +133,25 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
@Override
public byte[] toBytes() {
check();
byte[] keyUtf8 = paramKey.getBytes(StandardCharsets.UTF_8);
byte[] valUtf8 = paramValue.getBytes(StandardCharsets.UTF_8);
if (keyUtf8.length == 0 || keyUtf8.length > 65535) throw new IllegalArgumentException("paramKey utf8 len must be 1..65535");
if (valUtf8.length == 0 || valUtf8.length > 65535) throw new IllegalArgumentException("paramValue utf8 len must be 1..65535");
int cap = 4 + (4 + 32 + 4)
int cap = 4 + 32 + 4
+ 2 + keyUtf8.length
+ 2 + valUtf8.length;
ByteBuffer bb = ByteBuffer.allocate(cap).order(ByteOrder.BIG_ENDIAN);
bb.putInt(lineCode);
bb.putInt(prevLineNumber);
bb.put(prevLineHash32 == null ? new byte[32] : Arrays.copyOf(prevLineHash32, 32));
bb.putInt(thisLineNumber);
bb.putInt(prevProfileBlockNumber);
bb.put(prevProfileBlockHash32);
bb.putInt(profileSequence);
bb.putShort((short) keyUtf8.length);
bb.put(keyUtf8);
bb.putShort((short) valUtf8.length);
bb.put(valUtf8);
return bb.array();
}
@@ -187,15 +167,9 @@ public final class UserParamBody implements BodyRecord, BodyHasLine {
}
}
private static boolean isAllZero32(byte[] b) {
if (b == null || b.length != 32) return true;
for (int i = 0; i < 32; i++) if (b[i] != 0) return false;
return true;
}
/* ====================== BodyHasLine ====================== */
@Override public int lineCode() { return lineCode; }
@Override public int prevLineBlockGlobalNumber() { return prevLineNumber; }
@Override public byte[] prevLineBlockHash32() { return prevLineHash32 == null ? null : Arrays.copyOf(prevLineHash32, 32); }
@Override public int lineSeq() { return thisLineNumber; }
}
/* USER_PROFILE имеет единственную линию, логический lineCode всегда 0. */
@Override public int lineCode() { return 0; }
@Override public int prevLineBlockGlobalNumber() { return prevProfileBlockNumber; }
@Override public byte[] prevLineBlockHash32() { return Arrays.copyOf(prevProfileBlockHash32, 32); }
@Override public int lineSeq() { return profileSequence; }
}
@@ -1,71 +1,54 @@
package utils.blockchain;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/** Canonical physical fork name helper: login-NNN, forks are limited to 001..999. */
public final class BlockchainNameUtil {
/**
* Теперь новое правило:
* blockchainName = login + "-"+ 3 цифры
* Пример: "Dima-001" -> "Dima"
*
* Сколько символов отрезаем с конца blockchainName, чтобы получить login: "-001" = 4
*/
public static final int BLOCKCHAIN_NAME_LOGIN_SUFFIX_LEN = 4;
private static final Pattern SUFFIX = Pattern.compile("^(.*)-(\\d{3})$");
public static final int MIN_FORK_NUMBER = 1;
public static final int MAX_FORK_NUMBER = 999;
private BlockchainNameUtil() {}
/**
* Извлечь login из blockchainName: отрезаем последние 4 символа ("-NNN").
* Пример: "Dima-001" -> "Dima"
*/
public static String loginFromBlockchainName(String blockchainName) {
if (blockchainName == null) return null;
Matcher m = matcher(blockchainName);
return m == null ? null : m.group(1);
}
String s = blockchainName.trim();
if (!hasDashAnd3DigitsSuffix(s)) return null;
return s.substring(0, s.length() - BLOCKCHAIN_NAME_LOGIN_SUFFIX_LEN);
public static Integer forkNumberFromBlockchainName(String blockchainName) {
Matcher m = matcher(blockchainName);
if (m == null) return null;
int fork = Integer.parseInt(m.group(2));
return fork >= MIN_FORK_NUMBER && fork <= MAX_FORK_NUMBER ? fork : null;
}
/**
* Проверка правила:
* - blockchainName должен оканчиваться на "-"+3 цифры
* - blockchainName без суффикса "-NNN" должен равняться login
*
* ВАЖНО:
* - сравнение строгое (case-sensitive)
* - null/blank считаем невалидным
*/
public static boolean isBlockchainNameMatchesLogin(String blockchainName, String login) {
if (blockchainName == null || login == null) return false;
String bn = blockchainName.trim();
String lg = login.trim();
if (bn.isEmpty() || lg.isEmpty()) return false;
if (!hasDashAnd3DigitsSuffix(bn)) return false;
String extracted = bn.substring(0, bn.length() - BLOCKCHAIN_NAME_LOGIN_SUFFIX_LEN);
return Objects.equals(extracted, lg);
if (login == null || login.isBlank()) return false;
String extracted = loginFromBlockchainName(blockchainName);
return extracted != null && Objects.equals(extracted, login.trim());
}
private static boolean hasDashAnd3DigitsSuffix(String s) {
if (s == null) return false;
int len = s.length();
if (len <= BLOCKCHAIN_NAME_LOGIN_SUFFIX_LEN) return false;
int dashPos = len - 4;
if (s.charAt(dashPos) != '-') return false;
char c1 = s.charAt(len - 3);
char c2 = s.charAt(len - 2);
char c3 = s.charAt(len - 1);
return isDigit(c1) && isDigit(c2) && isDigit(c3);
public static String blockchainName(String login, int forkNumber) {
if (login == null || login.isBlank()) throw new IllegalArgumentException("login is blank");
if (forkNumber < MIN_FORK_NUMBER || forkNumber > MAX_FORK_NUMBER) {
throw new IllegalArgumentException("forkNumber must be 1..999");
}
return login.trim() + "-" + String.format("%03d", forkNumber);
}
private static boolean isDigit(char c) {
return c >= '0' && c <= '9';
private static Matcher matcher(String blockchainName) {
if (blockchainName == null) return null;
String s = blockchainName.trim();
if (s.isEmpty()) return null;
Matcher m = SUFFIX.matcher(s);
if (!m.matches() || m.group(1).isBlank()) return null;
try {
int fork = Integer.parseInt(m.group(2));
return fork >= MIN_FORK_NUMBER && fork <= MAX_FORK_NUMBER ? m : null;
} catch (NumberFormatException e) {
return null;
}
}
}
}
@@ -15,8 +15,8 @@ final class Ans104DataItemTest {
byte[] owner = Ed25519Util.derivePublicKey(privateKey);
byte[] data = "frame-v1-test".getBytes(StandardCharsets.UTF_8);
List<Ans104DataItem.Tag> tags = List.of(
new Ans104DataItem.Tag("App", "test5590"),
new Ans104DataItem.Tag("c_test5590", "books")
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag(ShineProtocolTags.CHANNEL_TAG_NAME, "books")
);
byte[] message = Ans104DataItem.buildSigningMessage(owner, tags, data);
@@ -27,8 +27,8 @@ final class Ans104DataItemTest {
assertEquals(2, parsed.signatureType());
assertArrayEquals(owner, parsed.owner32());
assertArrayEquals(data, parsed.data());
assertTrue(parsed.hasTag("App", "test5590"));
assertEquals("books", parsed.tagValue("c_test5590"));
assertTrue(parsed.hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE));
assertEquals("books", parsed.tagValue(ShineProtocolTags.CHANNEL_TAG_NAME));
assertTrue(parsed.verifySignature());
assertEquals(32, parsed.id32().length);
}
@@ -38,7 +38,7 @@ final class Ans104DataItemTest {
byte[] privateKey = Ed25519Util.generatePrivateKeyFromString("shine-ans104-mutation-key");
byte[] owner = Ed25519Util.derivePublicKey(privateKey);
byte[] data = "original".getBytes(StandardCharsets.UTF_8);
List<Ans104DataItem.Tag> tags = List.of(new Ans104DataItem.Tag("App", "test5590"));
List<Ans104DataItem.Tag> tags = List.of(new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE));
byte[] signature = Ed25519Util.sign(Ans104DataItem.buildSigningMessage(owner, tags, data), privateKey);
byte[] raw = Ans104DataItem.serializeEd25519(signature, owner, tags, data);
raw[raw.length - 1] ^= 1;
@@ -50,8 +50,8 @@ final class Ans104DataItemTest {
for (int i = 0; i < owner.length; i++) owner[i] = (byte) i;
byte[] data = "frame-v1-test".getBytes(StandardCharsets.UTF_8);
List<Ans104DataItem.Tag> tags = List.of(
new Ans104DataItem.Tag("App", "test5590"),
new Ans104DataItem.Tag("c_test5590", "books")
new Ans104DataItem.Tag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE),
new Ans104DataItem.Tag(ShineProtocolTags.CHANNEL_TAG_NAME, "books")
);
byte[] actual = Ans104DataItem.buildSigningMessage(owner, tags, data);
@@ -0,0 +1,100 @@
package blockchain;
import blockchain.body.ForkBody;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
final class ForkBodyTest {
@Test
void roundTripThroughBodyRecordParser() {
byte[] parentKey = filled(32, 0x11);
byte[] forkHash = filled(32, 0x22);
byte[] tipHash = filled(32, 0x33);
ForkBody source = new ForkBody(
0,
77,
filled(32, 0x44),
5,
parentKey,
120,
forkHash,
1_700_000_000_000L,
137,
tipHash,
1_700_100_000_000L,
17,
ForkBody.REASON_CONFIRMED_COMPROMISE_ROLLBACK,
"Удаляю неизвестные записи"
).check();
ForkBody parsed = assertInstanceOf(
ForkBody.class,
BodyRecordParser.parse(ForkBody.TYPE, ForkBody.SUBTYPE, ForkBody.VER, source.toBytes())
);
assertEquals(0, parsed.lineCode);
assertEquals(77, parsed.prevLineNumber);
assertEquals(5, parsed.thisLineNumber);
assertArrayEquals(parentKey, parsed.parentBlockchainKey32);
assertEquals(120, parsed.forkPointBlockNumber);
assertArrayEquals(forkHash, parsed.forkPointBlockHash32);
assertEquals(137, parsed.parentTipBlockNumber);
assertArrayEquals(tipHash, parsed.parentTipBlockHash32);
assertEquals(17, parsed.discardedBlocksCount);
assertEquals(ForkBody.REASON_CONFIRMED_COMPROMISE_ROLLBACK, parsed.reasonCode);
assertEquals("Удаляю неизвестные записи", parsed.comment);
}
@Test
void routineRotationMayDiscardNothing() {
ForkBody body = new ForkBody(
0,
0,
filled(32, 9),
1,
filled(32, 1),
10,
filled(32, 2),
1000,
10,
filled(32, 2),
1000,
0,
ForkBody.REASON_ROUTINE_ROTATION,
""
);
assertDoesNotThrow(body::check);
}
@Test
void rejectedWhenDiscardCountDoesNotMatchForkPointAndTip() {
ForkBody body = new ForkBody(
0,
0,
filled(32, 9),
1,
filled(32, 1),
10,
filled(32, 2),
1000,
12,
filled(32, 3),
2000,
99,
ForkBody.REASON_POSSIBLE_COMPROMISE,
""
);
assertThrows(IllegalArgumentException.class, body::check);
}
private static byte[] filled(int size, int value) {
byte[] out = new byte[size];
Arrays.fill(out, (byte) value);
return out;
}
}
@@ -0,0 +1,106 @@
package blockchain;
import blockchain.body.ConnectionBody;
import blockchain.body.HeaderBody;
import blockchain.body.ReactionBody;
import blockchain.body.StatusActionBody;
import blockchain.body.TextLineBody;
import blockchain.body.TextRatingBody;
import blockchain.body.TextReplyBody;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.*;
final class TargetLoginFormatTest {
private static final byte[] HASH = hash(7);
private static final byte[] INITIAL_KEY = hash(11);
@Test
void externalTargetRoundTripKeepsHistoricalForkMetadata() {
ReactionBody source = new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 7, 42, HASH);
ReactionBody parsed = new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, source.toBytes()).check();
assertEquals("alice", parsed.toLogin());
assertEquals(7, parsed.toForkNumber());
assertEquals(42, parsed.toBlockGlobalNumber());
assertArrayEquals(HASH, parsed.toBlockHashBytes());
assertFalse(new String(source.toBytes()).contains("alice-007"));
}
@Test
void replyIsExternalButEditReplyIsCompactOwnChainTarget() {
TextReplyBody reply = new TextReplyBody(MsgSubType.TEXT_REPLY, "alice", 12, 11, HASH, "reply");
TextReplyBody parsedReply = new TextReplyBody(MsgSubType.TEXT_REPLY, TextReplyBody.VER, reply.toBytes()).check();
assertEquals("alice", parsedReply.toLogin());
assertEquals(12, parsedReply.toForkNumber());
TextReplyBody edit = new TextReplyBody(MsgSubType.TEXT_EDIT_REPLY, null, null, 11, HASH, "");
TextReplyBody parsedEdit = new TextReplyBody(MsgSubType.TEXT_EDIT_REPLY, TextReplyBody.VER, edit.toBytes()).check();
assertNull(parsedEdit.toLogin());
assertNull(parsedEdit.toForkNumber());
assertEquals(11, parsedEdit.toBlockGlobalNumber());
assertArrayEquals(HASH, parsedEdit.toBlockHashBytes());
assertTrue(edit.toBytes().length < reply.toBytes().length);
}
@Test
void editPostIsCompactAndConnectionUsesRealExternalTarget() {
TextLineBody editPost = new TextLineBody(
0, -1, new byte[32], -1,
MsgSubType.TEXT_EDIT_POST,
null, null, 5, HASH, "edited"
);
TextLineBody parsedEditPost = new TextLineBody(MsgSubType.TEXT_EDIT_POST, TextLineBody.VER, editPost.toBytes()).check();
assertNull(parsedEditPost.toLogin());
assertNull(parsedEditPost.toForkNumber());
assertEquals(5, parsedEditPost.toBlockGlobalNumber());
ConnectionBody connection = new ConnectionBody(
0, HASH, 1,
MsgSubType.CONNECTION_FOLLOW,
"alice", 3, 0, HASH
);
ConnectionBody parsedConnection = new ConnectionBody(MsgSubType.CONNECTION_FOLLOW, ConnectionBody.VER, connection.toBytes()).check();
assertEquals("alice", parsedConnection.toLogin());
assertEquals(3, parsedConnection.toForkNumber());
assertEquals(0, parsedConnection.toBlockGlobalNumber());
assertArrayEquals(HASH, parsedConnection.toBlockHashBytes());
}
@Test
void ratingAndStatusCarryHistoricalForkNumber() {
TextRatingBody rating = new TextRatingBody("alice", 9, 70, HASH, "5");
TextRatingBody parsedRating = new TextRatingBody(MsgSubType.TEXT_RATING, TextRatingBody.VER, rating.toBytes()).check();
assertEquals(9, parsedRating.toForkNumber());
StatusActionBody status = new StatusActionBody(MsgSubType.STATUS_STARTED, "alice", 9, 77, HASH, "");
StatusActionBody parsedStatus = new StatusActionBody(MsgSubType.STATUS_STARTED, StatusActionBody.VER, status.toBytes()).check();
assertEquals("alice", parsedStatus.toLogin());
assertEquals(9, parsedStatus.toForkNumber());
assertEquals(77, parsedStatus.toBlockGlobalNumber());
}
@Test
void forkZeroIsReservedButStillDecodableAsHistoricalUnknown() {
ReactionBody source = new ReactionBody(MsgSubType.REACTION_LIKE, "alice", 0, 42, HASH);
ReactionBody parsed = new ReactionBody(MsgSubType.REACTION_LIKE, ReactionBody.VER, source.toBytes()).check();
assertEquals(0, parsed.toForkNumber());
}
@Test
void headerCarriesInitialBlockchainKey() {
HeaderBody source = new HeaderBody("alice", INITIAL_KEY);
HeaderBody parsed = new HeaderBody(HeaderBody.SUBTYPE_COMPAT, HeaderBody.VER, source.toBytes()).check();
assertEquals("alice", parsed.login);
assertArrayEquals(INITIAL_KEY, parsed.initialBlockchainKey32);
}
private static byte[] hash(int seed) {
byte[] out = new byte[32];
Arrays.fill(out, (byte) seed);
return out;
}
}
@@ -20,8 +20,8 @@ public final class ShineSignatureConstants {
/** Подписанный watermark чтения канала: prefix + login + owner_bch_name + channel_name + time_ms + read_count */
public static final String CHANNEL_READ_STATE_PREFIX = "SHiNe/ChannelReadState:";
/** TAG в HeaderBody (genesis). ASCII "SHiNe". */
public static final String BLOCKCHAIN_HEADER_TAG = "SHiNe";
/** TAG в HeaderBody (genesis). ASCII "SHiNE". */
public static final String BLOCKCHAIN_HEADER_TAG = "SHiNE";
/** DOMAIN для preimage при расчёте hash32 блока. ASCII "SHiNe". */
public static final String BLOCK_HASH_DOMAIN = "SHiNe";
@@ -17,56 +17,13 @@ import java.util.List;
public final class DatabaseInitializer {
public static final String DB_SCHEMA_VERSION_TABLE = "db_schema_version";
public static final String DB_FORMAT_MARKER_TABLE = "shine_database_metadata";
public static final String DB_FORMAT_MARKER = "SHiNE_DB_V2";
public static final int DB_FORMAT_VERSION = 2;
public static final int SCHEMA_VERSION_1 = 1;
public static final int SCHEMA_VERSION_2 = 2;
public static final int SCHEMA_VERSION_3 = 3;
public static final int SCHEMA_VERSION_4 = 4;
public static final int SCHEMA_VERSION_5 = 5;
public static final int SCHEMA_VERSION_6 = 6;
public static final int SCHEMA_VERSION_7 = 7;
public static final int SCHEMA_VERSION_8 = 8;
public static final int SCHEMA_VERSION_9 = 9;
public static final int SCHEMA_VERSION_10 = 10;
public static final int SCHEMA_VERSION_11 = 11;
public static final int SCHEMA_VERSION_12 = 12;
public static final int SCHEMA_VERSION_13 = 13;
public static final int SCHEMA_VERSION_14 = 14;
public static final int SCHEMA_VERSION_15 = 15;
public static final int SCHEMA_VERSION_16 = 16;
public static final int SCHEMA_VERSION_17 = 17;
public static final int SCHEMA_VERSION_18 = 18;
public static final int SCHEMA_VERSION_19 = 19;
public static final int SCHEMA_VERSION_20 = 20;
public static final int SCHEMA_VERSION_21 = 21;
public static final int SCHEMA_VERSION_22 = 22;
public static final int SCHEMA_VERSION_23 = 23;
public static final int SCHEMA_VERSION_24 = 24;
public static final int SCHEMA_VERSION_25 = 25;
public static final int SCHEMA_VERSION_31 = 31;
public static final String POSTGRES_SCHEMA_RESOURCE = "postgres/schema_v1.sql";
public static final String POSTGRES_MIGRATION_V2_RESOURCE = "postgres/migration_v2.sql";
public static final String POSTGRES_MIGRATION_V3_RESOURCE = "postgres/migration_v3.sql";
public static final String POSTGRES_MIGRATION_V4_RESOURCE = "postgres/migration_v4.sql";
public static final String POSTGRES_MIGRATION_V5_RESOURCE = "postgres/migration_v5.sql";
public static final String POSTGRES_MIGRATION_V6_RESOURCE = "postgres/migration_v6.sql";
public static final String POSTGRES_MIGRATION_V7_RESOURCE = "postgres/migration_v7.sql";
public static final String POSTGRES_MIGRATION_V8_RESOURCE = "postgres/migration_v8.sql";
public static final String POSTGRES_MIGRATION_V9_RESOURCE = "postgres/migration_v9.sql";
public static final String POSTGRES_MIGRATION_V10_RESOURCE = "postgres/migration_v10.sql";
public static final String POSTGRES_MIGRATION_V11_RESOURCE = "postgres/migration_v11.sql";
public static final String POSTGRES_MIGRATION_V12_RESOURCE = "postgres/migration_v12.sql";
public static final String POSTGRES_MIGRATION_V13_RESOURCE = "postgres/migration_v13.sql";
public static final String POSTGRES_MIGRATION_V14_RESOURCE = "postgres/migration_v14.sql";
public static final String POSTGRES_MIGRATION_V15_RESOURCE = "postgres/migration_v15.sql";
public static final String POSTGRES_MIGRATION_V16_RESOURCE = "postgres/migration_v16.sql";
public static final String POSTGRES_MIGRATION_V17_RESOURCE = "postgres/migration_v17.sql";
public static final String POSTGRES_MIGRATION_V18_RESOURCE = "postgres/migration_v18.sql";
public static final String POSTGRES_MIGRATION_V19_RESOURCE = "postgres/migration_v19.sql";
public static final String POSTGRES_MIGRATION_V20_RESOURCE = "postgres/migration_v20.sql";
public static final String POSTGRES_MIGRATION_V21_RESOURCE = "postgres/migration_v21.sql";
public static final String POSTGRES_MIGRATION_V22_RESOURCE = "postgres/migration_v22.sql";
public static final String POSTGRES_MIGRATION_V23_RESOURCE = "postgres/migration_v23.sql";
public static final String POSTGRES_MIGRATION_V24_RESOURCE = "postgres/migration_v24.sql";
public static final String POSTGRES_MIGRATION_V25_RESOURCE = "postgres/migration_v25.sql";
public static final String POSTGRES_MIGRATION_V31_RESOURCE = "postgres/migration_v31.sql";
private DatabaseInitializer() {}
@@ -77,6 +34,7 @@ public final class DatabaseInitializer {
public static final short TEXT_RATING = 30;
public static final short TEXT_REPOST = 50;
public static final short TEXT_CHANNEL_META = 90;
public static final short TEXT_CHANNEL_DELETE = 92;
public static final short TEXT_ENTRYPOINT = 100;
public static final short TEXT_EXERCISE = 110;
public static final short TEXT_SERVICE = 120;
@@ -135,106 +93,35 @@ public final class DatabaseInitializer {
}
try (Connection conn = openConnection(jdbcUrl, user, password)) {
if (!postgresSchemaVersionTableExists(conn)) {
boolean markerTableExists = postgresTableExists(conn, DB_FORMAT_MARKER_TABLE);
boolean schemaVersionTableExists = postgresTableExists(conn, DB_SCHEMA_VERSION_TABLE);
if (!markerTableExists) {
if (schemaVersionTableExists || currentSchemaHasBaseTables(conn)) {
throw new SQLException(
"Legacy/non-v2 SHiNE PostgreSQL database detected. "
+ "Stage 2 requires an empty database initialized as " + DB_FORMAT_MARKER
+ "; automatic migration from the old database is intentionally disabled.");
}
runSqlScript(conn, POSTGRES_SCHEMA_RESOURCE);
return;
markerTableExists = postgresTableExists(conn, DB_FORMAT_MARKER_TABLE);
schemaVersionTableExists = postgresTableExists(conn, DB_SCHEMA_VERSION_TABLE);
}
if (!markerTableExists || !schemaVersionTableExists) {
throw new SQLException(
"Invalid SHiNE PostgreSQL database: required v2 metadata/schema tables are missing.");
}
validateDatabaseFormatV2(conn);
int currentVersion = readCurrentSchemaVersion(conn);
if (currentVersion < SCHEMA_VERSION_2) {
runSqlScript(conn, POSTGRES_MIGRATION_V2_RESOURCE);
currentVersion = SCHEMA_VERSION_2;
if (currentVersion == 30) {
runSqlScript(conn, POSTGRES_MIGRATION_V31_RESOURCE);
currentVersion = readCurrentSchemaVersion(conn);
}
if (currentVersion < SCHEMA_VERSION_3) {
runSqlScript(conn, POSTGRES_MIGRATION_V3_RESOURCE);
currentVersion = SCHEMA_VERSION_3;
}
if (currentVersion < SCHEMA_VERSION_4) {
runSqlScript(conn, POSTGRES_MIGRATION_V4_RESOURCE);
currentVersion = SCHEMA_VERSION_4;
}
if (currentVersion < SCHEMA_VERSION_5) {
runSqlScript(conn, POSTGRES_MIGRATION_V5_RESOURCE);
currentVersion = SCHEMA_VERSION_5;
}
if (currentVersion < SCHEMA_VERSION_6) {
runSqlScript(conn, POSTGRES_MIGRATION_V6_RESOURCE);
currentVersion = SCHEMA_VERSION_6;
}
if (currentVersion < SCHEMA_VERSION_7) {
runSqlScript(conn, POSTGRES_MIGRATION_V7_RESOURCE);
currentVersion = SCHEMA_VERSION_7;
}
if (currentVersion < SCHEMA_VERSION_8) {
runSqlScript(conn, POSTGRES_MIGRATION_V8_RESOURCE);
currentVersion = SCHEMA_VERSION_8;
}
if (currentVersion < SCHEMA_VERSION_9) {
runSqlScript(conn, POSTGRES_MIGRATION_V9_RESOURCE);
currentVersion = SCHEMA_VERSION_9;
}
if (currentVersion < SCHEMA_VERSION_10) {
runSqlScript(conn, POSTGRES_MIGRATION_V10_RESOURCE);
currentVersion = SCHEMA_VERSION_10;
}
if (currentVersion < SCHEMA_VERSION_11) {
runSqlScript(conn, POSTGRES_MIGRATION_V11_RESOURCE);
currentVersion = SCHEMA_VERSION_11;
}
if (currentVersion < SCHEMA_VERSION_12) {
runSqlScript(conn, POSTGRES_MIGRATION_V12_RESOURCE);
currentVersion = SCHEMA_VERSION_12;
}
if (currentVersion < SCHEMA_VERSION_13) {
runSqlScript(conn, POSTGRES_MIGRATION_V13_RESOURCE);
currentVersion = SCHEMA_VERSION_13;
}
if (currentVersion < SCHEMA_VERSION_14) {
runSqlScript(conn, POSTGRES_MIGRATION_V14_RESOURCE);
currentVersion = SCHEMA_VERSION_14;
}
if (currentVersion < SCHEMA_VERSION_15) {
runSqlScript(conn, POSTGRES_MIGRATION_V15_RESOURCE);
currentVersion = SCHEMA_VERSION_15;
}
if (currentVersion < SCHEMA_VERSION_16) {
runSqlScript(conn, POSTGRES_MIGRATION_V16_RESOURCE);
currentVersion = SCHEMA_VERSION_16;
}
if (currentVersion < SCHEMA_VERSION_17) {
runSqlScript(conn, POSTGRES_MIGRATION_V17_RESOURCE);
currentVersion = SCHEMA_VERSION_17;
}
if (currentVersion < SCHEMA_VERSION_18) {
runSqlScript(conn, POSTGRES_MIGRATION_V18_RESOURCE);
currentVersion = SCHEMA_VERSION_18;
}
if (currentVersion < SCHEMA_VERSION_19) {
runSqlScript(conn, POSTGRES_MIGRATION_V19_RESOURCE);
currentVersion = SCHEMA_VERSION_19;
}
if (currentVersion < SCHEMA_VERSION_20) {
runSqlScript(conn, POSTGRES_MIGRATION_V20_RESOURCE);
currentVersion = SCHEMA_VERSION_20;
}
if (currentVersion < SCHEMA_VERSION_21) {
runSqlScript(conn, POSTGRES_MIGRATION_V21_RESOURCE);
currentVersion = SCHEMA_VERSION_21;
}
if (currentVersion < SCHEMA_VERSION_22) {
runSqlScript(conn, POSTGRES_MIGRATION_V22_RESOURCE);
currentVersion = SCHEMA_VERSION_22;
}
if (currentVersion < SCHEMA_VERSION_23) {
runSqlScript(conn, POSTGRES_MIGRATION_V23_RESOURCE);
currentVersion = SCHEMA_VERSION_23;
}
if (currentVersion < SCHEMA_VERSION_24) {
runSqlScript(conn, POSTGRES_MIGRATION_V24_RESOURCE);
currentVersion = SCHEMA_VERSION_24;
}
if (currentVersion < SCHEMA_VERSION_25) {
runSqlScript(conn, POSTGRES_MIGRATION_V25_RESOURCE);
currentVersion = SCHEMA_VERSION_25;
if (currentVersion != SCHEMA_VERSION_31) {
throw new SQLException(
"Unsupported SHiNE DB v2 schema version: expected 31, found " + currentVersion);
}
}
}
@@ -246,23 +133,60 @@ public final class DatabaseInitializer {
return DriverManager.getConnection(jdbcUrl, user, password == null ? "" : password);
}
private static boolean postgresSchemaVersionTableExists(Connection conn) throws SQLException {
private static boolean postgresTableExists(Connection conn, String tableName) throws SQLException {
String sql = """
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = current_schema()
AND table_name = ?
AND table_type = 'BASE TABLE'
)
""";
try (var ps = conn.prepareStatement(sql)) {
ps.setString(1, DB_SCHEMA_VERSION_TABLE);
ps.setString(1, tableName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() && rs.getBoolean(1);
}
}
}
private static boolean currentSchemaHasBaseTables(Connection conn) throws SQLException {
String sql = """
SELECT EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = current_schema()
AND table_type = 'BASE TABLE'
)
""";
try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
return rs.next() && rs.getBoolean(1);
}
}
private static void validateDatabaseFormatV2(Connection conn) throws SQLException {
String sql = """
SELECT database_format, database_generation
FROM shine_database_metadata
WHERE id = 1
""";
try (Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql)) {
if (!rs.next()) {
throw new SQLException(
"Invalid SHiNE PostgreSQL database: SHiNE_DB_V2 metadata row is missing.");
}
String format = rs.getString("database_format");
int generation = rs.getInt("database_generation");
if (!DB_FORMAT_MARKER.equals(format) || generation != DB_FORMAT_VERSION) {
throw new SQLException(
"Unsupported SHiNE PostgreSQL database format: expected " + DB_FORMAT_MARKER
+ " generation " + DB_FORMAT_VERSION
+ ", found format=" + format + ", generation=" + generation);
}
}
}
private static int readCurrentSchemaVersion(Connection conn) throws SQLException {
String sql = """
SELECT schema_version
@@ -4,7 +4,7 @@ package shine.db;
* MsgSubType — единое место для ВСЕХ subType сообщений (msg_sub_type).
*
* ВАЖНО:
* - Значения должны совпадать с body-классами (TextBody/ReactionBody/ConnectionBody/UserParamBody/HeaderBody).
* - Значения должны совпадать с body-классами (TextLineBody/TextReplyBody/TextRatingBody/ReactionBody/ConnectionBody/UserParamBody/HeaderBody).
* - После релиза менять числа нельзя (иначе ломается совместимость данных).
*/
public final class MsgSubType {
@@ -38,6 +38,7 @@ public final class MsgSubType {
/** CHANNEL_META — скрытый технический снимок профиля канала. */
public static final short TEXT_CHANNEL_META = 90;
public static final short TEXT_CHANNEL_DELETE = 92;
/** ENTRYPOINT — входная страница канала (line-based). */
public static final short TEXT_ENTRYPOINT = 100;
@@ -28,7 +28,7 @@ public final class PostgresDbController {
try {
DatabaseInitializer.ensurePostgresSchemaInitialized(jdbcUrl, dbUser, dbPassword);
} catch (SQLException e) {
throw new RuntimeException("PostgreSQL schema auto-init failed", e);
throw new RuntimeException("PostgreSQL database compatibility/init failed: " + e.getMessage(), e);
}
this.delegate = new DriverManagerDbProvider(jdbcUrl, dbUser, dbPassword, connection -> {
@@ -269,6 +269,57 @@ public final class ActiveSessionsDAO {
}
}
/**
* Удаляет все сессии пользователя, кроме указанной текущей, и возвращает их sessionId.
* Вариант с Connection используется внутри транзакции запуска key rotation.
*/
public List<String> deleteOtherSessions(Connection c, String login, String keepSessionId) throws SQLException {
List<String> sessionIds = new ArrayList<>();
String selectSql = """
SELECT session_id
FROM active_sessions
WHERE LOWER(login) = LOWER(?)
AND session_id <> ?
""";
try (PreparedStatement ps = c.prepareStatement(selectSql)) {
ps.setString(1, login);
ps.setString(2, keepSessionId == null ? "" : keepSessionId);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) sessionIds.add(rs.getString(1));
}
}
if (sessionIds.isEmpty()) return sessionIds;
String deleteSql = """
DELETE FROM active_sessions
WHERE LOWER(login) = LOWER(?)
AND session_id <> ?
""";
try (PreparedStatement ps = c.prepareStatement(deleteSql)) {
ps.setString(1, login);
ps.setString(2, keepSessionId == null ? "" : keepSessionId);
ps.executeUpdate();
}
return sessionIds;
}
public List<String> deleteOtherSessions(String login, String keepSessionId) throws SQLException {
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
List<String> ids = deleteOtherSessions(c, login, keepSessionId);
c.commit();
return ids;
} catch (SQLException e) {
c.rollback();
throw e;
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
// -------------------- MAPPER --------------------
private ActiveSessionEntry mapRow(ResultSet rs) throws SQLException {
@@ -13,7 +13,9 @@ public final class ArweaveBlockImportDAO {
public record QueueItem(byte[] dataItemId, long blockHeight,
byte[] rawDataItem, String status, String lastError,
long firstSeenAtMs, long updatedAtMs) {}
long firstSeenAtMs, long updatedAtMs,
String parsedLogin, Integer parsedForkNumber, Integer parsedBlockNumber, byte[] parsedBlockHash,
boolean metadataValidated) {}
private static volatile ArweaveBlockImportDAO instance;
private final DbController db = DbController.getInstance();
@@ -51,21 +53,22 @@ public final class ArweaveBlockImportDAO {
}
/** Insert once. Existing IDs (including REJECTED) are deliberately not re-enqueued. */
public boolean enqueueIfMissing(byte[] dataItemId, long blockHeight, byte[] rawDataItem, long nowMs)
public boolean enqueueIfMissing(byte[] dataItemId, String rootTxId, long blockHeight, byte[] rawDataItem, long nowMs)
throws SQLException {
String sql = """
INSERT INTO arweave_block_import_queue(
data_item_id,block_height,raw_data_item,status,last_error,first_seen_at_ms,updated_at_ms
) VALUES(?,?,?,?, '',?,?)
data_item_id,root_tx_id,block_height,raw_data_item,status,last_error,first_seen_at_ms,updated_at_ms
) VALUES(?,?,?,?,?, '',?,?)
ON CONFLICT(data_item_id) DO NOTHING
""";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBytes(1, dataItemId);
ps.setLong(2, blockHeight);
ps.setBytes(3, rawDataItem);
ps.setString(4, STATUS_PENDING);
ps.setLong(5, nowMs);
ps.setString(2, rootTxId == null ? "" : rootTxId.trim());
ps.setLong(3, blockHeight);
ps.setBytes(4, rawDataItem);
ps.setString(5, STATUS_PENDING);
ps.setLong(6, nowMs);
ps.setLong(7, nowMs);
return ps.executeUpdate() > 0;
}
}
@@ -81,7 +84,8 @@ public final class ArweaveBlockImportDAO {
public List<QueueItem> listPending(int limit) throws SQLException {
int safeLimit = Math.max(1, Math.min(limit, 100_000));
String sql = """
SELECT data_item_id,block_height,raw_data_item,status,last_error,first_seen_at_ms,updated_at_ms
SELECT data_item_id,block_height,raw_data_item,status,last_error,first_seen_at_ms,updated_at_ms,
parsed_login,parsed_fork_number,parsed_block_number,parsed_block_hash,metadata_validated
FROM arweave_block_import_queue
WHERE status=?
ORDER BY block_height ASC, first_seen_at_ms ASC
@@ -96,13 +100,55 @@ public final class ArweaveBlockImportDAO {
out.add(new QueueItem(
rs.getBytes("data_item_id"), rs.getLong("block_height"),
rs.getBytes("raw_data_item"), rs.getString("status"), rs.getString("last_error"),
rs.getLong("first_seen_at_ms"), rs.getLong("updated_at_ms")));
rs.getLong("first_seen_at_ms"), rs.getLong("updated_at_ms"),
rs.getString("parsed_login"), (Integer) rs.getObject("parsed_fork_number"),
(Integer) rs.getObject("parsed_block_number"), rs.getBytes("parsed_block_hash"),
rs.getBoolean("metadata_validated")));
}
}
}
return out;
}
/** Persist cryptographically validated parse metadata used to order canonical replay. */
public void markMetadataValidated(byte[] id, String login, int forkNumber, int blockNumber, byte[] blockHash, long nowMs)
throws SQLException {
String sql = """
UPDATE arweave_block_import_queue
SET parsed_login=?,parsed_fork_number=?,parsed_block_number=?,parsed_block_hash=?,metadata_validated=TRUE,
last_error='',updated_at_ms=?
WHERE data_item_id=? AND status=?
""";
try (Connection c=db.getConnection(); PreparedStatement ps=c.prepareStatement(sql)) {
ps.setString(1, login); ps.setInt(2, forkNumber); ps.setInt(3, blockNumber); ps.setBytes(4, blockHash);
ps.setLong(5, nowMs); ps.setBytes(6, id); ps.setString(7, STATUS_PENDING); ps.executeUpdate();
}
}
/** Pending items with verified signatures/owner metadata, in deterministic logical replay order. */
public List<QueueItem> listPendingValidated(int limit) throws SQLException {
int safeLimit=Math.max(1,Math.min(limit,100_000));
String sql="""
SELECT data_item_id,block_height,raw_data_item,status,last_error,first_seen_at_ms,updated_at_ms,
parsed_login,parsed_fork_number,parsed_block_number,parsed_block_hash,metadata_validated
FROM arweave_block_import_queue
WHERE status=? AND metadata_validated=TRUE
ORDER BY LOWER(parsed_login) ASC, parsed_block_number ASC, parsed_fork_number ASC, first_seen_at_ms ASC
LIMIT ?
""";
List<QueueItem> out=new ArrayList<>();
try(Connection c=db.getConnection();PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,STATUS_PENDING);ps.setInt(2,safeLimit);
try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(new QueueItem(
rs.getBytes("data_item_id"),rs.getLong("block_height"),rs.getBytes("raw_data_item"),
rs.getString("status"),rs.getString("last_error"),rs.getLong("first_seen_at_ms"),rs.getLong("updated_at_ms"),
rs.getString("parsed_login"),(Integer)rs.getObject("parsed_fork_number"),(Integer)rs.getObject("parsed_block_number"),
rs.getBytes("parsed_block_hash"),rs.getBoolean("metadata_validated")));
}
}
return out;
}
public void setPendingError(byte[] id, String error, long nowMs) throws SQLException {
updateStatus(id, STATUS_PENDING, error, nowMs);
}
@@ -0,0 +1,27 @@
package shine.db.dao;
import shine.db.DbController;
import java.sql.*;
/** Persistent ancestry/cache for segmented logical blockchains. */
public final class BlockchainForkSegmentsDAO {
private static volatile BlockchainForkSegmentsDAO instance;
private final DbController db=DbController.getInstance();
private BlockchainForkSegmentsDAO(){}
public static BlockchainForkSegmentsDAO getInstance(){ if(instance==null) synchronized(BlockchainForkSegmentsDAO.class){ if(instance==null) instance=new BlockchainForkSegmentsDAO(); } return instance; }
public record Segment(String login,int forkNumber,Integer parentForkNumber,int forkPointBlockNumber,byte[] forkPointBlockHash,int firstPhysicalBlockNumber,long createdAtMs){}
public Segment get(Connection c,String login,int fork)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("SELECT login,fork_number,parent_fork_number,fork_point_block_number,fork_point_block_hash,first_physical_block_number,created_at_ms FROM blockchain_fork_segments WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,login);ps.setInt(2,fork);try(ResultSet rs=ps.executeQuery()){if(!rs.next())return null; Object parent=rs.getObject(3); return new Segment(rs.getString(1),rs.getInt(2),parent==null?null:rs.getInt(3),rs.getInt(4),rs.getBytes(5),rs.getInt(6),rs.getLong(7));}
}
}
public Segment get(String login,int fork)throws SQLException{try(Connection c=db.getConnection()){return get(c,login,fork);}}
public void upsert(Connection c,Segment s)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO blockchain_fork_segments(login,fork_number,parent_fork_number,fork_point_block_number,fork_point_block_hash,first_physical_block_number,created_at_ms)
VALUES(?,?,?,?,?,?,?) ON CONFLICT(login,fork_number) DO UPDATE SET parent_fork_number=EXCLUDED.parent_fork_number,fork_point_block_number=EXCLUDED.fork_point_block_number,fork_point_block_hash=EXCLUDED.fork_point_block_hash,first_physical_block_number=EXCLUDED.first_physical_block_number
""")){ps.setString(1,s.login());ps.setInt(2,s.forkNumber());if(s.parentForkNumber()==null)ps.setNull(3,Types.INTEGER);else ps.setInt(3,s.parentForkNumber());ps.setInt(4,s.forkPointBlockNumber());if(s.forkPointBlockHash()==null)ps.setNull(5,Types.BINARY);else ps.setBytes(5,s.forkPointBlockHash());ps.setInt(6,s.firstPhysicalBlockNumber());ps.setLong(7,s.createdAtMs());ps.executeUpdate();}
}
}
@@ -1,509 +1,298 @@
package shine.db.dao;
import shine.db.DatabaseInitializer;
import shine.db.DbController;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
/**
* BlockchainResyncCleanupDAO — подготовительный "жёсткий reset" одной blockchain-цепочки
* перед её полной повторной загрузкой от сервера-партнёра.
*
* Что делает этот DAO:
* 1) в ОДНОЙ SQL-транзакции сначала аккуратно уменьшает чужие агрегаты,
* которые были увеличены блоками удаляемой цепочки:
* - likes_count
* - replies_count
* 2) затем удаляет все локальные записи самой цепочки и её производные состояния.
*
* Почему это вынесено в отдельный DAO-метод, а не в триггеры DELETE:
* - нам нужен один понятный "блок операции", который можно вызвать из resync-flow;
* - эта схема проще и прозрачнее, чем много обратных триггеров по разным таблицам;
* - если любой шаг не удался, делаем rollback и БД остаётся в исходном состоянии;
* - пользовательские blockchain-файлы больше не существуют; cleanup полностью DB-only.
* SQL-транзакция и файловая система не коммитятся атомарно вместе;
* поэтому БД-чистка делается здесь, а файловая чистка будет следующим шагом
* отдельным recovery/resync-слоем после успешного commit.
*
* Важный смысл текущей реализации:
* - мы НЕ трогаем current users слой (`solana_user_pda_current`) и НЕ трогаем DM-таблицы;
* - мы очищаем только блокчейн пользователя и derived-state, который строится из неё;
* - висячие cross-chain ссылки в чужих blocks допускаются как нормальное поведение системы.
* Atomic cleanup of one physical fork before deterministic replay.
* Physical fork identity is (login,fork_number). Incoming logical state is never rebound/deleted.
*/
public final class BlockchainResyncCleanupDAO {
private static final int BLOCKCHAIN_LOGIN_SUFFIX_LEN = 4; // "-001"
private static volatile BlockchainResyncCleanupDAO instance;
private final DbController db=DbController.getInstance();
private BlockchainResyncCleanupDAO(){}
public static BlockchainResyncCleanupDAO getInstance(){ if(instance==null) synchronized(BlockchainResyncCleanupDAO.class){if(instance==null)instance=new BlockchainResyncCleanupDAO();} return instance; }
private final DbController db = DbController.getInstance();
private BlockchainResyncCleanupDAO() {}
public static BlockchainResyncCleanupDAO getInstance() {
if (instance == null) {
synchronized (BlockchainResyncCleanupDAO.class) {
if (instance == null) instance = new BlockchainResyncCleanupDAO();
}
}
return instance;
}
/**
* Полностью очищает одну blockchain-цепочку и локальные derived-state, собранные из неё.
*
* Порядок внутри транзакции намеренно такой:
* 1. Сначала уменьшаем чужие likes_count для тех целей, где финальное состояние
* реакции этой цепочки было LIKE.
* 2. Сначала уменьшаем чужие replies_count для reply-блоков этой цепочки.
* 3. После этого удаляем локальные derived-state самой цепочки.
* 4. В конце удаляем blocks и blockchain_state.
*
* Это правильно потому, что агрегаты (`message_stats`) должны видеть исходные blocks
* и reactions_state на момент пересчёта. Если удалить blocks раньше, мы потеряем
* источник правды для корректного уменьшения счётчиков.
*
* Метод идемпотентен по смыслу:
* - если часть данных уже удалена раньше, повторный вызов просто удалит "0 строк";
* - если blockchain_state уже отсутствует, login берём из blockchainName.
*
* Отдельно важно:
* - filesystem blockchain storage отсутствует;
* - здесь НЕТ повторной загрузки цепочки;
* - это только атомарная SQL-очистка БД, на которую потом будет опираться resync-flow.
*/
public CleanupResult cleanupBlockchainForFullResync(String blockchainName) throws SQLException {
if (blockchainName == null || blockchainName.isBlank()) {
throw new IllegalArgumentException("blockchainName is blank");
}
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
String login = resolveLoginForCleanup(c, blockchainName);
int likesAdjusted = decreaseForeignLikesCount(c, blockchainName);
int repliesAdjusted = decreaseForeignRepliesCount(c, blockchainName);
int deletedMessageStats = deleteMessageStatsForOwnTargets(c, blockchainName);
int deletedReactionsState = deleteReactionsStateForActorChain(c, blockchainName);
int deletedConnectionsState = deleteConnectionsStateForLogin(c, login);
int deletedUsersParams = deleteUsersParamsForLogin(c, login);
int deletedChannelNames = deleteChannelNamesForOwnerChain(c, blockchainName);
int deletedChat200State = deleteChat200StateForOwnerChain(c, blockchainName);
int deletedChat200Members = deleteChat200MembersForOwnerChain(c, blockchainName);
int deletedBlocks = deleteBlocksForChain(c, blockchainName);
int deletedBlockchainState = deleteBlockchainStateForChain(c, blockchainName);
rebuildStatsState(c);
c.commit();
return new CleanupResult(
login,
likesAdjusted,
repliesAdjusted,
deletedMessageStats,
deletedReactionsState,
deletedConnectionsState,
deletedUsersParams,
deletedChannelNames,
deletedChat200State,
deletedChat200Members,
deletedBlocks,
deletedBlockchainState
);
} catch (Exception e) {
try { c.rollback(); } catch (Exception ignored) {}
if (e instanceof SQLException sqlEx) throw sqlEx;
throw new SQLException("Не удалось очистить blockchain для полного resync: " + blockchainName, e);
} finally {
try { c.setAutoCommit(oldAutoCommit); } catch (Exception ignored) {}
}
}
}
private String resolveLoginForCleanup(Connection c, String blockchainName) throws SQLException {
String sql = """
SELECT login
FROM blockchain_state
WHERE blockchain_name = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
String login = rs.getString("login");
if (login != null && !login.isBlank()) {
return login;
}
ChainRef ref=chainRef(blockchainName);
try(Connection c=db.getConnection()){
boolean ac=c.getAutoCommit(); c.setAutoCommit(false);
try{
// Targets liked by this actor must survive long enough to recount after actor rows are removed.
try(Statement st=c.createStatement()){
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_channels(owner_bch_name TEXT,root_number INTEGER,root_hash BYTEA,PRIMARY KEY(owner_bch_name,root_number,root_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_channels");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_users(login TEXT PRIMARY KEY) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_users");
}
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_targets(to_login,to_block_number,to_block_hash)
SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state
WHERE LOWER(from_login)=LOWER(?) AND reaction_type=1 AND last_sub_type=1
ON CONFLICT DO NOTHING
""")){ ps.setString(1,ref.login()); ps.executeUpdate(); }
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT to_login FROM connections_state
WHERE LOWER(login)=LOWER(?) AND to_login IS NOT NULL AND btrim(to_login)<>''
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_channels(owner_bch_name,root_number,root_hash)
SELECT DISTINCT cn.owner_bch_name,cn.channel_root_block_number,cn.channel_root_block_hash
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(?) AND cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
// Followers of channels owned by this login must be refreshed after those channel projections are removed.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT cs.login
FROM connections_state cs
JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(?)
AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cs.to_block_number=cn.channel_root_block_number
AND cs.to_block_hash=cn.channel_root_block_hash
WHERE cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
int deletedReactions=delete(c,"DELETE FROM reactions_state WHERE LOWER(from_login)=LOWER(?)",ref.login());
recountAffectedLikes(c);
int deletedConnections=delete(c,"DELETE FROM connections_state WHERE LOWER(login)=LOWER(?)",ref.login());
refreshAffectedChannelStats(c);
int deletedUsersParams=delete(c,"DELETE FROM users_params WHERE LOWER(login)=LOWER(?)",ref.login());
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_profile(?)")){ps.setString(1,ref.login());ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
// Channel/chat projections are owned by login; replay recreates them. Incoming social stats are intentionally untouched.
delete(c,"DELETE FROM channel_stats_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
int deletedChannelNames=delete(c,"DELETE FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
refreshAffectedUserStats(c);
int deletedChat200=delete(c,"DELETE FROM chat200_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
int deletedChatMembers=delete(c,"DELETE FROM chat200_members_state WHERE owner_bch_name LIKE ?",ref.login()+"-%");
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
int deletedBlocks;
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blocks_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedBlocks=ps.executeUpdate();
}
int deletedState;
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
}
c.commit();
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
finally{try{c.setAutoCommit(ac);}catch(Exception ignored){}}
}
}
/** Clears all materialized state and raw local forks for one login before canonical replay.
* Raw canonical bytes must already be persisted in rebuild staging.
*
* This operation is deliberately idempotent. Before deleting the actor's projections we
* remember every foreign user/channel/message aggregate touched by them, then repair those
* aggregates after the rows/blocks have been removed. Canonical replay can therefore start
* from a clean baseline without double-counting replies, likes or subscriptions.
*/
public void cleanupLoginForCanonicalReplay(String login) throws SQLException {
if(login==null||login.isBlank())throw new IllegalArgumentException("login is blank");
try(Connection c=db.getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
try(Statement st=c.createStatement()){
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_reply_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_reply_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_channels(owner_bch_name TEXT,root_number INTEGER,root_hash BYTEA,PRIMARY KEY(owner_bch_name,root_number,root_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_channels");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_users(login TEXT PRIMARY KEY) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_users");
}
}
String loginFromName = loginFromBlockchainName(blockchainName);
if (loginFromName == null || loginFromName.isBlank()) {
throw new IllegalArgumentException("Cannot derive login from blockchainName: " + blockchainName);
}
return loginFromName;
}
// Existing LIKE state produced by this actor.
try(PreparedStatement ps=c.prepareStatement("INSERT INTO shine_cleanup_targets SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state WHERE LOWER(from_login)=LOWER(?) AND reaction_type=1 AND last_sub_type=1 ON CONFLICT DO NOTHING")){ps.setString(1,login);ps.executeUpdate();}
/**
* DAO остаётся в модуле БД и не тянет зависимость на blockchain-utils модуль.
* Поэтому здесь локально повторяем минимальное правило имени chain:
* login + "-NNN".
*/
private String loginFromBlockchainName(String blockchainName) {
if (blockchainName == null) return null;
// Existing REPLY blocks produced by this actor. Their counters must be recomputed
// after deleting the old canonical blocks and before replay inserts the new canonical set.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_reply_targets(to_login,to_block_number,to_block_hash)
SELECT DISTINCT to_login,to_block_number,to_block_hash
FROM blocks_store
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=20
AND to_login IS NOT NULL AND to_block_number IS NOT NULL AND to_block_hash IS NOT NULL
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
String s = blockchainName.trim();
if (s.length() <= BLOCKCHAIN_LOGIN_SUFFIX_LEN) return null;
// Users whose social counters may change when this actor's connection projection disappears.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT to_login FROM connections_state
WHERE LOWER(login)=LOWER(?) AND to_login IS NOT NULL AND btrim(to_login)<>''
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("INSERT INTO shine_cleanup_users(login) VALUES(?) ON CONFLICT DO NOTHING")){ps.setString(1,login);ps.executeUpdate();}
int dashPos = s.length() - BLOCKCHAIN_LOGIN_SUFFIX_LEN;
if (s.charAt(dashPos) != '-') return null;
// Foreign channels followed/unfollowed by this actor.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_channels(owner_bch_name,root_number,root_hash)
SELECT DISTINCT cn.owner_bch_name,cn.channel_root_block_number,cn.channel_root_block_hash
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(?) AND cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
for (int i = dashPos + 1; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch < '0' || ch > '9') return null;
}
return s.substring(0, dashPos);
}
/**
* Уменьшаем likes_count только для ЧУЖИХ целей.
*
* Логика:
* - если у удаляемой цепочки финальное состояние реакции на цель = LIKE,
* значит при полном удалении цепочки этот активный лайк исчезает;
* - значит у message_stats этой чужой цели нужно сделать -1;
* - для целей внутри этой же chain этого делать не нужно, потому что сами цели
* тоже будут удалены вместе с цепочкой.
*/
private int decreaseForeignLikesCount(Connection c, String blockchainName) throws SQLException {
String sql = """
UPDATE message_stats
SET likes_count = GREATEST(
0,
likes_count - COALESCE((
SELECT COUNT(*)::int
FROM reactions_state rs
WHERE rs.from_bch_name = ?
AND rs.reaction_type = ?
AND rs.last_sub_type = ?
AND rs.to_login = message_stats.to_login
AND rs.to_bch_name = message_stats.to_bch_name
AND rs.to_block_number = message_stats.to_block_number
AND rs.to_block_hash = message_stats.to_block_hash
AND rs.to_bch_name <> ?
), 0)
)
WHERE EXISTS (
SELECT 1
FROM reactions_state rs
WHERE rs.from_bch_name = ?
AND rs.reaction_type = ?
AND rs.last_sub_type = ?
AND rs.to_login = message_stats.to_login
AND rs.to_bch_name = message_stats.to_bch_name
AND rs.to_block_number = message_stats.to_block_number
AND rs.to_block_hash = message_stats.to_block_hash
AND rs.to_bch_name <> ?
)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, blockchainName);
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
ps.setString(i++, blockchainName);
ps.setString(i++, blockchainName);
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
ps.setInt(i++, DatabaseInitializer.REACTION_LIKE);
ps.setString(i++, blockchainName);
return ps.executeUpdate();
}
}
/**
* Уменьшаем replies_count только для ЧУЖИХ целей.
*
* Если reply этой цепочки ссылался на сообщение из другой цепочки,
* значит после удаления blocks этой цепочки чужой replies_count должен уменьшиться.
* Reply на собственные сообщения здесь игнорируем: целевая цепочка тоже будет удалена.
*/
private int decreaseForeignRepliesCount(Connection c, String blockchainName) throws SQLException {
String sql = """
UPDATE message_stats
SET replies_count = GREATEST(
0,
replies_count - COALESCE((
SELECT COUNT(*)::int
FROM blocks b
WHERE b.bch_name = ?
AND b.msg_type = 1
AND b.msg_sub_type = ?
AND b.to_login = message_stats.to_login
AND b.to_bch_name = message_stats.to_bch_name
AND b.to_block_number = message_stats.to_block_number
AND b.to_block_hash = message_stats.to_block_hash
AND b.to_bch_name <> ?
), 0)
)
WHERE EXISTS (
SELECT 1
FROM blocks b
WHERE b.bch_name = ?
AND b.msg_type = 1
AND b.msg_sub_type = ?
AND b.to_login = message_stats.to_login
AND b.to_bch_name = message_stats.to_bch_name
AND b.to_block_number = message_stats.to_block_number
AND b.to_block_hash = message_stats.to_block_hash
AND b.to_bch_name <> ?
)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, blockchainName);
ps.setInt(i++, DatabaseInitializer.TEXT_REPLY);
ps.setString(i++, blockchainName);
ps.setString(i++, blockchainName);
ps.setInt(i++, DatabaseInitializer.TEXT_REPLY);
ps.setString(i++, blockchainName);
return ps.executeUpdate();
}
}
/**
* Статистика сообщений самой удаляемой цепочки после reset не нужна,
* потому что её цели исчезают вместе с chain source data.
*/
private int deleteMessageStatsForOwnTargets(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM message_stats
WHERE to_bch_name = ?
""", blockchainName);
}
/**
* reactions_state хранит финальное состояние реакций АКТОРА.
* После удаления всей цепочки актор этой цепочки исчезает, поэтому
* достаточно удалить все строки по from_bch_name.
*/
private int deleteReactionsStateForActorChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM reactions_state
WHERE from_bch_name = ?
""", blockchainName);
}
/**
* connections_state — текущее состояние связей, выставленных этим login.
* Чистим по владельцу состояния.
*/
private int deleteConnectionsStateForLogin(Connection c, String login) throws SQLException {
return executeDelete(c, """
DELETE FROM connections_state
WHERE LOWER(login) = LOWER(?)
""", login);
}
/**
* users_params — актуальные параметры, собранные из блоков пользователя.
*/
private int deleteUsersParamsForLogin(Connection c, String login) throws SQLException {
return executeDelete(c, """
DELETE FROM users_params
WHERE LOWER(login) = LOWER(?)
""", login);
}
/**
* Каналы принадлежат owner_bch_name.
*/
private int deleteChannelNamesForOwnerChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM channel_names_state
WHERE owner_bch_name = ?
""", blockchainName);
}
private int deleteChat200StateForOwnerChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM chat200_state
WHERE owner_bch_name = ?
""", blockchainName);
}
private int deleteChat200MembersForOwnerChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM chat200_members_state
WHERE owner_bch_name = ?
""", blockchainName);
}
/**
* blocks удаляем в конце, потому что до этого шага они нужны как источник правды
* для уменьшения replies_count.
*/
private int deleteBlocksForChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM blocks
WHERE bch_name = ?
""", blockchainName);
}
/**
* blockchain_state удаляем после blocks, чтобы не нарушать FK-связь blocks -> blockchain_state.
*/
private int deleteBlockchainStateForChain(Connection c, String blockchainName) throws SQLException {
return executeDelete(c, """
DELETE FROM blockchain_state
WHERE blockchain_name = ?
""", blockchainName);
}
private void rebuildStatsState(Connection c) throws SQLException {
try (PreparedStatement truncate = c.prepareStatement("""
TRUNCATE TABLE user_stats_state, channel_stats_state
""")) {
truncate.executeUpdate();
}
try (PreparedStatement ps = c.prepareStatement("""
INSERT INTO user_stats_state (
login,
owned_public_channels_count,
following_users_count,
following_channels_count,
close_friends_count,
updated_at_ms
)
SELECT
u.login,
COALESCE(own.owned_public_channels_count, 0),
COALESCE(fu.following_users_count, 0),
COALESCE(fc.following_channels_count, 0),
COALESCE(cf.close_friends_count, 0),
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
FROM solana_user_pda_current u
LEFT JOIN (
SELECT owner_login, COUNT(*)::INTEGER AS owned_public_channels_count
FROM channel_names_state
WHERE channel_type_code = 1
GROUP BY owner_login
) own ON LOWER(own.owner_login) = LOWER(u.login)
LEFT JOIN (
SELECT login, COUNT(*)::INTEGER AS following_users_count
FROM connections_state
WHERE rel_type = 30
AND to_block_number = 0
GROUP BY login
) fu ON LOWER(fu.login) = LOWER(u.login)
LEFT JOIN (
SELECT cs.login, COUNT(*)::INTEGER AS following_channels_count
// Followers of channels owned by this login are also affected while channel projections
// disappear and are recreated by replay.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT cs.login
FROM connections_state cs
JOIN channel_names_state cn
ON cn.owner_bch_name = cs.to_bch_name
AND cn.channel_root_block_number = cs.to_block_number
AND cn.channel_root_block_hash = cs.to_block_hash
WHERE cs.rel_type = 30
AND cn.channel_type_code = 1
GROUP BY cs.login
) fc ON LOWER(fc.login) = LOWER(u.login)
LEFT JOIN (
SELECT login, COUNT(*)::INTEGER AS close_friends_count
FROM connections_state
WHERE rel_type = 10
GROUP BY login
) cf ON LOWER(cf.login) = LOWER(u.login)
""")) {
ps.executeUpdate();
}
ON LOWER(cn.owner_login)=LOWER(?)
AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cs.to_block_number=cn.channel_root_block_number
AND cs.to_block_hash=cn.channel_root_block_hash
WHERE cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
delete(c,"DELETE FROM reactions_state WHERE LOWER(from_login)=LOWER(?)",login);
recountAffectedLikes(c);
delete(c,"DELETE FROM connections_state WHERE LOWER(login)=LOWER(?)",login);
refreshAffectedChannelStats(c);
delete(c,"DELETE FROM users_params WHERE LOWER(login)=LOWER(?)",login);
delete(c,"DELETE FROM channel_stats_state WHERE LOWER(owner_login)=LOWER(?)",login);
delete(c,"DELETE FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?)",login);
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_profile(login) FROM solana_user_pda_current")) {
ps.execute();
}
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
ps.execute();
}
try (PreparedStatement ps = c.prepareStatement("""
UPDATE message_stats ms SET
primary_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1
AND rs.to_login=ms.to_login AND rs.to_bch_name=ms.to_bch_name AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash
AND shine_is_primary(rs.from_login)),
shining_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1
AND rs.to_login=ms.to_login AND rs.to_bch_name=ms.to_bch_name AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash
AND shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))
""")) {
ps.executeUpdate();
}
// Notifications are projections of source blockchain blocks. Canonical replay recreates
// only the notifications that still exist on the selected branch.
delete(c,"DELETE FROM user_notifications_state WHERE LOWER(source_login)=LOWER(?)",login);
try (PreparedStatement ps = c.prepareStatement("""
INSERT INTO channel_stats_state (
owner_bch_name,
channel_root_block_number,
channel_root_block_hash,
owner_login,
channel_type_code,
subscribers_count,
updated_at_ms
)
SELECT
cn.owner_bch_name,
cn.channel_root_block_number,
cn.channel_root_block_hash,
cn.owner_login,
cn.channel_type_code,
COUNT(DISTINCT cs.login)::INTEGER AS subscribers_count,
CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
FROM channel_names_state cn
LEFT JOIN connections_state cs
ON cs.rel_type = 30
AND cs.to_bch_name = cn.owner_bch_name
AND cs.to_block_number = cn.channel_root_block_number
AND cs.to_block_hash = cn.channel_root_block_hash
WHERE cn.channel_type_code = 1
GROUP BY
cn.owner_bch_name,
cn.channel_root_block_number,
cn.channel_root_block_hash,
cn.owner_login,
cn.channel_type_code
""")) {
ps.executeUpdate();
}
}
// Chat200 is legacy/unused and is intentionally not maintained by segmented-fork replay.
delete(c,"DELETE FROM chat200_state WHERE LOWER(owner_login)=LOWER(?)",login);
delete(c,"DELETE FROM chat200_members_state WHERE owner_bch_name LIKE ?",login+"-%");
private int executeDelete(Connection c, String sql, String value) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, value);
return ps.executeUpdate();
}
delete(c,"DELETE FROM blocks_store WHERE LOWER(login)=LOWER(?)",login);
delete(c,"DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?)",login);
// With the old reply blocks gone, establish the exact baseline produced by all other
// actors. Replay will then add this actor's canonical replies exactly once.
recountAffectedReplies(c);
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_profile(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,login);ps.execute();}
refreshAffectedUserStats(c);
c.commit();
}catch(Exception e){c.rollback();if(e instanceof SQLException x)throw x;throw new SQLException("canonical replay cleanup failed",e);}finally{c.setAutoCommit(ac);}}
}
/**
* Технический результат cleanup-операции.
* Нужен для будущего логирования и ручной диагностики resync-flow.
* Repairs server-owned projections after canonical replay. It is safe to call repeatedly.
* Signed channel read watermarks are preserved; only server-owned unread values are recomputed.
*/
public record CleanupResult(
String login,
int likesAdjustedRows,
int repliesAdjustedRows,
int deletedMessageStatsRows,
int deletedReactionsStateRows,
int deletedConnectionsStateRows,
int deletedUsersParamsRows,
int deletedChannelNamesRows,
int deletedChat200StateRows,
int deletedChat200MembersRows,
int deletedBlocksRows,
int deletedBlockchainStateRows
) {}
public void finalizeCanonicalReplay(String login) throws SQLException {
if(login==null||login.isBlank())throw new IllegalArgumentException("login is blank");
try(Connection c=db.getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
// Remove view references to discarded messages of this user. Valid canonical targets survive.
try(PreparedStatement ps=c.prepareStatement("""
DELETE FROM message_views_state mv
WHERE LOWER(mv.to_login)=LOWER(?)
AND NOT EXISTS (
SELECT 1 FROM blocks_store b
WHERE LOWER(b.login)=LOWER(mv.to_login)
AND b.block_number=mv.to_block_number AND b.block_hash=mv.to_block_hash
)
""")){ps.setString(1,login);ps.executeUpdate();}
// Recompute all message aggregates whose target belongs to this user. This also fixes
// external reactions/replies that intentionally survive this user's rebuild.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,likes_count,primary_likes_count,shining_likes_count,replies_count)
SELECT t.login,t.block_number,t.block_hash,
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash),
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash AND shine_is_primary(r.from_login)),
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash AND shine_is_primary(r.from_login) AND shine_is_shining(r.from_login)),
(SELECT COUNT(*)::INTEGER FROM blocks_store rb WHERE rb.msg_type=1 AND rb.msg_sub_type=20 AND LOWER(rb.to_login)=LOWER(t.login) AND rb.to_block_number=t.block_number AND rb.to_block_hash=t.block_hash)
FROM blocks_store t
WHERE LOWER(t.login)=LOWER(?)
AND (
EXISTS(SELECT 1 FROM message_stats oldms WHERE LOWER(oldms.to_login)=LOWER(t.login) AND oldms.to_block_number=t.block_number AND oldms.to_block_hash=t.block_hash)
OR EXISTS(SELECT 1 FROM reactions_state r WHERE LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash)
OR EXISTS(SELECT 1 FROM blocks_store rb WHERE rb.msg_type=1 AND rb.msg_sub_type=20 AND LOWER(rb.to_login)=LOWER(t.login) AND rb.to_block_number=t.block_number AND rb.to_block_hash=t.block_hash)
)
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET
likes_count=EXCLUDED.likes_count,
primary_likes_count=EXCLUDED.primary_likes_count,
shining_likes_count=EXCLUDED.shining_likes_count,
replies_count=EXCLUDED.replies_count
""")){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("""
DELETE FROM message_stats ms
WHERE LOWER(ms.to_login)=LOWER(?)
AND NOT EXISTS (SELECT 1 FROM blocks_store b WHERE LOWER(b.login)=LOWER(ms.to_login) AND b.block_number=ms.to_block_number AND b.block_hash=ms.to_block_hash)
""")){ps.setString(1,login);ps.executeUpdate();}
// Recalculate social/channel aggregates from the final canonical projections.
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("""
SELECT shine_refresh_channel_follow_stats(owner_bch_name,channel_root_block_number,channel_root_block_hash)
FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?) AND channel_type_code=1
""")){ps.setString(1,login);ps.execute();}
ChannelReadStateDAO.getInstance().recalculateUnreadForOwnedChannels(c,login,System.currentTimeMillis());
c.commit();
}catch(Exception e){c.rollback();if(e instanceof SQLException x)throw x;throw new SQLException("canonical replay finalize failed",e);}finally{c.setAutoCommit(ac);}}
}
private void recountAffectedLikes(Connection c)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("""
UPDATE message_stats ms SET
likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash),
primary_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login)),
shining_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))
WHERE EXISTS(SELECT 1 FROM shine_cleanup_targets t WHERE t.to_login=ms.to_login AND t.to_block_number=ms.to_block_number AND t.to_block_hash=ms.to_block_hash)
""")){ps.executeUpdate();}
}
private void recountAffectedReplies(Connection c)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("""
UPDATE message_stats ms SET replies_count=(
SELECT COUNT(*)::INTEGER FROM blocks_store b
WHERE b.msg_type=1 AND b.msg_sub_type=20
AND LOWER(b.to_login)=LOWER(ms.to_login)
AND b.to_block_number=ms.to_block_number AND b.to_block_hash=ms.to_block_hash
)
WHERE EXISTS(SELECT 1 FROM shine_cleanup_reply_targets t
WHERE LOWER(t.to_login)=LOWER(ms.to_login) AND t.to_block_number=ms.to_block_number AND t.to_block_hash=ms.to_block_hash)
""")){ps.executeUpdate();}
}
private void refreshAffectedChannelStats(Connection c)throws SQLException{
try(PreparedStatement q=c.prepareStatement("SELECT owner_bch_name,root_number,root_hash FROM shine_cleanup_channels"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_channel_follow_stats(?,?,?)")){
while(rs.next()){p.setString(1,rs.getString(1));p.setInt(2,rs.getInt(2));p.setBytes(3,rs.getBytes(3));p.execute();}
}
}
private void refreshAffectedUserStats(Connection c)throws SQLException{
try(PreparedStatement q=c.prepareStatement("SELECT login FROM shine_cleanup_users"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){
while(rs.next()){p.setString(1,rs.getString(1));p.execute();}
}
}
private int delete(Connection c,String sql,String v)throws SQLException{try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,v);return ps.executeUpdate();}}
private record ChainRef(String login,int fork){}
private static ChainRef chainRef(String n){ if(n==null)throw new IllegalArgumentException("blockchainName is null"); String s=n.trim();int d=s.lastIndexOf('-');if(d<=0||s.length()-d-1!=3)throw new IllegalArgumentException("Bad blockchainName: "+n);try{int f=Integer.parseInt(s.substring(d+1));if(f<1||f>999)throw new IllegalArgumentException("fork out of range");return new ChainRef(s.substring(0,d),f);}catch(NumberFormatException e){throw new IllegalArgumentException("Bad blockchainName: "+n,e);} }
public record CleanupResult(String login,int deletedReactionsStateRows,int deletedConnectionsStateRows,int deletedUsersParamsRows,int deletedChannelNamesRows,int deletedChat200StateRows,int deletedChat200MembersRows,int deletedBlocksRows,int deletedBlockchainStateRows){}
}
@@ -34,8 +34,8 @@ public final class BlockchainStateDAO {
public BlockchainStateEntry getByBlockchainName(Connection c, String blockchainName) throws SQLException {
String sql = """
SELECT
blockchain_name,
login,
fork_number,
blockchain_key,
size_limit,
file_size_bytes,
@@ -43,11 +43,13 @@ public final class BlockchainStateDAO {
last_block_hash,
updated_at_ms
FROM blockchain_state
WHERE blockchain_name = ?
WHERE login = ? AND fork_number = ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, blockchainName);
ChainRef r=chainRef(blockchainName);
ps.setString(1, r.login());
ps.setInt(2, r.fork());
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
return mapRow(rs);
@@ -66,8 +68,8 @@ public final class BlockchainStateDAO {
public List<BlockchainStateEntry> listAll(Connection c) throws SQLException {
String sql = """
SELECT
blockchain_name,
login,
fork_number,
blockchain_key,
size_limit,
file_size_bytes,
@@ -75,7 +77,7 @@ public final class BlockchainStateDAO {
last_block_hash,
updated_at_ms
FROM blockchain_state
ORDER BY LOWER(blockchain_name)
ORDER BY LOWER(login), fork_number
""";
List<BlockchainStateEntry> result = new ArrayList<>();
@@ -98,9 +100,9 @@ public final class BlockchainStateDAO {
/** UPSERT с внешним соединением. Соединение НЕ закрывает. */
public void upsert(Connection c, BlockchainStateEntry e) throws SQLException {
String sql = """
INSERT INTO blockchain_state (
blockchain_name,
INSERT INTO blockchain_state_store (
login,
fork_number,
blockchain_key,
size_limit,
file_size_bytes,
@@ -108,9 +110,8 @@ public final class BlockchainStateDAO {
last_block_hash,
updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(blockchain_name)
ON CONFLICT(login, fork_number)
DO UPDATE SET
login = excluded.login,
blockchain_key = excluded.blockchain_key,
size_limit = excluded.size_limit,
file_size_bytes = excluded.file_size_bytes,
@@ -122,8 +123,8 @@ public final class BlockchainStateDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, e.getBlockchainName());
ps.setString(i++, nn(e.getLogin()));
ps.setInt(i++, e.getForkNumber());
ps.setString(i++, nn(e.getBlockchainKey()));
ps.setLong(i++, e.getSizeLimit());
@@ -148,9 +149,9 @@ public final class BlockchainStateDAO {
*/
public boolean insertIfMissing(Connection c, BlockchainStateEntry e) throws SQLException {
String sql = """
INSERT INTO blockchain_state (
blockchain_name,
INSERT INTO blockchain_state_store (
login,
fork_number,
blockchain_key,
size_limit,
file_size_bytes,
@@ -158,14 +159,14 @@ public final class BlockchainStateDAO {
last_block_hash,
updated_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(blockchain_name) DO NOTHING
ON CONFLICT(login, fork_number) DO NOTHING
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, e.getBlockchainName());
ps.setString(i++, nn(e.getLogin()));
ps.setInt(i++, e.getForkNumber());
ps.setString(i++, nn(e.getBlockchainKey()));
ps.setLong(i++, e.getSizeLimit());
@@ -191,20 +192,22 @@ public final class BlockchainStateDAO {
*/
public boolean tryIncreaseFileSizeWithinLimit(Connection c, String blockchainName, long deltaBytes, long nowMs) throws SQLException {
String sql = """
UPDATE blockchain_state
UPDATE blockchain_state_store
SET
file_size_bytes = file_size_bytes + ?,
updated_at_ms = ?
WHERE
blockchain_name = ?
login = ? AND fork_number = ?
AND (file_size_bytes + ?) <= size_limit
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setLong(1, deltaBytes);
ps.setLong(2, nowMs);
ps.setString(3, blockchainName);
ps.setLong(4, deltaBytes);
ChainRef r=chainRef(blockchainName);
ps.setString(3, r.login());
ps.setInt(4, r.fork());
ps.setLong(5, deltaBytes);
return ps.executeUpdate() > 0;
}
}
@@ -212,8 +215,8 @@ public final class BlockchainStateDAO {
private BlockchainStateEntry mapRow(ResultSet rs) throws SQLException {
BlockchainStateEntry e = new BlockchainStateEntry();
e.setBlockchainName(rs.getString("blockchain_name"));
e.setLogin(rs.getString("login"));
e.setForkNumber(rs.getInt("fork_number"));
e.setBlockchainKey(rs.getString("blockchain_key"));
e.setSizeLimit(rs.getLong("size_limit"));
@@ -227,6 +230,15 @@ public final class BlockchainStateDAO {
return e;
}
private record ChainRef(String login,int fork) {}
private static ChainRef chainRef(String name) {
if(name==null) throw new IllegalArgumentException("blockchainName is null");
String s=name.trim(); int d=s.lastIndexOf('-');
if(d<=0 || s.length()-d-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+name);
try { int f=Integer.parseInt(s.substring(d+1)); if(f<1||f>999) throw new IllegalArgumentException("fork out of range"); return new ChainRef(s.substring(0,d),f); }
catch(NumberFormatException e){ throw new IllegalArgumentException("Bad blockchainName: "+name,e); }
}
private static void setBytesNullable(PreparedStatement ps, int index, byte[] b) throws SQLException {
if (b != null) ps.setBytes(index, b);
else ps.setNull(index, Types.BINARY);
@@ -23,9 +23,9 @@ public final class BlocksDAO {
public void insert(Connection c, BlockEntry e) throws SQLException {
String sql = """
INSERT INTO blocks (
login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_bch_name,to_block_number,to_block_hash,
INSERT INTO blocks_store (
login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash,
block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
@@ -34,13 +34,13 @@ public final class BlocksDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
int i = 1;
ps.setString(i++, e.getLogin());
ps.setString(i++, e.getBchName());
ps.setInt(i++, e.getForkNumber());
ps.setInt(i++, e.getBlockNumber());
ps.setInt(i++, e.getMsgType());
ps.setInt(i++, e.getMsgSubType());
ps.setBytes(i++, e.getBlockBytes());
setNullableString(ps, i++, e.getToLogin());
setNullableString(ps, i++, e.getToBchName());
setNullableInt(ps, i++, e.getToForkNumber());
setNullableInt(ps, i++, e.getToBlockNumber());
setNullableBytes(ps, i++, e.getToBlockHash());
ps.setBytes(i++, e.getBlockHash());
@@ -68,16 +68,26 @@ public final class BlocksDAO {
}
}
/** Возвращает ещё не опубликованный пользовательский DataItem для быстрой Turbo-попытки. */
public BlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return null;
String sql = baseSelect() + " WHERE data_item_id=? AND arweave_publish_pending=TRUE LIMIT 1";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBytes(1, dataItemId);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? mapRow(rs) : null; }
}
}
public List<BlockEntry> listPendingArweave(int limit) throws SQLException {
int safeLimit = Math.max(1, Math.min(limit, 100_000));
String sql = """
SELECT login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_bch_name,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
FROM blocks
WHERE arweave_publish_pending = TRUE
ORDER BY bch_name ASC, block_number ASC
ORDER BY login ASC, fork_number ASC, block_number ASC
LIMIT ?
""";
List<BlockEntry> out = new ArrayList<>();
@@ -91,7 +101,7 @@ public final class BlocksDAO {
public void markArweavePublished(List<byte[]> dataItemIds, long publishedAtMs) throws SQLException {
if (dataItemIds == null || dataItemIds.isEmpty()) return;
String sql = """
UPDATE blocks
UPDATE blocks_store
SET arweave_publish_pending=FALSE, arweave_published_at_ms=?
WHERE data_item_id=?
""";
@@ -108,30 +118,45 @@ public final class BlocksDAO {
}
public byte[] getHashByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("SELECT block_hash FROM blocks WHERE bch_name=? AND block_number=? LIMIT 1")) {
ps.setString(1,bchName); ps.setInt(2,blockNumber);
try (PreparedStatement ps = c.prepareStatement("SELECT block_hash FROM blocks WHERE login=? AND fork_number=? AND block_number=? LIMIT 1")) {
ChainRef r=chainRef(bchName); ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber);
try (ResultSet rs=ps.executeQuery()) { return rs.next()?rs.getBytes(1):null; }
}
}
public byte[] getHashByNumber(String bchName, int blockNumber) throws SQLException { try(Connection c=db.getConnection()){return getHashByNumber(c,bchName,blockNumber);} }
public BlockEntry getByNumber(Connection c, String bchName, int blockNumber) throws SQLException {
String sql = baseSelect()+" WHERE bch_name=? AND block_number=? LIMIT 1";
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,bchName); ps.setInt(2,blockNumber); try(ResultSet rs=ps.executeQuery()){return rs.next()?mapRow(rs):null;} }
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND block_number=? LIMIT 1";
ChainRef r=chainRef(bchName);
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,blockNumber); try(ResultSet rs=ps.executeQuery()){return rs.next()?mapRow(rs):null;} }
}
public BlockEntry getByNumber(String bchName,int blockNumber)throws SQLException{try(Connection c=db.getConnection()){return getByNumber(c,bchName,blockNumber);} }
/** Последний принятый блок конкретной логической линии в текущем physical fork. */
public BlockEntry getLastLineBlock(Connection c, String bchName, int msgType, int lineCode) throws SQLException {
String sql = baseSelect()+" WHERE login=? AND fork_number=? AND msg_type=? AND line_code=? ORDER BY block_number DESC LIMIT 1";
ChainRef r=chainRef(bchName);
try(PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,r.login()); ps.setInt(2,r.fork()); ps.setInt(3,msgType); ps.setInt(4,lineCode);
try(ResultSet rs=ps.executeQuery()){ return rs.next()?mapRow(rs):null; }
}
}
public BlockEntry getLastLineBlock(String bchName, int msgType, int lineCode) throws SQLException {
try(Connection c=db.getConnection()){ return getLastLineBlock(c,bchName,msgType,lineCode); }
}
public List<BlockEntry> listRangeByNumber(String bchName,int from,int to)throws SQLException{try(Connection c=db.getConnection()){return listRangeByNumber(c,bchName,from,to);} }
public List<BlockEntry> listRangeByNumber(Connection c,String bchName,int from,int to)throws SQLException{
String sql=baseSelect()+" WHERE bch_name=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
String sql=baseSelect()+" WHERE login=? AND fork_number=? AND block_number>=? AND block_number<=? ORDER BY block_number ASC";
List<BlockEntry> out=new ArrayList<>();
try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,bchName);ps.setInt(2,from);ps.setInt(3,to);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(mapRow(rs));}}
ChainRef r=chainRef(bchName);
try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,r.login());ps.setInt(2,r.fork());ps.setInt(3,from);ps.setInt(4,to);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(mapRow(rs));}}
return out;
}
private static String baseSelect(){return """
SELECT login,bch_name,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_bch_name,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
SELECT login,fork_number,block_number,msg_type,msg_sub_type,block_bytes,
to_login,to_fork_number,to_block_number,to_block_hash,block_hash,block_signature,data_item_id,
arweave_publish_pending,arweave_published_at_ms,
edited_by_block_number,line_code,prev_line_number,prev_line_hash,this_line_number
FROM blocks
@@ -139,15 +164,27 @@ public final class BlocksDAO {
private BlockEntry mapRow(ResultSet rs)throws SQLException{
BlockEntry e=new BlockEntry();
e.setLogin(rs.getString("login")); e.setBchName(rs.getString("bch_name")); e.setBlockNumber(rs.getInt("block_number"));
e.setLogin(rs.getString("login")); e.setForkNumber(rs.getInt("fork_number")); e.setBlockNumber(rs.getInt("block_number"));
e.setMsgType(rs.getInt("msg_type")); e.setMsgSubType(rs.getInt("msg_sub_type")); e.setBlockBytes(rs.getBytes("block_bytes"));
e.setToLogin(rs.getString("to_login")); e.setToBchName(rs.getString("to_bch_name")); e.setToBlockNumber((Integer)rs.getObject("to_block_number")); e.setToBlockHash(rs.getBytes("to_block_hash"));
e.setToLogin(rs.getString("to_login")); e.setToForkNumber((Integer)rs.getObject("to_fork_number")); e.setToBlockNumber((Integer)rs.getObject("to_block_number")); e.setToBlockHash(rs.getBytes("to_block_hash"));
e.setBlockHash(rs.getBytes("block_hash")); e.setBlockSignature(rs.getBytes("block_signature")); e.setDataItemId(rs.getBytes("data_item_id"));
e.setArweavePublishPending(rs.getBoolean("arweave_publish_pending")); e.setArweavePublishedAtMs((Long)rs.getObject("arweave_published_at_ms"));
e.setEditedByBlockNumber((Integer)rs.getObject("edited_by_block_number")); e.setLineCode((Integer)rs.getObject("line_code")); e.setPrevLineNumber((Integer)rs.getObject("prev_line_number")); e.setPrevLineHash(rs.getBytes("prev_line_hash")); e.setThisLineNumber((Integer)rs.getObject("this_line_number"));
return e;
}
private record ChainRef(String login, int fork) {}
private static ChainRef chainRef(String name) {
if (name == null) throw new IllegalArgumentException("blockchainName is null");
String s=name.trim(); int dash=s.lastIndexOf('-');
if (dash <= 0 || s.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+name);
try {
int fork=Integer.parseInt(s.substring(dash+1));
if (fork < 1 || fork > 999) throw new IllegalArgumentException("fork out of range: "+name);
return new ChainRef(s.substring(0,dash),fork);
} catch(NumberFormatException ex){ throw new IllegalArgumentException("Bad blockchainName: "+name,ex); }
}
private static void setNullableString(PreparedStatement ps,int i,String v)throws SQLException{if(v==null)ps.setNull(i,Types.VARCHAR);else ps.setString(i,v);}
private static void setNullableInt(PreparedStatement ps,int i,Integer v)throws SQLException{if(v==null)ps.setNull(i,Types.INTEGER);else ps.setInt(i,v);}
private static void setNullableBytes(PreparedStatement ps,int i,byte[] v)throws SQLException{if(v==null)ps.setNull(i,Types.BINARY);else ps.setBytes(i,v);}
@@ -0,0 +1,36 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.entities.BlockEntry;
import java.sql.*;
/** Resolves a logical block number to the physical fork that owns it in a selected canonical history. */
public final class CanonicalChainResolver {
private static volatile CanonicalChainResolver instance;
private final DbController db=DbController.getInstance();
private final BlocksDAO blocks=BlocksDAO.getInstance();
private final BlockchainForkSegmentsDAO segments=BlockchainForkSegmentsDAO.getInstance();
private CanonicalChainResolver(){}
public static CanonicalChainResolver getInstance(){if(instance==null)synchronized(CanonicalChainResolver.class){if(instance==null)instance=new CanonicalChainResolver();}return instance;}
public BlockEntry getBlock(String blockchainName,int blockNumber)throws SQLException{try(Connection c=db.getConnection()){return getBlock(c,blockchainName,blockNumber);}}
public BlockEntry getBlock(Connection c,String blockchainName,int blockNumber)throws SQLException{
ChainRef r=ref(blockchainName); int physical=resolveFork(c,r.login,r.fork,blockNumber); return blocks.getByNumber(c,r.login+"-"+String.format("%03d",physical),blockNumber);
}
public byte[] getHash(String blockchainName,int blockNumber)throws SQLException{BlockEntry b=getBlock(blockchainName,blockNumber);return b==null?null:b.getBlockHash();}
public byte[] getHash(Connection c,String blockchainName,int blockNumber)throws SQLException{BlockEntry b=getBlock(c,blockchainName,blockNumber);return b==null?null:b.getBlockHash();}
public int resolveFork(Connection c,String login,int activeFork,int blockNumber)throws SQLException{
if(blockNumber<0)throw new IllegalArgumentException("blockNumber < 0"); int f=activeFork; int guard=0;
while(true){ if(++guard>1000)throw new SQLException("fork ancestry cycle for "+login); BlockchainForkSegmentsDAO.Segment s=segments.get(c,login,f);
if(s==null){ // legacy self-contained fork
return f;
}
if(s.parentForkNumber()==null || blockNumber>=s.firstPhysicalBlockNumber()) return f;
f=s.parentForkNumber();
}
}
public BlockEntry getLastLineBlock(Connection c,String blockchainName,int msgType,int lineCode,int beforeBlockExclusive)throws SQLException{
ChainRef r=ref(blockchainName); for(int n=beforeBlockExclusive-1;n>=0;n--){ BlockEntry b=getBlock(c,blockchainName,n); if(b!=null && b.getMsgType()==msgType && b.getLineCode()!=null && b.getLineCode()==lineCode)return b; } return null;
}
private record ChainRef(String login,int fork){}
private static ChainRef ref(String n){int d=n==null?-1:n.lastIndexOf('-');if(d<=0||n.length()-d-1!=3)throw new IllegalArgumentException("Bad blockchainName: "+n);return new ChainRef(n.substring(0,d),Integer.parseInt(n.substring(d+1)));}
}
@@ -28,11 +28,11 @@ public final class ChannelNameStateDAO {
String sql = """
SELECT 1
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_type_code = ? AND slug = ?
WHERE LOWER(owner_login) = LOWER(?) AND channel_type_code = ? AND slug = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBchName);
ps.setString(1, loginOf(ownerBchName));
ps.setInt(2, channelTypeCode);
ps.setString(3, slug);
try (ResultSet rs = ps.executeQuery()) {
@@ -100,7 +100,7 @@ public final class ChannelNameStateDAO {
ava_sha256 = ?,
ava_size = ?,
meta_updated_at_ms = ?
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, entry.getDisplayName() == null ? "" : entry.getDisplayName());
@@ -109,7 +109,7 @@ public final class ChannelNameStateDAO {
ps.setString(4, entry.getAvaSha256() == null ? "" : entry.getAvaSha256());
ps.setLong(5, Math.max(0L, entry.getAvaSize()));
ps.setLong(6, Math.max(0L, entry.getMetaUpdatedAtMs()));
ps.setString(7, entry.getOwnerBlockchainName());
ps.setString(7, entry.getOwnerLogin());
ps.setInt(8, entry.getChannelRootBlockNumber());
ps.executeUpdate();
}
@@ -120,10 +120,31 @@ public final class ChannelNameStateDAO {
insert(c, entry);
}
}
public boolean updateDeletedState(Connection c, String ownerBchName, int rootBlockNumber, boolean deleted, long deletedAtMs, Integer deletedBlockNumber) throws SQLException {
String sql = """
UPDATE channel_names_state
SET is_deleted = ?,
deleted_at_ms = ?,
deleted_block_number = ?
WHERE LOWER(owner_login) = LOWER(?)
AND channel_root_block_number = ?
AND is_deleted IS DISTINCT FROM ?
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setBoolean(1, deleted);
ps.setLong(2, deleted ? Math.max(0L, deletedAtMs) : 0L);
if (deleted && deletedBlockNumber != null) ps.setInt(3, deletedBlockNumber); else ps.setNull(3, java.sql.Types.INTEGER);
ps.setString(4, loginOf(ownerBchName));
ps.setInt(5, rootBlockNumber);
ps.setBoolean(6, deleted);
return ps.executeUpdate() > 0;
}
}
public String getSlugByOwnerAndRoot(String ownerBchName, int rootBlockNumber) throws SQLException {
String sql = "SELECT slug FROM channel_names_state WHERE owner_bch_name=? AND channel_root_block_number=? LIMIT 1";
String sql = "SELECT slug FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=? LIMIT 1";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBchName);
ps.setString(1, loginOf(ownerBchName));
ps.setInt(2, rootBlockNumber);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString(1) : null;
@@ -131,4 +152,5 @@ public final class ChannelNameStateDAO {
}
}
private static String loginOf(String bch){ if(bch==null)return ""; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch; }
}
@@ -39,12 +39,12 @@ public final class ChannelReadStateDAO {
String sql = """
SELECT read_count, unread_count, read_updated_at_ms, client_key, read_signature
FROM channel_read_state
WHERE LOWER(viewer_login)=LOWER(?) AND owner_bch_name=? AND channel_name=?
WHERE LOWER(viewer_login)=LOWER(?) AND LOWER(owner_login)=LOWER(?) AND channel_name=?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin);
ps.setString(2, ownerBchName);
ps.setString(2, loginFromChainName(ownerBchName));
ps.setString(3, channelName);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
@@ -74,12 +74,13 @@ public final class ChannelReadStateDAO {
JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=30
AND cs.to_bch_name=cns.owner_bch_name
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash
WHERE cns.owner_bch_name=crs.owner_bch_name
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
AND NOT cns.is_deleted
)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -101,10 +102,10 @@ public final class ChannelReadStateDAO {
JOIN connections_state cs
ON LOWER(cs.login)=LOWER(?)
AND cs.rel_type=?
AND cs.to_bch_name=cns.owner_bch_name
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash
WHERE cns.owner_bch_name=?
WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.slug=?
AND cns.channel_type_code=1
LIMIT 1
@@ -112,7 +113,7 @@ public final class ChannelReadStateDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin);
ps.setInt(2, followRelType);
ps.setString(3, ownerBchName);
ps.setString(3, loginFromChainName(ownerBchName));
ps.setString(4, channelName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
@@ -124,11 +125,11 @@ public final class ChannelReadStateDAO {
String sql = """
SELECT slug
FROM channel_names_state
WHERE owner_bch_name=? AND channel_root_block_number=? AND channel_type_code=1
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=? AND channel_type_code=1
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBchName);
ps.setString(1, loginFromChainName(ownerBchName));
ps.setInt(2, rootBlockNumber);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString("slug") : null;
@@ -141,11 +142,11 @@ public final class ChannelReadStateDAO {
String sql = """
SELECT channel_root_block_number
FROM channel_names_state
WHERE owner_bch_name=? AND slug=? AND channel_type_code=1
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBchName);
ps.setString(1, loginFromChainName(ownerBchName));
ps.setString(2, channelName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getInt("channel_root_block_number") : null;
@@ -157,11 +158,11 @@ public final class ChannelReadStateDAO {
String sql = """
SELECT owner_login
FROM channel_names_state
WHERE owner_bch_name=? AND slug=? AND channel_type_code=1
WHERE LOWER(owner_login)=LOWER(?) AND slug=? AND channel_type_code=1
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBchName);
ps.setString(1, loginFromChainName(ownerBchName));
ps.setString(2, channelName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getString("owner_login") : null;
@@ -189,9 +190,10 @@ public final class ChannelReadStateDAO {
read_count, unread_count,
read_updated_at_ms, client_key, read_signature, updated_at_ms
) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)
ON CONFLICT (viewer_login, owner_bch_name, channel_name)
ON CONFLICT (viewer_login, owner_login, channel_name)
DO UPDATE SET
owner_login = EXCLUDED.owner_login,
owner_bch_name = EXCLUDED.owner_bch_name,
unread_count = GREATEST(
0,
channel_read_state.unread_count -
@@ -209,7 +211,7 @@ public final class ChannelReadStateDAO {
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin);
ps.setString(2, ownerLogin);
ps.setString(3, ownerBchName);
ps.setString(3, loginFromChainName(ownerBchName));
ps.setString(4, channelName);
ps.setLong(5, Math.max(0L, readCount));
ps.setLong(6, readUpdatedAtMs);
@@ -244,7 +246,7 @@ public final class ChannelReadStateDAO {
UPDATE channel_read_state crs
SET unread_count = crs.unread_count + 1,
updated_at_ms = ?
WHERE crs.owner_bch_name = ?
WHERE LOWER(crs.owner_login)=LOWER(?)
AND crs.channel_name = ?
AND LOWER(crs.viewer_login) <> LOWER(crs.owner_login)
AND EXISTS (
@@ -253,10 +255,10 @@ public final class ChannelReadStateDAO {
JOIN connections_state cs
ON LOWER(cs.login)=LOWER(crs.viewer_login)
AND cs.rel_type=?
AND cs.to_bch_name=cns.owner_bch_name
AND LOWER(cs.to_login)=LOWER(cns.owner_login)
AND COALESCE(cs.to_block_number,0)=cns.channel_root_block_number
AND cs.to_block_hash=cns.channel_root_block_hash
WHERE cns.owner_bch_name=crs.owner_bch_name
WHERE LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name
AND cns.channel_type_code=1
)
@@ -265,7 +267,7 @@ public final class ChannelReadStateDAO {
List<String> affected = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setLong(1, nowMs);
ps.setString(2, ownerBchName);
ps.setString(2, loginFromChainName(ownerBchName));
ps.setString(3, channelName);
ps.setInt(4, followRelType);
try (ResultSet rs = ps.executeQuery()) {
@@ -282,17 +284,51 @@ public final class ChannelReadStateDAO {
DELETE FROM channel_read_state crs
USING channel_names_state cns
WHERE LOWER(crs.viewer_login)=LOWER(?)
AND crs.owner_bch_name=?
AND cns.owner_bch_name=crs.owner_bch_name
AND LOWER(crs.owner_login)=LOWER(?)
AND LOWER(cns.owner_login)=LOWER(crs.owner_login)
AND cns.slug=crs.channel_name
AND cns.channel_root_block_number=?
AND cns.channel_type_code=1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, viewerLogin);
ps.setString(2, ownerBchName);
ps.setString(2, loginFromChainName(ownerBchName));
ps.setInt(3, rootBlockNumber);
return ps.executeUpdate() > 0;
}
}
/**
* Recomputes server-owned unread counters for all public channels owned by one logical login.
* Signed read_count/read signature fields are preserved exactly. Safe to call repeatedly after replay.
*/
public int recalculateUnreadForOwnedChannels(Connection c, String ownerLogin, long nowMs) throws SQLException {
String sql = """
WITH counts AS (
SELECT cns.owner_login, cns.slug, COUNT(b.block_number)::BIGINT AS message_count
FROM channel_names_state cns
LEFT JOIN blocks_store b
ON LOWER(b.login)=LOWER(cns.owner_login)
AND b.line_code=cns.channel_root_block_number
AND b.msg_type=1
AND b.msg_sub_type IN (10,50,100,110,120,130)
WHERE LOWER(cns.owner_login)=LOWER(?)
AND cns.channel_type_code=1
GROUP BY cns.owner_login,cns.slug
)
UPDATE channel_read_state crs
SET unread_count=GREATEST(0, counts.message_count-crs.read_count),
updated_at_ms=?
FROM counts
WHERE LOWER(crs.owner_login)=LOWER(counts.owner_login)
AND crs.channel_name=counts.slug
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerLogin);
ps.setLong(2, nowMs);
return ps.executeUpdate();
}
}
private static String loginFromChainName(String bch){ if(bch==null)return null; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch; }
}
@@ -39,19 +39,14 @@ public final class ConnectionsStateDAO {
*/
public List<String> listOutgoingByRelTypeCanonical(Connection c, String loginAnyCase, int relType) throws SQLException {
String sql = """
SELECT COALESCE(u_login.login, u_bch.login, cs.to_login) AS friend_login
SELECT COALESCE(u_login.login, cs.to_login) AS friend_login
FROM connections_state cs
LEFT JOIN %s
ON LOWER(u_login.login) = LOWER(cs.to_login)
LEFT JOIN %s
ON LOWER(u_bch.blockchain_name) = LOWER(cs.to_bch_name)
WHERE LOWER(cs.login) = LOWER(?)
AND cs.rel_type = ?
ORDER BY friend_login
""".formatted(
CurrentUsersSql.usersSubquery("u_login"),
CurrentUsersSql.usersSubquery("u_bch")
);
""".formatted(CurrentUsersSql.usersSubquery("u_login"));
List<String> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
@@ -73,19 +68,14 @@ public final class ConnectionsStateDAO {
FROM connections_state cs
LEFT JOIN %s
ON LOWER(u_login.login) = LOWER(cs.to_login)
LEFT JOIN %s
ON LOWER(u_bch.blockchain_name) = LOWER(cs.to_bch_name)
WHERE LOWER(cs.login) = LOWER(?)
AND cs.rel_type = ?
AND (
LOWER(cs.to_login) = LOWER(?)
OR LOWER(COALESCE(u_login.login, u_bch.login, cs.to_login)) = LOWER(?)
OR LOWER(COALESCE(u_login.login, cs.to_login)) = LOWER(?)
)
LIMIT 1
""".formatted(
CurrentUsersSql.usersSubquery("u_login"),
CurrentUsersSql.usersSubquery("u_bch")
);
""".formatted(CurrentUsersSql.usersSubquery("u_login"));
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, loginAnyCase);
ps.setInt(2, relType);
@@ -104,33 +94,12 @@ public final class ConnectionsStateDAO {
String sql = """
SELECT COALESCE(u_actor.login, cs.login) AS friend_login
FROM connections_state cs
LEFT JOIN %s
ON LOWER(u_actor.login) = LOWER(cs.login)
LEFT JOIN %s
ON LOWER(u_target.login) = LOWER(?)
WHERE (
LOWER(cs.to_login) = LOWER(?)
OR (u_target.blockchain_name IS NOT NULL AND LOWER(cs.to_bch_name) = LOWER(u_target.blockchain_name))
)
AND cs.rel_type = ?
LEFT JOIN %s ON LOWER(u_actor.login)=LOWER(cs.login)
WHERE LOWER(cs.to_login)=LOWER(?) AND cs.rel_type=?
ORDER BY friend_login
""".formatted(
CurrentUsersSql.usersSubquery("u_actor"),
CurrentUsersSql.usersSubquery("u_target")
);
List<String> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, loginAnyCase);
ps.setString(2, loginAnyCase);
ps.setInt(3, relType);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String v = rs.getString("friend_login");
if (v != null) out.add(v);
}
}
}
""".formatted(CurrentUsersSql.usersSubquery("u_actor"));
List<String> out=new ArrayList<>();
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,loginAnyCase); ps.setInt(2,relType); try(ResultSet rs=ps.executeQuery()){while(rs.next()){String v=rs.getString("friend_login");if(v!=null)out.add(v);}}}
return out;
}
@@ -189,21 +158,17 @@ public final class ConnectionsStateDAO {
}
String sql = """
INSERT INTO connections_state (login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash) DO UPDATE SET
to_bch_name=excluded.to_bch_name,
to_block_number=excluded.to_block_number,
to_block_hash=excluded.to_block_hash
INSERT INTO connections_state (login, rel_type, to_login, to_block_number, to_block_hash)
VALUES (?, ?, ?, ?, ?)
ON CONFLICT(login, rel_type, to_login, to_block_number, to_block_hash) DO NOTHING
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setInt(2, relType);
ps.setString(3, toLogin);
ps.setString(4, toBchName);
if (toBlockNumber == null) ps.setNull(5, java.sql.Types.INTEGER); else ps.setInt(5, toBlockNumber);
ps.setBytes(6, toBlockHash);
if (toBlockNumber == null) ps.setNull(4, java.sql.Types.INTEGER); else ps.setInt(4, toBlockNumber);
ps.setBytes(5, toBlockHash);
ps.executeUpdate();
}
}
@@ -0,0 +1,250 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.entities.KeyRotationCandidateBlockEntry;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Хранилище candidate-блоков будущего fork во время ротации ключей. */
public final class KeyRotationCandidateBlocksDAO {
private static volatile KeyRotationCandidateBlocksDAO instance;
private final DbController db = DbController.getInstance();
private KeyRotationCandidateBlocksDAO() { }
public static KeyRotationCandidateBlocksDAO getInstance() {
if (instance == null) {
synchronized (KeyRotationCandidateBlocksDAO.class) {
if (instance == null) instance = new KeyRotationCandidateBlocksDAO();
}
}
return instance;
}
/**
* Идемпотентно сохраняет один candidate-блок.
* Повтор того же blockNumber допустим только при полном совпадении hash и DataItem id.
*/
public KeyRotationCandidateBlockEntry insertOrGet(Connection c, KeyRotationCandidateBlockEntry entry) throws SQLException {
KeyRotationCandidateBlockEntry existing = getByNumber(c, entry.getRotationSessionId(), entry.getBlockNumber());
if (existing != null) {
if (Arrays.equals(existing.getBlockHash(), entry.getBlockHash())
&& Arrays.equals(existing.getDataItemId(), entry.getDataItemId())) {
return existing;
}
throw new SQLException("Candidate block conflict at number=" + entry.getBlockNumber());
}
String sql = """
INSERT INTO key_rotation_candidate_blocks (
rotation_session_id, login, candidate_blockchain_name,
block_number, block_hash, data_item_id, block_bytes,
arweave_publish_pending, arweave_published_at_ms, created_at_ms
) VALUES (?, ?, ?, ?, ?, ?, ?, TRUE, NULL, ?)
""";
try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
int i = 1;
ps.setLong(i++, entry.getRotationSessionId());
ps.setString(i++, entry.getLogin());
ps.setString(i++, entry.getCandidateBlockchainName());
ps.setInt(i++, entry.getBlockNumber());
ps.setBytes(i++, entry.getBlockHash());
ps.setBytes(i++, entry.getDataItemId());
ps.setBytes(i++, entry.getBlockBytes());
ps.setLong(i++, entry.getCreatedAtMs());
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (!keys.next()) throw new SQLException("candidate block insert returned no id");
entry.setId(keys.getLong(1));
}
} catch (SQLException insertFailure) {
// Конкурирующий повтор из другой сессии мог успеть вставиться между SELECT и INSERT.
KeyRotationCandidateBlockEntry raced = getByNumber(c, entry.getRotationSessionId(), entry.getBlockNumber());
if (raced != null
&& Arrays.equals(raced.getBlockHash(), entry.getBlockHash())
&& Arrays.equals(raced.getDataItemId(), entry.getDataItemId())) {
return raced;
}
throw insertFailure;
}
entry.setArweavePublishPending(true);
return entry;
}
public KeyRotationCandidateBlockEntry getByNumber(Connection c, long sessionId, int blockNumber) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("""
SELECT * FROM key_rotation_candidate_blocks
WHERE rotation_session_id = ? AND block_number = ?
""")) {
ps.setLong(1, sessionId);
ps.setInt(2, blockNumber);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? map(rs) : null;
}
}
}
public int countStored(Connection c, long sessionId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("""
SELECT COUNT(*) FROM key_rotation_candidate_blocks WHERE rotation_session_id = ?
""")) {
ps.setLong(1, sessionId);
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getInt(1);
}
}
}
public int countPublished(Connection c, long sessionId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("""
SELECT COUNT(*) FROM key_rotation_candidate_blocks
WHERE rotation_session_id = ? AND arweave_publish_pending = FALSE
""")) {
ps.setLong(1, sessionId);
try (ResultSet rs = ps.executeQuery()) {
rs.next();
return rs.getInt(1);
}
}
}
/** Все candidate-блоки одной ротации в строгом порядке block_number. */
public List<KeyRotationCandidateBlockEntry> listBySession(Connection c, long sessionId) throws SQLException {
try (PreparedStatement ps = c.prepareStatement("""
SELECT * FROM key_rotation_candidate_blocks
WHERE rotation_session_id = ?
ORDER BY block_number
""")) {
ps.setLong(1, sessionId);
List<KeyRotationCandidateBlockEntry> out = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(map(rs));
}
return out;
}
}
/** Возвращает ещё не опубликованный candidate DataItem для быстрой Turbo-попытки. */
public KeyRotationCandidateBlockEntry getPendingArweaveByDataItemId(byte[] dataItemId) throws SQLException {
if (dataItemId == null || dataItemId.length != 32) return null;
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT * FROM key_rotation_candidate_blocks
WHERE data_item_id = ? AND arweave_publish_pending = TRUE
LIMIT 1
""")) {
ps.setBytes(1, dataItemId);
try (ResultSet rs = ps.executeQuery()) { return rs.next() ? map(rs) : null; }
}
}
/** Candidate-блоки имеют приоритет перед обычной очередью publisher-а. */
public List<KeyRotationCandidateBlockEntry> listPendingArweave(int limit) throws SQLException {
if (limit <= 0) return List.of();
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT * FROM key_rotation_candidate_blocks
WHERE arweave_publish_pending = TRUE
ORDER BY id
LIMIT ?
""")) {
ps.setInt(1, limit);
List<KeyRotationCandidateBlockEntry> out = new ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(map(rs));
}
return out;
}
}
/**
* Помечает DataItem опубликованными и синхронизирует progress_current ротации
* с реальным количеством DataItem, подтверждённых publisher-ом.
*/
public void markArweavePublished(List<byte[]> dataItemIds, long publishedAtMs) throws SQLException {
if (dataItemIds == null || dataItemIds.isEmpty()) return;
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
java.util.Set<Long> sessions = new java.util.HashSet<>();
try (PreparedStatement find = c.prepareStatement("""
SELECT rotation_session_id
FROM key_rotation_candidate_blocks
WHERE data_item_id = ?
""")) {
for (byte[] id : dataItemIds) {
find.setBytes(1, id);
try (ResultSet rs = find.executeQuery()) {
if (rs.next()) sessions.add(rs.getLong(1));
}
}
}
try (PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_candidate_blocks
SET arweave_publish_pending = FALSE,
arweave_published_at_ms = COALESCE(arweave_published_at_ms, ?)
WHERE data_item_id = ?
""")) {
for (byte[] id : dataItemIds) {
ps.setLong(1, publishedAtMs);
ps.setBytes(2, id);
ps.addBatch();
}
ps.executeBatch();
}
try (PreparedStatement progress = c.prepareStatement("""
UPDATE key_rotation_sessions s
SET progress_current = LEAST(s.progress_total, (
SELECT COUNT(*)::INTEGER
FROM key_rotation_candidate_blocks b
WHERE b.rotation_session_id = s.id
AND b.arweave_publish_pending = FALSE
)),
updated_at_ms = ?
WHERE s.id = ? AND s.status = 'COPYING_CHAIN'
""")) {
for (Long sessionId : sessions) {
progress.setLong(1, publishedAtMs);
progress.setLong(2, sessionId);
progress.addBatch();
}
progress.executeBatch();
}
c.commit();
} catch (Exception e) {
c.rollback();
if (e instanceof SQLException sql) throw sql;
throw new SQLException("Failed to mark candidate DataItems published", e);
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
private static KeyRotationCandidateBlockEntry map(ResultSet rs) throws SQLException {
KeyRotationCandidateBlockEntry e = new KeyRotationCandidateBlockEntry();
e.setId(rs.getLong("id"));
e.setRotationSessionId(rs.getLong("rotation_session_id"));
e.setLogin(rs.getString("login"));
e.setCandidateBlockchainName(rs.getString("candidate_blockchain_name"));
e.setBlockNumber(rs.getInt("block_number"));
e.setBlockHash(rs.getBytes("block_hash"));
e.setDataItemId(rs.getBytes("data_item_id"));
e.setBlockBytes(rs.getBytes("block_bytes"));
e.setArweavePublishPending(rs.getBoolean("arweave_publish_pending"));
e.setArweavePublishedAtMs((Long) rs.getObject("arweave_published_at_ms"));
e.setCreatedAtMs(rs.getLong("created_at_ms"));
return e;
}
}
@@ -0,0 +1,612 @@
package shine.db.dao;
import shine.db.DbController;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* DAO для серверной машины смены ключей.
*
* Все методы изменения статуса синхронно обновляют и key_rotation_sessions,
* и solana_user_pda_current.rotation_status / rotation_session_id.
*/
public final class KeyRotationSessionsDAO {
private static volatile KeyRotationSessionsDAO instance;
private final DbController db = DbController.getInstance();
private KeyRotationSessionsDAO() { }
public static KeyRotationSessionsDAO getInstance() {
if (instance == null) {
synchronized (KeyRotationSessionsDAO.class) {
if (instance == null) instance = new KeyRotationSessionsDAO();
}
}
return instance;
}
/**
* Атомарно создаёт первую серверную запись ротации сразу в COPYING_CHAIN.
* PREPARING в БД отсутствует: до этого момента всё является локальным UI-состоянием.
*/
public KeyRotationSessionEntry createCopyingSession(KeyRotationSessionEntry entry) throws SQLException {
validateNewSession(entry);
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
KeyRotationSessionEntry created = createCopyingSession(c, entry);
c.commit();
return created;
} catch (Exception e) {
c.rollback();
if (e instanceof SQLException sql) throw sql;
throw new SQLException("Failed to create key rotation session", e);
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
public KeyRotationSessionEntry createCopyingSession(Connection c, KeyRotationSessionEntry entry) throws SQLException {
validateNewSession(entry);
String currentStatus;
try (PreparedStatement ps = c.prepareStatement("""
SELECT rotation_status
FROM solana_user_pda_current
WHERE login = ?
FOR UPDATE
""")) {
ps.setString(1, entry.getLogin());
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) throw new SQLException("Unknown login for key rotation: " + entry.getLogin());
currentStatus = rs.getString(1);
}
}
if (!KeyRotationStatus.NONE.name().equals(currentStatus)) {
throw new SQLException("Key rotation already active for login=" + entry.getLogin() + ", status=" + currentStatus);
}
long now = entry.getCreatedAtMs() > 0 ? entry.getCreatedAtMs() : System.currentTimeMillis();
entry.setCreatedAtMs(now);
entry.setUpdatedAtMs(now);
entry.setStatus(KeyRotationStatus.COPYING_CHAIN);
if (entry.getComment() == null) entry.setComment("");
if (entry.getWalletMigrationStatus() == null) entry.setWalletMigrationStatus("PENDING");
if (entry.getMessageMigrationStatus() == null) entry.setMessageMigrationStatus("PENDING");
String sql = """
INSERT INTO key_rotation_sessions (
login, status,
source_blockchain_name, candidate_blockchain_name,
old_root_key, old_blockchain_key, old_client_key,
new_root_key, new_blockchain_key, new_client_key,
fork_from_block, fork_from_hash,
source_tip_block, source_tip_hash,
reason_code, comment,
progress_current, progress_total,
pda_rotation_signature,
wallet_migration_status, message_migration_status,
last_error, last_error_at_ms, retry_count,
created_at_ms, updated_at_ms, completed_at_ms, aborted_at_ms
) VALUES (
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
)
""";
long id;
try (PreparedStatement ps = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
int i = 1;
ps.setString(i++, entry.getLogin());
ps.setString(i++, entry.getStatus().name());
ps.setString(i++, entry.getSourceBlockchainName());
ps.setString(i++, entry.getCandidateBlockchainName());
ps.setString(i++, entry.getOldRootKey());
ps.setString(i++, entry.getOldBlockchainKey());
ps.setString(i++, entry.getOldClientKey());
ps.setString(i++, entry.getNewRootKey());
ps.setString(i++, entry.getNewBlockchainKey());
ps.setString(i++, entry.getNewClientKey());
ps.setInt(i++, entry.getForkFromBlock());
ps.setBytes(i++, entry.getForkFromHash());
ps.setInt(i++, entry.getSourceTipBlock());
ps.setBytes(i++, entry.getSourceTipHash());
ps.setShort(i++, entry.getReasonCode());
ps.setString(i++, entry.getComment());
ps.setInt(i++, entry.getProgressCurrent());
ps.setInt(i++, entry.getProgressTotal());
ps.setString(i++, entry.getPdaRotationSignature());
ps.setString(i++, entry.getWalletMigrationStatus());
ps.setString(i++, entry.getMessageMigrationStatus());
ps.setString(i++, entry.getLastError());
if (entry.getLastErrorAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getLastErrorAtMs());
ps.setInt(i++, entry.getRetryCount());
ps.setLong(i++, entry.getCreatedAtMs());
ps.setLong(i++, entry.getUpdatedAtMs());
if (entry.getCompletedAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getCompletedAtMs());
if (entry.getAbortedAtMs() == null) ps.setNull(i++, java.sql.Types.BIGINT); else ps.setLong(i++, entry.getAbortedAtMs());
ps.executeUpdate();
try (ResultSet keys = ps.getGeneratedKeys()) {
if (!keys.next()) throw new SQLException("key_rotation_sessions insert returned no id");
id = keys.getLong(1);
}
}
try (PreparedStatement ps = c.prepareStatement("""
UPDATE solana_user_pda_current
SET rotation_status = ?, rotation_session_id = ?
WHERE login = ? AND rotation_status = 'NONE'
""")) {
ps.setString(1, KeyRotationStatus.COPYING_CHAIN.name());
ps.setLong(2, id);
ps.setString(3, entry.getLogin());
if (ps.executeUpdate() != 1) {
throw new SQLException("Failed to attach key rotation session to login=" + entry.getLogin());
}
}
entry.setId(id);
return entry;
}
public KeyRotationSessionEntry getById(long id) throws SQLException {
try (Connection c = db.getConnection()) {
return getById(c, id);
}
}
public KeyRotationSessionEntry getById(Connection c, long id) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(selectBase() + " WHERE id = ?")) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
public KeyRotationSessionEntry getActiveByLogin(String login) throws SQLException {
try (Connection c = db.getConnection()) {
return getActiveByLogin(c, login);
}
}
public KeyRotationSessionEntry getActiveByLogin(Connection c, String login) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(selectBase() + """
WHERE login = ?
AND status NOT IN ('COMPLETE', 'ABORTED')
ORDER BY id DESC
LIMIT 1
""")) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
/** Возвращает несколько сессий одного состояния для фоновых workers. */
public java.util.List<KeyRotationSessionEntry> listByStatus(KeyRotationStatus status, int limit) throws SQLException {
if (status == null || status == KeyRotationStatus.NONE) return java.util.List.of();
int safeLimit = Math.max(1, Math.min(limit, 100));
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement(selectBase() + """
WHERE status = ?
ORDER BY updated_at_ms, id
LIMIT ?
""")) {
ps.setString(1, status.name());
ps.setInt(2, safeLimit);
java.util.List<KeyRotationSessionEntry> out = new java.util.ArrayList<>();
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(mapRow(rs));
}
return out;
}
}
/**
* Атомарный переход state machine. Смена статуса выполняется только из expected.
*/
public KeyRotationSessionEntry transition(long id,
KeyRotationStatus expected,
KeyRotationStatus next) throws SQLException {
if (expected == null || next == null || !expected.canTransitionTo(next)) {
throw new IllegalArgumentException("Forbidden key rotation transition: " + expected + " -> " + next);
}
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
if (current == null) throw new SQLException("Unknown key rotation session id=" + id);
if (current.getStatus() != expected) {
throw new SQLException("Key rotation status mismatch: expected=" + expected + ", actual=" + current.getStatus());
}
long now = System.currentTimeMillis();
Long completed = current.getCompletedAtMs();
if (next == KeyRotationStatus.COMPLETE) completed = now;
Long aborted = current.getAbortedAtMs();
if (next == KeyRotationStatus.ABORTED) aborted = now;
try (PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET status = ?, updated_at_ms = ?, completed_at_ms = ?, aborted_at_ms = ?
WHERE id = ? AND status = ?
""")) {
ps.setString(1, next.name());
ps.setLong(2, now);
if (completed == null) ps.setNull(3, java.sql.Types.BIGINT); else ps.setLong(3, completed);
if (aborted == null) ps.setNull(4, java.sql.Types.BIGINT); else ps.setLong(4, aborted);
ps.setLong(5, id);
ps.setString(6, expected.name());
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent key rotation transition for id=" + id);
}
KeyRotationStatus userStatus = next.userStatus();
try (PreparedStatement ps = c.prepareStatement("""
UPDATE solana_user_pda_current
SET rotation_status = ?, rotation_session_id = ?
WHERE login = ? AND rotation_session_id = ?
""")) {
ps.setString(1, userStatus.name());
if (userStatus == KeyRotationStatus.NONE) ps.setNull(2, java.sql.Types.BIGINT); else ps.setLong(2, id);
ps.setString(3, current.getLogin());
ps.setLong(4, id);
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to login=" + current.getLogin());
}
// Candidate-копии нужны только пока ротация активна. В Arweave они уже опубликованы,
// а в PostgreSQL после COMPLETE/ABORTED временные строки больше не нужны.
if (next.isTerminalSessionStatus()) {
try (PreparedStatement ps = c.prepareStatement(
"DELETE FROM key_rotation_candidate_blocks WHERE rotation_session_id = ?")) {
ps.setLong(1, id);
ps.executeUpdate();
}
}
c.commit();
current.setStatus(next);
current.setUpdatedAtMs(now);
current.setCompletedAtMs(completed);
current.setAbortedAtMs(aborted);
return current;
} catch (Exception e) {
c.rollback();
if (e instanceof SQLException sql) throw sql;
throw new SQLException("Failed key rotation transition", e);
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
public void updateProgress(long id, int current, int total) throws SQLException {
if (current < 0 || total < 0 || current > total) {
throw new IllegalArgumentException("Invalid rotation progress: " + current + "/" + total);
}
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET progress_current = ?, progress_total = ?, updated_at_ms = ?
WHERE id = ? AND status = 'COPYING_CHAIN'
""")) {
ps.setInt(1, current);
ps.setInt(2, total);
ps.setLong(3, System.currentTimeMillis());
ps.setLong(4, id);
if (ps.executeUpdate() != 1) throw new SQLException("Rotation progress can only be updated in COPYING_CHAIN, id=" + id);
}
}
/**
* Атомарно фиксирует tx signature и переводит CHAIN_READY -> ROTATING_PDA.
* Это точка, после которой Abort запрещён: отправленная Solana-транзакция может подтвердиться позже.
*/
public KeyRotationSessionEntry beginPdaRotation(long id, String signature) throws SQLException {
if (signature == null || signature.isBlank()) throw new IllegalArgumentException("signature is empty");
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
if (current == null) throw new SQLException("Unknown key rotation session id=" + id);
if (current.getStatus() != KeyRotationStatus.CHAIN_READY) {
throw new SQLException("PDA rotation requires CHAIN_READY, actual=" + current.getStatus());
}
long now = System.currentTimeMillis();
try (PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET status = 'ROTATING_PDA', pda_rotation_signature = ?, updated_at_ms = ?,
last_error = NULL, last_error_at_ms = NULL
WHERE id = ? AND status = 'CHAIN_READY'
""")) {
ps.setString(1, signature);
ps.setLong(2, now);
ps.setLong(3, id);
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent PDA rotation start for id=" + id);
}
try (PreparedStatement ps = c.prepareStatement("""
UPDATE solana_user_pda_current
SET rotation_status = 'ROTATING_PDA', rotation_session_id = ?
WHERE login = ? AND rotation_session_id = ? AND rotation_status = 'CHAIN_READY'
""")) {
ps.setLong(1, id);
ps.setString(2, current.getLogin());
ps.setLong(3, id);
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to login=" + current.getLogin());
}
c.commit();
current.setStatus(KeyRotationStatus.ROTATING_PDA);
current.setPdaRotationSignature(signature);
current.setUpdatedAtMs(now);
current.setLastError(null);
current.setLastErrorAtMs(null);
return current;
} catch (Exception e) {
c.rollback();
if (e instanceof SQLException sql) throw sql;
throw new SQLException("Failed to begin PDA rotation", e);
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
/**
* Если Solana sync уже записал в current-PDA весь ожидаемый новый набор ключей,
* атомарно переводит ROTATING_PDA -> PDA_ROTATED. Иначе возвращает null.
*/
public KeyRotationSessionEntry tryMarkPdaRotatedFromCurrentState(long id) throws SQLException {
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
KeyRotationSessionEntry current = getByIdForUpdate(c, id);
if (current == null || current.getStatus() != KeyRotationStatus.ROTATING_PDA) {
c.rollback();
return current != null && current.getStatus() == KeyRotationStatus.PDA_ROTATED ? current : null;
}
String root;
String blockchain;
String client;
String blockchainName;
try (PreparedStatement ps = c.prepareStatement("""
SELECT root_key, blockchain_key, client_key, blockchain_name
FROM solana_user_pda_current
WHERE login = ?
FOR UPDATE
""")) {
ps.setString(1, current.getLogin());
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) { c.rollback(); return null; }
root = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("root_key"));
blockchain = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("blockchain_key"));
client = shine.db.KeyEncodingUtil.normalizeKeyToBase64_32(rs.getString("client_key"));
blockchainName = rs.getString("blockchain_name");
}
}
if (!current.getNewRootKey().equals(root)
|| !current.getNewBlockchainKey().equals(blockchain)
|| !current.getNewClientKey().equals(client)
|| !current.getCandidateBlockchainName().equals(blockchainName)) {
c.rollback();
return null;
}
long now = System.currentTimeMillis();
try (PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET status = 'PDA_ROTATED', updated_at_ms = ?, last_error = NULL, last_error_at_ms = NULL
WHERE id = ? AND status = 'ROTATING_PDA'
""")) {
ps.setLong(1, now);
ps.setLong(2, id);
if (ps.executeUpdate() != 1) throw new SQLException("Concurrent PDA rotation confirm for id=" + id);
}
try (PreparedStatement ps = c.prepareStatement("""
UPDATE solana_user_pda_current
SET rotation_status = 'PDA_ROTATED', rotation_session_id = ?
WHERE login = ? AND rotation_session_id = ? AND rotation_status = 'ROTATING_PDA'
""")) {
ps.setLong(1, id);
ps.setString(2, current.getLogin());
ps.setLong(3, id);
if (ps.executeUpdate() != 1) throw new SQLException("Rotation session is not attached to current PDA login=" + current.getLogin());
}
c.commit();
current.setStatus(KeyRotationStatus.PDA_ROTATED);
current.setUpdatedAtMs(now);
current.setLastError(null);
current.setLastErrorAtMs(null);
return current;
} catch (Exception e) {
c.rollback();
if (e instanceof SQLException sql) throw sql;
throw new SQLException("Failed to confirm rotated PDA", e);
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
}
public void setPdaRotationSignature(long id, String signature) throws SQLException {
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET pda_rotation_signature = ?, updated_at_ms = ?
WHERE id = ? AND status = 'ROTATING_PDA'
""")) {
ps.setString(1, signature);
ps.setLong(2, System.currentTimeMillis());
ps.setLong(3, id);
if (ps.executeUpdate() != 1) throw new SQLException("PDA signature requires ROTATING_PDA, id=" + id);
}
}
/**
* Фиксирует результат необязательного этапа wallet/DM.
* Имя колонки выбирается только из закрытого списка — внешние значения в SQL не подставляются.
*/
public void setMigrationSubStatus(long id, String column, String value) throws SQLException {
String safeColumn = switch (String.valueOf(column)) {
case "wallet_migration_status" -> "wallet_migration_status";
case "message_migration_status" -> "message_migration_status";
default -> throw new IllegalArgumentException("Unsupported migration status column: " + column);
};
String safeValue = switch (String.valueOf(value)) {
case "PENDING", "COMPLETE", "SKIPPED", "NOT_IMPLEMENTED" -> String.valueOf(value);
default -> throw new IllegalArgumentException("Unsupported migration status value: " + value);
};
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement(
"UPDATE key_rotation_sessions SET " + safeColumn + " = ?, updated_at_ms = ? WHERE id = ?")) {
ps.setString(1, safeValue);
ps.setLong(2, System.currentTimeMillis());
ps.setLong(3, id);
if (ps.executeUpdate() != 1) throw new SQLException("Unknown key rotation session id=" + id);
}
}
public void recordError(long id, String error) throws SQLException {
long now = System.currentTimeMillis();
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET last_error = ?, last_error_at_ms = ?, retry_count = retry_count + 1, updated_at_ms = ?
WHERE id = ? AND status NOT IN ('COMPLETE', 'ABORTED')
""")) {
ps.setString(1, error);
ps.setLong(2, now);
ps.setLong(3, now);
ps.setLong(4, id);
if (ps.executeUpdate() != 1) throw new SQLException("Cannot record error for inactive rotation id=" + id);
}
}
public void clearError(long id) throws SQLException {
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
UPDATE key_rotation_sessions
SET last_error = NULL, last_error_at_ms = NULL, updated_at_ms = ?
WHERE id = ?
""")) {
ps.setLong(1, System.currentTimeMillis());
ps.setLong(2, id);
ps.executeUpdate();
}
}
private KeyRotationSessionEntry getByIdForUpdate(Connection c, long id) throws SQLException {
try (PreparedStatement ps = c.prepareStatement(selectBase() + " WHERE id = ? FOR UPDATE")) {
ps.setLong(1, id);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
private static String selectBase() {
return """
SELECT
id, login, status,
source_blockchain_name, candidate_blockchain_name,
old_root_key, old_blockchain_key, old_client_key,
new_root_key, new_blockchain_key, new_client_key,
fork_from_block, fork_from_hash,
source_tip_block, source_tip_hash,
reason_code, comment,
progress_current, progress_total,
pda_rotation_signature,
wallet_migration_status, message_migration_status,
last_error, last_error_at_ms, retry_count,
created_at_ms, updated_at_ms, completed_at_ms, aborted_at_ms
FROM key_rotation_sessions
""";
}
private static KeyRotationSessionEntry mapRow(ResultSet rs) throws SQLException {
KeyRotationSessionEntry e = new KeyRotationSessionEntry();
e.setId(rs.getLong("id"));
e.setLogin(rs.getString("login"));
e.setStatus(KeyRotationStatus.valueOf(rs.getString("status")));
e.setSourceBlockchainName(rs.getString("source_blockchain_name"));
e.setCandidateBlockchainName(rs.getString("candidate_blockchain_name"));
e.setOldRootKey(rs.getString("old_root_key"));
e.setOldBlockchainKey(rs.getString("old_blockchain_key"));
e.setOldClientKey(rs.getString("old_client_key"));
e.setNewRootKey(rs.getString("new_root_key"));
e.setNewBlockchainKey(rs.getString("new_blockchain_key"));
e.setNewClientKey(rs.getString("new_client_key"));
e.setForkFromBlock(rs.getInt("fork_from_block"));
e.setForkFromHash(rs.getBytes("fork_from_hash"));
e.setSourceTipBlock(rs.getInt("source_tip_block"));
e.setSourceTipHash(rs.getBytes("source_tip_hash"));
e.setReasonCode(rs.getShort("reason_code"));
e.setComment(rs.getString("comment"));
e.setProgressCurrent(rs.getInt("progress_current"));
e.setProgressTotal(rs.getInt("progress_total"));
e.setPdaRotationSignature(rs.getString("pda_rotation_signature"));
e.setWalletMigrationStatus(rs.getString("wallet_migration_status"));
e.setMessageMigrationStatus(rs.getString("message_migration_status"));
e.setLastError(rs.getString("last_error"));
long lastErrorAt = rs.getLong("last_error_at_ms");
e.setLastErrorAtMs(rs.wasNull() ? null : lastErrorAt);
e.setRetryCount(rs.getInt("retry_count"));
e.setCreatedAtMs(rs.getLong("created_at_ms"));
e.setUpdatedAtMs(rs.getLong("updated_at_ms"));
long completed = rs.getLong("completed_at_ms");
e.setCompletedAtMs(rs.wasNull() ? null : completed);
long aborted = rs.getLong("aborted_at_ms");
e.setAbortedAtMs(rs.wasNull() ? null : aborted);
return e;
}
private static void validateNewSession(KeyRotationSessionEntry e) {
if (e == null) throw new IllegalArgumentException("entry is null");
if (blank(e.getLogin())) throw new IllegalArgumentException("login is required");
if (blank(e.getSourceBlockchainName()) || blank(e.getCandidateBlockchainName())) {
throw new IllegalArgumentException("source/candidate blockchain names are required");
}
if (blank(e.getOldRootKey()) || blank(e.getOldBlockchainKey()) || blank(e.getOldClientKey())
|| blank(e.getNewRootKey()) || blank(e.getNewBlockchainKey()) || blank(e.getNewClientKey())) {
throw new IllegalArgumentException("all old/new public keys are required");
}
if (e.getForkFromHash() == null || e.getForkFromHash().length != 32) {
throw new IllegalArgumentException("forkFromHash must be 32 bytes");
}
if (e.getSourceTipHash() == null || e.getSourceTipHash().length != 32) {
throw new IllegalArgumentException("sourceTipHash must be 32 bytes");
}
if (e.getForkFromBlock() < 0 || e.getSourceTipBlock() < e.getForkFromBlock()) {
throw new IllegalArgumentException("invalid fork/source tip block numbers");
}
if (e.getReasonCode() < 1 || e.getReasonCode() > 4) {
throw new IllegalArgumentException("reasonCode must be 1..4");
}
String comment = e.getComment() == null ? "" : e.getComment();
if (comment.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 1024) {
throw new IllegalArgumentException("comment must be <= 1024 UTF-8 bytes");
}
if (e.getProgressCurrent() < 0 || e.getProgressTotal() < e.getProgressCurrent()) {
throw new IllegalArgumentException("invalid initial progress");
}
}
private static boolean blank(String value) {
return value == null || value.isBlank();
}
}
@@ -377,6 +377,7 @@ public final class SignedMessagesDAO {
String peerLogin,
long beforeTimeMs,
String beforeMessageKey,
long reencryptedBeforeMs,
int limit
) throws Exception {
try (Connection c = db.getConnection()) {
@@ -398,6 +399,7 @@ public final class SignedMessagesDAO {
OR time_ms < ?
OR (time_ms = ? AND (? = '' OR message_key < ?))
)
AND (? <= 0 OR (created_at_ms <= ? AND reencrypted_at_ms < ?))
ORDER BY time_ms DESC, message_key DESC
LIMIT ?
""".formatted(messagesTable());
@@ -413,7 +415,10 @@ public final class SignedMessagesDAO {
ps.setLong(8, beforeTimeMs);
ps.setString(9, beforeMessageKey == null ? "" : beforeMessageKey);
ps.setString(10, beforeMessageKey == null ? "" : beforeMessageKey);
ps.setInt(11, limit);
ps.setLong(11, reencryptedBeforeMs);
ps.setLong(12, reencryptedBeforeMs);
ps.setLong(13, reencryptedBeforeMs);
ps.setInt(14, limit);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) out.add(mapRow(rs));
}
@@ -422,6 +427,102 @@ public final class SignedMessagesDAO {
}
}
public long countMessagesNeedingReencryption(String login, long reencryptedBeforeMs) throws SQLException {
if (reencryptedBeforeMs <= 0) return 0;
try (Connection c = db.getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT COUNT(*)
FROM %s
WHERE LOWER(target_login) = LOWER(?)
AND message_type IN (1, 2)
AND created_at_ms <= ?
AND reencrypted_at_ms < ?
""".formatted(messagesTable()))) {
ps.setString(1, login);
ps.setLong(2, reencryptedBeforeMs);
ps.setLong(3, reencryptedBeforeMs);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getLong(1) : 0L;
}
}
}
/** Обновляет только уже существующую локальную type=1/2 копию при key rotation. */
public ApplyStatus upsertReencryptedLocalCopy(SignedMessageEntry next) throws Exception {
return withBusyRetry(() -> {
try (Connection c = db.getConnection()) {
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
SignedMessageEntry current = getByMessageKey(c, next.getMessageKey());
if (current == null) { c.rollback(); return ApplyStatus.DUPLICATE_OR_OLDER; }
if (current.getMessageType() != next.getMessageType()
|| current.getTimeMs() != next.getTimeMs()
|| current.getNonce() != next.getNonce()
|| current.getRevisionTimeMs() != next.getRevisionTimeMs()
|| !current.getFromLogin().equalsIgnoreCase(next.getFromLogin())
|| !current.getToLogin().equalsIgnoreCase(next.getToLogin())
|| !current.getBaseKey().equals(next.getBaseKey())
|| next.getReencryptedAtMs() <= current.getReencryptedAtMs()) {
c.rollback();
return ApplyStatus.DUPLICATE_OR_OLDER;
}
updateReencryptedLocalCopy(c, next);
DmDialogStateDAO.getInstance().refreshConversationPair(c, next.getFromLogin(), next.getToLogin());
c.commit();
return ApplyStatus.APPLIED;
} catch (Exception e) {
try { c.rollback(); } catch (Exception ignored) {}
throw e;
} finally {
c.setAutoCommit(oldAutoCommit);
}
}
});
}
/**
* Перезаписывает только криптографическую локальную копию сообщения при key rotation.
* Исторические metadata (created_at_ms/source_api/origin_session_id/read_at_ms) сохраняются.
*/
private void updateReencryptedLocalCopy(Connection c, SignedMessageEntry next) throws SQLException {
String sql = """
UPDATE %s
SET reencrypted_at_ms = ?,
raw_block = ?
WHERE message_key = ?
AND reencrypted_at_ms < ?
""".formatted(messagesTable());
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setLong(1, next.getReencryptedAtMs());
ps.setBytes(2, next.getRawBlock());
ps.setString(3, next.getMessageKey());
ps.setLong(4, next.getReencryptedAtMs());
int changed = ps.executeUpdate();
if (changed != 1) {
throw new SQLException("Reencrypted local copy was not updated: " + next.getMessageKey());
}
}
}
private SignedMessageEntry getByMessageKey(Connection c, String messageKey) throws Exception {
String sql = """
SELECT
message_key, base_key, target_login, from_login, to_login,
time_ms, nonce, message_type, revision_time_ms, reencrypted_at_ms,
raw_block, created_at_ms, source_api, origin_session_id,
receipt_ref_base_key, receipt_ref_type, read_at_ms
FROM %s
WHERE message_key = ?
""".formatted(messagesTable());
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, messageKey);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
public SyncBatch listSyncBatch(
String ownerLogin,
long afterStoredAtMs,
@@ -37,6 +37,27 @@ public final class SolanaUserPdaCurrentDAO {
}
}
public SolanaUserPdaCurrentEntry getByLogin(String login) throws SQLException {
String sql = """
SELECT
login,
blockchain_name,
blockchain_key,
paid_limit_bytes
FROM solana_user_pda_current
WHERE LOWER(login) = LOWER(?)
LIMIT 1
""";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
return mapRow(rs);
}
}
}
public SolanaUserPdaCurrentEntry getByBlockchainName(Connection c, String blockchainName) throws SQLException {
String sql = """
SELECT
@@ -73,6 +94,7 @@ public final class SolanaUserPdaCurrentDAO {
FROM solana_user_pda_current u
CROSS JOIN LATERAL jsonb_array_elements(COALESCE(NULLIF(u.blockchain_forks_json, ''), '[]')::jsonb) AS fork_item(value)
WHERE fork_item.value ->> 'blockchainKey' = ?
AND ((fork_item.value ->> 'forkIndex')::integer + 1) BETWEEN 1 AND 999
LIMIT 1
""";
try (Connection c = db.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
@@ -106,11 +106,12 @@ public final class SubscriptionsDAO {
WITH subs AS (
-- 1) FOLLOW-каналы
SELECT
cs.to_login AS channel_login,
cs.to_bch_name AS channel_bch_name
cs.to_login AS channel_login,
cn.owner_bch_name AS channel_bch_name
FROM connections_state cs
WHERE cs.login = ?
AND cs.rel_type = ?
JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login)
AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
WHERE cs.login = ? AND cs.rel_type = ?
UNION
@@ -37,9 +37,8 @@ public final class UserProfileStateDAO {
/**
* Effective outgoing social relation with priority close_friend > friend > contact > none.
*
* Use the canonical relation lookup instead of comparing only connections_state.to_login:
* older/current blocks may address a user by blockchain name, so a direct to_login-only
* query can incorrectly report "none" even when ListContacts/Connections sees the relation.
* Use the canonical relation lookup so all UI paths share the same normalized login matching.
* Stage 2 connections_state identity is logical and no longer contains a physical target fork.
*/
public String getEffectiveRelationType(Connection c, String ownerLogin, String targetLogin) throws SQLException {
if (ownerLogin == null || ownerLogin.isBlank() || targetLogin == null || targetLogin.isBlank()) return "none";
@@ -112,31 +111,48 @@ public final class UserProfileStateDAO {
return out;
}
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, int limit, int offset) throws SQLException {
public List<ChannelCard> listPublicChannels(Connection c, String login, String mode, boolean includeDeleted, int limit, int offset) throws SQLException {
int safeLimit=Math.max(1,Math.min(limit<=0?100:limit,500)), safeOffset=Math.max(0,offset);
String sql;
if ("owned".equals(mode)) {
sql="""
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash
FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1
SELECT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
FROM channel_names_state cn
WHERE LOWER(cn.owner_login)=LOWER(?) AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
""";
} else if ("following".equals(mode)) {
sql="""
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.owner_bch_name, cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash
FROM connections_state cs JOIN channel_names_state cn ON cn.owner_bch_name=cs.to_bch_name 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(?) AND cs.rel_type=30 AND cn.channel_type_code=1
SELECT DISTINCT cn.owner_login, cn.slug, cn.display_name, cn.ava_ar, cn.ava_sha256, cn.owner_bch_name,
cn.channel_root_block_number, encode(cn.channel_root_block_hash,'hex') root_hash,
cn.is_deleted, cn.deleted_at_ms, cn.deleted_block_number
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(?) AND cs.rel_type=30 AND cn.channel_type_code=1 AND (? OR NOT cn.is_deleted)
ORDER BY cn.display_name, cn.slug LIMIT ? OFFSET ?
""";
} else throw new IllegalArgumentException("Unsupported channel mode: "+mode);
List<ChannelCard> out=new ArrayList<>();
try(PreparedStatement ps=c.prepareStatement(sql)){ ps.setString(1,login);ps.setInt(2,safeLimit);ps.setInt(3,safeOffset);
try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(new ChannelCard(rs.getString("owner_login"),rs.getString("slug"),rs.getString("display_name"),rs.getString("ava_ar"),rs.getString("owner_bch_name"),rs.getInt("channel_root_block_number"),rs.getString("root_hash")));}}
try(PreparedStatement ps=c.prepareStatement(sql)){
ps.setString(1,login); ps.setBoolean(2,includeDeleted); ps.setInt(3,safeLimit); ps.setInt(4,safeOffset);
try(ResultSet rs=ps.executeQuery()){
while(rs.next()) out.add(new ChannelCard(
rs.getString("owner_login"), rs.getString("slug"), rs.getString("display_name"), rs.getString("ava_ar"), rs.getString("ava_sha256"),
rs.getString("owner_bch_name"), rs.getInt("channel_root_block_number"), rs.getString("root_hash"),
rs.getBoolean("is_deleted"), rs.getLong("deleted_at_ms"), (Integer) rs.getObject("deleted_block_number")
));
}
}
return out;
}
private static ProfileCard map(ResultSet rs)throws SQLException{return new ProfileCard(rs.getString("login"),rs.getString("first_name"),rs.getString("last_name"),rs.getString("ava_ar"),rs.getString("account_role"),rs.getString("shine_status"));}
public record ProfileCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus){}
public record RelationCard(String login,String firstName,String lastName,String avatarAr,String accountRole,String shineStatus,boolean primaryConfirmed,boolean shineConfirmed,String relationType,int primaryConfirmationsCount,int shineConfirmationsCount){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex){}
public record ChannelCard(String ownerLogin,String slug,String displayName,String avatarAr,String avatarSha256,String ownerBlockchainName,int rootBlockNumber,String rootBlockHashHex,boolean deleted,long deletedAtMs,Integer deletedBlockNumber){}
}
@@ -4,7 +4,7 @@ package shine.db.entities;
* Запись блока (таблица blocks) — обновлённая модель под новый формат.
*
* Храним:
* - login, bch_name (как было в проекте, чтобы не ломать общую БД)
* - login + fork_number (physical fork identity; bch_name is derived only for display/API)
* - block_number (глобальный номер в этой цепочке)
* - block_bytes (полный блок: preimage + signature)
* - block_hash (32 байта вычисленный SHA-256(preimage))
@@ -21,7 +21,7 @@ package shine.db.entities;
public class BlockEntry {
private String login;
private String bchName;
private int forkNumber;
private int blockNumber;
@@ -31,7 +31,7 @@ public class BlockEntry {
private byte[] blockBytes;
private String toLogin;
private String toBchName;
private Integer toForkNumber;
private Integer toBlockNumber;
private byte[] toBlockHash;
@@ -55,8 +55,14 @@ public class BlockEntry {
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getBchName() { return bchName; }
public void setBchName(String bchName) { this.bchName = bchName; }
public int getForkNumber() { return forkNumber; }
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
/** Compatibility/display helper. DB does not store bch_name anymore. */
public String getBchName() {
if (login == null || login.isBlank() || forkNumber < 1 || forkNumber > 999) return null;
return login + "-" + String.format("%03d", forkNumber);
}
public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
@@ -73,8 +79,14 @@ public class BlockEntry {
public String getToLogin() { return toLogin; }
public void setToLogin(String toLogin) { this.toLogin = toLogin; }
public String getToBchName() { return toBchName; }
public void setToBchName(String toBchName) { this.toBchName = toBchName; }
/** Derived historical display value only; never part of target identity. */
public String getToBchName() {
if (toLogin == null || toLogin.isBlank() || toForkNumber == null || toForkNumber < 1 || toForkNumber > 999) return null;
return toLogin + "-" + String.format("%03d", toForkNumber);
}
public Integer getToForkNumber() { return toForkNumber; }
public void setToForkNumber(Integer toForkNumber) { if (toForkNumber != null && (toForkNumber < 1 || toForkNumber > 999)) throw new IllegalArgumentException("toForkNumber must be 1..999"); this.toForkNumber = toForkNumber; }
public Integer getToBlockNumber() { return toBlockNumber; }
public void setToBlockNumber(Integer toBlockNumber) { this.toBlockNumber = toBlockNumber; }
@@ -16,8 +16,8 @@ import java.util.Base64;
*/
public final class BlockchainStateEntry {
private String blockchainName;
private String login;
private int forkNumber;
private String blockchainKey; // Base64(32)
@@ -31,8 +31,22 @@ public final class BlockchainStateEntry {
public BlockchainStateEntry() {}
public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
public String getBlockchainName() {
if (login == null || login.isBlank() || forkNumber < 1 || forkNumber > 999) return null;
return login + "-" + String.format("%03d", forkNumber);
}
/** Compatibility setter for API/import code; DB stores login + forkNumber. */
public void setBlockchainName(String blockchainName) {
if (blockchainName == null) return;
int dash=blockchainName.lastIndexOf('-');
if (dash <= 0 || blockchainName.length()-dash-1 != 3) throw new IllegalArgumentException("Bad blockchainName: "+blockchainName);
int parsedFork=Integer.parseInt(blockchainName.substring(dash+1));
if (parsedFork < 1 || parsedFork > 999) throw new IllegalArgumentException("forkNumber must be 1..999");
this.login=blockchainName.substring(0,dash);
this.forkNumber=parsedFork;
}
public int getForkNumber() { return forkNumber; }
public void setForkNumber(int forkNumber) { if (forkNumber < 1 || forkNumber > 999) throw new IllegalArgumentException("forkNumber must be 1..999"); this.forkNumber = forkNumber; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
@@ -0,0 +1,45 @@
package shine.db.entities;
/**
* Candidate-блок будущего fork во время смены ключей.
*
* Эти записи намеренно не попадают в обычную таблицу blocks и поэтому
* не влияют на лайки, ответы, каналы и другие materialized state до
* финального переключения активного fork.
*/
public final class KeyRotationCandidateBlockEntry {
private long id;
private long rotationSessionId;
private String login;
private String candidateBlockchainName;
private int blockNumber;
private byte[] blockHash;
private byte[] dataItemId;
private byte[] blockBytes;
private boolean arweavePublishPending;
private Long arweavePublishedAtMs;
private long createdAtMs;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public long getRotationSessionId() { return rotationSessionId; }
public void setRotationSessionId(long rotationSessionId) { this.rotationSessionId = rotationSessionId; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getCandidateBlockchainName() { return candidateBlockchainName; }
public void setCandidateBlockchainName(String candidateBlockchainName) { this.candidateBlockchainName = candidateBlockchainName; }
public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
public byte[] getBlockHash() { return blockHash; }
public void setBlockHash(byte[] blockHash) { this.blockHash = blockHash; }
public byte[] getDataItemId() { return dataItemId; }
public void setDataItemId(byte[] dataItemId) { this.dataItemId = dataItemId; }
public byte[] getBlockBytes() { return blockBytes; }
public void setBlockBytes(byte[] blockBytes) { this.blockBytes = blockBytes; }
public boolean isArweavePublishPending() { return arweavePublishPending; }
public void setArweavePublishPending(boolean arweavePublishPending) { this.arweavePublishPending = arweavePublishPending; }
public Long getArweavePublishedAtMs() { return arweavePublishedAtMs; }
public void setArweavePublishedAtMs(Long arweavePublishedAtMs) { this.arweavePublishedAtMs = arweavePublishedAtMs; }
public long getCreatedAtMs() { return createdAtMs; }
public void setCreatedAtMs(long createdAtMs) { this.createdAtMs = createdAtMs; }
}
@@ -0,0 +1,96 @@
package shine.db.entities;
/**
* Публичное/runtime-состояние одной смены ключей.
* Приватные ключи и пароли в этой сущности не хранятся никогда.
*/
public final class KeyRotationSessionEntry {
private long id;
private String login;
private KeyRotationStatus status;
private String sourceBlockchainName;
private String candidateBlockchainName;
private String oldRootKey;
private String oldBlockchainKey;
private String oldClientKey;
private String newRootKey;
private String newBlockchainKey;
private String newClientKey;
private int forkFromBlock;
private byte[] forkFromHash;
private int sourceTipBlock;
private byte[] sourceTipHash;
private short reasonCode;
private String comment;
private int progressCurrent;
private int progressTotal;
private String pdaRotationSignature;
private String walletMigrationStatus;
private String messageMigrationStatus;
private String lastError;
private Long lastErrorAtMs;
private int retryCount;
private long createdAtMs;
private long updatedAtMs;
private Long completedAtMs;
private Long abortedAtMs;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public KeyRotationStatus getStatus() { return status; }
public void setStatus(KeyRotationStatus status) { this.status = status; }
public String getSourceBlockchainName() { return sourceBlockchainName; }
public void setSourceBlockchainName(String sourceBlockchainName) { this.sourceBlockchainName = sourceBlockchainName; }
public String getCandidateBlockchainName() { return candidateBlockchainName; }
public void setCandidateBlockchainName(String candidateBlockchainName) { this.candidateBlockchainName = candidateBlockchainName; }
public String getOldRootKey() { return oldRootKey; }
public void setOldRootKey(String oldRootKey) { this.oldRootKey = oldRootKey; }
public String getOldBlockchainKey() { return oldBlockchainKey; }
public void setOldBlockchainKey(String oldBlockchainKey) { this.oldBlockchainKey = oldBlockchainKey; }
public String getOldClientKey() { return oldClientKey; }
public void setOldClientKey(String oldClientKey) { this.oldClientKey = oldClientKey; }
public String getNewRootKey() { return newRootKey; }
public void setNewRootKey(String newRootKey) { this.newRootKey = newRootKey; }
public String getNewBlockchainKey() { return newBlockchainKey; }
public void setNewBlockchainKey(String newBlockchainKey) { this.newBlockchainKey = newBlockchainKey; }
public String getNewClientKey() { return newClientKey; }
public void setNewClientKey(String newClientKey) { this.newClientKey = newClientKey; }
public int getForkFromBlock() { return forkFromBlock; }
public void setForkFromBlock(int forkFromBlock) { this.forkFromBlock = forkFromBlock; }
public byte[] getForkFromHash() { return forkFromHash; }
public void setForkFromHash(byte[] forkFromHash) { this.forkFromHash = forkFromHash; }
public int getSourceTipBlock() { return sourceTipBlock; }
public void setSourceTipBlock(int sourceTipBlock) { this.sourceTipBlock = sourceTipBlock; }
public byte[] getSourceTipHash() { return sourceTipHash; }
public void setSourceTipHash(byte[] sourceTipHash) { this.sourceTipHash = sourceTipHash; }
public short getReasonCode() { return reasonCode; }
public void setReasonCode(short reasonCode) { this.reasonCode = reasonCode; }
public String getComment() { return comment; }
public void setComment(String comment) { this.comment = comment; }
public int getProgressCurrent() { return progressCurrent; }
public void setProgressCurrent(int progressCurrent) { this.progressCurrent = progressCurrent; }
public int getProgressTotal() { return progressTotal; }
public void setProgressTotal(int progressTotal) { this.progressTotal = progressTotal; }
public String getPdaRotationSignature() { return pdaRotationSignature; }
public void setPdaRotationSignature(String pdaRotationSignature) { this.pdaRotationSignature = pdaRotationSignature; }
public String getWalletMigrationStatus() { return walletMigrationStatus; }
public void setWalletMigrationStatus(String walletMigrationStatus) { this.walletMigrationStatus = walletMigrationStatus; }
public String getMessageMigrationStatus() { return messageMigrationStatus; }
public void setMessageMigrationStatus(String messageMigrationStatus) { this.messageMigrationStatus = messageMigrationStatus; }
public String getLastError() { return lastError; }
public void setLastError(String lastError) { this.lastError = lastError; }
public Long getLastErrorAtMs() { return lastErrorAtMs; }
public void setLastErrorAtMs(Long lastErrorAtMs) { this.lastErrorAtMs = lastErrorAtMs; }
public int getRetryCount() { return retryCount; }
public void setRetryCount(int retryCount) { this.retryCount = retryCount; }
public long getCreatedAtMs() { return createdAtMs; }
public void setCreatedAtMs(long createdAtMs) { this.createdAtMs = createdAtMs; }
public long getUpdatedAtMs() { return updatedAtMs; }
public void setUpdatedAtMs(long updatedAtMs) { this.updatedAtMs = updatedAtMs; }
public Long getCompletedAtMs() { return completedAtMs; }
public void setCompletedAtMs(Long completedAtMs) { this.completedAtMs = completedAtMs; }
public Long getAbortedAtMs() { return abortedAtMs; }
public void setAbortedAtMs(Long abortedAtMs) { this.abortedAtMs = abortedAtMs; }
}
@@ -0,0 +1,71 @@
package shine.db.entities;
import java.util.EnumSet;
import java.util.Set;
/**
* Состояния серверной машины смены ключей.
*
* NONE используется только в solana_user_pda_current.rotation_status.
* COMPLETE/ABORTED остаются в истории key_rotation_sessions, после чего
* пользователь снова получает rotation_status=NONE.
*/
public enum KeyRotationStatus {
NONE,
COPYING_CHAIN,
CHAIN_READY,
ROTATING_PDA,
PDA_ROTATED,
REBUILDING_SERVER,
WALLET_MIGRATION,
MESSAGE_MIGRATION,
FINALIZING,
COMPLETE,
ABORTED;
public boolean isTerminalSessionStatus() {
return this == COMPLETE || this == ABORTED;
}
public boolean isUserActiveStatus() {
return this != NONE && !isTerminalSessionStatus();
}
/**
* Допустимые переходы одной ротации.
* Abort сознательно разрешён только до начала ROTATING_PDA: после отправки
* Solana-транзакции нельзя надёжно знать, не будет ли она подтверждена позже.
*/
public boolean canTransitionTo(KeyRotationStatus next) {
if (next == null) return false;
return switch (this) {
case COPYING_CHAIN -> EnumSet.of(CHAIN_READY, ABORTED).contains(next);
case CHAIN_READY -> EnumSet.of(ROTATING_PDA, ABORTED).contains(next);
case ROTATING_PDA -> next == PDA_ROTATED;
case PDA_ROTATED -> next == REBUILDING_SERVER;
case REBUILDING_SERVER -> next == WALLET_MIGRATION;
case WALLET_MIGRATION -> next == MESSAGE_MIGRATION;
case MESSAGE_MIGRATION -> next == FINALIZING;
case FINALIZING -> next == COMPLETE;
case NONE, COMPLETE, ABORTED -> false;
};
}
public static Set<KeyRotationStatus> activeStatuses() {
return EnumSet.of(
COPYING_CHAIN,
CHAIN_READY,
ROTATING_PDA,
PDA_ROTATED,
REBUILDING_SERVER,
WALLET_MIGRATION,
MESSAGE_MIGRATION,
FINALIZING
);
}
/** Статус, который должен храниться у пользователя для данной session-state. */
public KeyRotationStatus userStatus() {
return isTerminalSessionStatus() ? NONE : this;
}
}
@@ -0,0 +1,123 @@
-- v26: серверная state machine смены ключей пользователя.
--
-- Важно:
-- - rotation_status / rotation_session_id являются ЛОКАЛЬНЫМ runtime-состоянием сервера,
-- а не полями Solana PDA;
-- - Solana sync не должен перезаписывать эти колонки при upsert PDA;
-- - приватные ключи здесь никогда не хранятся, только публичные ключи ротации.
ALTER TABLE solana_user_pda_current
ADD COLUMN IF NOT EXISTS rotation_status TEXT NOT NULL DEFAULT 'NONE';
ALTER TABLE solana_user_pda_current
ADD COLUMN IF NOT EXISTS rotation_session_id BIGINT;
ALTER TABLE solana_user_pda_current
DROP CONSTRAINT IF EXISTS chk_solana_user_pda_current_rotation_status;
ALTER TABLE solana_user_pda_current
ADD CONSTRAINT chk_solana_user_pda_current_rotation_status CHECK (
rotation_status IN (
'NONE',
'COPYING_CHAIN',
'CHAIN_READY',
'ROTATING_PDA',
'PDA_ROTATED',
'REBUILDING_SERVER',
'WALLET_MIGRATION',
'MESSAGE_MIGRATION',
'FINALIZING'
)
);
CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_rotation_active
ON solana_user_pda_current(rotation_status)
WHERE rotation_status <> 'NONE';
CREATE TABLE IF NOT EXISTS key_rotation_sessions (
id BIGSERIAL PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE,
status TEXT NOT NULL CHECK (
status IN (
'COPYING_CHAIN',
'CHAIN_READY',
'ROTATING_PDA',
'PDA_ROTATED',
'REBUILDING_SERVER',
'WALLET_MIGRATION',
'MESSAGE_MIGRATION',
'FINALIZING',
'COMPLETE',
'ABORTED'
)
),
source_blockchain_name TEXT NOT NULL,
candidate_blockchain_name TEXT NOT NULL,
old_root_key TEXT NOT NULL,
old_blockchain_key TEXT NOT NULL,
old_client_key TEXT NOT NULL,
new_root_key TEXT NOT NULL,
new_blockchain_key TEXT NOT NULL,
new_client_key TEXT NOT NULL,
fork_from_block INTEGER NOT NULL CHECK (fork_from_block >= 0),
fork_from_hash BYTEA NOT NULL CHECK (octet_length(fork_from_hash) = 32),
source_tip_block INTEGER NOT NULL CHECK (source_tip_block >= 0),
source_tip_hash BYTEA NOT NULL CHECK (octet_length(source_tip_hash) = 32),
reason_code SMALLINT NOT NULL CHECK (reason_code BETWEEN 1 AND 4),
comment TEXT NOT NULL DEFAULT '' CHECK (octet_length(convert_to(comment, 'UTF8')) <= 1024),
progress_current INTEGER NOT NULL DEFAULT 0 CHECK (progress_current >= 0),
progress_total INTEGER NOT NULL DEFAULT 0 CHECK (progress_total >= 0),
pda_rotation_signature TEXT,
wallet_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
wallet_migration_status IN ('PENDING', 'COMPLETE', 'SKIPPED', 'NOT_IMPLEMENTED')
),
message_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
message_migration_status IN ('PENDING', 'COMPLETE', 'SKIPPED', 'NOT_IMPLEMENTED')
),
last_error TEXT,
last_error_at_ms BIGINT,
retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
created_at_ms BIGINT NOT NULL,
updated_at_ms BIGINT NOT NULL,
completed_at_ms BIGINT,
aborted_at_ms BIGINT,
CHECK (progress_current <= progress_total),
CHECK (fork_from_block <= source_tip_block)
);
-- У одного login одновременно может существовать только одна незавершённая ротация.
CREATE UNIQUE INDEX IF NOT EXISTS uq_key_rotation_sessions_active_login
ON key_rotation_sessions(login)
WHERE status NOT IN ('COMPLETE', 'ABORTED');
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_login_created
ON key_rotation_sessions(login, created_at_ms DESC);
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_status
ON key_rotation_sessions(status);
-- Быстрый указатель из текущего пользователя на активную/последнюю runtime-сессию.
-- FK добавляется после создания key_rotation_sessions, чтобы не создавать циклический DDL порядок.
ALTER TABLE solana_user_pda_current
DROP CONSTRAINT IF EXISTS fk_solana_user_pda_current_rotation_session;
ALTER TABLE solana_user_pda_current
ADD CONSTRAINT fk_solana_user_pda_current_rotation_session
FOREIGN KEY (rotation_session_id)
REFERENCES key_rotation_sessions(id)
ON DELETE SET NULL;
UPDATE db_schema_version
SET schema_version = 26,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
@@ -0,0 +1,31 @@
BEGIN;
CREATE TABLE IF NOT EXISTS key_rotation_candidate_blocks (
id BIGSERIAL PRIMARY KEY,
rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE,
login TEXT NOT NULL,
candidate_blockchain_name TEXT NOT NULL,
block_number INTEGER NOT NULL CHECK (block_number >= 0),
block_hash BYTEA NOT NULL CHECK (octet_length(block_hash) = 32),
data_item_id BYTEA NOT NULL CHECK (octet_length(data_item_id) = 32),
block_bytes BYTEA NOT NULL,
arweave_publish_pending BOOLEAN NOT NULL DEFAULT TRUE,
arweave_published_at_ms BIGINT,
created_at_ms BIGINT NOT NULL,
UNIQUE (rotation_session_id, block_number),
UNIQUE (rotation_session_id, data_item_id)
);
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_pending
ON key_rotation_candidate_blocks(id)
WHERE arweave_publish_pending = TRUE;
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_session
ON key_rotation_candidate_blocks(rotation_session_id, block_number);
UPDATE db_schema_version
SET schema_version = 27,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -0,0 +1,32 @@
BEGIN;
ALTER TABLE channel_names_state
ADD COLUMN IF NOT EXISTS is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
ADD COLUMN IF NOT EXISTS deleted_at_ms BIGINT NOT NULL DEFAULT 0,
ADD COLUMN IF NOT EXISTS deleted_block_number INTEGER;
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(p_login) AND shine_target_accepts_primary_confirmation(cs.to_login)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(p_login) AND shine_is_shining(p_login) AND shine_target_accepts_shine_confirmation(cs.to_login)),v_now
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
UPDATE db_schema_version
SET schema_version = 31,
updated_at_ms = CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT)
WHERE id = 1;
COMMIT;
@@ -1,5 +1,6 @@
-- SHiNE PostgreSQL runtime schema v1
-- Дата: 2026-07-28
-- SHiNE PostgreSQL database format v2 / runtime schema revision 30
-- Stage 2 baseline. This file is only for a NEW, EMPTY database.
-- Дата: 2026-09-29
--
-- Назначение:
-- - поднять пустую PostgreSQL БД сервера SHiNE с нуля;
@@ -15,14 +16,42 @@
BEGIN;
-- Safety guard: DB v2 is a fresh-baseline format, not an in-place migration.
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM information_schema.tables
WHERE table_schema = current_schema()
AND table_type = 'BASE TABLE'
) THEN
RAISE EXCEPTION 'SHiNE_DB_V2 bootstrap requires an empty PostgreSQL schema; legacy/in-place migration is disabled';
END IF;
END
$$;
CREATE TABLE IF NOT EXISTS db_schema_version (
id INTEGER PRIMARY KEY,
schema_version INTEGER NOT NULL,
updated_at_ms BIGINT NOT NULL
);
-- Hard database-generation marker. Stage 2 server MUST NOT run on an older SHiNE DB.
CREATE TABLE IF NOT EXISTS shine_database_metadata (
id INTEGER PRIMARY KEY CHECK (id = 1),
database_format TEXT NOT NULL CHECK (database_format = 'SHiNE_DB_V2'),
database_generation INTEGER NOT NULL CHECK (database_generation = 2),
created_at_ms BIGINT NOT NULL
);
INSERT INTO shine_database_metadata(id, database_format, database_generation, created_at_ms)
VALUES (1, 'SHiNE_DB_V2', 2, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
ON CONFLICT (id) DO NOTHING;
COMMENT ON TABLE shine_database_metadata IS 'SHiNE database generation marker. Stage 2 requires SHiNE_DB_V2 / generation 2.';
INSERT INTO db_schema_version (id, schema_version, updated_at_ms)
VALUES (1, 24, CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT))
VALUES (1, 29, 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;
@@ -494,6 +523,7 @@ CREATE TABLE IF NOT EXISTS blocks (
block_bytes BYTEA NOT NULL,
to_login TEXT,
to_bch_name TEXT,
to_fork_number INTEGER CHECK (to_fork_number IS NULL OR (to_fork_number >= 0 AND to_fork_number <= 999)),
to_block_number INTEGER CHECK (to_block_number IS NULL OR to_block_number >= 0),
to_block_hash BYTEA,
block_hash BYTEA NOT NULL,
@@ -535,18 +565,26 @@ INSERT INTO arweave_block_sync_state(id, last_block_height, updated_at_ms)
VALUES (1, 0, 0) ON CONFLICT (id) DO NOTHING;
CREATE TABLE IF NOT EXISTS arweave_block_import_queue (
data_item_id BYTEA PRIMARY KEY,
root_tx_id TEXT NOT NULL,
block_height BIGINT NOT NULL,
raw_data_item BYTEA NOT NULL,
status TEXT NOT NULL,
last_error TEXT NOT NULL DEFAULT '',
first_seen_at_ms BIGINT NOT NULL,
updated_at_ms BIGINT NOT NULL
data_item_id BYTEA PRIMARY KEY,
root_tx_id TEXT NOT NULL,
block_height BIGINT NOT NULL,
raw_data_item BYTEA NOT NULL,
status TEXT NOT NULL,
last_error TEXT NOT NULL DEFAULT '',
first_seen_at_ms BIGINT NOT NULL,
updated_at_ms BIGINT NOT NULL,
parsed_login TEXT,
parsed_fork_number INTEGER CHECK (parsed_fork_number IS NULL OR parsed_fork_number BETWEEN 1 AND 999),
parsed_block_number INTEGER CHECK (parsed_block_number IS NULL OR parsed_block_number >= 0),
parsed_block_hash BYTEA,
metadata_validated BOOLEAN NOT NULL DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_arweave_block_import_queue_pending
ON arweave_block_import_queue(block_height,first_seen_at_ms)
WHERE status='PENDING';
CREATE INDEX IF NOT EXISTS idx_arweave_block_import_queue_canonical_order
ON arweave_block_import_queue(parsed_login,parsed_block_number,parsed_fork_number,first_seen_at_ms)
WHERE status='PENDING' AND metadata_validated=TRUE;
CREATE TABLE IF NOT EXISTS connections_state (
login TEXT NOT NULL REFERENCES solana_user_pda_current(normalized_login),
@@ -627,7 +665,10 @@ CREATE TABLE IF NOT EXISTS channel_names_state (
ava_ar TEXT NOT NULL DEFAULT '',
ava_sha256 TEXT NOT NULL DEFAULT '',
ava_size BIGINT NOT NULL DEFAULT 0,
meta_updated_at_ms BIGINT NOT NULL DEFAULT 0
meta_updated_at_ms BIGINT NOT NULL DEFAULT 0,
is_deleted BOOLEAN NOT NULL DEFAULT FALSE,
deleted_at_ms BIGINT NOT NULL DEFAULT 0,
deleted_block_number INTEGER
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_channel_names_state_owner_type_slug
@@ -1080,6 +1121,7 @@ LANGUAGE plpgsql
AS $$
DECLARE
prev_block RECORD;
tail_block_number INTEGER;
BEGIN
IF NEW.line_code IS NULL
AND NEW.prev_line_number IS NULL
@@ -1119,26 +1161,35 @@ BEGIN
RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH';
END IF;
IF NEW.prev_line_number = NEW.line_code THEN
SELECT block_number
INTO tail_block_number
FROM blocks
WHERE bch_name = NEW.bch_name
AND msg_type = NEW.msg_type
AND line_code = NEW.line_code
ORDER BY block_number DESC
LIMIT 1;
IF tail_block_number IS NULL THEN
IF NEW.prev_line_number <> NEW.line_code THEN
RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL';
END IF;
IF NEW.this_line_number <> (CASE WHEN NEW.msg_type = 1 THEN 0 ELSE 1 END) THEN
RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS';
END IF;
RETURN NEW;
END IF;
IF NEW.prev_line_number <> tail_block_number THEN
RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL';
END IF;
IF prev_block.this_line_number IS NULL THEN
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
END IF;
IF NEW.msg_type = 1 THEN
IF NEW.this_line_number <> prev_block.this_line_number
AND NEW.this_line_number <> prev_block.this_line_number + 1 THEN
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
END IF;
ELSE
IF NEW.this_line_number <> prev_block.this_line_number + 1 THEN
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
END IF;
IF NEW.this_line_number <> prev_block.this_line_number + 1 THEN
RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP';
END IF;
RETURN NEW;
@@ -1826,11 +1877,11 @@ BEGIN
primary_confirmations_received_count, primary_confirmations_given_count,
shine_confirmations_received_count, shine_confirmations_given_count, updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1),
(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),
0,
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn
ON cn.owner_bch_name=cs.to_bch_name 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),
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs
WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14
@@ -2081,8 +2132,532 @@ CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_archive_pending
ON solana_user_pda_current(is_server, archive_imported)
WHERE archive_head_tx_id <> '';
INSERT INTO db_schema_version(id,schema_version,updated_at_ms)
VALUES(1,24,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;
-- Server-local key rotation state machine (schema v26).
-- Эти поля не являются частью Solana PDA и не перезаписываются Solana sync upsert-ом.
ALTER TABLE solana_user_pda_current
ADD COLUMN IF NOT EXISTS rotation_status TEXT NOT NULL DEFAULT 'NONE';
ALTER TABLE solana_user_pda_current
ADD COLUMN IF NOT EXISTS rotation_session_id BIGINT;
ALTER TABLE solana_user_pda_current
DROP CONSTRAINT IF EXISTS chk_solana_user_pda_current_rotation_status;
ALTER TABLE solana_user_pda_current
ADD CONSTRAINT chk_solana_user_pda_current_rotation_status CHECK (
rotation_status IN (
'NONE','COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED',
'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING'
)
);
CREATE INDEX IF NOT EXISTS idx_solana_user_pda_current_rotation_active
ON solana_user_pda_current(rotation_status)
WHERE rotation_status <> 'NONE';
CREATE TABLE IF NOT EXISTS key_rotation_sessions (
id BIGSERIAL PRIMARY KEY,
login TEXT NOT NULL REFERENCES solana_user_pda_current(login) ON DELETE CASCADE,
status TEXT NOT NULL CHECK (
status IN (
'COPYING_CHAIN','CHAIN_READY','ROTATING_PDA','PDA_ROTATED',
'REBUILDING_SERVER','WALLET_MIGRATION','MESSAGE_MIGRATION','FINALIZING',
'COMPLETE','ABORTED'
)
),
source_blockchain_name TEXT NOT NULL,
candidate_blockchain_name TEXT NOT NULL,
old_root_key TEXT NOT NULL,
old_blockchain_key TEXT NOT NULL,
old_client_key TEXT NOT NULL,
new_root_key TEXT NOT NULL,
new_blockchain_key TEXT NOT NULL,
new_client_key TEXT NOT NULL,
fork_from_block INTEGER NOT NULL CHECK (fork_from_block >= 0),
fork_from_hash BYTEA NOT NULL CHECK (octet_length(fork_from_hash) = 32),
source_tip_block INTEGER NOT NULL CHECK (source_tip_block >= 0),
source_tip_hash BYTEA NOT NULL CHECK (octet_length(source_tip_hash) = 32),
reason_code SMALLINT NOT NULL CHECK (reason_code BETWEEN 1 AND 4),
comment TEXT NOT NULL DEFAULT '' CHECK (octet_length(convert_to(comment, 'UTF8')) <= 1024),
progress_current INTEGER NOT NULL DEFAULT 0 CHECK (progress_current >= 0),
progress_total INTEGER NOT NULL DEFAULT 0 CHECK (progress_total >= 0),
pda_rotation_signature TEXT,
wallet_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
wallet_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED')
),
message_migration_status TEXT NOT NULL DEFAULT 'PENDING' CHECK (
message_migration_status IN ('PENDING','COMPLETE','SKIPPED','NOT_IMPLEMENTED')
),
last_error TEXT,
last_error_at_ms BIGINT,
retry_count INTEGER NOT NULL DEFAULT 0 CHECK (retry_count >= 0),
created_at_ms BIGINT NOT NULL,
updated_at_ms BIGINT NOT NULL,
completed_at_ms BIGINT,
aborted_at_ms BIGINT,
CHECK (progress_current <= progress_total),
CHECK (fork_from_block <= source_tip_block)
);
CREATE UNIQUE INDEX IF NOT EXISTS uq_key_rotation_sessions_active_login
ON key_rotation_sessions(login)
WHERE status NOT IN ('COMPLETE','ABORTED');
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_login_created
ON key_rotation_sessions(login, created_at_ms DESC);
CREATE INDEX IF NOT EXISTS idx_key_rotation_sessions_status
ON key_rotation_sessions(status);
CREATE TABLE IF NOT EXISTS key_rotation_candidate_blocks (
id BIGSERIAL PRIMARY KEY,
rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE,
login TEXT NOT NULL,
candidate_blockchain_name TEXT NOT NULL,
block_number INTEGER NOT NULL CHECK (block_number >= 0),
block_hash BYTEA NOT NULL CHECK (octet_length(block_hash) = 32),
data_item_id BYTEA NOT NULL CHECK (octet_length(data_item_id) = 32),
block_bytes BYTEA NOT NULL,
arweave_publish_pending BOOLEAN NOT NULL DEFAULT TRUE,
arweave_published_at_ms BIGINT,
created_at_ms BIGINT NOT NULL,
UNIQUE (rotation_session_id, block_number),
UNIQUE (rotation_session_id, data_item_id)
);
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_pending
ON key_rotation_candidate_blocks(id)
WHERE arweave_publish_pending = TRUE;
CREATE INDEX IF NOT EXISTS idx_key_rotation_candidate_blocks_session
ON key_rotation_candidate_blocks(rotation_session_id, block_number);
ALTER TABLE solana_user_pda_current
DROP CONSTRAINT IF EXISTS fk_solana_user_pda_current_rotation_session;
ALTER TABLE solana_user_pda_current
ADD CONSTRAINT fk_solana_user_pda_current_rotation_session
FOREIGN KEY (rotation_session_id)
REFERENCES key_rotation_sessions(id)
ON DELETE SET NULL;
-- Stage 2 final schema: numeric physical forks and logical cross-fork targets.
-- Stage 2: physical fork identity = (login,fork_number); logical target = (login,block_number,hash).
ALTER TABLE solana_user_pda_current
ADD CONSTRAINT chk_solana_current_blockchain_name_fork
CHECK (blockchain_name ~ '-[0-9]{3}$'
AND substring(blockchain_name from '([0-9]{3})$')::INTEGER BETWEEN 1 AND 999);
ALTER TABLE blockchain_state ADD COLUMN IF NOT EXISTS fork_number INTEGER;
UPDATE blockchain_state
SET fork_number = NULLIF(regexp_replace(blockchain_name, '^.*-([0-9]{3})$', '\1'), blockchain_name)::INTEGER
WHERE fork_number IS NULL AND blockchain_name ~ '-[0-9]{3}$';
ALTER TABLE blockchain_state ALTER COLUMN fork_number SET NOT NULL;
ALTER TABLE blockchain_state ADD CONSTRAINT chk_blockchain_state_fork CHECK (fork_number BETWEEN 1 AND 999);
CREATE UNIQUE INDEX IF NOT EXISTS uq_blockchain_state_login_fork ON blockchain_state(login,fork_number);
ALTER TABLE blocks ADD COLUMN IF NOT EXISTS fork_number INTEGER;
UPDATE blocks b SET fork_number=s.fork_number FROM blockchain_state s WHERE b.bch_name=s.blockchain_name AND b.fork_number IS NULL;
ALTER TABLE blocks ALTER COLUMN fork_number SET NOT NULL;
ALTER TABLE blocks ADD CONSTRAINT chk_blocks_fork CHECK (fork_number BETWEEN 1 AND 999);
-- Triggers stay attached when tables are renamed; replace their functions below before new writes.
ALTER TABLE blocks DROP CONSTRAINT IF EXISTS blocks_bch_name_fkey;
ALTER TABLE blocks RENAME TO blocks_store;
ALTER TABLE blockchain_state RENAME TO blockchain_state_store;
ALTER TABLE blocks_store DROP COLUMN bch_name;
ALTER TABLE blocks_store DROP COLUMN to_bch_name;
ALTER TABLE blockchain_state_store DROP CONSTRAINT IF EXISTS blockchain_state_pkey;
ALTER TABLE blockchain_state_store DROP COLUMN blockchain_name;
ALTER TABLE blockchain_state_store ADD PRIMARY KEY(login,fork_number);
ALTER TABLE blocks_store ADD CONSTRAINT fk_blocks_physical_fork FOREIGN KEY(login,fork_number)
REFERENCES blockchain_state_store(login,fork_number);
DROP INDEX IF EXISTS idx_blocks_by_chain_number;
DROP INDEX IF EXISTS idx_blocks_to_target;
DROP INDEX IF EXISTS idx_blocks_by_line;
CREATE UNIQUE INDEX uq_blocks_physical_number ON blocks_store(login,fork_number,block_number);
CREATE INDEX idx_blocks_to_logical_target ON blocks_store(to_login,to_block_number,to_block_hash);
CREATE INDEX idx_blocks_by_line_v29 ON blocks_store(login,fork_number,line_code,this_line_number);
-- Compatibility views: names are derived, never stored.
CREATE VIEW blockchain_state AS
SELECT login || '-' || lpad(fork_number::text,3,'0') AS blockchain_name, s.* FROM blockchain_state_store s;
CREATE VIEW blocks AS
SELECT b.login,
b.login || '-' || lpad(b.fork_number::text,3,'0') AS bch_name,
b.fork_number,b.block_number,b.msg_type,b.msg_sub_type,b.block_bytes,
b.to_login,
CASE WHEN b.to_login IS NOT NULL AND b.to_fork_number BETWEEN 1 AND 999
THEN b.to_login || '-' || lpad(b.to_fork_number::text,3,'0') END AS to_bch_name,
b.to_fork_number,b.to_block_number,b.to_block_hash,b.block_hash,b.block_signature,b.data_item_id,
b.arweave_publish_pending,b.arweave_published_at_ms,b.arweave_root_tx_id,b.edited_by_block_number,
b.line_code,b.prev_line_number,b.prev_line_hash,b.this_line_number
FROM blocks_store b;
-- Channel read state keeps the signed/display owner_bch_name, but identity no longer depends on a fork.
ALTER TABLE channel_read_state DROP CONSTRAINT IF EXISTS channel_read_state_pkey;
ALTER TABLE channel_read_state ADD PRIMARY KEY(viewer_login,owner_login,channel_name);
-- Derived social state is cheap to rebuild and intentionally loses physical fork names.
DROP TABLE IF EXISTS reactions_state CASCADE;
DROP TABLE IF EXISTS message_stats CASCADE;
DROP TABLE IF EXISTS connections_state CASCADE;
CREATE TABLE connections_state(
login TEXT NOT NULL, rel_type INTEGER NOT NULL, to_login TEXT NOT NULL,
to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL,
UNIQUE(login,rel_type,to_login,to_block_number,to_block_hash)
);
CREATE INDEX idx_connections_state_login_v29 ON connections_state(login);
CREATE INDEX idx_connections_state_to_login_v29 ON connections_state(to_login);
CREATE INDEX idx_connections_state_target_v29 ON connections_state(to_login,to_block_number,to_block_hash);
CREATE TABLE message_stats(
to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL,
likes_count INTEGER NOT NULL DEFAULT 0,
primary_likes_count INTEGER NOT NULL DEFAULT 0,
shining_likes_count INTEGER NOT NULL DEFAULT 0,
replies_count INTEGER NOT NULL DEFAULT 0,
UNIQUE(to_login,to_block_number,to_block_hash)
);
CREATE INDEX idx_message_stats_target_v29 ON message_stats(to_login,to_block_number,to_block_hash);
CREATE TABLE reactions_state(
from_login TEXT NOT NULL, reaction_type INTEGER NOT NULL,
to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL, to_block_hash BYTEA NOT NULL,
last_sub_type INTEGER NOT NULL,
UNIQUE(from_login,reaction_type,to_login,to_block_number,to_block_hash)
);
CREATE INDEX idx_reactions_state_target_v29 ON reactions_state(to_login,to_block_number,to_block_hash);
CREATE INDEX idx_reactions_state_actor_v29 ON reactions_state(from_login,reaction_type);
DROP TABLE IF EXISTS message_views_state;
CREATE TABLE message_views_state(
viewer_login TEXT NOT NULL, to_login TEXT NOT NULL, to_block_number INTEGER NOT NULL,
to_block_hash BYTEA NOT NULL, first_seen_at_ms BIGINT NOT NULL,
PRIMARY KEY(viewer_login,to_login,to_block_number,to_block_hash)
);
CREATE INDEX idx_message_views_target_v29 ON message_views_state(to_login,to_block_number,to_block_hash);
CREATE OR REPLACE FUNCTION shine_refresh_user_stats(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
IF p_login IS NULL OR btrim(p_login)='' THEN RETURN; END IF;
INSERT INTO user_stats_state(login,owned_public_channels_count,following_users_count,following_channels_count,close_friends_count,friends_count,
primary_confirmations_received_count,primary_confirmations_given_count,shine_confirmations_received_count,shine_confirmations_given_count,updated_at_ms)
SELECT p_login,
(SELECT COUNT(*)::INT FROM channel_names_state cn WHERE LOWER(cn.owner_login)=LOWER(p_login) AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cs.to_block_number=0),
(SELECT COUNT(*)::INT FROM connections_state cs JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=30 AND cn.channel_type_code=1 AND NOT cn.is_deleted),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=10),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=14 AND NOT EXISTS(SELECT 1 FROM connections_state cf WHERE LOWER(cf.login)=LOWER(p_login) AND LOWER(cf.to_login)=LOWER(cs.to_login) AND cf.rel_type=10)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(cs.login) AND shine_target_accepts_primary_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=80 AND shine_is_primary(p_login) AND shine_target_accepts_primary_confirmation(cs.to_login)),
(SELECT COUNT(DISTINCT LOWER(cs.login))::INT FROM connections_state cs WHERE LOWER(cs.to_login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(cs.login) AND shine_is_shining(cs.login) AND shine_target_accepts_shine_confirmation(p_login)),
(SELECT COUNT(DISTINCT LOWER(cs.to_login))::INT FROM connections_state cs WHERE LOWER(cs.login)=LOWER(p_login) AND cs.rel_type=70 AND shine_is_primary(p_login) AND shine_is_shining(p_login) AND shine_target_accepts_shine_confirmation(cs.to_login)),v_now
ON CONFLICT(login) DO UPDATE SET owned_public_channels_count=EXCLUDED.owned_public_channels_count,following_users_count=EXCLUDED.following_users_count,following_channels_count=EXCLUDED.following_channels_count,close_friends_count=EXCLUDED.close_friends_count,friends_count=EXCLUDED.friends_count,primary_confirmations_received_count=EXCLUDED.primary_confirmations_received_count,primary_confirmations_given_count=EXCLUDED.primary_confirmations_given_count,shine_confirmations_received_count=EXCLUDED.shine_confirmations_received_count,shine_confirmations_given_count=EXCLUDED.shine_confirmations_given_count,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
CREATE OR REPLACE FUNCTION shine_refresh_message_qualified_likes_for_actor(p_login TEXT) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE r RECORD;
BEGIN
FOR r IN SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state WHERE LOWER(from_login)=LOWER(p_login) AND reaction_type=1 AND last_sub_type=1 LOOP
UPDATE message_stats ms SET
primary_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login)),
shining_likes_count=(SELECT COUNT(*)::INT FROM reactions_state x WHERE x.reaction_type=1 AND x.last_sub_type=1 AND x.to_login=r.to_login AND x.to_block_number=r.to_block_number AND x.to_block_hash=r.to_block_hash AND shine_is_primary(x.from_login) AND shine_is_shining(x.from_login))
WHERE ms.to_login=r.to_login AND ms.to_block_number=r.to_block_number AND ms.to_block_hash=r.to_block_hash;
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION shine_refresh_channel_follow_stats(p_bch_name TEXT,p_block_number INTEGER,p_block_hash BYTEA) RETURNS VOID LANGUAGE plpgsql AS $$
DECLARE v_owner TEXT; v_type INTEGER; v_count INTEGER; v_now BIGINT:=CAST(EXTRACT(EPOCH FROM clock_timestamp())*1000 AS BIGINT);
BEGIN
SELECT owner_login,channel_type_code INTO v_owner,v_type FROM channel_names_state WHERE owner_bch_name=p_bch_name AND channel_root_block_number=p_block_number AND channel_root_block_hash=p_block_hash LIMIT 1;
IF v_owner IS NULL THEN RETURN; END IF;
SELECT COUNT(DISTINCT cs.login)::INTEGER INTO v_count FROM connections_state cs WHERE cs.rel_type=30 AND LOWER(cs.to_login)=LOWER(v_owner) AND cs.to_block_number=p_block_number AND cs.to_block_hash=p_block_hash;
INSERT INTO channel_stats_state(owner_bch_name,channel_root_block_number,channel_root_block_hash,owner_login,channel_type_code,subscribers_count,updated_at_ms)
VALUES(p_bch_name,p_block_number,p_block_hash,v_owner,v_type,COALESCE(v_count,0),v_now)
ON CONFLICT(owner_bch_name,channel_root_block_number,channel_root_block_hash) DO UPDATE SET subscribers_count=EXCLUDED.subscribers_count,owner_login=EXCLUDED.owner_login,channel_type_code=EXCLUDED.channel_type_code,updated_at_ms=EXCLUDED.updated_at_ms;
END $$;
-- Channel-name projection must also use logical connection targets; the physical owner name is display/state only.
CREATE OR REPLACE FUNCTION shine_channel_names_state_stats_ai()
RETURNS TRIGGER
LANGUAGE plpgsql
AS $$
DECLARE
now_ms BIGINT;
public_subscribers_count INTEGER;
r RECORD;
BEGIN
now_ms := CAST(EXTRACT(EPOCH FROM clock_timestamp()) * 1000 AS BIGINT);
IF NEW.owner_login IS NULL OR btrim(NEW.owner_login) = '' THEN
RETURN NEW;
END IF;
IF NEW.channel_type_code = 1 THEN
IF EXISTS (
SELECT 1 FROM solana_user_pda_current su WHERE LOWER(su.login)=LOWER(NEW.owner_login)
) THEN
INSERT INTO user_stats_state (
login, owned_public_channels_count, following_users_count, following_channels_count,
close_friends_count, updated_at_ms
) VALUES (NEW.owner_login, 1, 0, 0, 0, now_ms)
ON CONFLICT (login) DO UPDATE SET
owned_public_channels_count = user_stats_state.owned_public_channels_count + 1,
updated_at_ms = EXCLUDED.updated_at_ms;
END IF;
SELECT COUNT(*)::INTEGER
INTO public_subscribers_count
FROM connections_state cs
WHERE cs.rel_type = 30
AND LOWER(cs.to_login)=LOWER(NEW.owner_login)
AND cs.to_block_number = NEW.channel_root_block_number
AND cs.to_block_hash = NEW.channel_root_block_hash;
INSERT INTO channel_stats_state (
owner_bch_name, channel_root_block_number, channel_root_block_hash,
owner_login, channel_type_code, subscribers_count, updated_at_ms
) VALUES (
NEW.owner_bch_name, NEW.channel_root_block_number, NEW.channel_root_block_hash,
NEW.owner_login, NEW.channel_type_code, COALESCE(public_subscribers_count, 0), now_ms
)
ON CONFLICT (owner_bch_name, channel_root_block_number, channel_root_block_hash) DO UPDATE SET
owner_login = EXCLUDED.owner_login,
channel_type_code = EXCLUDED.channel_type_code,
subscribers_count = EXCLUDED.subscribers_count,
updated_at_ms = EXCLUDED.updated_at_ms;
-- A channel may disappear during cleanup and reappear during replay. Recompute followers from logical state.
FOR r IN
SELECT DISTINCT cs.login
FROM connections_state cs
WHERE cs.rel_type = 30
AND LOWER(cs.to_login)=LOWER(NEW.owner_login)
AND cs.to_block_number = NEW.channel_root_block_number
AND cs.to_block_hash = NEW.channel_root_block_hash
LOOP
PERFORM shine_refresh_user_stats(r.login);
END LOOP;
ELSE
WITH pending AS (
SELECT cs.login, COUNT(*)::INTEGER AS cnt
FROM connections_state cs
WHERE cs.rel_type = 30
AND LOWER(cs.to_login)=LOWER(NEW.owner_login)
AND cs.to_block_number = NEW.channel_root_block_number
AND cs.to_block_hash = NEW.channel_root_block_hash
GROUP BY cs.login
)
UPDATE user_stats_state us
SET following_channels_count = GREATEST(0, us.following_channels_count - pending.cnt),
updated_at_ms = now_ms
FROM pending
WHERE LOWER(us.login)=LOWER(pending.login);
END IF;
RETURN NEW;
END;
$$;
-- Physical chain integrity uses numeric fork identity.
CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE prev_block RECORD; tail_block_number INTEGER;
BEGIN
IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF;
IF NEW.msg_type NOT IN (0,1,3,4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF;
IF NEW.line_code IS NULL OR NEW.prev_line_number IS NULL OR NEW.prev_line_hash IS NULL OR NEW.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_PARTIAL_FIELDS'; END IF;
SELECT * INTO prev_block FROM blocks_store WHERE login=NEW.login AND fork_number=NEW.fork_number AND block_number=NEW.prev_line_number LIMIT 1;
IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF;
IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF;
IF NEW.prev_line_number<>NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF;
SELECT block_number INTO tail_block_number FROM blocks_store
WHERE login=NEW.login AND fork_number=NEW.fork_number AND msg_type=NEW.msg_type AND line_code=NEW.line_code
ORDER BY block_number DESC LIMIT 1;
IF tail_block_number IS NULL THEN
IF NEW.prev_line_number<>NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF;
RETURN NEW;
END IF;
IF NEW.prev_line_number<>tail_block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
RETURN NEW;
END $$;
CREATE OR REPLACE FUNCTION shine_blocks_connection_state_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE positive_rel_type INTEGER; channel_bch TEXT;
BEGIN
IF NEW.msg_type<>3 OR NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
IF NEW.msg_sub_type IN (10,14,20,30,40,50,52,54,60,70,74,80) THEN
DELETE FROM connections_state WHERE login=NEW.login AND rel_type=NEW.msg_sub_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
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);
ELSE
positive_rel_type := CASE NEW.msg_sub_type WHEN 11 THEN 10 WHEN 15 THEN 14 WHEN 21 THEN 20 WHEN 31 THEN 30 WHEN 41 THEN 40 WHEN 51 THEN 50 WHEN 53 THEN 52 WHEN 55 THEN 54 WHEN 61 THEN 60 WHEN 71 THEN 70 WHEN 75 THEN 74 WHEN 81 THEN 80 ELSE NULL END;
IF positive_rel_type IS NOT NULL THEN DELETE FROM connections_state WHERE login=NEW.login AND rel_type=positive_rel_type AND to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash; END IF;
END IF;
PERFORM shine_refresh_user_stats(NEW.login);
PERFORM shine_refresh_user_stats(NEW.to_login);
IF NEW.msg_sub_type IN (30,31) AND NEW.to_block_number>0 THEN
SELECT owner_bch_name INTO channel_bch FROM channel_names_state WHERE LOWER(owner_login)=LOWER(NEW.to_login) AND channel_root_block_number=NEW.to_block_number AND channel_root_block_hash=NEW.to_block_hash LIMIT 1;
IF channel_bch IS NOT NULL THEN PERFORM shine_refresh_channel_follow_stats(channel_bch,NEW.to_block_number,NEW.to_block_hash); END IF;
END IF;
RETURN NEW;
END $$;
CREATE OR REPLACE FUNCTION shine_blocks_message_stats_like_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE previous_sub_type INTEGER;
BEGIN
IF NEW.msg_type<>2 OR NEW.msg_sub_type NOT IN (1,2) THEN RETURN NEW; END IF;
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
INSERT INTO message_stats(to_login,to_block_number,to_block_hash) VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash)
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;
IF NEW.msg_sub_type=1 AND previous_sub_type IS DISTINCT FROM 1 THEN
UPDATE message_stats SET likes_count=likes_count+1,
primary_likes_count=primary_likes_count+CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END,
shining_likes_count=shining_likes_count+CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
ELSIF NEW.msg_sub_type=2 AND previous_sub_type=1 THEN
UPDATE message_stats SET likes_count=GREATEST(0,likes_count-1),
primary_likes_count=GREATEST(0,primary_likes_count-CASE WHEN shine_is_primary(NEW.login) THEN 1 ELSE 0 END),
shining_likes_count=GREATEST(0,shining_likes_count-CASE WHEN shine_is_primary(NEW.login) AND shine_is_shining(NEW.login) THEN 1 ELSE 0 END)
WHERE to_login=NEW.to_login AND to_block_number=NEW.to_block_number AND to_block_hash=NEW.to_block_hash;
END IF;
INSERT INTO reactions_state(from_login,reaction_type,to_login,to_block_number,to_block_hash,last_sub_type)
VALUES(NEW.login,1,NEW.to_login,NEW.to_block_number,NEW.to_block_hash,NEW.msg_sub_type)
ON CONFLICT(from_login,reaction_type,to_login,to_block_number,to_block_hash) DO UPDATE SET last_sub_type=EXCLUDED.last_sub_type;
RETURN NEW;
END $$;
-- Existing REPLY counter semantics are preserved; only the removed physical target-name column is adapted.
CREATE OR REPLACE FUNCTION shine_blocks_message_stats_reply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
IF NEW.msg_type<>1 OR NEW.msg_sub_type<>20 THEN RETURN NEW; END IF;
IF NEW.to_login IS NULL OR NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,replies_count)
VALUES(NEW.to_login,NEW.to_block_number,NEW.to_block_hash,1)
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET replies_count=message_stats.replies_count+1;
RETURN NEW;
END $$;
-- EDIT applies to own physical fork; no edits_count aggregate is maintained.
CREATE OR REPLACE FUNCTION shine_blocks_edit_apply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$
BEGIN
IF NEW.msg_type<>1 OR NEW.msg_sub_type NOT IN (11,21) THEN RETURN NEW; END IF;
IF NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
UPDATE blocks_store SET edited_by_block_number=NEW.block_number
WHERE login=NEW.login AND fork_number=NEW.fork_number AND block_number=NEW.to_block_number AND block_hash=NEW.to_block_hash;
RETURN NEW;
END $$;
-- Triggers moved with blocks_store on rename; make sure they exist there.
DROP TRIGGER IF EXISTS trg_blocks_line_integrity_bi ON blocks_store;
CREATE TRIGGER trg_blocks_line_integrity_bi BEFORE INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_line_integrity_bi();
DROP TRIGGER IF EXISTS trg_blocks_connection_state_ai ON blocks_store;
CREATE TRIGGER trg_blocks_connection_state_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_connection_state_ai();
DROP TRIGGER IF EXISTS trg_blocks_message_stats_like_ai ON blocks_store;
CREATE TRIGGER trg_blocks_message_stats_like_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_like_ai();
DROP TRIGGER IF EXISTS trg_blocks_message_stats_reply_ai ON blocks_store;
CREATE TRIGGER trg_blocks_message_stats_reply_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_message_stats_reply_ai();
DROP TRIGGER IF EXISTS trg_blocks_edit_apply_ai ON blocks_store;
CREATE TRIGGER trg_blocks_edit_apply_ai AFTER INSERT ON blocks_store FOR EACH ROW EXECUTE FUNCTION shine_blocks_edit_apply_ai();
-- Segmented fork ancestry (schema v30).
CREATE TABLE IF NOT EXISTS blockchain_fork_segments (
login TEXT NOT NULL,
fork_number INTEGER NOT NULL CHECK (fork_number BETWEEN 1 AND 999),
parent_fork_number INTEGER,
fork_point_block_number INTEGER NOT NULL DEFAULT -1,
fork_point_block_hash BYTEA,
first_physical_block_number INTEGER NOT NULL DEFAULT 0,
created_at_ms BIGINT NOT NULL DEFAULT 0,
PRIMARY KEY(login,fork_number),
CHECK ((fork_number=1 AND parent_fork_number IS NULL AND fork_point_block_number=-1 AND first_physical_block_number=0)
OR (fork_number>1 AND parent_fork_number IS NOT NULL AND parent_fork_number BETWEEN 1 AND 999
AND fork_point_block_number>=0 AND octet_length(fork_point_block_hash)=32
AND first_physical_block_number=fork_point_block_number+1))
);
CREATE INDEX IF NOT EXISTS idx_blockchain_fork_segments_parent ON blockchain_fork_segments(login,parent_fork_number);
-- Existing chains predate segmented forks. Their current physical fork is self-contained;
-- register fork 1 where possible. Later segmented forks are inserted by key rotation/recovery.
INSERT INTO blockchain_fork_segments(login,fork_number,parent_fork_number,fork_point_block_number,fork_point_block_hash,first_physical_block_number,created_at_ms)
SELECT login,fork_number,NULL,-1,NULL,0,updated_at_ms FROM blockchain_state_store
WHERE fork_number=1
ON CONFLICT(login,fork_number) DO NOTHING;
-- Segmented-fork canonical helpers/triggers (schema v30 final overrides).
CREATE OR REPLACE FUNCTION shine_canonical_fork(p_login TEXT,p_active_fork INTEGER,p_block_number INTEGER) RETURNS INTEGER LANGUAGE plpgsql STABLE AS $$
DECLARE f INTEGER:=p_active_fork; seg RECORD; guard INTEGER:=0;
BEGIN
LOOP
guard:=guard+1; IF guard>1000 THEN RAISE EXCEPTION 'fork ancestry cycle'; END IF;
SELECT * INTO seg FROM blockchain_fork_segments WHERE LOWER(login)=LOWER(p_login) AND fork_number=f;
IF NOT FOUND THEN RETURN f; END IF;
IF seg.parent_fork_number IS NULL OR p_block_number>=seg.first_physical_block_number THEN RETURN f; END IF;
f:=seg.parent_fork_number;
END LOOP;
END $$;
CREATE OR REPLACE FUNCTION shine_blocks_line_integrity_bi() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE prev_block RECORD; tail_block RECORD; prev_fork INTEGER;
BEGIN
IF NEW.line_code IS NULL AND NEW.prev_line_number IS NULL AND NEW.prev_line_hash IS NULL AND NEW.this_line_number IS NULL THEN RETURN NEW; END IF;
IF NEW.msg_type NOT IN (0,1,3,4) THEN RAISE EXCEPTION 'LINE_ERR_UNSUPPORTED_TYPE_WITH_LINE'; END IF;
IF NEW.line_code IS NULL OR NEW.prev_line_number IS NULL OR NEW.prev_line_hash IS NULL OR NEW.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_PARTIAL_FIELDS'; END IF;
prev_fork:=shine_canonical_fork(NEW.login,NEW.fork_number,NEW.prev_line_number);
SELECT * INTO prev_block FROM blocks_store WHERE LOWER(login)=LOWER(NEW.login) AND fork_number=prev_fork AND block_number=NEW.prev_line_number LIMIT 1;
IF NOT FOUND THEN RAISE EXCEPTION 'LINE_ERR_NO_PREV'; END IF;
IF prev_block.block_hash IS DISTINCT FROM NEW.prev_line_hash THEN RAISE EXCEPTION 'LINE_ERR_PREV_HASH_MISMATCH'; END IF;
IF NEW.prev_line_number<>NEW.line_code AND prev_block.line_code IS DISTINCT FROM NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_LINE_CODE_MISMATCH'; END IF;
SELECT b.* INTO tail_block FROM blocks_store b
WHERE LOWER(b.login)=LOWER(NEW.login) AND b.block_number<NEW.block_number AND b.msg_type=NEW.msg_type AND b.line_code=NEW.line_code
AND b.fork_number=shine_canonical_fork(NEW.login,NEW.fork_number,b.block_number)
ORDER BY b.block_number DESC LIMIT 1;
IF NOT FOUND THEN
IF NEW.prev_line_number<>NEW.line_code THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
IF NEW.this_line_number<>(CASE WHEN NEW.msg_type=1 THEN 0 ELSE 1 END) THEN RAISE EXCEPTION 'LINE_ERR_FIRST_STEP_BAD_THIS'; END IF;
RETURN NEW;
END IF;
IF NEW.prev_line_number<>tail_block.block_number THEN RAISE EXCEPTION 'LINE_ERR_NOT_CURRENT_TAIL'; END IF;
IF prev_block.this_line_number IS NULL THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
IF NEW.this_line_number<>prev_block.this_line_number+1 THEN RAISE EXCEPTION 'LINE_ERR_THIS_LINE_BAD_STEP'; END IF;
RETURN NEW;
END $$;
CREATE OR REPLACE FUNCTION shine_blocks_edit_apply_ai() RETURNS TRIGGER LANGUAGE plpgsql AS $$
DECLARE target_fork INTEGER;
BEGIN
IF NEW.msg_type<>1 OR NEW.msg_sub_type NOT IN (11,21) THEN RETURN NEW; END IF;
IF NEW.to_block_number IS NULL OR NEW.to_block_hash IS NULL THEN RETURN NEW; END IF;
target_fork:=shine_canonical_fork(NEW.login,NEW.fork_number,NEW.to_block_number);
UPDATE blocks_store SET edited_by_block_number=NEW.block_number
WHERE LOWER(login)=LOWER(NEW.login) AND fork_number=target_fork AND block_number=NEW.to_block_number AND block_hash=NEW.to_block_hash;
RETURN NEW;
END $$;
CREATE TABLE IF NOT EXISTS key_rotation_rebuild_staging (
rotation_session_id BIGINT NOT NULL REFERENCES key_rotation_sessions(id) ON DELETE CASCADE,
logical_block_number INTEGER NOT NULL, physical_fork_number INTEGER NOT NULL,
blockchain_key TEXT NOT NULL, block_bytes BYTEA NOT NULL, block_hash BYTEA NOT NULL,
PRIMARY KEY(rotation_session_id,logical_block_number)
);
CREATE INDEX IF NOT EXISTS idx_key_rotation_rebuild_staging_session ON key_rotation_rebuild_staging(rotation_session_id,logical_block_number);
-- Generic crash-safe staging used when this server learns a remote fork through Arweave.
CREATE TABLE IF NOT EXISTS canonical_rebuild_staging (
login TEXT NOT NULL,
logical_block_number INTEGER NOT NULL,
physical_fork_number INTEGER NOT NULL,
block_bytes BYTEA NOT NULL,
block_hash BYTEA NOT NULL,
PRIMARY KEY(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;
COMMIT;
@@ -6,6 +6,7 @@ import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_AuthChallenge_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ResolveLoginForAuth_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CloseActiveSession_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CloseOtherSessions_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_CreateAuthSession__Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListSessions_Handler;
import server.logic.ws_protocol.JSON.handlers.auth.Net_ListEspPairingRequests_Handler;
@@ -25,6 +26,7 @@ import server.logic.ws_protocol.JSON.handlers.auth.Net_UpsertEspPairingSettings_
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_AuthChallenge_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ResolveLoginForAuth_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CreateAuthSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_ListEspPairingRequests_Request;
@@ -42,8 +44,25 @@ import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_UpsertEspPairing
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_AddBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetBlockchainBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.Net_GetMyBlockchain_Handler;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_AddBlock_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_GetBlockchainBlock_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_GetMyBlockchain_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationStart_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationAddBlock_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationFinishChain_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationRotatePda_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationStatus_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationAbort_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.Net_KeyRotationContinue_Handler;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStart_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationAddBlock_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationFinishChain_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationRotatePda_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationStatus_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationAbort_Request;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationContinue_Request;
import server.logic.ws_protocol.JSON.handlers.tempToTest.Net_GetUser_Handler;
import server.logic.ws_protocol.JSON.handlers.tempToTest.entyties.Net_GetUser_Request;
@@ -109,6 +128,7 @@ import server.logic.ws_protocol.JSON.messages.Net_CallSignalToSession_Handler;
import server.logic.ws_protocol.JSON.messages.Net_DeleteConversation_Handler;
import server.logic.ws_protocol.JSON.messages.Net_DeleteMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_GetDirectMessages_Handler;
import server.logic.ws_protocol.JSON.messages.Net_ReencryptDirectMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_SendSignal_Handler;
import server.logic.ws_protocol.JSON.messages.Net_ReceiveIncomingMessage_Handler;
import server.logic.ws_protocol.JSON.messages.Net_SendMessagePair_Handler;
@@ -120,6 +140,7 @@ import server.logic.ws_protocol.JSON.messages.entyties.Net_CallSignalToSession_R
import server.logic.ws_protocol.JSON.messages.entyties.Net_DeleteConversation_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_DeleteMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_GetDirectMessages_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReencryptDirectMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendSignal_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_ReceiveIncomingMessage_Request;
import server.logic.ws_protocol.JSON.messages.entyties.Net_SendMessagePair_Request;
@@ -167,6 +188,7 @@ public final class JsonHandlerRegistry {
Map.entry("AuthChallenge", new Net_AuthChallenge_Handler()),
Map.entry("CreateAuthSession", new Net_CreateAuthSession__Handler()),
Map.entry("CloseActiveSession", new Net_CloseActiveSession_Handler()),
Map.entry("CloseOtherSessions", new Net_CloseOtherSessions_Handler()),
Map.entry("ListSessions", new Net_ListSessions_Handler()),
// --- login to existing session in 2 steps ---
@@ -191,6 +213,16 @@ public final class JsonHandlerRegistry {
// --- blockchain ---
Map.entry("AddBlock", new Net_AddBlock_Handler()),
Map.entry("GetBlockchainBlock", new Net_GetBlockchainBlock_Handler()),
Map.entry("GetMyBlockchain", new Net_GetMyBlockchain_Handler()),
// --- key rotation ---
Map.entry("KeyRotationStart", new Net_KeyRotationStart_Handler()),
Map.entry("KeyRotationStatus", new Net_KeyRotationStatus_Handler()),
Map.entry("KeyRotationAddBlock", new Net_KeyRotationAddBlock_Handler()),
Map.entry("KeyRotationFinishChain", new Net_KeyRotationFinishChain_Handler()),
Map.entry("KeyRotationRotatePda", new Net_KeyRotationRotatePda_Handler()),
Map.entry("KeyRotationContinue", new Net_KeyRotationContinue_Handler()),
Map.entry("KeyRotationAbort", new Net_KeyRotationAbort_Handler()),
// --- userParams ---
Map.entry("UpsertUserParam", new Net_UpsertUserParam_Handler()),
@@ -230,6 +262,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", new Net_DeleteMessage_Handler()),
Map.entry("DeleteConversation", new Net_DeleteConversation_Handler()),
Map.entry("GetDirectMessages", new Net_GetDirectMessages_Handler()),
Map.entry("ReencryptDirectMessage", new Net_ReencryptDirectMessage_Handler()),
Map.entry("AckSessionDelivery", new Net_AckSessionDelivery_Handler()),
Map.entry("CallInviteBroadcast", new Net_CallInviteBroadcast_Handler()),
Map.entry("CallSignalToSession", new Net_CallSignalToSession_Handler()),
@@ -259,6 +292,7 @@ public final class JsonHandlerRegistry {
Map.entry("AuthChallenge", Net_AuthChallenge_Request.class),
Map.entry("CreateAuthSession", Net_CreateAuthSession_Request.class),
Map.entry("CloseActiveSession", Net_CloseActiveSession_Request.class),
Map.entry("CloseOtherSessions", Net_CloseOtherSessions_Request.class),
Map.entry("ListSessions", Net_ListSessions_Request.class),
// --- NEW v2 ---
@@ -283,6 +317,16 @@ public final class JsonHandlerRegistry {
// --- blockchain ---
Map.entry("AddBlock", Net_AddBlock_Request.class),
Map.entry("GetBlockchainBlock", Net_GetBlockchainBlock_Request.class),
Map.entry("GetMyBlockchain", Net_GetMyBlockchain_Request.class),
// --- key rotation ---
Map.entry("KeyRotationStart", Net_KeyRotationStart_Request.class),
Map.entry("KeyRotationStatus", Net_KeyRotationStatus_Request.class),
Map.entry("KeyRotationAddBlock", Net_KeyRotationAddBlock_Request.class),
Map.entry("KeyRotationFinishChain", Net_KeyRotationFinishChain_Request.class),
Map.entry("KeyRotationRotatePda", Net_KeyRotationRotatePda_Request.class),
Map.entry("KeyRotationContinue", Net_KeyRotationContinue_Request.class),
Map.entry("KeyRotationAbort", Net_KeyRotationAbort_Request.class),
// --- userParams ---
Map.entry("UpsertUserParam", Net_UpsertUserParam_Request.class),
@@ -322,6 +366,7 @@ public final class JsonHandlerRegistry {
Map.entry("DeleteMessage", Net_DeleteMessage_Request.class),
Map.entry("DeleteConversation", Net_DeleteConversation_Request.class),
Map.entry("GetDirectMessages", Net_GetDirectMessages_Request.class),
Map.entry("ReencryptDirectMessage", Net_ReencryptDirectMessage_Request.class),
Map.entry("AckSessionDelivery", Net_AckSessionDelivery_Request.class),
Map.entry("CallInviteBroadcast", Net_CallInviteBroadcast_Request.class),
Map.entry("CallSignalToSession", Net_CallSignalToSession_Request.class),
@@ -1,10 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
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;
@@ -12,10 +9,7 @@ import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseActiveSession_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import server.logic.ws_protocol.JSON.utils.NetIdGenerator;
import server.logic.ws_protocol.WireCodes;
import server.ws.WsConnectionUtils;
import shine.db.dao.ActiveSessionsDAO;
import shine.db.entities.ActiveSessionEntry;
import shine.db.entities.CurrentUserEntry;
@@ -36,7 +30,6 @@ import java.sql.SQLException;
public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_CloseActiveSession_Handler.class);
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) throws Exception {
@@ -103,7 +96,7 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
boolean isCurrentSession = targetSessionId.equals(ctx.getSessionId());
closeActiveSession(targetSessionId, ctx, isCurrentSession);
closeActiveSession(targetSessionId, isCurrentSession);
Net_CloseActiveSession_Response resp = new Net_CloseActiveSession_Response();
resp.setOp(req.getOp());
@@ -113,7 +106,6 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
}
private void closeActiveSession(String targetSessionId,
ConnectionContext currentCtx,
boolean isCurrentSession) {
try {
@@ -122,32 +114,20 @@ public class Net_CloseActiveSession_Handler implements JsonMessageHandler {
log.error("Ошибка БД при удалении сессии sessionId={}", targetSessionId, e);
}
ConnectionContext ctxToClose =
ActiveConnectionsRegistry.getInstance().getBySessionId(targetSessionId);
if (ctxToClose == null) return;
String eventId = NetIdGenerator.eventId("evt");
ObjectNode payload = MAPPER.createObjectNode();
payload.put("eventId", eventId);
payload.put("sessionId", targetSessionId);
payload.put("reason", "closed_from_another_device");
payload.put("timeMs", System.currentTimeMillis());
WsEventSender.sendEvent(ctxToClose, "SessionRevoked", eventId, payload);
if (isCurrentSession && ctxToClose == currentCtx) {
if (isCurrentSession) {
// Для текущей сессии даём ответу успеть уйти клиенту.
new Thread(() -> {
try { Thread.sleep(50); } catch (InterruptedException ignored) {}
WsConnectionUtils.closeConnection(
ctxToClose,
4000,
SessionRevocationSupport.revokeConnection(
targetSessionId,
"closed_from_another_device",
"Session closed by client via CloseActiveSession"
);
}, "CloseSession-" + targetSessionId).start();
} else {
WsConnectionUtils.closeConnection(
ctxToClose,
4000,
SessionRevocationSupport.revokeConnection(
targetSessionId,
"closed_from_another_device",
"Session closed by client via CloseActiveSession"
);
}
@@ -0,0 +1,44 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Request;
import server.logic.ws_protocol.JSON.handlers.auth.entyties.Net_CloseOtherSessions_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import java.util.List;
/** Закрывает все остальные сессии пользователя одним запросом. */
public final class Net_CloseOtherSessions_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_CloseOtherSessions_Handler.class);
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_CloseOtherSessions_Request req = (Net_CloseOtherSessions_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()
|| ctx.getSessionId() == null || ctx.getSessionId().isBlank()) {
return NetExceptionResponseFactory.error(req, WireCodes.Status.UNVERIFIED,
"NOT_AUTHENTICATED", "Операция доступна только для авторизованной сессии");
}
try {
List<String> ids = SessionRevocationSupport.deleteOtherSessions(ctx.getLogin().trim(), ctx.getSessionId());
SessionRevocationSupport.revokeConnections(ids, "closed_other_sessions",
"Session closed by CloseOtherSessions");
Net_CloseOtherSessions_Response resp = new Net_CloseOtherSessions_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setClosedCount(ids.size());
return resp;
} catch (Exception e) {
log.error("CloseOtherSessions failed login={}", ctx.getLogin(), e);
return NetExceptionResponseFactory.error(req, WireCodes.Status.SERVER_DATA_ERROR,
"DB_ERROR", "Не удалось закрыть остальные сессии");
}
}
}
@@ -0,0 +1,49 @@
package server.logic.ws_protocol.JSON.handlers.auth;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import server.logic.ws_protocol.JSON.ActiveConnectionsRegistry;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.push.WsEventSender;
import server.logic.ws_protocol.JSON.utils.NetIdGenerator;
import server.ws.WsConnectionUtils;
import shine.db.dao.ActiveSessionsDAO;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/** Общая логика отзыва пользовательских сессий. */
public final class SessionRevocationSupport {
private static final ObjectMapper MAPPER = new ObjectMapper();
private SessionRevocationSupport() {}
public static List<String> deleteOtherSessions(Connection c, String login, String keepSessionId) throws SQLException {
return ActiveSessionsDAO.getInstance().deleteOtherSessions(c, login, keepSessionId);
}
public static List<String> deleteOtherSessions(String login, String keepSessionId) throws SQLException {
return ActiveSessionsDAO.getInstance().deleteOtherSessions(login, keepSessionId);
}
public static void revokeConnections(List<String> sessionIds, String reason, String closeReason) {
if (sessionIds == null) return;
for (String sessionId : sessionIds) {
revokeConnection(sessionId, reason, closeReason);
}
}
public static void revokeConnection(String sessionId, String reason, String closeReason) {
ConnectionContext target = ActiveConnectionsRegistry.getInstance().getBySessionId(sessionId);
if (target == null) return;
String eventId = NetIdGenerator.eventId("evt");
ObjectNode payload = MAPPER.createObjectNode();
payload.put("eventId", eventId);
payload.put("sessionId", sessionId);
payload.put("reason", reason == null ? "session_revoked" : reason);
payload.put("timeMs", System.currentTimeMillis());
WsEventSender.sendEvent(target, "SessionRevoked", eventId, payload);
WsConnectionUtils.closeConnection(target, 4000, closeReason == null ? "Session revoked" : closeReason);
}
}
@@ -252,7 +252,7 @@ public final class SolanaUserPdaImportService {
c = payloadEnd;
}
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0) return null;
if (blockchainKey32 == null || clientKey32 == null || forkCount <= 0 || forkCount > 999) return null;
String blockchainName = login + "-" + String.format(Locale.ROOT, "%03d", forkCount);
return new ParsedSolanaUser(
login,
@@ -0,0 +1,7 @@
package server.logic.ws_protocol.JSON.handlers.auth.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Закрыть все активные сессии текущего пользователя, кроме текущей. */
public final class Net_CloseOtherSessions_Request extends Net_Request {
}
@@ -0,0 +1,9 @@
package server.logic.ws_protocol.JSON.handlers.auth.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
public final class Net_CloseOtherSessions_Response extends Net_Response {
private int closedCount;
public int getClosedCount() { return closedCount; }
public void setClosedCount(int closedCount) { this.closedCount = closedCount; }
}
@@ -3,10 +3,13 @@ package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.BodyHasLine;
import blockchain.body.BodyHasTarget;
import blockchain.body.ConnectionBody;
import blockchain.body.CreateChannelBody;
import blockchain.body.HeaderBody;
import blockchain.body.ForkBody;
import blockchain.body.StatusActionBody;
import blockchain.body.TextReplyBody;
import blockchain.body.TextLineBody;
@@ -28,10 +31,11 @@ import server.logic.ws_protocol.JSON.handlers.channels.ChannelMetaTextParser;
import server.logic.ws_protocol.JSON.handlers.channels.ChannelNamesStateBootstrapper;
import server.logic.ws_protocol.JSON.handlers.channels.UserCountersSupport;
import server.logic.ws_protocol.WireCodes;
import server.sync.AddBlockSyncService;
import server.sync.ArweavePublishSignal;
import shine.db.channels.ChannelNameRules;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.BlocksDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.ChannelNameStateDAO;
import shine.db.dao.UserNotificationsStateDAO;
import shine.db.dao.UserParamsDAO;
@@ -62,10 +66,10 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_AddBlock_Handler.class);
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final CanonicalChainResolver canonicalChain = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO stateDAO = BlockchainStateDAO.getInstance();
private final UserParamsDAO userParamsDAO = UserParamsDAO.getInstance();
private final ChannelNameStateDAO channelNameStateDAO = ChannelNameStateDAO.getInstance();
private final AddBlockSyncService addBlockSyncService = new AddBlockSyncService();
private final BlockchainWriter dbWriter = new BlockchainWriter(
blocksDAO, stateDAO, userParamsDAO, channelNameStateDAO, UserNotificationsStateDAO.getInstance());
@@ -98,13 +102,26 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
ReentrantLock lock = BlockchainLocks.lockFor(blockchainName);
lock.lock();
try {
try {
if (isKeyRotationActive(blockchainName)) {
BlockchainStateEntry currentState = stateDAO.getByBlockchainName(blockchainName);
int lastNum = currentState != null ? currentState.getLastBlockNumber() : -1;
String lastHash = currentState != null ? toHex(currentState.getLastBlockHash()) : "";
return error(req, 423, "key_rotation_in_progress", lastNum, lastHash);
}
} catch (Exception e) {
log.error("AddBlock: не удалось проверить key rotation status для {}", blockchainName, e);
return error(req, WireCodes.Status.INTERNAL_ERROR, "key_rotation_check_failed", -1, "");
}
AddBlockResult r = addBlock(
blockchainName,
req.getBlockNumber(), // старое поле, пока оставляем
req.getPrevBlockHash(), // старое поле, пока оставляем
req.getBlockBytesB64(),
true,
true
true,
false
);
// ✅ УСПЕХ: как раньше
@@ -152,6 +169,23 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return resp;
}
private boolean isKeyRotationActive(String blockchainName) throws java.sql.SQLException {
String login = BlockchainNameUtil.loginFromBlockchainName(blockchainName);
if (login == null || login.isBlank()) return false;
try (Connection c = shine.db.DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT rotation_status
FROM solana_user_pda_current
WHERE normalized_login = LOWER(BTRIM(?))
LIMIT 1
""")) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() && !"NONE".equals(rs.getString(1));
}
}
}
private static String humanMessage(String code) {
if (code == null) return "Ошибка добавления блока";
return switch (code) {
@@ -165,18 +199,27 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "limit_check_failed" -> "Ошибка проверки лимита размера";
case "bad_block_format" -> "Некорректный формат блока";
case "bad_app_tag" -> "Некорректный тестовый тег ANS-104";
case "bad_type_tag" -> "Некорректный индексный t-тег ANS-104";
case "bad_channel_tag" -> "Некорректный тег канала ANS-104";
case "bad_block_body" -> "Некорректное тело блока";
case "bad_channel_name" -> "Некорректное название канала";
case "bad_block_number" -> "Некорректный номер блока";
case "req_global_mismatch" -> "Номер блока в запросе не совпадает с номером в блоке";
case "bad_prev_hash" -> "Некорректный prevHash (цепочка не совпадает)";
case "bad_back32_hash" -> "Некорректный back32Hash (резервная ссылка N-32 не совпадает)";
case "db_error_back32_check" -> "Ошибка БД при проверке back32Hash";
case "bad_blockchain_key_len" -> "Некорректный ключ блокчейна в состоянии (ожидалось 32 байта)";
case "signature_verify_failed" -> "Ошибка проверки подписи блока";
case "bad_signature" -> "Некорректная подпись блока";
case "prev_line_block_not_found" -> "Не найден блок prevLineNumber для проверки линии";
case "prev_line_block_not_found", "line_root_not_found" -> "Не найден root/prev блок логической линии";
case "bad_line_code" -> "Некорректный код логической линии";
case "bad_line_root" -> "Некорректный root логической линии";
case "bad_line_state" -> "Повреждено состояние логической линии";
case "bad_prev_line_number" -> "Блок не продолжает текущий хвост логической линии";
case "bad_prev_line_hash" -> "Некорректный prevLineHash";
case "db_error_prev_line_check" -> "Ошибка БД при проверке prevLine";
case "bad_line_sequence" -> "Некорректный порядковый номер логической линии";
case "unsupported_line_body" -> "Этот body не поддерживает логическую линию";
case "db_error_prev_line_check", "db_error_line_check" -> "Ошибка БД при проверке логической линии";
case "channel_name_already_exists" -> "Такое название канала уже занято";
case "repost_disabled" -> "Репосты временно отключены до будущей реализации";
case "entrypoint_edit_forbidden" -> "TEXT_ENTRYPOINT нельзя редактировать через TEXT_EDIT_POST";
@@ -184,6 +227,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
case "status_action_target_not_allowed" -> "Этот STATUS_ACTION нельзя ставить на выбранный тип материала";
case "internal_error" -> "Внутренняя ошибка сервера при записи блока";
case "chain_resync_in_progress" -> "Цепочка сейчас пересинхронизируется";
case "key_rotation_in_progress" -> "Сейчас выполняется смена ключей; обычные новые блоки временно запрещены";
case "key_rotation_check_failed" -> "Не удалось проверить состояние смены ключей";
default -> "Ошибка: " + code;
};
}
@@ -194,7 +239,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
String prevGlobalHashHexFromReq,
String blockBytesB64,
boolean replicateAfterWrite,
boolean publishToArweave
boolean publishToArweave,
boolean replayMode
) {
if (blockchainName == null || blockchainName.isBlank()) {
log.warn("AddBlock: пустой blockchainName (reqGlobalNumber={})", globalNumberFromReq);
@@ -276,10 +322,21 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_format", serverLastNum, serverLastHashHex);
}
if (!block.getDataItem().hasTag("App", "test5590")) {
if (!block.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_app_tag", serverLastNum, serverLastHashHex);
}
// Signed secondary index for the fixed SHiNE streams.
String expectedTypeTag = expectedTypeTag(block);
String actualTypeTag = block.getDataItem().tagValue(ShineProtocolTags.TYPE_TAG_NAME);
if (expectedTypeTag != null) {
if (!expectedTypeTag.equals(actualTypeTag)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
}
} else if (actualTypeTag != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_type_tag", serverLastNum, serverLastHashHex);
}
// body.check()
try {
block.body.check();
@@ -289,6 +346,18 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_block_body", serverLastNum, serverLastHashHex);
}
// Canonical chain bootstrap: block #0 is always HEADER.
if (serverLastNum == -1) {
if (!(block.body instanceof HeaderBody headerBody)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_required_as_block_zero", serverLastNum, serverLastHashHex);
}
if (!login.equals(headerBody.login)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_login_mismatch", serverLastNum, serverLastHashHex);
}
} else if (block.body instanceof HeaderBody) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_must_be_block_zero", serverLastNum, serverLastHashHex);
}
// Репосты временно отключены до будущей реализации.
// Точка возврата: docs/Future_Features/2026-05-24_1140_репосты_в_каналах_и_тредах.md
if ((block.type & 0xFFFF) == 1
@@ -300,7 +369,6 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
ChannelNameStateEntry channelNameStateEntry = null;
ChannelNameStateEntry channelMetaUpdateEntry = null;
Chat200CreateSeed chat200CreateSeed = null;
if (block.body instanceof CreateChannelBody createChannelBody) {
int channelTypeCode = Short.toUnsignedInt(createChannelBody.channelTypeCode);
int channelTypeVersion = Short.toUnsignedInt(createChannelBody.channelTypeVersion);
@@ -363,17 +431,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
channelNameStateEntry.setChannelRootBlockHash(block.getHash32());
channelNameStateEntry.setCreatedAtMs(block.timestamp * 1000L);
if (channelTypeCode == (CreateChannelBody.CHANNEL_TYPE_GROUP & 0xFFFF)) {
chat200CreateSeed = new Chat200CreateSeed();
chat200CreateSeed.ownerLogin = login;
chat200CreateSeed.ownerBch = blockchainName;
chat200CreateSeed.rootBlockNumber = block.blockNumber;
chat200CreateSeed.rootBlockHash = block.getHash32();
chat200CreateSeed.channelName = normalizedName;
chat200CreateSeed.channelTypeVersion = channelTypeVersion;
chat200CreateSeed.chatTitle = channelNameStateEntry.getChannelDescription();
chat200CreateSeed.updatedAtMs = block.timestamp * 1000L;
}
// Chat200 group projection intentionally retired; legacy helpers remain @Deprecated only.
} else if ((block.type & 0xFFFF) == 1
&& (block.subType & 0xFFFF) == (MsgSubType.TEXT_CHANNEL_META & 0xFFFF)
&& block.body instanceof TextLineBody metaBody) {
@@ -399,6 +457,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, e.getMessage(), serverLastNum, serverLastHashHex);
}
channelMetaUpdateEntry = new ChannelNameStateEntry();
channelMetaUpdateEntry.setOwnerLogin(login);
channelMetaUpdateEntry.setOwnerBlockchainName(blockchainName);
channelMetaUpdateEntry.setChannelRootBlockNumber(lineCode);
channelMetaUpdateEntry.setDisplayName(parsedMeta.title());
@@ -409,10 +468,10 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
channelMetaUpdateEntry.setMetaUpdatedAtMs(block.timestamp * 1000L);
}
// Channel DataItems are indexed by a signed canonical channel slug tag: c_test5590=<slug>.
// Channel DataItems are indexed by a signed canonical channel slug tag: c=<slug>.
try {
String expectedChannelSlug = expectedChannelSlug(blockchainName, block, channelNameStateEntry);
String actualChannelSlug = block.getDataItem().tagValue("c_test5590");
String actualChannelSlug = block.getDataItem().tagValue(ShineProtocolTags.CHANNEL_TAG_NAME);
if (expectedChannelSlug != null) {
if (!expectedChannelSlug.equals(actualChannelSlug)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_channel_tag", serverLastNum, serverLastHashHex);
@@ -439,6 +498,20 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
}
if ((block.type & 0xFFFF) == 1
&& (block.subType & 0xFFFF) == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF)) {
try {
String editError = validateEditReplyTarget(blockchainName, block);
if (editError != null) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, editError, serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: edit_reply_target_check_failed (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "internal_error", serverLastNum, serverLastHashHex);
}
}
if ((block.type & 0xFFFF) == 5) {
try {
String statusError = validateStatusActionTarget(block);
@@ -474,6 +547,29 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_prev_hash", serverLastNum, serverLastHashHex);
}
// 4.4) резервная глобальная ссылка: N<32 -> ZERO32, иначе hash блока N-32.
try {
byte[] expectedBack32 = new byte[32];
if (block.blockNumber >= 32) {
byte[] storedBack32 = canonicalChain.getHash(blockchainName, block.blockNumber - 32);
if (storedBack32 == null || storedBack32.length != 32) {
log.error("AddBlock: missing N-32 block for back32 validation (blockchainName={}, blockNumber={}, target={})",
blockchainName, block.blockNumber, block.blockNumber - 32);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_back32_check", serverLastNum, serverLastHashHex);
}
expectedBack32 = storedBack32;
}
if (!Arrays.equals(block.back32Hash32, expectedBack32)) {
log.warn("AddBlock: bad_back32_hash (login={}, blockchainName={}, blockNumber={}, clientBack32={}, expectedBack32={})",
login, blockchainName, block.blockNumber, toHex(block.back32Hash32), toHex(expectedBack32));
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_back32_hash", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: db_error_back32_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_back32_check", serverLastNum, serverLastHashHex);
}
// 5) pubKey
final byte[] pubKey32 = st.getBlockchainKeyBytes();
if (pubKey32 == null || pubKey32.length != 32) {
@@ -482,6 +578,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_blockchain_key_len", serverLastNum, serverLastHashHex);
}
if (serverLastNum == -1 && block.body instanceof HeaderBody headerBody
&& !Arrays.equals(headerBody.initialBlockchainKey32, pubKey32)) {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "header_initial_key_mismatch", serverLastNum, serverLastHashHex);
}
// 6) ANS-104 Ed25519 подпись и owner
boolean sigOk;
try {
@@ -498,7 +599,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_signature", serverLastNum, serverLastHashHex);
}
// 7) line columns (only for BodyHasLine)
// 7) line columns + strict continuity check.
Integer lineCode = null;
Integer prevLineNumber = null;
byte[] prevLineHash32 = null;
@@ -510,33 +611,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
prevLineHash32 = bl.prevLineBlockHash32();
thisLineNumber = bl.lineSeq();
// Нормализация: -1 не пишем в БД (для совместимости со старым TextBody)
if (prevLineNumber != null && prevLineNumber == -1) {
lineCode = null;
prevLineNumber = null;
prevLineHash32 = null;
thisLineNumber = null;
}
// Если prevLineNumber задан — проверяем его хэш
if (prevLineNumber != null) {
try {
byte[] dbPrevHash = blocksDAO.getHashByNumber(blockchainName, prevLineNumber);
if (dbPrevHash == null) {
log.warn("AddBlock: prev_line_block_not_found (login={}, blockchainName={}, blockNumber={}, prevLineNumber={})",
login, blockchainName, block.blockNumber, prevLineNumber);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "prev_line_block_not_found", serverLastNum, serverLastHashHex);
}
if (!Arrays.equals(dbPrevHash, require32OrThrow(prevLineHash32, "prevLineHash32 invalid"))) {
log.warn("AddBlock: bad_prev_line_hash (login={}, blockchainName={}, blockNumber={}, prevLineNumber={})",
login, blockchainName, block.blockNumber, prevLineNumber);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, "bad_prev_line_hash", serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: db_error_prev_line_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_prev_line_check", serverLastNum, serverLastHashHex);
try {
String lineError = validateLineContinuity(blockchainName, block, bl);
if (lineError != null) {
log.warn("AddBlock: {} (login={}, blockchainName={}, blockNumber={}, lineCode={}, prevLineNumber={}, lineSeq={})",
lineError, login, blockchainName, block.blockNumber, lineCode, prevLineNumber, thisLineNumber);
return new AddBlockResult(WireCodes.Status.BAD_REQUEST, lineError, serverLastNum, serverLastHashHex);
}
} catch (Exception e) {
log.error("AddBlock: db_error_line_check (login={}, blockchainName={}, blockNumber={})",
login, blockchainName, block.blockNumber, e);
return new AddBlockResult(WireCodes.Status.INTERNAL_ERROR, "db_error_line_check", serverLastNum, serverLastHashHex);
}
}
@@ -544,7 +629,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
try {
BlockEntry be = new BlockEntry();
be.setLogin(login);
be.setBchName(blockchainName);
be.setForkNumber(java.util.Objects.requireNonNull(BlockchainNameUtil.forkNumberFromBlockchainName(blockchainName), "invalid blockchainName fork"));
be.setBlockNumber(block.blockNumber);
be.setMsgType(block.type & 0xFFFF);
@@ -562,28 +647,29 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
be.setPrevLineHash(prevLineHash32);
be.setThisLineNumber(thisLineNumber);
// target columns (optional)
// target columns (optional). Signed identity is login + blockNumber + blockHash.
// toForkNumber is historical metadata only and never participates in target identity.
if (block.body instanceof BodyHasTarget t) {
String targetBchName = t.toBchName();
int type = block.type & 0xFFFF;
int sub = block.subType & 0xFFFF;
boolean isTextEdit = type == 1
&& (sub == (MsgSubType.TEXT_EDIT_POST & 0xFFFF) || sub == (MsgSubType.TEXT_EDIT_REPLY & 0xFFFF));
if (isTextEdit && (targetBchName == null || targetBchName.isBlank())) {
targetBchName = blockchainName;
String targetLogin = t.toLogin();
Integer targetForkNumber = t.toForkNumber();
if (isTextEdit) {
// EDIT target is compact and belongs to this logical user history; physical fork is resolved canonically.
targetLogin = login;
targetForkNumber = null;
}
be.setToLogin(t.toLogin());
be.setToBchName(targetBchName);
be.setToLogin(targetLogin);
be.setToForkNumber(targetForkNumber);
be.setToBlockNumber(t.toBlockGlobalNumber());
be.setToBlockHash(t.toBlockHashBytes());
if (isTextEdit && (be.getToLogin() == null || be.getToLogin().isBlank()) && targetBchName != null && !targetBchName.isBlank()) {
be.setToLogin(BlockchainNameUtil.loginFromBlockchainName(targetBchName));
}
}
// edit helper (optional): если TEXT_EDIT_* — это "редактирование блока цели"
// edit helper (optional): TEXT_EDIT_* targets are resolved against logical canonical history
int type = block.type & 0xFFFF;
int sub = block.subType & 0xFFFF;
@@ -617,16 +703,21 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
UserNotificationEntry notificationEntry = buildNotificationEntry(block, be);
List<String> counterChangedLogins = dbWriter.appendBlockAndState(
blockchainName, block, st, be, upsertedParam, channelNameStateEntry, channelMetaUpdateEntry, notificationEntry);
blockchainName, block, st, be, upsertedParam, channelNameStateEntry, channelMetaUpdateEntry, notificationEntry, replayMode);
for (String changedLogin : counterChangedLogins) {
UserCountersSupport.pushChanged(changedLogin);
if (!replayMode) {
for (String changedLogin : counterChangedLogins) {
UserCountersSupport.pushChanged(changedLogin);
}
}
if (chat200CreateSeed != null) {
upsertChat200StateFromCreate(chat200CreateSeed);
// Chat200 is legacy/non-working/unused. Do not create or mutate Chat200 projections.
// The historical helper code remains below only for archive compatibility and may be removed later.
if (publishToArweave) {
// Только ставим быструю публикацию в очередь: ответ клиенту не ждёт сеть Turbo/Arweave.
ArweavePublishSignal.userBlockAccepted(be.getDataItemId());
}
maybeApplyChat200Command(blockchainName, block);
} catch (Exception e) {
if (isChannelSlugConflict(e)) {
return new AddBlockResult(409, "channel_name_already_exists", serverLastNum, serverLastHashHex);
@@ -641,9 +732,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
log.info("✅ AddBlock ok: login={}, blockchainName={}, blockNumber={}, newHash={}",
login, blockchainName, block.blockNumber, newHashHex);
if (replicateAfterWrite) {
addBlockSyncService.replicateAsync(blockchainName, block.blockNumber);
}
// Legacy server-to-server replication is intentionally disabled.
// Arweave/Turbo is the supported cross-server recovery/synchronization source.
return new AddBlockResult(WireCodes.Status.OK, null, block.blockNumber, newHashHex);
}
@@ -653,7 +743,16 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
* но не запускает повторную межсерверную репликацию уже импортированного блока.
*/
public ArweaveImportResult addBlockFromArweave(String blockchainName, byte[] rawBlockBytes) {
if (BlockchainResyncGuard.isBlockedForExternalAddBlock(blockchainName)) {
return addBlockFromStoredBytes(blockchainName, rawBlockBytes, false);
}
/** Deterministic local replay: rebuild SQL projections without live notifications/unread/push side effects. */
public ArweaveImportResult addBlockFromReplay(String blockchainName, byte[] rawBlockBytes) {
return addBlockFromStoredBytes(blockchainName, rawBlockBytes, true);
}
private ArweaveImportResult addBlockFromStoredBytes(String blockchainName, byte[] rawBlockBytes, boolean replayMode) {
if (!replayMode && BlockchainResyncGuard.isBlockedForExternalAddBlock(blockchainName)) {
return new ArweaveImportResult(false, "chain_resync_in_progress", -1, "");
}
if (rawBlockBytes == null || rawBlockBytes.length == 0) {
@@ -682,7 +781,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
toHex(parsed.prevHash32),
Base64Ws.encode(rawBlockBytes),
false,
false
false,
replayMode
);
return new ArweaveImportResult(r.isOk(), r.reasonCode, r.serverLastBlockNumber, r.serverLastBlockHashHex);
} finally {
@@ -696,6 +796,84 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
/* ====================== Helpers ====================================== */
/* ===================================================================== */
private static String expectedTypeTag(BchBlockEntry block) {
int type = block.type & 0xffff;
return switch (type) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
/**
* Проверяет не просто существование prev-блока, а именно продолжение текущего хвоста линии.
* Это запрещает боковые ветки линии и гарантирует монотонный sequence.
*/
private String validateLineContinuity(String blockchainName, BchBlockEntry block, BodyHasLine line) throws Exception {
int type = block.type & 0xffff;
int lineCode = line.lineCode();
int rootBlockNumber;
int firstSequence;
if (block.body instanceof UserParamBody || block.body instanceof ConnectionBody) {
if (lineCode != 0) return "bad_line_code";
rootBlockNumber = 0;
firstSequence = 1;
} else if (block.body instanceof CreateChannelBody || block.body instanceof ForkBody) {
if (lineCode != 0) return "bad_line_code";
rootBlockNumber = 0;
firstSequence = 1;
} else if (block.body instanceof TextLineBody) {
if (lineCode < 0) return "bad_line_code";
rootBlockNumber = lineCode;
// Channel sequence is zero-based after its root anchor.
firstSequence = 0;
} else {
return "unsupported_line_body";
}
BlockEntry root = canonicalChain.getBlock(blockchainName, rootBlockNumber);
if (root == null) return "line_root_not_found";
if (rootBlockNumber == 0) {
try {
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof HeaderBody)) return "bad_line_root";
} catch (Exception e) {
return "bad_line_root";
}
} else {
try {
if (!(new BchBlockEntry(root.getBlockBytes()).body instanceof CreateChannelBody)) return "bad_line_root";
} catch (Exception e) {
return "bad_line_root";
}
}
BlockEntry tail;
try (Connection resolverConnection = shine.db.DbController.getInstance().getConnection()) {
tail = canonicalChain.getLastLineBlock(resolverConnection, blockchainName, type, lineCode, block.blockNumber);
}
int expectedPrevNumber;
byte[] expectedPrevHash;
int expectedSequence;
if (tail == null) {
expectedPrevNumber = rootBlockNumber;
expectedPrevHash = root.getBlockHash();
expectedSequence = firstSequence;
} else {
if (tail.getThisLineNumber() == null) return "bad_line_state";
expectedPrevNumber = tail.getBlockNumber();
expectedPrevHash = tail.getBlockHash();
expectedSequence = Math.addExact(tail.getThisLineNumber(), 1);
}
if (line.prevLineBlockGlobalNumber() != expectedPrevNumber) return "bad_prev_line_number";
byte[] suppliedPrevHash = require32OrThrow(line.prevLineBlockHash32(), "prevLineHash32 invalid");
if (!Arrays.equals(expectedPrevHash, suppliedPrevHash)) return "bad_prev_line_hash";
if (line.lineSeq() != expectedSequence) return "bad_line_sequence";
return null;
}
private String expectedChannelSlug(String blockchainName, BchBlockEntry block, ChannelNameStateEntry justCreated) throws Exception {
if (block.body instanceof CreateChannelBody) {
return justCreated == null ? null : justCreated.getSlug();
@@ -706,6 +884,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
sub == (MsgSubType.TEXT_POST & 0xffff)
|| sub == (MsgSubType.TEXT_REPOST & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_META & 0xffff)
|| sub == (MsgSubType.TEXT_CHANNEL_DELETE & 0xffff)
|| sub == (MsgSubType.TEXT_ENTRYPOINT & 0xffff)
|| sub == (MsgSubType.TEXT_EXERCISE & 0xffff)
|| sub == (MsgSubType.TEXT_SERVICE & 0xffff)
@@ -759,6 +938,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
return false;
}
/** @deprecated Chat200 is legacy/non-working/unused. */
@Deprecated
private static final class Chat200CreateSeed {
String ownerLogin;
String ownerBch;
@@ -775,41 +956,58 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
private String validateEditPostTarget(String ownerBch, BchBlockEntry block) throws Exception {
if (!(block.body instanceof TextLineBody editBody)) return null;
if (!(block.body instanceof TextLineBody editBody)) return "bad_block_body";
Integer targetBlockNumber = editBody.toBlockGlobalNumber();
byte[] targetHash = editBody.toBlockHashBytes();
if (targetBlockNumber == null || targetHash == null || targetHash.length != 32) return "bad_block_body";
BlockEntry target = blocksDAO.getByNumber(ownerBch, targetBlockNumber);
BlockEntry target = canonicalChain.getBlock(ownerBch, targetBlockNumber);
if (target == null || target.getBlockHash() == null || !Arrays.equals(target.getBlockHash(), targetHash)) {
return null;
return "edit_target_not_found";
}
if (target.getMsgType() != 1) return null;
if (target.getMsgSubType() == (MsgSubType.TEXT_ENTRYPOINT & 0xFFFF)) {
return "entrypoint_edit_forbidden";
if (target.getMsgType() != 1 || target.getMsgSubType() != (MsgSubType.TEXT_POST & 0xFFFF)) {
return "edit_post_target_must_be_text_post";
}
return null;
}
private String validateEditReplyTarget(String ownerBch, BchBlockEntry block) throws Exception {
if (!(block.body instanceof TextReplyBody editBody)) return "bad_block_body";
Integer targetBlockNumber = editBody.toBlockGlobalNumber();
byte[] targetHash = editBody.toBlockHashBytes();
if (targetBlockNumber == null || targetHash == null || targetHash.length != 32) return "bad_block_body";
BlockEntry target = canonicalChain.getBlock(ownerBch, targetBlockNumber);
if (target == null || target.getBlockHash() == null || !Arrays.equals(target.getBlockHash(), targetHash)) {
return "edit_target_not_found";
}
if (target.getMsgType() != 1 || target.getMsgSubType() != (MsgSubType.TEXT_REPLY & 0xFFFF)) {
return "edit_reply_target_must_be_text_reply";
}
return null;
}
private String validateStatusActionTarget(BchBlockEntry block) throws Exception {
if (!(block.body instanceof StatusActionBody statusBody)) return "bad_block_body";
String targetBch = statusBody.toBchName();
String targetLogin = statusBody.toLogin();
Integer targetFork = statusBody.toForkNumber();
Integer targetBlockNumber = statusBody.toBlockGlobalNumber();
byte[] targetHash = statusBody.toBlockHashBytes();
if (targetBch == null || targetBch.isBlank() || targetBlockNumber == null || targetHash == null || targetHash.length != 32) {
if (targetLogin == null || targetLogin.isBlank() || targetFork == null
|| targetBlockNumber == null || targetHash == null || targetHash.length != 32) {
return "bad_block_body";
}
// forkNumber is historical only. It is used here solely as a physical lookup hint.
if (targetFork <= 0) return null;
String targetBch = BlockchainNameUtil.blockchainName(targetLogin, targetFork);
BlockEntry target = blocksDAO.getByNumber(targetBch, targetBlockNumber);
if (target == null || target.getBlockHash() == null || !Arrays.equals(target.getBlockHash(), targetHash)) {
return null;
}
int statusSubType = block.subType & 0xFFFF;
if (statusSubType == (MsgSubType.STATUS_CONFIRMED & 0xFFFF)) {
if (target.getMsgType() != 5) {
return "status_confirmed_target_must_be_status_action";
}
return null;
return target.getMsgType() == 5 ? null : "status_confirmed_target_must_be_status_action";
}
if (target.getMsgType() != 1) return "status_action_target_not_allowed";
@@ -836,10 +1034,10 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
PreparedStatement ps = c.prepareStatement("""
SELECT slug
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""")) {
ps.setString(1, ownerBch);
ps.setString(1, BlockchainNameUtil.loginFromBlockchainName(ownerBch));
ps.setInt(2, rootBlockNumber);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
@@ -850,6 +1048,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
}
/** @deprecated Chat200 is legacy/non-working/unused. */
@Deprecated
private void upsertChat200StateFromCreate(Chat200CreateSeed seed) throws Exception {
try (Connection c = shine.db.DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
@@ -877,6 +1077,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
}
/** @deprecated Chat200 is legacy/non-working/unused. */
@Deprecated
private void maybeApplyChat200Command(String ownerBch, BchBlockEntry block) throws Exception {
int msgType = block.type & 0xFFFF;
int msgSubType = block.subType & 0xFFFF;
@@ -887,6 +1089,8 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
if (lineCode == null || lineCode <= 0) return;
if (!isChat200Channel(ownerBch, lineCode)) return;
BlockEntry rootPhysical = canonicalChain.getBlock(ownerBch, lineCode);
String chatOwnerBch = rootPhysical == null ? ownerBch : rootPhysical.getBchName();
CommandParsed cmd = parseChatCommand(tlb.message);
if (cmd == null) return;
@@ -897,11 +1101,11 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
PreparedStatement ps = c.prepareStatement("""
UPDATE chat200_state
SET chat_title = ?, updated_at_ms = ?
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
""")) {
ps.setString(1, cmd.arg1 == null ? "" : cmd.arg1);
ps.setLong(2, updatedAtMs);
ps.setString(3, ownerBch);
ps.setString(3, chatOwnerBch);
ps.setInt(4, lineCode);
ps.executeUpdate();
}
@@ -925,7 +1129,7 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
updated_at_ms = excluded.updated_at_ms,
updated_by_block_number = excluded.updated_by_block_number
""")) {
ps.setString(1, ownerBch);
ps.setString(1, chatOwnerBch);
ps.setInt(2, lineCode);
ps.setString(3, memberLogin);
ps.setString(4, memberChannel);
@@ -936,15 +1140,17 @@ public final class Net_AddBlock_Handler implements JsonMessageHandler {
}
}
/** @deprecated Chat200 is legacy/non-working/unused. */
@Deprecated
private boolean isChat200Channel(String ownerBch, int rootBlockNumber) throws Exception {
try (Connection c = shine.db.DbController.getInstance().getConnection();
PreparedStatement ps = c.prepareStatement("""
SELECT channel_type_code
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""")) {
ps.setString(1, ownerBch);
ps.setString(1, BlockchainNameUtil.loginFromBlockchainName(ownerBch));
ps.setInt(2, rootBlockNumber);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return false;
@@ -17,7 +17,9 @@ import shine.db.entities.UserNotificationEntry;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/** Stores the complete ANS-104 DataItem and all derived SHiNE state atomically in PostgreSQL.
* Local .bch/tmp/marker files are intentionally not used.
@@ -55,11 +57,12 @@ public final class BlockchainWriter {
UserParamEntry userParamEntry,
ChannelNameStateEntry channelNameStateEntry,
ChannelNameStateEntry channelMetaUpdateEntry,
UserNotificationEntry notificationEntry) throws SQLException {
UserNotificationEntry notificationEntry,
boolean replayMode) throws SQLException {
long nowMs = System.currentTimeMillis();
byte[] rawDataItem = block.toBytes();
List<String> counterChangedLogins = new ArrayList<>();
Set<String> counterChangedLogins = new LinkedHashSet<>();
try (Connection c = shine.db.DbController.getInstance().getConnection()) {
c.setAutoCommit(false);
try {
@@ -79,7 +82,18 @@ public final class BlockchainWriter {
int msgType = block.type & 0xFFFF;
int msgSubType = block.subType & 0xFFFF;
Integer lineCode = be.getLineCode();
if (isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode > 0) {
boolean channelVisibilityChanged = false;
if (msgType == 1 && lineCode != null && lineCode > 0) {
if (msgSubType == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF)) {
channelVisibilityChanged = channelNameStateDAO.updateDeletedState(
c, blockchainName, lineCode, true, block.timestamp * 1000L, block.blockNumber);
} else if (isPublicChannelPublication(msgType, msgSubType)) {
channelVisibilityChanged = channelNameStateDAO.updateDeletedState(
c, blockchainName, lineCode, false, 0L, null);
}
if (channelVisibilityChanged) counterChangedLogins.addAll(refreshChannelVisibilityStats(c, blockchainName, lineCode));
}
if (!replayMode && isPublicChannelPublication(msgType, msgSubType) && lineCode != null && lineCode > 0) {
String channelName = channelReadStateDAO.resolvePublicChannelNameByRoot(c, blockchainName, lineCode);
if (channelName != null && !channelName.isBlank()) {
counterChangedLogins.addAll(channelReadStateDAO.incrementUnreadForSubscribers(
@@ -87,7 +101,7 @@ public final class BlockchainWriter {
}
}
if (msgType == 3
if (!replayMode && msgType == 3
&& msgSubType == (MsgSubType.CONNECTION_UNFOLLOW & 0xFFFF)
&& be.getToBchName() != null && !be.getToBchName().isBlank()
&& be.getToBlockNumber() != null && be.getToBlockNumber() > 0) {
@@ -106,7 +120,67 @@ public final class BlockchainWriter {
try { c.setAutoCommit(true); } catch (Exception ignored) {}
}
}
return counterChangedLogins;
return new ArrayList<>(counterChangedLogins);
}
private static List<String> refreshChannelVisibilityStats(Connection c, String blockchainName, int lineCode) throws SQLException {
String sql = """
SELECT owner_login, channel_root_block_hash
FROM channel_names_state
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number=?
LIMIT 1
""";
String ownerLogin = null;
byte[] rootHash = null;
try (var ps = c.prepareStatement(sql)) {
ps.setString(1, loginFromBlockchainName(blockchainName));
ps.setInt(2, lineCode);
try (var rs = ps.executeQuery()) {
if (rs.next()) {
ownerLogin = rs.getString("owner_login");
rootHash = rs.getBytes("channel_root_block_hash");
}
}
}
if (ownerLogin == null || ownerLogin.isBlank() || rootHash == null) return List.of();
Set<String> affected = new LinkedHashSet<>();
affected.add(ownerLogin);
try (var ps = c.prepareStatement("SELECT shine_refresh_user_stats(?)")) {
ps.setString(1, ownerLogin);
ps.execute();
}
String followersSql = """
SELECT DISTINCT cs.login
FROM connections_state cs
WHERE cs.rel_type=?
AND LOWER(cs.to_login)=LOWER(?)
AND cs.to_block_number=?
AND cs.to_block_hash=?
""";
try (var ps = c.prepareStatement(followersSql)) {
ps.setInt(1, MsgSubType.CONNECTION_FOLLOW);
ps.setString(2, ownerLogin);
ps.setInt(3, lineCode);
ps.setBytes(4, rootHash);
try (var rs = ps.executeQuery(); var refresh = c.prepareStatement("SELECT shine_refresh_user_stats(?)")) {
while (rs.next()) {
String follower = rs.getString(1);
if (follower == null || follower.isBlank()) continue;
refresh.setString(1, follower);
refresh.execute();
affected.add(follower);
}
}
}
return new ArrayList<>(affected);
}
private static String loginFromBlockchainName(String blockchainName) {
if (blockchainName == null) return "";
int dash = blockchainName.lastIndexOf('-');
return dash > 0 ? blockchainName.substring(0, dash) : blockchainName;
}
private static boolean isPublicChannelPublication(int msgType, int msgSubType) {
@@ -21,6 +21,7 @@ public final class Net_GetBlockchainBlock_Handler implements JsonMessageHandler
private static final Logger log = LoggerFactory.getLogger(Net_GetBlockchainBlock_Handler.class);
private final BlocksDAO blocksDAO = BlocksDAO.getInstance();
private final shine.db.dao.CanonicalChainResolver canonicalChain = shine.db.dao.CanonicalChainResolver.getInstance();
@Override
public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
@@ -37,7 +38,7 @@ public final class Net_GetBlockchainBlock_Handler implements JsonMessageHandler
}
try {
BlockEntry block = blocksDAO.getByNumber(blockchainName, req.getBlockNumber());
BlockEntry block = canonicalChain.getBlock(blockchainName, req.getBlockNumber());
if (block == null || block.getBlockBytes() == null) {
return NetExceptionResponseFactory.error(
req,
@@ -0,0 +1,107 @@
package server.logic.ws_protocol.JSON.handlers.blockchain;
import blockchain.BchBlockEntry;
import blockchain.body.BodyHasTarget;
import server.logic.ws_protocol.Base64Ws;
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.blockchain.entyties.Net_GetMyBlockchain_Request;
import server.logic.ws_protocol.JSON.handlers.blockchain.entyties.Net_GetMyBlockchain_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.BlockchainStateDAO;
import shine.db.dao.CanonicalChainResolver;
import shine.db.dao.SolanaUserPdaCurrentDAO;
import shine.db.entities.BlockEntry;
import shine.db.entities.BlockchainStateEntry;
import shine.db.entities.SolanaUserPdaCurrentEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/** Authenticated, paginated current-chain view used by "Мой блокчейн" and key rotation. */
public final class Net_GetMyBlockchain_Handler implements JsonMessageHandler {
private final CanonicalChainResolver canonical = CanonicalChainResolver.getInstance();
private final BlockchainStateDAO states = BlockchainStateDAO.getInstance();
private final SolanaUserPdaCurrentDAO users = SolanaUserPdaCurrentDAO.getInstance();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_GetMyBlockchain_Request req = (Net_GetMyBlockchain_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
try {
String login = ctx.getLogin().trim();
SolanaUserPdaCurrentEntry user = users.getByLogin(login);
if (user == null || user.getBlockchainName() == null || user.getBlockchainName().isBlank()) {
return NetExceptionResponseFactory.error(req, 404, "BLOCKCHAIN_NOT_FOUND", "Текущий блокчейн пользователя не найден");
}
String bch = user.getBlockchainName();
BlockchainStateEntry state = states.getByBlockchainName(bch);
int tip = state == null ? -1 : state.getLastBlockNumber();
String tipHash = state == null ? null : hex(state.getLastBlockHash());
int limit = req.getLimit() == null ? 50 : Math.max(1, Math.min(100, req.getLimit()));
int before = req.getBeforeBlock() == null || req.getBeforeBlock() < 0 ? tip : Math.min(tip, req.getBeforeBlock());
boolean includeBytes = Boolean.TRUE.equals(req.getIncludeBlockBytes());
List<BlockEntry> rows = new ArrayList<>();
if (before >= 0) {
int low = Math.max(0, before - limit + 1);
for (int n = before; n >= low; n--) {
BlockEntry row = canonical.getBlock(bch, n);
if (row == null) {
return NetExceptionResponseFactory.error(req, 409, "CANONICAL_HISTORY_GAP",
"В канонической истории отсутствует блок #" + n);
}
rows.add(row);
}
}
List<Net_GetMyBlockchain_Response.BlockItem> items = new ArrayList<>(rows.size());
for (BlockEntry row : rows) {
BchBlockEntry parsed = new BchBlockEntry(row.getBlockBytes());
Net_GetMyBlockchain_Response.BlockItem item = new Net_GetMyBlockchain_Response.BlockItem();
item.setBlockNumber(row.getBlockNumber());
item.setBlockHash(hex(row.getBlockHash()));
item.setPrevBlockHash(hex(parsed.prevHash32));
item.setTimestampMs(parsed.timestamp * 1000L);
item.setMsgType(Short.toUnsignedInt(parsed.type));
item.setMsgSubType(Short.toUnsignedInt(parsed.subType));
item.setMsgVersion(Short.toUnsignedInt(parsed.version));
if (parsed.body instanceof BodyHasTarget target) {
item.setToLogin(target.toLogin());
item.setToForkNumber(target.toForkNumber());
item.setToBlockNumber(target.toBlockGlobalNumber());
item.setToBlockHash(hex(target.toBlockHashBytes()));
}
if (includeBytes) item.setBlockBytesB64(Base64Ws.encode(row.getBlockBytes()));
items.add(item);
}
Net_GetMyBlockchain_Response resp = new Net_GetMyBlockchain_Response();
resp.setOp(req.getOp());
resp.setRequestId(req.getRequestId());
resp.setStatus(WireCodes.Status.OK);
resp.setLogin(login);
resp.setBlockchainName(bch);
resp.setTipBlockNumber(tip);
resp.setTipBlockHash(tipHash);
resp.setBlocks(items);
int lowest = rows.isEmpty() ? -1 : rows.get(rows.size() - 1).getBlockNumber();
resp.setNextBeforeBlock(lowest > 0 ? lowest - 1 : null);
return resp;
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "GET_MY_BLOCKCHAIN_FAILED", "Не удалось прочитать блокчейн пользователя");
}
}
private static String hex(byte[] bytes) {
if (bytes == null) return null;
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
}
@@ -0,0 +1,20 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
/** Paginated read of the authenticated user's current materialized blockchain. */
public final class Net_GetMyBlockchain_Request extends Net_Request {
/** Inclusive highest block number to return. Null/<0 means current tip. */
private Integer beforeBlock;
/** 1..100, default 50. */
private Integer limit;
/** Include complete serialized ANS-104 DataItem for rotation/UI inspection. */
private Boolean includeBlockBytes;
public Integer getBeforeBlock() { return beforeBlock; }
public void setBeforeBlock(Integer beforeBlock) { this.beforeBlock = beforeBlock; }
public Integer getLimit() { return limit; }
public void setLimit(Integer limit) { this.limit = limit; }
public Boolean getIncludeBlockBytes() { return includeBlockBytes; }
public void setIncludeBlockBytes(Boolean includeBlockBytes) { this.includeBlockBytes = includeBlockBytes; }
}
@@ -0,0 +1,67 @@
package server.logic.ws_protocol.JSON.handlers.blockchain.entyties;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import java.util.ArrayList;
import java.util.List;
public final class Net_GetMyBlockchain_Response extends Net_Response {
private String login;
private String blockchainName;
private int tipBlockNumber;
private String tipBlockHash;
private Integer nextBeforeBlock;
private List<BlockItem> blocks = new ArrayList<>();
public String getLogin() { return login; }
public void setLogin(String login) { this.login = login; }
public String getBlockchainName() { return blockchainName; }
public void setBlockchainName(String blockchainName) { this.blockchainName = blockchainName; }
public int getTipBlockNumber() { return tipBlockNumber; }
public void setTipBlockNumber(int tipBlockNumber) { this.tipBlockNumber = tipBlockNumber; }
public String getTipBlockHash() { return tipBlockHash; }
public void setTipBlockHash(String tipBlockHash) { this.tipBlockHash = tipBlockHash; }
public Integer getNextBeforeBlock() { return nextBeforeBlock; }
public void setNextBeforeBlock(Integer nextBeforeBlock) { this.nextBeforeBlock = nextBeforeBlock; }
public List<BlockItem> getBlocks() { return blocks; }
public void setBlocks(List<BlockItem> blocks) { this.blocks = blocks; }
public static final class BlockItem {
private int blockNumber;
private String blockHash;
private String prevBlockHash;
private long timestampMs;
private int msgType;
private int msgSubType;
private int msgVersion;
private String toLogin;
private Integer toForkNumber;
private Integer toBlockNumber;
private String toBlockHash;
private String blockBytesB64;
public int getBlockNumber() { return blockNumber; }
public void setBlockNumber(int blockNumber) { this.blockNumber = blockNumber; }
public String getBlockHash() { return blockHash; }
public void setBlockHash(String blockHash) { this.blockHash = blockHash; }
public String getPrevBlockHash() { return prevBlockHash; }
public void setPrevBlockHash(String prevBlockHash) { this.prevBlockHash = prevBlockHash; }
public long getTimestampMs() { return timestampMs; }
public void setTimestampMs(long timestampMs) { this.timestampMs = timestampMs; }
public int getMsgType() { return msgType; }
public void setMsgType(int msgType) { this.msgType = msgType; }
public int getMsgSubType() { return msgSubType; }
public void setMsgSubType(int msgSubType) { this.msgSubType = msgSubType; }
public int getMsgVersion() { return msgVersion; }
public void setMsgVersion(int msgVersion) { this.msgVersion = msgVersion; }
public String getToLogin() { return toLogin; }
public void setToLogin(String toLogin) { this.toLogin = toLogin; }
public Integer getToForkNumber() { return toForkNumber; }
public void setToForkNumber(Integer toForkNumber) { this.toForkNumber = toForkNumber; }
public Integer getToBlockNumber() { return toBlockNumber; }
public void setToBlockNumber(Integer toBlockNumber) { this.toBlockNumber = toBlockNumber; }
public String getToBlockHash() { return toBlockHash; }
public void setToBlockHash(String toBlockHash) { this.toBlockHash = toBlockHash; }
public String getBlockBytesB64() { return blockBytesB64; }
public void setBlockBytesB64(String blockBytesB64) { this.blockBytesB64 = blockBytesB64; }
}
}
@@ -72,7 +72,7 @@ public final class ChannelMetaTextParser {
String ar = String.valueOf(fields.getOrDefault("ar", "")).trim();
String sha256 = String.valueOf(fields.getOrDefault("sha256", "")).trim().toLowerCase();
String sizeRaw = String.valueOf(fields.containsKey("sz") ? fields.get("sz") : fields.getOrDefault("size", "")).trim();
if (!ar.matches("^[A-Za-z0-9_-]{43}$")) throw new IllegalArgumentException("bad_channel_meta_avatar_ar");
if (!ar.isEmpty() && !ar.matches("^[A-Za-z0-9_-]{43}$")) throw new IllegalArgumentException("bad_channel_meta_avatar_ar");
if (!sha256.matches("^[0-9a-f]{64}$")) throw new IllegalArgumentException("bad_channel_meta_avatar_sha256");
long size;
try {
@@ -17,6 +17,7 @@ import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public final class ChannelNamesStateBootstrapper {
@@ -48,7 +49,15 @@ public final class ChannelNamesStateBootstrapper {
SELECT login, bch_name, block_number, block_hash, block_bytes
FROM blocks
WHERE msg_type = ? AND msg_sub_type = ?
ORDER BY bch_name, block_number
AND fork_number=shine_canonical_fork(
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number
""";
try (Connection c = DbController.getInstance().getConnection()) {
@@ -107,7 +116,7 @@ public final class ChannelNamesStateBootstrapper {
}
String identity = ownerBch + "#" + blockNumber;
String ownerTypeSlug = ownerBch + "|" + channelTypeCode + "|" + slug;
String ownerTypeSlug = ownerLogin.toLowerCase(Locale.ROOT) + "|" + channelTypeCode + "|" + slug;
String existing = slugToIdentity.putIfAbsent(ownerTypeSlug, identity);
if (existing != null && !existing.equals(identity)) {
conflicts.add("owner/type/slug=\"" + ownerTypeSlug + "\" conflicts: " + existing + " vs " + identity);
@@ -138,6 +147,7 @@ public final class ChannelNamesStateBootstrapper {
dao.insertAll(c, entries);
applyMetaUpdates(c, dao, entries, skipped);
applyDeletionStates(c, dao, skipped);
// v18: counters are a projection, so rebuild them from current state after a full channel-name bootstrap.
try (PreparedStatement ps = c.prepareStatement("SELECT shine_refresh_user_stats(login) FROM solana_user_pda_current")) {
ps.execute();
@@ -182,26 +192,76 @@ public final class ChannelNamesStateBootstrapper {
}
}
private static void applyDeletionStates(Connection c, ChannelNameStateDAO dao, List<String> skipped) throws Exception {
String sql = """
SELECT bch_name, block_number, block_bytes, msg_sub_type
FROM blocks
WHERE msg_type = ? AND msg_sub_type IN (?, ?, ?, ?, ?, ?, ?)
AND fork_number=shine_canonical_fork(
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, MSG_TYPE_TEXT);
ps.setInt(2, MsgSubType.TEXT_CHANNEL_DELETE);
ps.setInt(3, MsgSubType.TEXT_POST);
ps.setInt(4, MsgSubType.TEXT_REPOST);
ps.setInt(5, MsgSubType.TEXT_ENTRYPOINT);
ps.setInt(6, MsgSubType.TEXT_EXERCISE);
ps.setInt(7, MsgSubType.TEXT_SERVICE);
ps.setInt(8, MsgSubType.TEXT_COURSE);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String ownerBch = rs.getString("bch_name");
int blockNumber = rs.getInt("block_number");
try {
BchBlockEntry parsed = new BchBlockEntry(rs.getBytes("block_bytes"));
if (!(parsed.body instanceof TextLineBody body) || body.lineCode() <= 0) continue;
boolean deleted = rs.getInt("msg_sub_type") == (MsgSubType.TEXT_CHANNEL_DELETE & 0xFFFF);
dao.updateDeletedState(c, ownerBch, body.lineCode(), deleted, deleted ? parsed.timestamp * 1000L : 0L, deleted ? blockNumber : null);
} catch (Exception e) {
skipped.add(ownerBch + "#" + blockNumber + " (invalid_channel_state_event)");
}
}
}
}
}
private static void applyMetaUpdates(Connection c,
ChannelNameStateDAO dao,
List<ChannelNameStateEntry> entries,
List<String> skipped) throws Exception {
Map<String, String> fallbackTitles = new LinkedHashMap<>();
for (ChannelNameStateEntry entry : entries) {
fallbackTitles.put(entry.getOwnerBlockchainName() + "#" + entry.getChannelRootBlockNumber(), entry.getSlug());
fallbackTitles.put(entry.getOwnerLogin().toLowerCase() + "#" + entry.getChannelRootBlockNumber(), entry.getSlug());
}
String sql = """
SELECT bch_name, block_number, block_bytes
SELECT login, bch_name, block_number, block_bytes
FROM blocks
WHERE msg_type = ? AND msg_sub_type = ?
ORDER BY bch_name, block_number
AND fork_number=shine_canonical_fork(
login,
(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(blocks.login)
LIMIT 1),
block_number
)
ORDER BY LOWER(login), block_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, MSG_TYPE_TEXT);
ps.setInt(2, MsgSubType.TEXT_CHANNEL_META);
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
String ownerLogin = rs.getString("login");
String ownerBch = rs.getString("bch_name");
int blockNumber = rs.getInt("block_number");
byte[] blockBytes = rs.getBytes("block_bytes");
@@ -209,11 +269,12 @@ public final class ChannelNamesStateBootstrapper {
BchBlockEntry parsed = new BchBlockEntry(blockBytes);
if (!(parsed.body instanceof TextLineBody metaBody)) continue;
int lineCode = metaBody.lineCode();
String fallbackTitle = fallbackTitles.get(ownerBch + "#" + lineCode);
String fallbackTitle = fallbackTitles.get(ownerLogin.toLowerCase() + "#" + lineCode);
if (fallbackTitle == null) continue;
ChannelMetaTextParser.Parsed parsedMeta = ChannelMetaTextParser.parseStrict(metaBody.message, fallbackTitle);
ChannelNameStateEntry update = new ChannelNameStateEntry();
update.setOwnerLogin(ownerLogin);
update.setOwnerBlockchainName(ownerBch);
update.setChannelRootBlockNumber(lineCode);
update.setDisplayName(parsedMeta.title());
@@ -3,7 +3,6 @@ package server.logic.ws_protocol.JSON.handlers.channels;
import blockchain.BchBlockEntry;
import blockchain.body.BodyRecord;
import blockchain.body.CreateChannelBody;
import blockchain.body.TextBody;
import blockchain.body.TextLineBody;
import blockchain.body.TextReplyBody;
import shine.db.channels.ChannelNameRules;
@@ -54,13 +53,13 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT slug, display_name, channel_description, channel_type_code, channel_type_version,
ava_ar, ava_sha256, ava_size, meta_updated_at_ms
created_at_ms, ava_ar, ava_sha256, ava_size, meta_updated_at_ms, is_deleted, deleted_at_ms, deleted_block_number
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(stateSql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, rootNumber);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
@@ -69,10 +68,14 @@ final class ChannelsReadSupport {
meta.channelDescription = String.valueOf(rs.getString("channel_description") == null ? "" : rs.getString("channel_description"));
meta.channelTypeCode = rs.getInt("channel_type_code");
meta.channelTypeVersion = rs.getInt("channel_type_version");
meta.createdAtMs = rs.getLong("created_at_ms");
meta.avaAr = String.valueOf(rs.getString("ava_ar") == null ? "" : rs.getString("ava_ar"));
meta.avaSha256 = String.valueOf(rs.getString("ava_sha256") == null ? "" : rs.getString("ava_sha256"));
meta.avaSize = rs.getLong("ava_size");
meta.metaUpdatedAtMs = rs.getLong("meta_updated_at_ms");
meta.deleted = rs.getBoolean("is_deleted");
meta.deletedAtMs = rs.getLong("deleted_at_ms");
meta.deletedBlockNumber = (Integer) rs.getObject("deleted_block_number");
return meta;
}
}
@@ -80,10 +83,17 @@ final class ChannelsReadSupport {
// fallback ниже для окружений до миграции.
}
String sql = "SELECT block_bytes FROM blocks WHERE bch_name=? AND block_number=? LIMIT 1";
String sql = """
SELECT block_bytes FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
String ownerLogin=loginFromChainName(ownerBch);
ps.setString(1, ownerLogin);
ps.setInt(2, rootNumber);
ps.setString(3, ownerLogin);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
meta.channelName = null;
@@ -107,6 +117,7 @@ final class ChannelsReadSupport {
meta.avaAr = parsedMeta.avaAr();
meta.avaSha256 = parsedMeta.avaSha256();
meta.avaSize = parsedMeta.avaSize();
meta.createdAtMs = e.timestamp * 1000L;
meta.metaUpdatedAtMs = e.timestamp * 1000L;
}
} else {
@@ -127,20 +138,14 @@ final class ChannelsReadSupport {
}
static int countPosts(Connection c, String ownerBch, int lineCode) throws SQLException {
String sql = "SELECT COUNT(*) AS cnt FROM blocks WHERE bch_name=? AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?";
String sql = """
SELECT COUNT(*) AS cnt FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_POST);
ps.setInt(4, MsgSubType.TEXT_REPOST);
ps.setInt(5, MsgSubType.TEXT_ENTRYPOINT);
ps.setInt(6, MsgSubType.TEXT_EXERCISE);
ps.setInt(7, MsgSubType.TEXT_SERVICE);
ps.setInt(8, MsgSubType.TEXT_COURSE);
ps.setInt(9, lineCode);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getInt("cnt") : 0;
}
String login=loginFromChainName(ownerBch); ps.setString(1,login); ps.setInt(2,MSG_TYPE_TEXT); ps.setInt(3,MsgSubType.TEXT_POST); ps.setInt(4,MsgSubType.TEXT_REPOST); ps.setInt(5,MsgSubType.TEXT_ENTRYPOINT); ps.setInt(6,MsgSubType.TEXT_EXERCISE); ps.setInt(7,MsgSubType.TEXT_SERVICE); ps.setInt(8,MsgSubType.TEXT_COURSE); ps.setInt(9,lineCode); ps.setString(10,login);
try(ResultSet rs=ps.executeQuery()){return rs.next()?rs.getInt("cnt"):0;}
}
}
@@ -153,52 +158,32 @@ final class ChannelsReadSupport {
}
static PostBlock loadLastPost(Connection c, String ownerBch, int lineCode) throws SQLException {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
ORDER BY block_number DESC
LIMIT 1
String sql="""
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number DESC LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_POST);
ps.setInt(4, MsgSubType.TEXT_REPOST);
ps.setInt(5, MsgSubType.TEXT_ENTRYPOINT);
ps.setInt(6, MsgSubType.TEXT_EXERCISE);
ps.setInt(7, MsgSubType.TEXT_SERVICE);
ps.setInt(8, MsgSubType.TEXT_COURSE);
ps.setInt(9, lineCode);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
PostBlock pb = new PostBlock();
pb.login = rs.getString("login");
pb.bchName = rs.getString("bch_name");
pb.blockNumber = rs.getInt("block_number");
pb.blockHash = rs.getBytes("block_hash");
pb.blockBytes = rs.getBytes("block_bytes");
return pb;
}
}
try(PreparedStatement ps=c.prepareStatement(sql)){String login=loginFromChainName(ownerBch);ps.setString(1,login);ps.setInt(2,MSG_TYPE_TEXT);ps.setInt(3,MsgSubType.TEXT_POST);ps.setInt(4,MsgSubType.TEXT_REPOST);ps.setInt(5,MsgSubType.TEXT_ENTRYPOINT);ps.setInt(6,MsgSubType.TEXT_EXERCISE);ps.setInt(7,MsgSubType.TEXT_SERVICE);ps.setInt(8,MsgSubType.TEXT_COURSE);ps.setInt(9,lineCode);ps.setString(10,login);try(ResultSet rs=ps.executeQuery()){if(!rs.next())return null;PostBlock pb=new PostBlock();pb.login=rs.getString("login");pb.bchName=rs.getString("bch_name");pb.blockNumber=rs.getInt("block_number");pb.blockHash=rs.getBytes("block_hash");pb.blockBytes=rs.getBytes("block_bytes");return pb;}}
}
static PostBlock loadLastVersion(Connection c, String ownerBch, int originalBlockNumber, byte[] originalHash) throws SQLException {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type=?
AND to_bch_name=? AND to_block_number=? AND to_block_hash=?
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number DESC
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_EDIT_POST);
ps.setString(4, ownerBch);
ps.setInt(5, originalBlockNumber);
ps.setBytes(6, originalHash);
ps.setInt(4, originalBlockNumber);
ps.setBytes(5, originalHash);
ps.setString(6, loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return null;
PostBlock pb = new PostBlock();
@@ -225,8 +210,6 @@ final class ChannelsReadSupport {
ti.text = trb.message;
} else if (e.body instanceof blockchain.body.StatusActionBody sab) {
ti.text = sab.message;
} else if (e.body instanceof TextBody tb) {
ti.text = tb.message;
}
return ti;
} catch (Exception ex) {
@@ -240,11 +223,12 @@ final class ChannelsReadSupport {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,msg_sub_type,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type IN (?, ?, ?, ?, ?, ?) AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number
""" + order + (bounded ? " LIMIT ?" : "");
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_POST);
ps.setInt(4, MsgSubType.TEXT_REPOST);
@@ -253,7 +237,8 @@ final class ChannelsReadSupport {
ps.setInt(7, MsgSubType.TEXT_SERVICE);
ps.setInt(8, MsgSubType.TEXT_COURSE);
ps.setInt(9, lineCode);
if (bounded) ps.setInt(10, limit);
ps.setString(10, loginFromChainName(ownerBch));
if (bounded) ps.setInt(11, limit);
try (ResultSet rs = ps.executeQuery()) {
List<PostBlock> out = new ArrayList<>();
while (rs.next()) {
@@ -288,18 +273,18 @@ final class ChannelsReadSupport {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type=?
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
AND (to_bch_name=? OR to_bch_name IS NULL OR to_bch_name='')
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_EDIT_POST);
ps.setInt(4, originalBlock);
ps.setBytes(5, originalHash);
ps.setString(6, ownerBch);
ps.setString(6, loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
List<PostBlock> out = new ArrayList<>();
while (rs.next()) {
@@ -317,13 +302,13 @@ final class ChannelsReadSupport {
}
static int[] loadStats(Connection c, String bch, int blockNumber, byte[] blockHash) throws SQLException {
String sql = "SELECT likes_count,primary_likes_count,shining_likes_count,replies_count FROM message_stats WHERE to_bch_name=? AND to_block_number=? AND to_block_hash=? LIMIT 1";
String sql = "SELECT likes_count,primary_likes_count,shining_likes_count,replies_count FROM message_stats WHERE LOWER(to_login)=LOWER(?) AND to_block_number=? AND to_block_hash=? LIMIT 1";
int likesCount = 0;
int primaryLikesCount = 0;
int shiningLikesCount = 0;
int repliesCount = 0;
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, bch);
ps.setString(1, loginFromChainName(bch));
ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash);
try (ResultSet rs = ps.executeQuery()) {
@@ -340,15 +325,16 @@ final class ChannelsReadSupport {
FROM blocks
WHERE msg_type = ?
AND msg_sub_type = ?
AND to_bch_name = ?
AND LOWER(to_login) = LOWER(?)
AND to_block_number = ?
AND to_block_hash = ?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
""";
int ratingsCount = 0;
try (PreparedStatement ps = c.prepareStatement(ratingsSql)) {
ps.setInt(1, MSG_TYPE_TEXT);
ps.setInt(2, MsgSubType.TEXT_RATING);
ps.setString(3, bch);
ps.setString(3, loginFromChainName(bch));
ps.setInt(4, blockNumber);
ps.setBytes(5, blockHash);
try (ResultSet rs = ps.executeQuery()) {
@@ -369,11 +355,11 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT channel_description
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(stateSql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, rootNumber);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
@@ -386,10 +372,17 @@ final class ChannelsReadSupport {
}
// Fallback: parse root block directly.
String sql = "SELECT block_bytes FROM blocks WHERE bch_name=? AND block_number=? LIMIT 1";
String sql = """
SELECT block_bytes FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
String ownerLogin=loginFromChainName(ownerBch);
ps.setString(1, ownerLogin);
ps.setInt(2, rootNumber);
ps.setString(3, ownerLogin);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return "";
byte[] bytes = rs.getBytes("block_bytes");
@@ -411,11 +404,11 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT channel_type_code
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(stateSql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, rootNumber);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) return rs.getInt("channel_type_code");
@@ -434,11 +427,11 @@ final class ChannelsReadSupport {
String stateSql = """
SELECT channel_type_version
FROM channel_names_state
WHERE owner_bch_name = ? AND channel_root_block_number = ?
WHERE LOWER(owner_login)=LOWER(?) AND channel_root_block_number = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(stateSql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, rootNumber);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) return rs.getInt("channel_type_version");
@@ -458,14 +451,17 @@ final class ChannelsReadSupport {
String rootSql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type=? AND block_number=?
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(rootSql)) {
ps.setString(1, ownerBch);
String ownerLogin=loginFromChainName(ownerBch);
ps.setString(1, ownerLogin);
ps.setInt(2, MSG_TYPE_TECH);
ps.setInt(3, 1);
ps.setInt(4, lineCode);
ps.setString(5, ownerLogin);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
MetaEvent event = new MetaEvent();
@@ -507,14 +503,16 @@ final class ChannelsReadSupport {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=? AND msg_sub_type=? AND line_code=?
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_CHANNEL_META);
ps.setInt(4, lineCode);
ps.setString(5, loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
byte[] bytes = rs.getBytes("block_bytes");
@@ -541,6 +539,36 @@ final class ChannelsReadSupport {
}
}
}
String deleteSql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND msg_type=? AND msg_sub_type=? AND line_code=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""";
try (PreparedStatement ps = c.prepareStatement(deleteSql)) {
ps.setString(1, loginFromChainName(ownerBch));
ps.setInt(2, MSG_TYPE_TEXT);
ps.setInt(3, MsgSubType.TEXT_CHANNEL_DELETE);
ps.setInt(4, lineCode);
ps.setString(5, loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
MetaEvent event = new MetaEvent();
event.kind = "deleted";
event.login = rs.getString("login");
event.bchName = rs.getString("bch_name");
event.blockNumber = rs.getInt("block_number");
event.blockHash = rs.getBytes("block_hash");
event.lineStep = (Integer) rs.getObject("this_line_number");
try { event.createdAtMs = new BchBlockEntry(rs.getBytes("block_bytes")).timestamp * 1000L; }
catch (Exception ignored) { event.createdAtMs = 0L; }
out.add(event);
}
}
}
out.sort(Comparator.comparingLong((MetaEvent e) -> e.createdAtMs).thenComparingInt(e -> e.blockNumber));
return out;
}
@@ -552,9 +580,8 @@ final class ChannelsReadSupport {
String partnerBchSql = """
SELECT blockchain_name
FROM blockchain_state
FROM solana_user_pda_current
WHERE LOWER(login) = LOWER(?)
ORDER BY blockchain_name
LIMIT 1
""";
@@ -577,14 +604,14 @@ final class ChannelsReadSupport {
String rootSql = """
SELECT channel_root_block_number
FROM channel_names_state
WHERE owner_bch_name = ?
WHERE LOWER(owner_login)=LOWER(?)
AND channel_type_code = ?
AND slug = ?
ORDER BY channel_root_block_number DESC
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(rootSql)) {
ps.setString(1, partnerBch);
ps.setString(1, canonicalPartner);
ps.setInt(2, CreateChannelBody.CHANNEL_TYPE_PERSONAL & 0xFFFF);
ps.setString(3, ownerSlug);
try (ResultSet rs = ps.executeQuery()) {
@@ -601,26 +628,25 @@ final class ChannelsReadSupport {
if (login == null || login.isBlank() || toBch == null || toBch.isBlank() || toBlockHash == null || toBlockHash.length != 32) {
return false;
}
String targetLogin = loginFromChainName(toBch);
if (targetLogin == null || targetLogin.isBlank()) return false;
String sql = """
SELECT msg_sub_type
FROM blocks
WHERE LOWER(login) = LOWER(?)
AND msg_type = ?
AND to_bch_name = ?
SELECT last_sub_type
FROM reactions_state
WHERE LOWER(from_login) = LOWER(?)
AND reaction_type = 1
AND LOWER(to_login) = LOWER(?)
AND to_block_number = ?
AND to_block_hash = ?
ORDER BY block_number DESC
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setInt(2, MSG_TYPE_REACTION);
ps.setString(3, toBch);
ps.setInt(4, toBlockNumber);
ps.setBytes(5, toBlockHash);
ps.setString(2, targetLogin);
ps.setInt(3, toBlockNumber);
ps.setBytes(4, toBlockHash);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return false;
return rs.getInt("msg_sub_type") == MsgSubType.REACTION_LIKE;
return rs.next() && rs.getInt("last_sub_type") == MsgSubType.REACTION_LIKE;
}
}
}
@@ -689,7 +715,11 @@ final class ChannelsReadSupport {
String avaAr = "";
String avaSha256 = "";
long avaSize = 0L;
long createdAtMs = 0L;
long metaUpdatedAtMs = 0L;
boolean deleted = false;
long deletedAtMs = 0L;
Integer deletedBlockNumber;
}
static final class MetaEvent {
@@ -711,4 +741,8 @@ final class ChannelsReadSupport {
String ownerBlockchainName;
int channelRootBlockNumber;
}
static String loginFromChainName(String bch) {
if (bch == null) return null; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch;
}
}
@@ -67,9 +67,13 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
channel.setAvaSha256(meta.avaSha256);
channel.setAvaSize(meta.avaSize);
channel.setMetaUpdatedAtMs(meta.metaUpdatedAtMs);
channel.setCreatedAtMs(meta.createdAtMs);
channel.setChannelTypeCode(meta.channelTypeCode);
channel.setChannelTypeVersion(meta.channelTypeVersion);
channel.setSubscribersCount(loadSubscribersCount(c, ownerBch, lineCode, meta.channelTypeCode));
channel.setDeleted(meta.deleted);
channel.setDeletedAtMs(meta.deletedAtMs);
channel.setDeletedBlockNumber(meta.deletedBlockNumber);
Net_GetChannelMessages_Response.BlockRef rootRef = new Net_GetChannelMessages_Response.BlockRef();
rootRef.setBlockNumber(lineCode);
rootRef.setBlockHash(req.getChannel().getChannelRootBlockHash());
@@ -195,12 +199,12 @@ public class Net_GetChannelMessages_Handler implements JsonMessageHandler {
String sql = """
SELECT subscribers_count
FROM channel_stats_state
WHERE owner_bch_name = ?
WHERE LOWER(owner_login)=LOWER(?)
AND channel_root_block_number = ?
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, BlockchainNameUtil.loginFromBlockchainName(ownerBch));
ps.setInt(2, rootNumber);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return 0;
@@ -20,6 +20,8 @@ import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
/** @deprecated Chat200 is legacy/non-working/unused and is not maintained for segmented forks. */
@Deprecated
public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_GetGroupDialog_Handler.class);
@@ -156,13 +158,14 @@ public class Net_GetGroupDialog_Handler implements JsonMessageHandler {
String sql = """
SELECT login, bch_name, block_number, block_hash, block_bytes
FROM blocks
WHERE bch_name = ? AND msg_type = 1 AND line_code = ?
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND line_code=? AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""";
List<MsgRow> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, ownerBch);
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
ps.setInt(2, line);
ps.setString(3, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
MsgRow row = new MsgRow();
@@ -53,7 +53,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
LEFT JOIN user_profile_state ups ON LOWER(ups.login) = LOWER(rs.from_login)
WHERE rs.reaction_type = 1
AND rs.last_sub_type = 1
AND rs.to_bch_name = ?
AND LOWER(rs.to_login) = LOWER(?)
AND rs.to_block_number = ?
AND rs.to_block_hash = ?
ORDER BY LOWER(rs.from_login)
@@ -63,7 +63,7 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
List<Net_GetMessageLikes_Response.UserItem> official = new ArrayList<>();
List<Net_GetMessageLikes_Response.UserItem> others = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, message.getBlockchainName().trim());
ps.setString(1, loginFromChainName(message.getBlockchainName().trim()));
ps.setInt(2, message.getBlockNumber());
ps.setBytes(3, blockHash);
try (ResultSet rs = ps.executeQuery()) {
@@ -98,4 +98,8 @@ public class Net_GetMessageLikes_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR, "internal_error", "Внутренняя ошибка сервера");
}
}
private static String loginFromChainName(String bch) {
if (bch == null) return null; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch;
}
}
@@ -56,8 +56,17 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
List<Net_GetMessageThread_Response.MessageNode> ancestors = new ArrayList<>();
PostRow cur = focusRow;
for (int i = 0; i < depthUp; i++) {
if (cur.toBlockNumber == null || cur.toBchName == null) break;
PostRow parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
if (cur.toBlockNumber == null) break;
PostRow parent;
if (cur.msgSubType == MsgSubType.TEXT_RATING
&& cur.toLogin != null && !cur.toLogin.isBlank()
&& cur.toBlockHash != null && cur.toBlockHash.length == 32) {
parent = findByLogicalTarget(c, cur.toLogin, cur.toBlockNumber, cur.toBlockHash);
} else {
// REPLY and other legacy thread links intentionally keep their existing physical-target behavior.
if (cur.toBchName == null) break;
parent = findByNumber(c, cur.toBchName, cur.toBlockNumber);
}
if (parent == null) break;
ancestors.add(0, toNode(c, parent, viewerLogin));
cur = parent;
@@ -102,18 +111,28 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
}
private List<PostRow> findRepliesAndRatings(Connection c, String toBchName, int toBlockNumber, byte[] toBlockHash, int limit) throws Exception {
String targetLogin = ChannelsReadSupport.loginFromChainName(toBchName);
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE msg_type=1 AND msg_sub_type IN (?, ?)
AND to_bch_name=? AND to_block_number=? AND to_block_hash=?
WHERE msg_type=1
AND to_block_number=? AND to_block_hash=?
AND (
(msg_sub_type=? AND (LOWER(to_login)=LOWER(?) OR to_bch_name=?))
OR (msg_sub_type=? AND LOWER(to_login)=LOWER(?))
)
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(blocks.login) LIMIT 1),block_number)
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setInt(1, MsgSubType.TEXT_REPLY);
ps.setInt(2, MsgSubType.TEXT_RATING);
ps.setString(3, toBchName);
ps.setInt(4, toBlockNumber);
ps.setBytes(5, toBlockHash);
ps.setInt(1, toBlockNumber);
ps.setBytes(2, toBlockHash);
// REPLY keeps its legacy physical-target lookup intentionally.
ps.setInt(3, MsgSubType.TEXT_REPLY);
ps.setString(4, targetLogin);
ps.setString(5, toBchName);
// RATING follows the Stage 2 logical target identity.
ps.setInt(6, MsgSubType.TEXT_RATING);
ps.setString(7, targetLogin);
try (ResultSet rs = ps.executeQuery()) {
List<PostRow> out = new ArrayList<>();
while (rs.next()) out.add(mapRow(rs));
@@ -129,16 +148,38 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
}
}
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
private PostRow findByLogicalTarget(Connection c, String login, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE bch_name=? AND block_number=?
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, bchName);
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
}
}
private PostRow findByNumber(Connection c, String bchName, int blockNumber) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE LOWER(login)=LOWER(?) AND block_number=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
String login=ChannelsReadSupport.loginFromChainName(bchName);
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setString(3, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
@@ -147,15 +188,18 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private PostRow findByNumberAndHash(Connection c, String bchName, int blockNumber, byte[] blockHash) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE bch_name=? AND block_number=? AND block_hash=?
WHERE LOWER(login)=LOWER(?) AND block_number=? AND block_hash=?
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
LIMIT 1
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, bchName);
String login=ChannelsReadSupport.loginFromChainName(bchName);
ps.setString(1, login);
ps.setInt(2, blockNumber);
ps.setBytes(3, blockHash);
ps.setString(4, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? mapRow(rs) : null;
}
@@ -179,6 +223,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
row.blockNumber = rs.getInt("block_number");
row.blockHash = rs.getBytes("block_hash");
row.blockBytes = rs.getBytes("block_bytes");
row.toLogin = rs.getString("to_login");
row.toBchName = rs.getString("to_bch_name");
row.toBlockNumber = (Integer) rs.getObject("to_block_number");
row.toBlockHash = rs.getBytes("to_block_hash");
@@ -262,19 +307,20 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
private List<PostRow> findEdits(Connection c, String bch, int targetBlock, byte[] targetHash, int subType) throws Exception {
String sql = """
SELECT login,bch_name,block_number,block_hash,block_bytes,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
SELECT login,bch_name,block_number,block_hash,block_bytes,to_login,to_bch_name,to_block_number,to_block_hash,line_code,msg_sub_type,this_line_number
FROM blocks
WHERE bch_name=? AND msg_type=1 AND msg_sub_type=?
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=?
AND to_block_number=? AND to_block_hash=?
AND (to_bch_name=? OR to_bch_name IS NULL OR to_bch_name='')
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, bch);
String login=ChannelsReadSupport.loginFromChainName(bch);
ps.setString(1, login);
ps.setInt(2, subType);
ps.setInt(3, targetBlock);
ps.setBytes(4, targetHash);
ps.setString(5, bch);
ps.setString(5, login);
try (ResultSet rs = ps.executeQuery()) {
List<PostRow> out = new ArrayList<>();
while (rs.next()) out.add(mapRow(rs));
@@ -289,6 +335,7 @@ public class Net_GetMessageThread_Handler implements JsonMessageHandler {
int blockNumber;
byte[] blockHash;
byte[] blockBytes;
String toLogin;
String toBchName;
Integer toBlockNumber;
byte[] toBlockHash;
@@ -89,9 +89,8 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
private String loadPrimaryBlockchainName(Connection c, String canonicalLogin) throws Exception {
try (PreparedStatement ps = c.prepareStatement("""
SELECT blockchain_name
FROM blockchain_state
WHERE login = ?
ORDER BY blockchain_name
FROM solana_user_pda_current
WHERE LOWER(login)=LOWER(?)
LIMIT 1
""")) {
ps.setString(1, canonicalLogin);
@@ -105,7 +104,8 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
String order = asc ? "ASC" : "DESC";
List<Net_GetChannelMessages_Response.MessageItem> out = new ArrayList<>();
try (PreparedStatement ps = c.prepareStatement("""
SELECT login, bch_name, block_number, block_hash, block_bytes, msg_sub_type
SELECT login, bch_name, block_number, block_hash, block_bytes, msg_sub_type,
to_login, to_bch_name, to_block_number, to_block_hash
FROM blocks
WHERE login = ? AND msg_type = ?
ORDER BY block_number
@@ -132,9 +132,9 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
item.setLikedByMe(false);
item.setRepliesCount(0);
item.setRatingsCount(0);
item.setTargetBlockchainName(statusBody.toBchName());
item.setTargetBlockNumber(statusBody.toBlockGlobalNumber());
item.setTargetBlockHash(ChannelsReadSupport.toHex(statusBody.toBlockHashBytes()));
item.setTargetBlockchainName(rs.getString("to_bch_name"));
item.setTargetBlockNumber((Integer) rs.getObject("to_block_number"));
item.setTargetBlockHash(ChannelsReadSupport.toHex(rs.getBytes("to_block_hash")));
List<Net_GetChannelMessages_Response.VersionItem> versions = loadVersionsForDiaryItem(
c,
@@ -148,7 +148,8 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
item.setVersionsTotal(versions.size());
item.setText(versions.get(versions.size() - 1).getText());
fillTargetDetails(c, item, statusBody.toBchName(), statusBody.toBlockGlobalNumber(), statusBody.toBlockHashBytes());
fillTargetDetails(c, item, rs.getString("to_login"),
(Integer) rs.getObject("to_block_number"), rs.getBytes("to_block_hash"));
out.add(item);
}
}
@@ -175,20 +176,20 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
try (PreparedStatement ps = c.prepareStatement("""
SELECT block_number, block_hash, block_bytes
FROM blocks
WHERE bch_name = ?
WHERE LOWER(login)=LOWER(?)
AND msg_type = ?
AND msg_sub_type = ?
AND to_block_number = ?
AND to_block_hash = ?
AND (to_bch_name = ? OR to_bch_name IS NULL OR to_bch_name = '')
AND fork_number=shine_canonical_fork(login,(SELECT substring(blockchain_name from '([0-9]{3})$')::INTEGER FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1),block_number)
ORDER BY block_number ASC
""")) {
ps.setString(1, ownerBch);
ps.setString(1, ChannelsReadSupport.loginFromChainName(ownerBch));
ps.setInt(2, ChannelsReadSupport.MSG_TYPE_TEXT);
ps.setInt(3, shine.db.MsgSubType.TEXT_EDIT_REPLY);
ps.setInt(4, originalBlockNumber);
ps.setBytes(5, originalBlockHash);
ps.setString(6, ownerBch);
ps.setString(6, ChannelsReadSupport.loginFromChainName(ownerBch));
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
ChannelsReadSupport.TextInfo editText = ChannelsReadSupport.parseTextAndTime(rs.getBytes("block_bytes"));
@@ -208,24 +209,25 @@ public class Net_GetPersonalDiary_Handler implements JsonMessageHandler {
private void fillTargetDetails(Connection c,
Net_GetChannelMessages_Response.MessageItem item,
String targetBch,
String targetLogin,
Integer targetBlockNumber,
byte[] targetHash) throws Exception {
if (targetBch == null || targetBch.isBlank() || targetBlockNumber == null || targetHash == null || targetHash.length != 32) {
if (targetLogin == null || targetLogin.isBlank() || targetBlockNumber == null || targetHash == null || targetHash.length != 32) {
return;
}
try (PreparedStatement ps = c.prepareStatement("""
SELECT login, bch_name, block_number, block_hash, block_bytes, msg_sub_type
SELECT login, bch_name, block_number, block_hash, block_bytes, msg_sub_type,
to_login, to_bch_name, to_block_number, to_block_hash
FROM blocks
WHERE bch_name = ? AND block_number = ?
WHERE LOWER(login) = LOWER(?) AND block_number = ? AND block_hash = ?
ORDER BY fork_number DESC
LIMIT 1
""")) {
ps.setString(1, targetBch);
ps.setString(1, targetLogin);
ps.setInt(2, targetBlockNumber);
ps.setBytes(3, targetHash);
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) return;
byte[] actualHash = rs.getBytes("block_hash");
if (actualHash == null || !java.util.Arrays.equals(actualHash, targetHash)) return;
item.setTargetMsgSubType(rs.getInt("msg_sub_type"));
item.setTargetAuthorLogin(rs.getString("login"));
item.setTargetAuthorBlockchainName(rs.getString("bch_name"));
@@ -18,6 +18,8 @@ import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
/** @deprecated Chat200 is legacy/non-working/unused and is not maintained for segmented forks. */
@Deprecated
public class Net_ListGroupChats200_Handler implements JsonMessageHandler {
private static final Logger log = LoggerFactory.getLogger(Net_ListGroupChats200_Handler.class);
@@ -75,6 +75,9 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
channelRef.setChannelTypeCode(meta.channelTypeCode);
channelRef.setChannelTypeVersion(meta.channelTypeVersion);
channelRef.setPersonal(meta.channelTypeCode == 100);
channelRef.setDeleted(meta.deleted);
channelRef.setDeletedAtMs(meta.deletedAtMs);
channelRef.setDeletedBlockNumber(meta.deletedBlockNumber);
Net_ListSubscriptionsFeed_Response.BlockRef rootRef = new Net_ListSubscriptionsFeed_Response.BlockRef();
rootRef.setBlockNumber(key.rootNumber);
@@ -117,27 +120,14 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
private List<ChannelKey> loadOwnChannels(Connection c, String canonicalLogin) throws Exception {
List<ChannelKey> out = new ArrayList<>();
String bchSql = "SELECT blockchain_name FROM blockchain_state WHERE login=? ORDER BY blockchain_name";
try (PreparedStatement bchPs = c.prepareStatement(bchSql)) {
bchPs.setString(1, canonicalLogin);
try (ResultSet bchRs = bchPs.executeQuery()) {
while (bchRs.next()) {
String bch = bchRs.getString("blockchain_name");
out.add(new ChannelKey(canonicalLogin, bch, 0, new byte[32]));
String chSql = "SELECT block_number,block_hash FROM blocks WHERE bch_name=? AND msg_type=? AND msg_sub_type=? ORDER BY block_number";
try (PreparedStatement chPs = c.prepareStatement(chSql)) {
chPs.setString(1, bch);
chPs.setInt(2, ChannelsReadSupport.MSG_TYPE_TECH);
chPs.setInt(3, 1);
try (ResultSet chRs = chPs.executeQuery()) {
while (chRs.next()) {
out.add(new ChannelKey(canonicalLogin, bch, chRs.getInt("block_number"), chRs.getBytes("block_hash")));
}
}
}
}
}
String activeBch = null;
try (PreparedStatement ps=c.prepareStatement("SELECT blockchain_name FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1")){
ps.setString(1,canonicalLogin);try(ResultSet rs=ps.executeQuery()){if(rs.next())activeBch=rs.getString(1);}
}
if(activeBch==null||activeBch.isBlank())return out;
out.add(new ChannelKey(canonicalLogin,activeBch,0,new byte[32]));
try(PreparedStatement ps=c.prepareStatement("SELECT owner_bch_name,channel_root_block_number,channel_root_block_hash FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?) ORDER BY channel_root_block_number")){
ps.setString(1,canonicalLogin);try(ResultSet rs=ps.executeQuery()){while(rs.next())out.add(new ChannelKey(canonicalLogin,rs.getString(1),rs.getInt(2),rs.getBytes(3)));}
}
return out;
}
@@ -145,10 +135,13 @@ public class Net_ListSubscriptionsFeed_Handler implements JsonMessageHandler {
private List<ChannelKey> loadFollowedChannels(Connection c, String canonicalLogin, boolean onlyUserRoots) throws Exception {
List<ChannelKey> out = new ArrayList<>();
String sql = """
SELECT cs.to_login, cs.to_bch_name, COALESCE(cs.to_block_number,0) AS root_number, cs.to_block_hash
SELECT cs.to_login,
COALESCE(cn.owner_bch_name,(SELECT su.blockchain_name FROM solana_user_pda_current su WHERE LOWER(su.login)=LOWER(cs.to_login) LIMIT 1)) AS to_bch_name,
COALESCE(cs.to_block_number,0) AS root_number, cs.to_block_hash
FROM connections_state cs
LEFT JOIN channel_names_state cn ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
WHERE cs.login=? AND cs.rel_type=?
ORDER BY cs.to_login, cs.to_bch_name, root_number
ORDER BY cs.to_login, root_number
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, canonicalLogin);
@@ -48,13 +48,14 @@ public class Net_MarkChannelMessagesSeen_Handler implements JsonMessageHandler {
Integer expectedRoot = req.getChannel() != null ? req.getChannel().getChannelRootBlockNumber() : null;
String expectedOwnerBch = req.getChannel() != null ? req.getChannel().getOwnerBlockchainName() : null;
String expectedOwnerLogin = loginFromChainName(expectedOwnerBch);
boolean strictChannelMatch = expectedRoot != null && expectedRoot >= 0
&& expectedOwnerBch != null && !expectedOwnerBch.isBlank();
&& expectedOwnerLogin != null && !expectedOwnerLogin.isBlank();
String existsSql = """
SELECT 1
FROM blocks
WHERE bch_name = ?
WHERE LOWER(login) = LOWER(?)
AND block_number = ?
AND block_hash = ?
AND msg_type = ?
@@ -65,7 +66,7 @@ public class Net_MarkChannelMessagesSeen_Handler implements JsonMessageHandler {
String insertSql = """
INSERT INTO message_views_state (
viewer_login, to_bch_name, to_block_number, to_block_hash, first_seen_at_ms
viewer_login, to_login, to_block_number, to_block_hash, first_seen_at_ms
) VALUES (?, ?, ?, ?, ?)
ON CONFLICT DO NOTHING
""";
@@ -87,13 +88,15 @@ public class Net_MarkChannelMessagesSeen_Handler implements JsonMessageHandler {
if (bch.isBlank() || no == null || no < 0) continue;
if (!hashHex.matches("^[0-9a-f]{64}$")) continue;
if (strictChannelMatch && !bch.equals(expectedOwnerBch)) continue;
String targetLogin = loginFromChainName(bch);
if (targetLogin == null || targetLogin.isBlank()) continue;
if (strictChannelMatch && !targetLogin.equalsIgnoreCase(expectedOwnerLogin)) continue;
String key = bch + "|" + no + "|" + hashHex;
String key = targetLogin.toLowerCase(java.util.Locale.ROOT) + "|" + no + "|" + hashHex;
if (!dedup.add(key)) continue;
existsPs.clearParameters();
existsPs.setString(1, bch);
existsPs.setString(1, targetLogin);
existsPs.setInt(2, no);
existsPs.setBytes(3, ChannelsReadSupport.hexToBytes(hashHex));
existsPs.setInt(4, ChannelsReadSupport.MSG_TYPE_TEXT);
@@ -117,7 +120,7 @@ public class Net_MarkChannelMessagesSeen_Handler implements JsonMessageHandler {
insertPs.clearParameters();
insertPs.setString(1, viewerLogin);
insertPs.setString(2, bch);
insertPs.setString(2, targetLogin);
insertPs.setInt(3, no);
insertPs.setBytes(4, ChannelsReadSupport.hexToBytes(hashHex));
insertPs.setLong(5, nowMs);
@@ -137,4 +140,6 @@ public class Net_MarkChannelMessagesSeen_Handler implements JsonMessageHandler {
return NetExceptionResponseFactory.error(req, WireCodes.Status.INTERNAL_ERROR, "internal_error", "Internal server error");
}
}
private static String loginFromChainName(String bch) { if(bch==null)return null; int d=bch.lastIndexOf('-'); return d>0?bch.substring(0,d):bch; }
}
@@ -30,9 +30,13 @@ public class Net_GetChannelMessages_Response extends Net_Response {
private String avaSha256;
private Long avaSize;
private Long metaUpdatedAtMs;
private Long createdAtMs;
private Integer channelTypeCode;
private Integer channelTypeVersion;
private Integer subscribersCount;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; }
@@ -62,6 +66,9 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public Long getMetaUpdatedAtMs() { return metaUpdatedAtMs; }
public void setMetaUpdatedAtMs(Long metaUpdatedAtMs) { this.metaUpdatedAtMs = metaUpdatedAtMs; }
public Long getCreatedAtMs() { return createdAtMs; }
public void setCreatedAtMs(Long createdAtMs) { this.createdAtMs = createdAtMs; }
public Integer getChannelTypeCode() { return channelTypeCode; }
public void setChannelTypeCode(Integer channelTypeCode) { this.channelTypeCode = channelTypeCode; }
@@ -71,6 +78,13 @@ public class Net_GetChannelMessages_Response extends Net_Response {
public Integer getSubscribersCount() { return subscribersCount; }
public void setSubscribersCount(Integer subscribersCount) { this.subscribersCount = subscribersCount; }
public boolean isDeleted() { return deleted; }
public void setDeleted(boolean deleted) { this.deleted = deleted; }
public long getDeletedAtMs() { return deletedAtMs; }
public void setDeletedAtMs(long deletedAtMs) { this.deletedAtMs = deletedAtMs; }
public Integer getDeletedBlockNumber() { return deletedBlockNumber; }
public void setDeletedBlockNumber(Integer deletedBlockNumber) { this.deletedBlockNumber = deletedBlockNumber; }
public BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = channelRoot; }
}
@@ -63,6 +63,9 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
private Integer channelTypeCode;
private Integer channelTypeVersion;
private boolean personal;
private boolean deleted;
private long deletedAtMs;
private Integer deletedBlockNumber;
private BlockRef channelRoot;
public String getOwnerLogin() { return ownerLogin; }
@@ -100,6 +103,12 @@ public class Net_ListSubscriptionsFeed_Response extends Net_Response {
public boolean isPersonal() { return personal; }
public void setPersonal(boolean personal) { this.personal = personal; }
public boolean isDeleted() { return deleted; }
public void setDeleted(boolean deleted) { this.deleted = deleted; }
public long getDeletedAtMs() { return deletedAtMs; }
public void setDeletedAtMs(long deletedAtMs) { this.deletedAtMs = deletedAtMs; }
public Integer getDeletedBlockNumber() { return deletedBlockNumber; }
public void setDeletedBlockNumber(Integer deletedBlockNumber) { this.deletedBlockNumber = deletedBlockNumber; }
public BlockRef getChannelRoot() { return channelRoot; }
public void setChannelRoot(BlockRef channelRoot) { this.channelRoot = channelRoot; }
@@ -44,7 +44,11 @@ public class Net_AddCloseFriend_Handler implements JsonMessageHandler {
// Idempotent insert for close-friend relation.
// Rely on PostgreSQL ON CONFLICT DO NOTHING.
insertCloseFriendIgnoreDuplicate(c, from, canonicalTo, targetBch);
byte[] targetHeaderHash = findHeaderHash(c, targetBch);
if (targetHeaderHash == null || targetHeaderHash.length != 32) {
return NetExceptionResponseFactory.error(req, 409, "HEADER_NOT_FOUND", "У целевого blockchain нет HEADER block 0");
}
insertCloseFriendIgnoreDuplicate(c, from, canonicalTo, targetBch, targetHeaderHash);
Net_AddCloseFriend_Response resp = new Net_AddCloseFriend_Response();
resp.setOp(req.getOp());
@@ -69,7 +73,7 @@ public class Net_AddCloseFriend_Handler implements JsonMessageHandler {
}
private String findPrimaryBlockchain(Connection c, String login) throws Exception {
String sql = "SELECT blockchain_name FROM blockchain_state WHERE LOWER(login) = LOWER(?) ORDER BY blockchain_name LIMIT 1";
String sql = "SELECT blockchain_name FROM solana_user_pda_current WHERE LOWER(login)=LOWER(?) LIMIT 1";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
@@ -78,25 +82,37 @@ public class Net_AddCloseFriend_Handler implements JsonMessageHandler {
}
}
private byte[] findHeaderHash(Connection c, String blockchainName) throws Exception {
String login = blockchainName.substring(0, blockchainName.lastIndexOf('-'));
// Only fork1 owns HEADER #0 in segmented history.
String sql = "SELECT block_hash FROM blocks_store WHERE LOWER(login)=LOWER(?) AND block_number=0 ORDER BY fork_number ASC LIMIT 1";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
try (ResultSet rs = ps.executeQuery()) {
return rs.next() ? rs.getBytes("block_hash") : null;
}
}
}
private void insertCloseFriendIgnoreDuplicate(Connection c,
String login,
String toLogin,
String toBchName) throws Exception {
String toBchName,
byte[] targetHeaderHash) throws Exception {
String sql = """
INSERT INTO connections_state (
login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash
login, rel_type, to_login, to_block_number, to_block_hash
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT (login, rel_type, to_login, to_bch_name, to_block_number, to_block_hash) DO NOTHING
VALUES (?, ?, ?, ?, ?)
ON CONFLICT (login, rel_type, to_login, to_block_number, to_block_hash) DO NOTHING
""";
try (PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, login);
ps.setInt(2, MsgSubType.CONNECTION_CLOSE_FRIEND);
ps.setString(3, toLogin);
ps.setString(4, toBchName);
ps.setInt(5, 0);
ps.setBytes(6, new byte[32]);
ps.setInt(4, 0);
ps.setBytes(5, targetHeaderHash);
ps.executeUpdate();
}
}
@@ -6,6 +6,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_GetUserConnectionsGraph_Request;
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_GetUserConnectionsGraph_Response;
import server.logic.ws_protocol.JSON.handlers.profile.AvatarValueParser;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.MsgSubType;
@@ -234,7 +235,7 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
meta.accountRole=rs.getString("account_role"); meta.shineStatus=rs.getString("shine_status");
meta.gender=normalizeGender(rs.getString("gender_value")); meta.official="primary".equals(meta.accountRole); meta.shine="shining".equals(meta.shineStatus);
meta.primaryConfirmationsCount=rs.getInt("primary_confirmations_count"); meta.shineConfirmationsCount=rs.getInt("shine_confirmations_count");
meta.avatarAr=extractArAvatarTxId(rs.getString("avatar_value")); out.put(normKey(login),meta);
meta.avatarValue=String.valueOf(rs.getString("avatar_value") == null ? "" : rs.getString("avatar_value")); out.put(normKey(login),meta);
}}
}
return out;
@@ -291,11 +292,12 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
return txId;
}
private Net_GetUserConnectionsGraph_Response.AvatarItem makeAvatarItem(String avatarAr) {
String txId = String.valueOf(avatarAr == null ? "" : avatarAr).trim();
if (txId.isEmpty()) return null;
private Net_GetUserConnectionsGraph_Response.AvatarItem makeAvatarItem(String avatarValue) {
AvatarValueParser.Parsed parsed = AvatarValueParser.parse(avatarValue);
if (!parsed.ok()) return null;
Net_GetUserConnectionsGraph_Response.AvatarItem avatar = new Net_GetUserConnectionsGraph_Response.AvatarItem();
avatar.setAr(txId);
avatar.setAr(parsed.ar());
avatar.setSha256Hex(parsed.sha256Hex());
return avatar;
}
@@ -315,7 +317,7 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
it.setLogin(clean);
it.setGender(gender);
it.setGenderLabel(genderLabel(gender));
it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarAr));
it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarValue));
items.add(it);
}
return items;
@@ -354,7 +356,7 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
it.setShine(shine);
it.setOfficialLabel(official ? "официальный" : "неофициальный");
it.setShineLabel(shine ? "сияющий" : "несияющий");
it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarAr));
it.setAvatar(makeAvatarItem(meta == null ? null : meta.avatarValue));
items.add(it);
}
return items;
@@ -370,6 +372,6 @@ public class Net_GetUserConnectionsGraph_Handler implements JsonMessageHandler {
private int shineConfirmationsCount = 0;
private boolean official = false;
private boolean shine = false;
private String avatarAr = null;
private String avatarValue = "";
}
}
@@ -6,6 +6,7 @@ import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_ListContacts_Request;
import server.logic.ws_protocol.JSON.handlers.connections.entyties.Net_ListContacts_Response;
import server.logic.ws_protocol.JSON.handlers.profile.AvatarValueParser;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;
import shine.db.dao.DmDialogStateDAO;
@@ -59,12 +60,12 @@ public class Net_ListContacts_Handler implements JsonMessageHandler {
}
private static Net_ListContacts_Response.Avatar parseAvatar(String value) {
Net_ListContacts_Response.Avatar out = new Net_ListContacts_Response.Avatar();
String raw = value == null ? "" : value.trim();
java.util.regex.Matcher ar = java.util.regex.Pattern.compile("AR:([A-Za-z0-9_-]{43})").matcher(raw);
if (ar.find()) out.setAr(ar.group(1));
java.util.regex.Matcher sha = java.util.regex.Pattern.compile("SHA256:([A-Fa-f0-9]{64})").matcher(raw);
if (sha.find()) out.setSha256Hex(sha.group(1).toLowerCase());
AvatarValueParser.Parsed parsed = AvatarValueParser.parse(value);
if (!parsed.ok()) return out;
out.setAr(parsed.ar());
out.setSha256Hex(parsed.sha256Hex());
return out;
}
}
@@ -39,9 +39,12 @@ public class Net_GetUserConnectionsGraph_Response extends Net_Response {
public static class AvatarItem {
private String ar;
private String sha256Hex;
public String getAr() { return ar; }
public void setAr(String ar) { this.ar = ar; }
public String getSha256Hex() { return sha256Hex; }
public void setSha256Hex(String sha256Hex) { this.sha256Hex = sha256Hex; }
}
public static class RelativeItem {
@@ -0,0 +1,120 @@
package server.logic.ws_protocol.JSON.handlers.keyRotation;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationState_Response;
import shine.db.KeyEncodingUtil;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
import java.util.Arrays;
import java.util.Base64;
final class KeyRotationApiSupport {
private KeyRotationApiSupport() {}
static String normalizePublicKey32(String raw) {
String normalized = KeyEncodingUtil.normalizeKeyToBase64_32(raw);
if (normalized == null || normalized.isBlank()) {
throw new IllegalArgumentException("public key is empty");
}
try {
byte[] decoded = Base64.getDecoder().decode(normalized);
if (decoded.length != 32) throw new IllegalArgumentException("public key must be 32 bytes");
return Base64.getEncoder().encodeToString(decoded);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("public key must be Base58/Base64 of 32 bytes", e);
}
}
static byte[] parseHash32(String hex) {
if (hex == null) throw new IllegalArgumentException("hash is null");
String s = hex.trim();
if (s.length() != 64) throw new IllegalArgumentException("hash must contain 64 hex chars");
byte[] out = new byte[32];
for (int i = 0; i < 32; i++) {
int hi = Character.digit(s.charAt(i * 2), 16);
int lo = Character.digit(s.charAt(i * 2 + 1), 16);
if (hi < 0 || lo < 0) throw new IllegalArgumentException("hash contains non-hex chars");
out[i] = (byte) ((hi << 4) | lo);
}
return out;
}
static String toHex(byte[] bytes) {
if (bytes == null) return null;
StringBuilder sb = new StringBuilder(bytes.length * 2);
for (byte b : bytes) sb.append(String.format("%02x", b & 0xff));
return sb.toString();
}
static String nextBlockchainName(String login, String source) {
if (login == null || login.isBlank() || source == null || source.length() < 5) {
throw new IllegalArgumentException("bad source blockchain name");
}
String prefix = login + "-";
if (!source.startsWith(prefix) || source.length() != prefix.length() + 3) {
throw new IllegalArgumentException("source blockchain name does not match login");
}
String suffix = source.substring(prefix.length());
if (!suffix.chars().allMatch(Character::isDigit)) {
throw new IllegalArgumentException("bad blockchain suffix");
}
int n = Integer.parseInt(suffix);
if (n < 1 || n >= 999) throw new IllegalArgumentException("blockchain fork limit reached");
return login + "-" + String.format("%03d", n + 1);
}
static void requireKeysChangedAndDistinct(String oldRoot, String oldBlockchain, String oldClient,
String newRoot, String newBlockchain, String newClient) {
java.util.Set<String> oldKeys = java.util.Set.of(oldRoot, oldBlockchain, oldClient);
java.util.Set<String> newKeys = java.util.Set.of(newRoot, newBlockchain, newClient);
if (newKeys.size() != 3) {
throw new IllegalArgumentException("new root/blockchain/client keys must be distinct");
}
for (String newKey : newKeys) {
if (oldKeys.contains(newKey)) {
throw new IllegalArgumentException("new keys must not reuse any key from the old key set");
}
}
}
static boolean hashesEqual(byte[] a, byte[] b) {
return Arrays.equals(a, b);
}
static Net_KeyRotationState_Response response(String op, String requestId, KeyRotationSessionEntry e) {
Net_KeyRotationState_Response r = new Net_KeyRotationState_Response();
r.setOp(op);
r.setRequestId(requestId);
r.setStatus(200);
if (e == null) {
r.setRotationStatus(KeyRotationStatus.NONE.name());
return r;
}
r.setRotationSessionId(e.getId());
r.setRotationStatus(e.getStatus().name());
r.setSourceBlockchainName(e.getSourceBlockchainName());
r.setCandidateBlockchainName(e.getCandidateBlockchainName());
r.setOldRootKey(e.getOldRootKey());
r.setOldBlockchainKey(e.getOldBlockchainKey());
r.setOldClientKey(e.getOldClientKey());
r.setNewRootKey(e.getNewRootKey());
r.setNewBlockchainKey(e.getNewBlockchainKey());
r.setNewClientKey(e.getNewClientKey());
r.setForkFromBlock(e.getForkFromBlock());
r.setForkFromHash(toHex(e.getForkFromHash()));
r.setSourceTipBlock(e.getSourceTipBlock());
r.setSourceTipHash(toHex(e.getSourceTipHash()));
r.setReasonCode(e.getReasonCode());
r.setComment(e.getComment());
r.setProgressCurrent(e.getProgressCurrent());
r.setProgressTotal(e.getProgressTotal());
r.setPdaRotationSignature(e.getPdaRotationSignature());
r.setWalletMigrationStatus(e.getWalletMigrationStatus());
r.setMessageMigrationStatus(e.getMessageMigrationStatus());
r.setLastError(e.getLastError());
r.setRetryCount(e.getRetryCount());
r.setCreatedAtMs(e.getCreatedAtMs());
r.setUpdatedAtMs(e.getUpdatedAtMs());
return r;
}
}
@@ -0,0 +1,36 @@
package server.logic.ws_protocol.JSON.handlers.keyRotation;
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.keyRotation.entyties.Net_KeyRotationAbort_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
/** Прерывание разрешено только пока Solana-транзакция ротации ещё не могла быть отправлена. */
public final class Net_KeyRotationAbort_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_KeyRotationAbort_Request req = (Net_KeyRotationAbort_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
try {
KeyRotationSessionEntry current = rotations.getActiveByLogin(ctx.getLogin().trim());
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
if (current.getStatus() != KeyRotationStatus.COPYING_CHAIN && current.getStatus() != KeyRotationStatus.CHAIN_READY) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_ABORT_TOO_LATE",
"После начала ротации PDA процесс можно только завершить");
}
KeyRotationSessionEntry aborted = rotations.transition(current.getId(), current.getStatus(), KeyRotationStatus.ABORTED);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), aborted);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_ABORT_FAILED", "Не удалось прервать смену ключей");
}
}
}
@@ -0,0 +1,240 @@
package server.logic.ws_protocol.JSON.handlers.keyRotation;
import blockchain.BchBlockEntry;
import blockchain.BchCryptoVerifier;
import blockchain.MsgSubType;
import blockchain.ShineProtocolTags;
import blockchain.body.ForkBody;
import server.logic.ws_protocol.Base64Ws;
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.blockchain.Net_AddBlock_Handler_utils.BlockchainLocks;
import server.logic.ws_protocol.JSON.handlers.keyRotation.entyties.Net_KeyRotationAddBlock_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.sync.ArweavePublishSignal;
import shine.db.DbController;
import shine.db.dao.BlocksDAO;
import shine.db.dao.KeyRotationCandidateBlocksDAO;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.entities.BlockEntry;
import shine.db.entities.KeyRotationCandidateBlockEntry;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
import java.sql.Connection;
import java.util.Arrays;
import java.util.Base64;
import java.util.concurrent.locks.ReentrantLock;
/**
* Принимает DataItem будущего fork во время COPYING_CHAIN.
* Candidate-блок сохраняется отдельно от blocks и не влияет на materialized state.
*/
public final class Net_KeyRotationAddBlock_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance();
private final KeyRotationCandidateBlocksDAO candidates = KeyRotationCandidateBlocksDAO.getInstance();
private final BlocksDAO blocks = BlocksDAO.getInstance();
private final shine.db.dao.CanonicalChainResolver canonicalChain = shine.db.dao.CanonicalChainResolver.getInstance();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_KeyRotationAddBlock_Request req = (Net_KeyRotationAddBlock_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
if (req.getBlockNumber() < 0 || req.getBlockBytesB64() == null || req.getBlockBytesB64().isBlank()) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "blockNumber и blockBytesB64 обязательны");
}
String login = ctx.getLogin().trim();
KeyRotationSessionEntry initial;
try {
initial = rotations.getActiveByLogin(login);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_DB_ERROR", "Не удалось прочитать состояние смены ключей");
}
if (initial == null || initial.getStatus() != KeyRotationStatus.COPYING_CHAIN) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_COPYING", "Ротация не находится на этапе COPYING_CHAIN");
}
ReentrantLock lock = BlockchainLocks.lockFor(initial.getCandidateBlockchainName());
lock.lock();
try (Connection c = DbController.getInstance().getConnection()) {
KeyRotationSessionEntry session = rotations.getActiveByLogin(c, login);
if (session == null || session.getStatus() != KeyRotationStatus.COPYING_CHAIN) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_NOT_COPYING", "Ротация больше не находится на этапе COPYING_CHAIN");
}
int stored = candidates.countStored(c, session.getId());
int expectedBlockNumber = session.getForkFromBlock() + 1;
KeyRotationCandidateBlockEntry existing = candidates.getByNumber(c, session.getId(), req.getBlockNumber());
if (existing != null) {
BchBlockEntry repeated;
try { repeated = new BchBlockEntry(Base64Ws.decode(req.getBlockBytesB64())); }
catch (Exception e) { return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Не удалось распарсить DataItem"); }
if (!Arrays.equals(existing.getBlockHash(), repeated.getHash32()) || !Arrays.equals(existing.getDataItemId(), repeated.getDataItemId32())) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BLOCK_CONFLICT", "TECH_FORK уже сохранён с другим содержимым");
}
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), session);
}
if (req.getBlockNumber() != expectedBlockNumber) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BLOCK_OUT_OF_ORDER", "Segmented fork принимает только TECH_FORK #" + expectedBlockNumber);
}
if (stored >= 1) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_CHAIN_ALREADY_COMPLETE", "TECH_FORK уже принят сервером");
}
final byte[] raw;
final BchBlockEntry block;
try {
raw = Base64Ws.decode(req.getBlockBytesB64());
block = new BchBlockEntry(raw);
block.body.check();
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_BLOCK", "Некорректный SHiNE/ANS-104 блок");
}
if (block.blockNumber != req.getBlockNumber()) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BLOCK_NUMBER_MISMATCH", "blockNumber запроса не совпадает с блоком");
}
if (!block.getDataItem().hasTag(ShineProtocolTags.APP_TAG_NAME, ShineProtocolTags.APP_TAG_VALUE)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_APP_TAG", "Отсутствует App=" + ShineProtocolTags.APP_TAG_VALUE);
}
String expectedTypeTag = expectedTypeTag(block);
String actualTypeTag = block.getDataItem().tagValue(ShineProtocolTags.TYPE_TAG_NAME);
if (expectedTypeTag != null ? !expectedTypeTag.equals(actualTypeTag) : actualTypeTag != null) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_TYPE_TAG", "Некорректный t-тег candidate DataItem");
}
if (!requestPrevHashMatches(req.getPrevBlockHash(), block.prevHash32)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_PREV_HASH_MISMATCH", "prevBlockHash запроса не совпадает с блоком");
}
byte[] expectedBack32 = new byte[32];
if (block.blockNumber >= 32) {
expectedBack32 = canonicalChain.getHash(c, session.getSourceBlockchainName(), block.blockNumber - 32);
if (expectedBack32 == null || expectedBack32.length != 32) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BACK32_SOURCE_MISSING", "Нет канонического блока N-32 для проверки back32Hash");
}
}
if (!Arrays.equals(block.back32Hash32, expectedBack32)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BACK32_HASH_MISMATCH", "back32Hash candidate-блока не совпадает с N-32");
}
byte[] newBlockchainKey;
try {
newBlockchainKey = Base64.getDecoder().decode(session.getNewBlockchainKey());
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_BAD_STORED_KEY", "Некорректный new blockchain public key в rotation session");
}
if (newBlockchainKey.length != 32 || !BchCryptoVerifier.verifyBlock(block, newBlockchainKey)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_SIGNATURE", "Candidate DataItem должен быть подписан новым blockchain key");
}
String validationError;
try {
validationError = validateCandidate(c, session, block);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_VALIDATE_FAILED", "Не удалось проверить candidate-блок");
}
if (validationError != null) {
return NetExceptionResponseFactory.error(req, 400, validationError, "Candidate-блок не соответствует выбранному fork");
}
KeyRotationCandidateBlockEntry entry = new KeyRotationCandidateBlockEntry();
entry.setRotationSessionId(session.getId());
entry.setLogin(login);
entry.setCandidateBlockchainName(session.getCandidateBlockchainName());
entry.setBlockNumber(block.blockNumber);
entry.setBlockHash(block.getHash32());
entry.setDataItemId(block.getDataItemId32());
entry.setBlockBytes(raw);
entry.setCreatedAtMs(System.currentTimeMillis());
boolean oldAutoCommit = c.getAutoCommit();
c.setAutoCommit(false);
try {
candidates.insertOrGet(c, entry);
c.commit();
} catch (Exception e) {
c.rollback();
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_BLOCK_CONFLICT", "Не удалось сохранить candidate-блок");
} finally {
c.setAutoCommit(oldAutoCommit);
}
// Как и обычный пользовательский блок, candidate сразу ставится в неблокирующую Turbo-очередь.
// При сетевой ошибке pending-флаг остаётся TRUE и его подберёт плановый retry.
ArweavePublishSignal.keyRotationCandidateAccepted(entry.getDataItemId());
// progressCurrent обновляет Arweave publisher только после реальной публикации.
KeyRotationSessionEntry refreshed = rotations.getActiveByLogin(login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), refreshed == null ? session : refreshed);
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_ADD_BLOCK_FAILED", "Не удалось принять candidate-блок");
} finally {
lock.unlock();
}
}
private String validateCandidate(Connection c, KeyRotationSessionEntry session, BchBlockEntry candidate) throws Exception {
int techForkNumber = session.getForkFromBlock() + 1;
if (candidate.blockNumber != techForkNumber) return "KEY_ROTATION_UNEXPECTED_BLOCK_NUMBER";
if ((candidate.type & 0xFFFF) != 0
|| (candidate.subType & 0xFFFF) != (MsgSubType.TECH_FORK & 0xFFFF)
|| !(candidate.body instanceof ForkBody fork)) {
return "KEY_ROTATION_TECH_FORK_REQUIRED";
}
if (!Arrays.equals(candidate.prevHash32, session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_PREV_HASH";
BlockEntry forkSourceEntry = canonicalChain.getBlock(c, session.getSourceBlockchainName(), session.getForkFromBlock());
BlockEntry tipSourceEntry = blocks.getByNumber(c, session.getSourceBlockchainName(), session.getSourceTipBlock());
if (forkSourceEntry == null || tipSourceEntry == null) return "KEY_ROTATION_SOURCE_BLOCK_MISSING";
BchBlockEntry forkSource = new BchBlockEntry(forkSourceEntry.getBlockBytes());
BchBlockEntry tipSource = new BchBlockEntry(tipSourceEntry.getBlockBytes());
byte[] oldBlockchain = Base64.getDecoder().decode(session.getOldBlockchainKey());
if (!Arrays.equals(fork.parentBlockchainKey32, oldBlockchain)) return "KEY_ROTATION_TECH_FORK_PARENT_KEY";
if (fork.forkPointBlockNumber != session.getForkFromBlock()) return "KEY_ROTATION_TECH_FORK_POINT";
if (!Arrays.equals(fork.forkPointBlockHash32, session.getForkFromHash())) return "KEY_ROTATION_TECH_FORK_POINT_HASH";
if (fork.forkPointTimestampMs != Math.multiplyExact(forkSource.timestamp, 1000L)) return "KEY_ROTATION_TECH_FORK_POINT_TIME";
if (fork.parentTipBlockNumber != session.getSourceTipBlock()) return "KEY_ROTATION_TECH_FORK_TIP";
if (!Arrays.equals(fork.parentTipBlockHash32, session.getSourceTipHash())) return "KEY_ROTATION_TECH_FORK_TIP_HASH";
if (fork.parentTipTimestampMs != Math.multiplyExact(tipSource.timestamp, 1000L)) return "KEY_ROTATION_TECH_FORK_TIP_TIME";
if (fork.discardedBlocksCount != session.getSourceTipBlock() - session.getForkFromBlock()) return "KEY_ROTATION_TECH_FORK_DISCARDED";
if (fork.reasonCode != session.getReasonCode()) return "KEY_ROTATION_TECH_FORK_REASON";
if (!normalizeComment(fork.comment).equals(normalizeComment(session.getComment()))) return "KEY_ROTATION_TECH_FORK_COMMENT";
return null;
}
private static boolean requestPrevHashMatches(String raw, byte[] actual) {
if (raw == null || raw.isBlank()) {
return isZero32(actual);
}
try {
return Arrays.equals(KeyRotationApiSupport.parseHash32(raw), actual);
} catch (Exception e) {
return false;
}
}
private static boolean isZero32(byte[] value) {
if (value == null || value.length != 32) return false;
for (byte b : value) if (b != 0) return false;
return true;
}
private static String normalizeComment(String value) {
if (value == null) return "";
return value.trim().replace("\r\n", "\n").replace('\r', '\n');
}
private static String expectedTypeTag(BchBlockEntry block) {
int type = block.type & 0xffff;
return switch (type) {
case 0 -> "tech";
case 3 -> "conn";
case 4 -> "prof";
default -> null;
};
}
}
@@ -0,0 +1,71 @@
package server.logic.ws_protocol.JSON.handlers.keyRotation;
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.keyRotation.entyties.Net_KeyRotationContinue_Request;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import shine.db.dao.CurrentUsersDAO;
import shine.db.dao.KeyRotationSessionsDAO;
import shine.db.dao.SignedMessagesDAO;
import shine.db.entities.KeyRotationSessionEntry;
import shine.db.entities.KeyRotationStatus;
/** Координирует реально выполненные wallet/DM этапы после rebuild. */
public final class Net_KeyRotationContinue_Handler implements JsonMessageHandler {
private final KeyRotationSessionsDAO rotations = KeyRotationSessionsDAO.getInstance();
@Override
public Net_Response handle(Net_Request baseReq, ConnectionContext ctx) {
Net_KeyRotationContinue_Request req = (Net_KeyRotationContinue_Request) baseReq;
if (ctx == null || !ctx.isAuthenticatedUser() || ctx.getLogin() == null || ctx.getLogin().isBlank()) {
return NetExceptionResponseFactory.error(req, 401, "AUTH_REQUIRED", "Нужна авторизованная пользовательская сессия");
}
try {
String login = ctx.getLogin().trim();
KeyRotationSessionEntry current = rotations.getActiveByLogin(login);
if (current == null) return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), null);
if (current.getStatus() == KeyRotationStatus.WALLET_MIGRATION) {
String walletStatus = String.valueOf(req.getWalletMigrationStatus() == null ? "" : req.getWalletMigrationStatus()).trim().toUpperCase();
if (!"COMPLETE".equals(walletStatus) && !"SKIPPED".equals(walletStatus)) {
return NetExceptionResponseFactory.error(req, 400, "KEY_ROTATION_BAD_WALLET_STATUS",
"walletMigrationStatus должен быть COMPLETE или SKIPPED");
}
rotations.setMigrationSubStatus(current.getId(), "wallet_migration_status", walletStatus);
current = rotations.transition(current.getId(), KeyRotationStatus.WALLET_MIGRATION, KeyRotationStatus.MESSAGE_MIGRATION);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
if (current.getStatus() == KeyRotationStatus.MESSAGE_MIGRATION) {
long remaining = SignedMessagesDAO.getInstance()
.countMessagesNeedingReencryption(login, current.getUpdatedAtMs());
if (remaining > 0) {
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_DM_PENDING",
"Остались неперешифрованные личные сообщения: " + remaining);
}
rotations.setMigrationSubStatus(current.getId(), "message_migration_status", "COMPLETE");
current = rotations.transition(current.getId(), KeyRotationStatus.MESSAGE_MIGRATION, KeyRotationStatus.FINALIZING);
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
if (current.getStatus() == KeyRotationStatus.FINALIZING) {
current = rotations.transition(current.getId(), KeyRotationStatus.FINALIZING, KeyRotationStatus.COMPLETE);
refreshCurrentUser(ctx, login);
return KeyRotationApiSupport.response(req.getOp(), req.getRequestId(), current);
}
return NetExceptionResponseFactory.error(req, 409, "KEY_ROTATION_CONTINUE_NOT_ALLOWED",
"На текущем этапе продолжение этой операцией не требуется");
} catch (Exception e) {
return NetExceptionResponseFactory.error(req, 500, "KEY_ROTATION_CONTINUE_FAILED",
"Не удалось продолжить смену ключей");
}
}
private static void refreshCurrentUser(ConnectionContext ctx, String login) throws Exception {
var fresh = CurrentUsersDAO.getInstance().getByLogin(login);
if (fresh != null) ctx.setCurrentUser(fresh);
}
}

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