-
Notifications
You must be signed in to change notification settings - Fork 178
/
reader.go
54 lines (45 loc) · 1.54 KB
/
reader.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
package blockconsumer
import (
"fmt"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/storage"
)
// FinalizedBlockReader provides an abstraction for consumers to read blocks as job.
type FinalizedBlockReader struct {
state protocol.State
blocks storage.Blocks
}
// NewFinalizedBlockReader creates and returns a FinalizedBlockReader.
func NewFinalizedBlockReader(state protocol.State, blocks storage.Blocks) *FinalizedBlockReader {
return &FinalizedBlockReader{
state: state,
blocks: blocks,
}
}
// AtIndex returns the block job at the given index.
// The block job at an index is just the finalized block at that index (i.e., height).
func (r FinalizedBlockReader) AtIndex(index uint64) (module.Job, error) {
block, err := r.blockByHeight(index)
if err != nil {
return nil, fmt.Errorf("could not get block by index %v: %w", index, err)
}
return BlockToJob(block), nil
}
// blockByHeight returns the block at the given height.
func (r FinalizedBlockReader) blockByHeight(height uint64) (*flow.Block, error) {
block, err := r.blocks.ByHeight(height)
if err != nil {
return nil, fmt.Errorf("could not get block by height %d: %w", height, err)
}
return block, nil
}
// Head returns the last finalized height as job index.
func (r FinalizedBlockReader) Head() (uint64, error) {
header, err := r.state.Final().Head()
if err != nil {
return 0, fmt.Errorf("could not get header of last finalized block: %w", err)
}
return header.Height, nil
}