/
checkpoint.go
259 lines (236 loc) · 7.03 KB
/
checkpoint.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
package consensus
import (
"encoding/binary"
"fmt"
"github.com/coschain/contentos-go/common"
"github.com/coschain/contentos-go/common/constants"
"github.com/coschain/contentos-go/db/storage"
"github.com/coschain/gobft/message"
)
/***************************
validators:
if reach consensus:
add checkPoint
if do commit success:
flush checkPoint
else if committing a missing block:
do sync
recv message.Commit:
if not committed already:
pass message.Commit to gobft
non-validators:
recv message.Commit:
if not committed already && num within range:
add checkPoint
if lib num == (message.Commit).LastCommitted:
if validate(message.Commit)==true:
if has the block about to be committed:
if do commit success:
flush checkPoint
commit later blocks if possible
else:
do sync
else:
remove checkPoint
push block b:
if b.id == next_checkPoint.id:
if do commit success:
flush checkPoint
***************************/
// BFTCheckPoint maintains the bft consensus evidence, the votes collected
// for the same checkpoint in different validators might differ. But all
// nodes including validators should have the same number of checkpoints with
// exact same order.
// all methods have time complexity of O(1)
type BFTCheckPoint struct {
sabft *SABFT
dataDir string
db storage.Database
lastCommitted common.BlockID
nextCP common.BlockID
cache map[common.BlockID]*message.Commit // lastCommitted-->Commit
indexPrefix [8]byte
}
func NewBFTCheckPoint(dir string, sabft *SABFT) *BFTCheckPoint {
db, err := storage.NewLevelDatabase(dir)
if err != nil {
panic(err)
}
lc := sabft.ForkDB.LastCommitted()
return &BFTCheckPoint{
sabft: sabft,
dataDir: dir,
db: db,
lastCommitted: lc,
nextCP: common.EmptyBlockID,
cache: make(map[common.BlockID]*message.Commit),
indexPrefix: [8]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff},
}
}
func (cp *BFTCheckPoint) Close() {
cp.db.Close()
}
func (cp *BFTCheckPoint) getIdxKey(idx uint64) []byte {
idxKey := make([]byte, 16)
copy(idxKey, cp.indexPrefix[:])
binary.BigEndian.PutUint64(idxKey[8:], idx)
return idxKey
}
func (cp *BFTCheckPoint) Flush(bid common.BlockID) error {
key := make([]byte, 8)
for {
binary.BigEndian.PutUint64(key, cp.nextCP.BlockNum())
batch := cp.db.NewBatch()
err := batch.Put(key, cp.cache[cp.lastCommitted].Bytes())
if err != nil {
cp.sabft.log.Fatalf("BFT-Flush: %v",err)
return err
}
if cp.cache[cp.lastCommitted] == nil {
errstr := fmt.Sprintf("*********** %s lc %v/ cp lc %v nextCP %v",
cp.sabft.Name, cp.sabft.ForkDB.LastCommitted(), cp.lastCommitted, cp.nextCP)
panic(errstr)
}
err = batch.Put(cp.getIdxKey(uint64(cp.cache[cp.lastCommitted].Height())), key)
if err != nil {
cp.sabft.log.Fatalf("BFT-Flush: %v",err)
return err
}
if err = batch.Write(); err != nil {
panic(fmt.Sprintf("BFT-Flush error: %v", err) )
}
delete(cp.cache, cp.lastCommitted)
cp.lastCommitted = cp.nextCP
cp.sabft.log.Info("checkpoint flushed at block height ", cp.nextCP.BlockNum())
cp.nextCP = common.EmptyBlockID
if v, ok := cp.cache[cp.lastCommitted]; ok {
cp.nextCP = ConvertToBlockID(v.ProposedData)
}
if cp.lastCommitted == bid {
// TODO: purge garbage Commit in cache
return nil
}
if cp.nextCP == common.EmptyBlockID {
break
}
}
cp.sabft.log.Warnf("checkpoint flushing interrupted after block height %d, meant to flush to %d",
cp.lastCommitted.BlockNum(), bid.BlockNum())
return nil
}
func (cp *BFTCheckPoint) Add(commit *message.Commit) error {
if err := commit.ValidateBasic(); err != nil {
cp.sabft.log.Error(err)
return ErrInvalidCheckPoint
}
blockID := ExtractBlockID(commit)
blockNum := blockID.BlockNum()
libNum := cp.lastCommitted.BlockNum()
if blockNum > libNum+constants.MaxUncommittedBlockNum ||
blockNum <= libNum {
cp.sabft.log.Errorf("last commit: %d, commit num: %d, err: %s",
libNum, blockNum, ErrCheckPointOutOfRange.Error())
return ErrCheckPointOutOfRange
}
prev := ConvertToBlockID(commit.Prev)
if _, ok := cp.cache[prev]; ok {
return ErrCheckPointExists
}
cp.cache[prev] = commit // prev could be malformed
if cp.lastCommitted == prev {
cp.nextCP = blockID
}
cp.sabft.log.Infof("CheckPoint added %v %d, prev = %v, lib = %d",
blockID, blockID.BlockNum(), commit.Prev, cp.sabft.ForkDB.LastCommitted().BlockNum())
return nil
}
func (cp *BFTCheckPoint) Remove(commit *message.Commit) {
if cp.lastCommitted != ConvertToBlockID(commit.Prev) {
panic("removing a invalid checkpoint")
}
delete(cp.cache, cp.lastCommitted)
cp.nextCP = common.EmptyBlockID
}
func (cp *BFTCheckPoint) HasDanglingCheckPoint() bool {
return cp.NextUncommitted() == nil && len(cp.cache) > 0
}
// (from, to)
// @from is the last committed checkpoint
// @to is any of the dangling uncommitted checkpoints
// Only call it if HasDanglingCheckPoint returns true
func (cp *BFTCheckPoint) MissingRange() (from, to uint64) {
var v *message.Commit
for _, v = range cp.cache {
break
}
return cp.lastCommitted.BlockNum(), ExtractBlockID(v).BlockNum()
}
func (cp *BFTCheckPoint) NextUncommitted() *message.Commit {
if v, ok := cp.cache[cp.lastCommitted]; ok {
return v
}
return nil
}
func (cp *BFTCheckPoint) RemoveNextUncommitted() {
delete(cp.cache, cp.lastCommitted)
cp.nextCP = common.EmptyBlockID
}
func (cp *BFTCheckPoint) IsNextCheckPoint(commit *message.Commit) bool {
id := ExtractBlockID(commit)
if id == common.EmptyBlockID {
cp.sabft.log.Fatal("checkpoint on an empty block")
return false
}
cp.sabft.log.Warn("cp.nextCP: ", cp.nextCP.BlockNum(), " commit number: ", id.BlockNum())
_, ok := cp.cache[cp.lastCommitted]
if !ok {
cp.sabft.log.Warn("cp not in cache, cp.lastCommitted: ", cp.lastCommitted.BlockNum(), " commit: ", commit)
return false
}
return cp.nextCP == id // && ConvertToBlockID(v.Prev) == cp.lastCommitted
}
func (cp *BFTCheckPoint) Validate(commit *message.Commit) bool {
if !cp.sabft.verifyCommitSig(commit) {
return false
}
return true
}
func (cp *BFTCheckPoint) GetNext(blockNum uint64) (*message.Commit, error) {
key := make([]byte, 8)
binary.BigEndian.PutUint64(key, blockNum+1)
var val []byte
cp.db.Iterate(key, cp.indexPrefix[:], false, func(key, value []byte) bool {
val = common.CopyBytes(value)
return false
})
if len(val) == 0 {
return nil, fmt.Errorf("BFTCheckPoint.GetNext(%d) not found", blockNum)
}
commit, err := message.DecodeConsensusMsg(val)
if err != nil {
return nil, err
}
if err = commit.(*message.Commit).ValidateBasic(); err != nil {
cp.sabft.log.Error(err)
return nil, err
}
return commit.(*message.Commit), nil
}
func (cp *BFTCheckPoint) GetIth(i uint64) (*message.Commit, error) {
idxKey := cp.getIdxKey(i)
blockNum, err := cp.db.Get(idxKey)
if err != nil {
cp.sabft.log.Error(err)
return nil, err
}
c, err := cp.db.Get(blockNum)
if err != nil {
cp.sabft.log.Error(err)
return nil, err
}
commit, err := message.DecodeConsensusMsg(c)
if err != nil {
return nil, err
}
return commit.(*message.Commit), nil
}