github.com/koko1123/flow-go-1@v0.29.6/storage/badger/cluster_blocks.go (about) 1 package badger 2 3 import ( 4 "fmt" 5 6 "github.com/dgraph-io/badger/v3" 7 8 "github.com/koko1123/flow-go-1/model/cluster" 9 "github.com/koko1123/flow-go-1/model/flow" 10 "github.com/koko1123/flow-go-1/storage/badger/operation" 11 "github.com/koko1123/flow-go-1/storage/badger/transaction" 12 ) 13 14 // ClusterBlocks implements a simple block storage around a badger DB. 15 type ClusterBlocks struct { 16 db *badger.DB 17 chainID flow.ChainID 18 headers *Headers 19 payloads *ClusterPayloads 20 } 21 22 func NewClusterBlocks(db *badger.DB, chainID flow.ChainID, headers *Headers, payloads *ClusterPayloads) *ClusterBlocks { 23 b := &ClusterBlocks{ 24 db: db, 25 chainID: chainID, 26 headers: headers, 27 payloads: payloads, 28 } 29 return b 30 } 31 32 func (b *ClusterBlocks) Store(block *cluster.Block) error { 33 return operation.RetryOnConflictTx(b.db, transaction.Update, b.storeTx(block)) 34 } 35 36 func (b *ClusterBlocks) storeTx(block *cluster.Block) func(*transaction.Tx) error { 37 return func(tx *transaction.Tx) error { 38 err := b.headers.storeTx(block.Header)(tx) 39 if err != nil { 40 return fmt.Errorf("could not store header: %w", err) 41 } 42 err = b.payloads.storeTx(block.ID(), block.Payload)(tx) 43 if err != nil { 44 return fmt.Errorf("could not store payload: %w", err) 45 } 46 return nil 47 } 48 } 49 50 func (b *ClusterBlocks) ByID(blockID flow.Identifier) (*cluster.Block, error) { 51 header, err := b.headers.ByBlockID(blockID) 52 if err != nil { 53 return nil, fmt.Errorf("could not get header: %w", err) 54 } 55 payload, err := b.payloads.ByBlockID(blockID) 56 if err != nil { 57 return nil, fmt.Errorf("could not retrieve payload: %w", err) 58 } 59 block := cluster.Block{ 60 Header: header, 61 Payload: payload, 62 } 63 return &block, nil 64 } 65 66 func (b *ClusterBlocks) ByHeight(height uint64) (*cluster.Block, error) { 67 var blockID flow.Identifier 68 err := b.db.View(operation.LookupClusterBlockHeight(b.chainID, height, &blockID)) 69 if err != nil { 70 return nil, fmt.Errorf("could not look up block: %w", err) 71 } 72 return b.ByID(blockID) 73 }