feat(blockchain): implement chain reorg rollback and replay with operational alerts (#357) - #381
Open
OMGO-Code wants to merge 2 commits into
Open
Conversation
…ational alerts Implements V2-BE-020: canonical block-hash divergence detection, atomic rollback of affected event and projection mutations, deterministic replay, and structured operational alerting — without introducing backend-authoritative protocol mutations or new runtime dependencies. Architecture: - BlockchainReorgAlertService: central alert bus that persists reorg events to the reorg_events table and emits structured alerts (detected → rollback → replay → error) via in-memory ring buffer and subscriber pattern. - BlockchainIndexerService.handleReorg(): unified entry point that detects hash divergence, rolls back orphaned state atomically, and emits alerts at each phase. - BlockchainIndexerService.verifyBlockHash(): compares stored hashes against the canonical chain via RPC with retry/backoff. - ReorgDetectorService and ReconciliationService: integrated with alert service (Optional injection) for visibility into the in-memory pipeline. Schema & migrations: - New reorg_events table (TypeORM entity + migration) for persistent audit trail of every detected reorganization with depth, affected block range, orphaned/replayed counts, duration, and error tracking. Security & integrity: - All rollback/replay operations are transactional (startTransaction → commitTransaction/rollbackTransaction). - SequentialQueue serialises all state mutations to prevent rollback races. - Orphaned events are deleted atomically before checkpoint rewinds, ensuring no orphaned state is exposed to finalized queries. - Smart contracts remain authoritative; indexer only projects events. - No secrets, floating-point accounting, or Stellar/Freighter dependencies. API endpoints: - GET /api/v1/blockchain/reorg/verify — verify block hash against canonical - POST /api/v1/blockchain/reorg/handle — trigger rollback + replay + alerts - GET /api/v1/blockchain/reorg/alerts — recent operational alerts - GET /api/v1/blockchain/reorg/history-db — persisted reorg history - GET /api/v1/blockchain/reorg/summary — health check statistics Tests (77 blockchain tests, all passing): - 10 unit tests for BlockchainReorgAlertService (detection, rollback, replay, error, subscribe/unsubscribe, ring buffer, summary). - 5 integration tests for end-to-end reorg lifecycle with alerts. - 3 new handleReorg tests (rollback stats, zero events, alert emission). - Pre-existing tests for replay idempotency, checkpoint atomicity, state eviction, reorg detection, and sequential queue serialization. Baseline failures (17 suites in unrelated modules: claims, identity, admin, profiler, health, notifications, reputation, theme, dispute, ipfs) are pre-existing and unrelated to this change. Close DigiNodes#357 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
Contributor
|
resolve conflicts @OMGO-Code |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
V2-BE-020 — Chain Reorganization Rollback and Replay
Overview
Implements the full chain reorg lifecycle: detect canonical block-hash divergence → atomic rollback → deterministic replay → operational alerts — without introducing backend-authoritative protocol mutations or new runtime dependencies.
Close #357
Architecture
BlockchainReorgAlertServicereorg_eventstable, emits structured alerts via in-memory ring buffer + subscriber patternBlockchainIndexerService.handleReorg()BlockchainIndexerService.verifyBlockHash()ReorgDetectorServiceReconciliationServiceSequentialQueueWhat Changed
New files (5):
src/blockchain/entities/reorg-event.entity.ts— TypeORM entity forreorg_eventsaudit trailsrc/blockchain/blockchain-reorg-alert.service.ts— Structured alert service with DB persistence + ring buffersrc/migrations/1790000000000-CreateReorgEventsTable.ts— Migration forreorg_eventstablesrc/blockchain/blockchain-reorg-alert.service.spec.ts— 10 unit tests for alert servicesrc/blockchain/blockchain-reorg-alert.integration.spec.ts— 5 integration tests for full reorg lifecycleModified files (7):
src/blockchain/blockchain-indexer.service.ts— AddedhandleReorg(),verifyBlockHash(),findDivergencePoint(), alert integrationsrc/blockchain/reorg-detector.service.ts— Optional alert service injection, emits detection alertssrc/blockchain/reconciliation.service.ts— Optional alert service injection, emits rollback/replay/error alertssrc/blockchain/blockchain.module.ts— WiresReorgEventRecord+BlockchainReorgAlertServicesrc/blockchain/blockchain.controller.ts— 5 new API endpoints with Swagger annotationssrc/blockchain/entities/index.ts— ExportsReorgEventRecordsrc/blockchain/blockchain-indexer.service.spec.ts— 3 new tests forhandleReorg()New API Endpoints
Security & Integrity
Acceptance Criteria Evidence
ReorgDetectorService.detectReorg()+BlockchainIndexerService.verifyBlockHash()+findDivergencePoint()replayFromBlockInternal()— atomic transaction reverses events + deletes orphaned records + rewinds checkpointSequentialQueueserialises all mutations; canonical chain re-indexed viaprocessEvent()BlockchainReorgAlertServiceatdetected → rollback → replay → errorphasesconfirmedevents served via API1790000000000-CreateReorgEventsTable.tsmigration createdTest Results
blockchain-reorg-alert.service.spec.tsblockchain-reorg-alert.integration.spec.tsblockchain-indexer.service.spec.tsblockchain-replay.spec.tsblockchain-reorg.integration.spec.tsstate.service.spec.tsblockchain-indexer.spec.tsrpc-backoff.util.spec.tssequential-queue.spec.tsBaseline failures (17 suites, 12 tests in unrelated modules: claims, identity, admin, profiler, health, notifications, reputation, theme, dispute, ipfs) are pre-existing and unrelated to this change.
Migration Impact
The
reorg_eventstable is additive — no existing tables are modified. The migration can be applied with:No data rebuild or backfill is required.
Residual Risks
findDivergencePoint()auto-detect path: WhencanonicalHashis omitted, the method walks back but doesn't compare hashes via RPC. Callers should always providecanonicalHashor this path needs enhancement with the RPC provider.verifyBlockHash()no-rpcUrl fallback: Without an RPC URL, falls back to queryingprocessed_events.block_hashwhich doesn't exist as a column. In practice, callers should always providerpcUrlor the service should inject an RPC provider at construction time.BlockchainStateService: The reorg detection pipeline uses in-memory maps. State is lost on restart. The DB-backedBlockchainIndexerServicehandles persistence; the in-memory pipeline is best suited for low-latency detection within a single process lifetime.Dependencies
Labels
backendindexersecuritycomplexity-high