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