forked from cometbft/cometbft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblock_meta.go
78 lines (65 loc) · 1.63 KB
/
block_meta.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
73
74
75
76
77
78
package types
import (
"bytes"
"errors"
"fmt"
cmtproto "github.com/cometbft/cometbft/api/cometbft/types/v1"
)
// BlockMeta contains meta information.
type BlockMeta struct {
BlockID BlockID `json:"block_id"`
BlockSize int `json:"block_size"`
Header Header `json:"header"`
NumTxs int `json:"num_txs"`
}
// NewBlockMeta returns a new BlockMeta.
func NewBlockMeta(block *Block, blockParts *PartSet) *BlockMeta {
return &BlockMeta{
BlockID: BlockID{block.Hash(), blockParts.Header()},
BlockSize: block.Size(),
Header: block.Header,
NumTxs: len(block.Data.Txs),
}
}
func (bm *BlockMeta) ToProto() *cmtproto.BlockMeta {
if bm == nil {
return nil
}
pb := &cmtproto.BlockMeta{
BlockID: bm.BlockID.ToProto(),
BlockSize: int64(bm.BlockSize),
Header: *bm.Header.ToProto(),
NumTxs: int64(bm.NumTxs),
}
return pb
}
func BlockMetaFromTrustedProto(pb *cmtproto.BlockMeta) (*BlockMeta, error) {
if pb == nil {
return nil, errors.New("blockmeta is empty")
}
bm := new(BlockMeta)
bi, err := BlockIDFromProto(&pb.BlockID)
if err != nil {
return nil, err
}
h, err := HeaderFromProto(&pb.Header)
if err != nil {
return nil, err
}
bm.BlockID = *bi
bm.BlockSize = int(pb.BlockSize)
bm.Header = h
bm.NumTxs = int(pb.NumTxs)
return bm, nil
}
// ValidateBasic performs basic validation.
func (bm *BlockMeta) ValidateBasic() error {
if err := bm.BlockID.ValidateBasic(); err != nil {
return err
}
if !bytes.Equal(bm.BlockID.Hash, bm.Header.Hash()) {
return fmt.Errorf("expected BlockID#Hash and Header#Hash to be the same, got %X != %X",
bm.BlockID.Hash, bm.Header.Hash())
}
return nil
}