feat(chain): add BlockCallback fired after every block stored
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 <charon@lethean.io>
This commit is contained in:
parent
350ff6f4af
commit
8a4a9c0cb7
2 changed files with 26 additions and 2 deletions
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue