Files
SHiNE-server/docs/Blockchain/CORE_CONTENT_B4_WS.md
T

17 KiB
Raw Blame History

B4a — CORE WebSocket runtime (development only)

Актуализация: теперь единственный WsServer и JsonHandlerRegistry. См. текущую схему. Описания отдельного CoreWsEntry / CoreWsRouteRegistry ниже — история.

This is the first network integration slice, not the final production cutover or completed B. The binary protocol is unchanged. --core-ws binds only 127.0.0.1, uses the same AppConfig db.* as auth DAOs, and requires explicit disposable staging opt-in, a shine_core_* localhost database, nonempty password and server login. Existing --core-staging remains an offline fixture tool. A default Frame server refuses a CORE database before bootstrap. Do not run two epochs against one DB.

Local use

Use a disposable PostgreSQL database, with a private runtime application.properties on the classpath as required by AppConfig (copy the safe example to an untracked local resource and override private values; never commit credentials). Configure db.url=jdbc:postgresql://127.0.0.1:5432/shine_core_ws, db.user, db.password, server.SHiNE.login, optionally core.ws.port=7071. Run the regular build with JDK 17 and Gradle 8.14, then start WsServer --core-ws with SHINE_CORE_STAGING_DISPOSABLE=YES. For example SHINE_CORE_STAGING_DISPOSABLE=YES bash gradlew run --args='--core-ws'. The listener is loopback, not a deployment mode. The database needs a trusted registered PDA/account + local routing fixture before authentication; no sync/registration service auto-populates it. Paid auth's existing session-type verification can contact configured Solana RPC; never point tests at production or initiate real transactions.

Explicit route table (no Frame fallback)

  • Ping, ResolveLoginForAuth, AuthChallenge, CreateAuthSession, SessionChallenge, SessionLogin, CloseActiveSession, CloseOtherSessions, ListSessions: existing auth/session behavior and DAO (not legacy blockchain writers).
  • CreateGenesis: provisional new network command; same fields as AddBlock, blockNumber=0 and prevBlockHash="", authenticated LOCAL and fork 001. Registered identity/owner still validated by PDA policy; no account creation. Both AddBlock and CreateGenesis validate session existence inside append transaction (account/PDA lock before session FOR SHARE), as well as resync/rotation and owner checks. Revoked session cannot replay a signed pair. Existing offline trusted methods deliberately remain.
  • AddBlock, GetMyBlockchain, GetBlockchainBlock, ListBlockchainHeads: existing CORE WS implementation. Public raw chain reads preserve prior technical read intent, not social visibility semantics. Other operations are UNKNOWN_OP, with no fallback or legacy registry bootstrap. Use provisional contract only for testing; C waits for final contract.
  • Same JSON envelope; root op/requestId override nested copies. Request limit 24 MiB of text accommodates two 8 MiB raw objects plus base64 and envelope. Full JSON/Jetty limits and load behavior are NOT verified. CORE listener does not log raw incoming/outgoing messages at endpoint or normal dispatcher DEBUG paths. Legacy behavior otherwise retained. No legacy debug/file servlets, free registration bootstrap, sync/publisher/rebuild/DM schedulers or connection pool are started in CORE mode.

Verification and remaining integration

bash scripts/tests/test_core_content_stage_b_partial.sh verifies core autonomous tests and compiles JDBC fixtures. Existing corePgB1Runtime fixture now also exercises authenticated genesis, rejected missing/revoked sessions, and authenticated append. Run bash gradlew :shine-server-net-protocol:coreWsGuards :shine-server-net-protocol:coreWsRoutes compileJava with real dependencies; then B0 PG suite and actual WS E2E with a fixture user. Do not mistake pre-DB tests for real Jetty. No production change.

Next B4 slice: register actual CORE social readers with visibility/ACL and original DTO semantics; signed read/notification state, post-commit effects; then registration/FREE_CERT, key rotation network flow/session revocation/resync and DM continuation, identity sync and all remaining B1–B3 tasks. Legacy registry must remain unreachable in CORE mode. Recheck live routing/identity concurrency (current scope preflight is not transactional), auth/session races, full response bounds, origin/rate/queue limits, actual Jetty/Jackson and PostgreSQL. Arweave transport is D. B not closed; no transition to C yet.

B4b — CORE social readers (development only)

The explicit allowlist now has 23 operations (14 from B4a and 9 new). See B4b wire contract. The new readers use CoreCommandService and existing CoreSocialQueries; no legacy Frame tables or fallback. Case-insensitive owner resolution uses the registered PDA spelling in the same repeatable-read transaction. Public channel/stories readers validate exact root number + hash and canonical applicability; deleted public channels are only readable through the authenticated owner route. Personal/group channel pages fail closed pending pair/ACL integration. Raw technical blockchain reads remain public as before; social visibility is not encryption or confidentiality. Profiles expose signed PROFILE events, not the separate legacy signed user settings table. Personal relations/feed and likedByMe derive the viewer from the authenticated session. Read guards are preflight, not transactional session locks; revoke races still need review.

