From 8a4a9c0cb758144e9e5dd38c6fc9da4a89d1ec19 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 2 Apr 2026 04:43:02 +0100 Subject: [PATCH] feat(chain): add BlockCallback fired after every block stored MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Chain.SetBlockCallback(func(height, hash, aliasName)) enables event-driven architecture — the EventBus subscribes to block storage and emits events without coupling chain to events. Callback fires in processBlockBlobs after PutBlock succeeds. Includes alias name if the block contains an alias registration. Co-Authored-By: Charon --- chain/chain.go | 13 ++++++++++++- chain/sync.go | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/chain/chain.go b/chain/chain.go index c69016f..b373b68 100644 --- a/chain/chain.go +++ b/chain/chain.go @@ -16,7 +16,8 @@ import ( // Chain manages blockchain storage and indexing. // Usage: var value chain.Chain type Chain struct { - store *store.Store + store *store.Store + blockCallback BlockCallback } // New creates a Chain backed by the given store. @@ -64,3 +65,13 @@ func (c *Chain) Snapshot() (uint64, *types.Block, *BlockMeta) { } return height, blk, meta } + +// BlockCallback is called after a block is successfully stored. +type BlockCallback func(height uint64, hash string, aliasName string) + +// SetBlockCallback sets a function called after each block is stored. +// +// c.SetBlockCallback(func(height uint64, hash string, alias string) { ... }) +func (c *Chain) SetBlockCallback(cb BlockCallback) { + c.blockCallback = cb +} diff --git a/chain/sync.go b/chain/sync.go index d8bfbe0..d01545c 100644 --- a/chain/sync.go +++ b/chain/sync.go @@ -280,7 +280,20 @@ func (c *Chain) processBlockBlobs(blockBlob []byte, txBlobs [][]byte, CumulativeDiff: cumulDiff, GeneratedCoins: 0, // not available from wire; RPC path passes via bd.BaseReward } - return c.PutBlock(&blk, meta) + if err := c.PutBlock(&blk, meta); err != nil { + return err + } + + // Fire block callback if registered. + if c.blockCallback != nil { + aliasName := "" + if alias := ExtractAliasFromExtra(blk.MinerTx.Extra); alias != nil { + aliasName = alias.Name + } + c.blockCallback(height, blockHash.String(), aliasName) + } + + return nil } // indexOutputs adds each output of a transaction to the global output index.