@@ -42,17 +42,22 @@ type LndRpcChainBridge struct {
4242
4343 // assetStore is a handle to the asset store.
4444 assetStore * tapdb.AssetStore
45+
46+ // headerCache is a cache for block headers to reduce RPC calls.
47+ headerCache * BlockHeaderCache
4548}
4649
4750// NewLndRpcChainBridge creates a new chain bridge from an active lnd services
4851// client.
4952func NewLndRpcChainBridge (lnd * lndclient.LndServices ,
50- assetStore * tapdb.AssetStore ) * LndRpcChainBridge {
53+ assetStore * tapdb.AssetStore ,
54+ headerCache * BlockHeaderCache ) * LndRpcChainBridge {
5155
5256 return & LndRpcChainBridge {
5357 lnd : lnd ,
5458 retryConfig : fn .DefaultRetryConfig (),
5559 assetStore : assetStore ,
60+ headerCache : headerCache ,
5661 }
5762}
5863
@@ -118,6 +123,11 @@ func (l *LndRpcChainBridge) GetBlock(ctx context.Context,
118123func (l * LndRpcChainBridge ) GetBlockHeader (ctx context.Context ,
119124 hash chainhash.Hash ) (* wire.BlockHeader , error ) {
120125
126+ // First, check the cache for the requested block header.
127+ if header , ok := l .headerCache .GetByHash (hash ); ok {
128+ return & header , nil
129+ }
130+
121131 return fn .RetryFuncN (
122132 ctx , l .retryConfig , func () (* wire.BlockHeader , error ) {
123133 header , err := l .lnd .ChainKit .GetBlockHeader (ctx , hash )
@@ -136,6 +146,14 @@ func (l *LndRpcChainBridge) GetBlockHeader(ctx context.Context,
136146func (l * LndRpcChainBridge ) GetBlockHeaderByHeight (ctx context.Context ,
137147 blockHeight int64 ) (* wire.BlockHeader , error ) {
138148
149+ // Convert to uint32 for cache operations.
150+ height := uint32 (blockHeight )
151+
152+ // First, check the cache for the requested block header by height.
153+ if header , ok := l .headerCache .GetByHeight (height ); ok {
154+ return & header , nil
155+ }
156+
139157 // First, we need to resolve the block hash at the given height.
140158 blockHash , err := fn .RetryFuncN (
141159 ctx , l .retryConfig , func () (chainhash.Hash , error ) {
@@ -171,6 +189,13 @@ func (l *LndRpcChainBridge) GetBlockHeaderByHeight(ctx context.Context,
171189 )
172190 }
173191
192+ // Store the retrieved header in the cache.
193+ err = l .headerCache .Put (height , * header )
194+ if err != nil {
195+ return nil , fmt .Errorf ("failed to cache block " +
196+ "header: %w" , err )
197+ }
198+
174199 return header , nil
175200 },
176201 )
0 commit comments