Nine CORE-specific operation names and response DTOs are provisional, not drop-in replacements for legacy UI requests. The binary protocol and old operations are unchanged. The client has not been migrated. No notification/state writers, pushes or identity/rotation integration added here. Next: B4c signed read/unread, notification readers and post-commit dispatch; B4d identity/registration, B4e rotation, B4f audit and real integration. Outstanding personal pair, thread, versions, incoming graph, counters, legacy DTO mapping and real PG/WS verification remain mandatory before B closure.

B4c: notifications WS (частично)

CORE allowlist теперь 26 операций. CoreNotificationWsHandler и CoreContentStore.advanceNotificationSeen сохраняют прежний пакет SHiNE_NTF с проверкой текущего clientKey и auth session внутри транзакции. CoreSocialQueries использует общий фильтр страниц/счётчиков; агрегат трёх категорий читается из одного canonical snapshot. Локальный AddBlock после успешного commit определяет адресата только для нового VALID notification event; push отправляется после освобождения blockchain lock. Сигнал не содержит содержания/чисел. При повторном AddBlock, отказе/rollback и старой отметке push не вызывается. Реальная доставка/Jetty и SQL требуют интеграционной проверки.

Открыто: подписанный channel read/unread state (не переносить слепо Frame count: после rollback нужно пересчитать сохранившийся префикс), feed unread, общие counters, текст уведомлений/DTO, импорт/rotation invalidation и publisher wake-up (D). Не включать legacy DAO/handlers. Следующая задача — закрыть остаток B4c и затем B4d/e/f. См. API 22.

B4c continuation — canonical read prefix

27 CORE routes. SetCoreChannelReadState подписывает root/follow/anchor hash, проверяет PDA clientKey/session, каноническую подписку и anchor; сохраняет signed mark в additive shine_core_v2.channel_read_prefix (revision 3 сохраняется, DDL идемпотентен; legacy tables не меняются). CoreSocialQueries.feed отдаёт readState в том же snapshot. Общая часть двух физических ancestry ограничивает прочитанный префикс; замещённые посты unread. Отписка/новая подписка не наследует baseline, повтор FOLLOW без UNFOLLOW сохраняет. Адресный CoreChannelReadChanged после commit отметки и локальной публикации. См. API 22 для точного preliminary signing contract и ограничений. Общие counters, импорт/rotation invalidation, нагрузочные проверки и полная интеграция остаются. Следующая основная реализация — B4d registration/FREE_CERT/identity, затем B4e и B4f. B не закрыта.

B4d — registration and identity (25.11.2026)

CORE allowlist 33 routes: reused registration DTO/handlers GetNamespaces, CheckRegistrationLogin, CheckRegistrationEmail, StartFreeRegistration, ConfirmFreeRegistration, GetRegistrationStatus. The existing email challenge/issuer/publisher workflow is instantiated with explicit epoch CORE_CONTENT; registration DataItem payload and inner signature are unchanged, the outer signed tags use App=test5593,t=reg,Protocol=SHiNE-Free-Registration-V1. Frame/CORE verifiers and importers reject the other epoch; import requires the matching database epoch. No Frame blockchain state is created for CORE FREE_CERT. The registrar identity is read from synchronized type-2 namespace, not WS-supplied. Repeated email hash is rechecked under a transaction lock if reuse is forbidden (base v39 removed the unique index).

The existing --core-ws loopback/disposable restriction remains. Registration discovery/status is wired by default; email availability for free registration and issuance are disabled by default. To exercise free issuance in a dedicated test configuration, explicitly set SHINE_CORE_REGISTRATION_ENABLED=YES, freeRegistration.enabled=true and the existing registrar/namespace/Turbo/email settings (real external effects possible; do not use production secrets). The legacy allowTestCode bypass is disabled in CORE. If the namespace is missing or the registrar does not match, startup fails. No real email/Turbo operation was executed during this change.

Optional read-only Solana RPC identity sync: SHINE_CORE_IDENTITY_SYNC=YES, configure the existing solana.users.sync.* parameters with exactly the same local JDBC URL/user/password as the CORE listener; initial readiness is bounded to 60 seconds. It reuses common PDA/namespace upserts, not Frame quota copy or legacy rotation reconciliation; skips the support history indexer for this restricted test mode. The common solana_sync_state.update_fee_lamports column is ensured idempotently (same additive DDL as existing sync startup). This path is not verified against RPC. No real Solana transactions submitted.

CORE reads/writes now resolve both paid PDA and verified FREE_CERT. Free identity can use only fork 1 and the registered exact spelling/key; Long.MAX_VALUE models the original free size_limit=0 (unbounded), not a paid zero quota. Paid grants/rotation policy unchanged. Signed notification/read-state checks resolve the client key from the same authoritative identity. Canonical heads, public reads and cross-account social queries include free accounts. FREE_CERT → PAID uses existing v35/v37 trigger (same registered spelling and three keys), keeps the same history; paid quota applies thereafter. CORE first HEADER remains a client-signed pair through CreateGenesis, after registration and auth; not generated by the registrar. No changes to CORE/CONTENT binary format or existing registration payload.

corePgRegistration tests actual importer, FREE_CERT, genesis/post, public readers, existing paid-upgrade trigger, restart and absence of Frame state against a disposable full schema. Written and compiled with compile-only DbController adapter; not run. The optional Solana sync runtime, actual Jetty/Jackson, PostgreSQL and external issuance still require integration testing. B4d main code path implemented; B4e must connect rotation/resume to trusted snapshots, not the old reconciler. B not closed.

B4e — возврат к оригинальному сценарию

Ротация сохраняет исходный API 19 и статусы. Общие SQL-операции извлечены из старого DAO и используются обоими путями; новый формат касается только FORK, хешей, публикации и canonical history. Публичные семь маршрутов ещё не включены; их необходимо адаптировать, не проектируя новый workflow. См. CORE_CONTENT_STAGE_B_STAGING.md.

B4e — исходные операции ротации в CORE

Актуально: 43 маршрута. Семь имён API 19 и поля состояния сохранены. Единственное изменение входного DTO формата блока — KeyRotationAddBlock: blockNumber, prevBlockHash (CORE hash), coreDataItemB64, contentDataItemB64 (standard Base64). blockBytesB64 не принимается в CORE. KeyRotationStart.forkFromHash и response hashes теперь CORE. Клиент C должен адаптировать чтение и формирование FORK, не менять сценарий. KeyRotationStatus использует оригинальный handler, остальные — адаптер к общей SQL state machine. В --core-ws три прежних DM операции разрешены только на MESSAGE_MIGRATION.

Тестовый publisher FORK (Turbo/L1): SHINE_CORE_ROTATION_PUBLISH=YES, существующие arweave.blocks.publish.*, режим не none; серверный период 60 секунд. Не включать на production, внешние запросы/расходы реальны. L1 публикует CONTENT и CORE отдельными одноэлементными bundles; это две платные L1 транзакции, порядок сохранён. Общий CORE outbox и импорт остаются D. Для RPC snapshot SHINE_CORE_IDENTITY_SYNC=YES. Клиентская signature PDA не доказывает смену ключей; scheduler ждёт доверенное состояние трёх ключей и имени. Реальный WS/PG/RPC/Turbo/L1 ещё не проверены.

B4f — compatibility pass

68 routes (55 original names, 13 CORE-only); 25 original names restored since B4e. See remaining compatibility matrix. Original settings and device pairing handlers reused; canonical queries supply original profile/directory/channel/counters DTOs. No Frame fallback. No binary or schema changes. Real Gradle/PG/WS still not verified. B remains open.

B4f — второй проход (актуальная точка)

81 routes, 68 original names of 90; 22 missing (см. docs/Blockchain/CORE_CONTENT_B4F_REMAINING.md). Оригинальные calls, push, diagnostics, signed userParams и AckSessionDelivery переиспользованы без изменения handlers/DTO. Используется оригинальный UserCountersChanged с исходным payload, вычисляемым по CORE + DM; прежние временные CoreNotificationsChanged/CoreChannelReadChanged больше не посылаются в CORE runtime. Остальные места post-commit (import/rotation/DM) ещё не перенесены. Numeric read state пока не возвращён: требуется адаптация старой семантики, не подключать старый Frame DAO. DM ordinary flow зависит от legacy relation/profile/routing projections; не включать слепо. Сохранить исходные сценарии и не вводить независимые улучшения. B не закрыта. Gradle/PG/real WS не проверены.

B4f — граф и списки отношений (актуальная точка)

92 routes, 79 original names of 90, 11 missing. GetUserConnectionsGraph и ListUserProfileRelations используют прежние DTO и обработчики с адаптированным чтением CORE; не вводят новых API. Подробности и остаток — docs/Blockchain/CORE_CONTENT_B4F_REMAINING.md. B открыта; реальный PostgreSQL/WS и полная сборка не проверены.