/
block_finalisation.go
282 lines (225 loc) · 7.57 KB
/
block_finalisation.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Copyright 2021 ChainSafe Systems (ON)
// SPDX-License-Identifier: LGPL-3.0-only
package state
import (
"encoding/binary"
"errors"
"fmt"
"github.com/ChainSafe/gossamer/dot/telemetry"
"github.com/ChainSafe/gossamer/dot/types"
"github.com/ChainSafe/gossamer/lib/common"
)
var errSetIDLowerThanHighest = errors.New("set id lower than highest")
var highestRoundAndSetIDKey = []byte("hrs")
// finalisedHashKey = FinalizedBlockHashKey + round + setID (LE encoded)
func finalisedHashKey(round, setID uint64) []byte {
return append(common.FinalizedBlockHashKey, roundAndSetIDToBytes(round, setID)...)
}
// HasFinalisedBlock returns true if there is a finalised block for a given round and setID, false otherwise
func (bs *BlockState) HasFinalisedBlock(round, setID uint64) (bool, error) {
return bs.db.Has(finalisedHashKey(round, setID))
}
// NumberIsFinalised checks if a block number is finalised or not
func (bs *BlockState) NumberIsFinalised(num uint) (bool, error) {
header, err := bs.GetHighestFinalisedHeader()
if err != nil {
return false, err
}
return num <= header.Number, nil
}
// GetFinalisedHeader returns the finalised block header by round and setID
func (bs *BlockState) GetFinalisedHeader(round, setID uint64) (*types.Header, error) {
bs.lock.Lock()
defer bs.lock.Unlock()
h, err := bs.GetFinalisedHash(round, setID)
if err != nil {
return nil, err
}
header, err := bs.GetHeader(h)
if err != nil {
return nil, err
}
return header, nil
}
// GetFinalisedHash gets the finalised block header by round and setID
func (bs *BlockState) GetFinalisedHash(round, setID uint64) (common.Hash, error) {
h, err := bs.db.Get(finalisedHashKey(round, setID))
if err != nil {
return common.Hash{}, err
}
return common.NewHash(h), nil
}
func (bs *BlockState) setHighestRoundAndSetID(round, setID uint64) error {
_, highestSetID, err := bs.GetHighestRoundAndSetID()
if err != nil {
return err
}
if setID < highestSetID {
return fmt.Errorf("%w: %d should be greater or equal %d", errSetIDLowerThanHighest, setID, highestSetID)
}
return bs.db.Put(highestRoundAndSetIDKey, roundAndSetIDToBytes(round, setID))
}
// GetHighestRoundAndSetID gets the highest round and setID that have been finalised
func (bs *BlockState) GetHighestRoundAndSetID() (uint64, uint64, error) {
b, err := bs.db.Get(highestRoundAndSetIDKey)
if err != nil {
return 0, 0, fmt.Errorf("failed to get highest round and setID: %w", err)
}
round := binary.LittleEndian.Uint64(b[:8])
setID := binary.LittleEndian.Uint64(b[8:16])
return round, setID, nil
}
// GetHighestFinalisedHash returns the highest finalised block hash
func (bs *BlockState) GetHighestFinalisedHash() (common.Hash, error) {
round, setID, err := bs.GetHighestRoundAndSetID()
if err != nil {
return common.Hash{}, err
}
return bs.GetFinalisedHash(round, setID)
}
// GetHighestFinalisedHeader returns the highest finalised block header
func (bs *BlockState) GetHighestFinalisedHeader() (*types.Header, error) {
h, err := bs.GetHighestFinalisedHash()
if err != nil {
return nil, err
}
header, err := bs.GetHeader(h)
if err != nil {
return nil, err
}
return header, nil
}
// SetFinalisedHash sets the latest finalised block hash
func (bs *BlockState) SetFinalisedHash(hash common.Hash, round, setID uint64) error {
bs.lock.Lock()
defer bs.lock.Unlock()
has, err := bs.HasHeader(hash)
if err != nil {
return fmt.Errorf("could not check header for hash %s: %w", hash, err)
}
if !has {
return fmt.Errorf("cannot finalise unknown block %s", hash)
}
if err := bs.handleFinalisedBlock(hash); err != nil {
return fmt.Errorf("failed to set finalised subchain in db on finalisation: %w", err)
}
if err := bs.db.Put(finalisedHashKey(round, setID), hash[:]); err != nil {
return fmt.Errorf("failed to set finalised hash key: %w", err)
}
if err := bs.setHighestRoundAndSetID(round, setID); err != nil {
return fmt.Errorf("failed to set highest round and set ID: %w", err)
}
if round > 0 {
bs.notifyFinalized(hash, round, setID)
}
pruned := bs.bt.Prune(hash)
for _, hash := range pruned {
blockHeader := bs.unfinalisedBlocks.delete(hash)
if blockHeader == nil {
continue
}
bs.tries.delete(blockHeader.StateRoot)
logger.Tracef("pruned block number %d with hash %s", blockHeader.Number, hash)
}
// if nothing was previously finalised, set the first slot of the network to the
// slot number of block 1, which is now being set as final
if bs.lastFinalised == bs.genesisHash && hash != bs.genesisHash {
if err := bs.setFirstSlotOnFinalisation(); err != nil {
return fmt.Errorf("failed to set first slot on finalisation: %w", err)
}
}
header, err := bs.GetHeader(hash)
if err != nil {
return fmt.Errorf("failed to get finalised header, hash: %s, error: %s", hash, err)
}
bs.telemetry.SendMessage(
telemetry.NewNotifyFinalized(
header.Hash(),
fmt.Sprint(header.Number),
),
)
if bs.lastFinalised != hash {
err := bs.deleteFromTries(bs.lastFinalised)
if err != nil {
logger.Debugf("%v", err)
}
}
bs.lastFinalised = hash
logger.Infof(
"🔨 finalised block #%d (%s), round %d, set id %d", header.Number, hash, round, setID)
return nil
}
func (bs *BlockState) deleteFromTries(lastFinalised common.Hash) error {
lastFinalisedHeader, err := bs.GetHeader(lastFinalised)
if err != nil {
return fmt.Errorf("unable to retrieve header for last finalised block, hash: %s, err: %s", bs.lastFinalised, err)
}
stateRootTrie := bs.tries.get(lastFinalisedHeader.StateRoot)
if stateRootTrie != nil {
bs.tries.delete(lastFinalisedHeader.StateRoot)
} else {
return fmt.Errorf("unable to find trie with stateroot hash: %s", lastFinalisedHeader.StateRoot)
}
return nil
}
func (bs *BlockState) handleFinalisedBlock(currentFinalizedHash common.Hash) error {
if currentFinalizedHash == bs.lastFinalised {
return nil
}
subchain, err := bs.RangeInMemory(bs.lastFinalised, currentFinalizedHash)
if err != nil {
return err
}
batch := bs.db.NewBatch()
subchainExcludingLatestFinalized := subchain[1:]
// root of subchain is previously finalised block, which has already been stored in the db
for _, subchainHash := range subchainExcludingLatestFinalized {
if subchainHash == bs.genesisHash {
continue
}
block := bs.unfinalisedBlocks.getBlock(subchainHash)
if block == nil {
return fmt.Errorf("failed to find block in unfinalised block map, block=%s", subchainHash)
}
if err = bs.SetHeader(&block.Header); err != nil {
return err
}
if err = bs.SetBlockBody(subchainHash, &block.Body); err != nil {
return err
}
arrivalTime, err := bs.bt.GetArrivalTime(subchainHash)
if err != nil {
return err
}
if err = bs.setArrivalTime(subchainHash, arrivalTime); err != nil {
return err
}
if err = batch.Put(headerHashKey(uint64(block.Header.Number)), subchainHash.ToBytes()); err != nil {
return err
}
// delete from the unfinalisedBlockMap and delete reference to in-memory trie
blockHeader := bs.unfinalisedBlocks.delete(subchainHash)
if blockHeader == nil {
continue
}
// prune all the subchain hashes state tries from memory
// but keep the state trie from the current finalized block
if currentFinalizedHash != subchainHash {
bs.tries.delete(blockHeader.StateRoot)
}
logger.Tracef("cleaned out finalised block from memory; block number %d with hash %s",
blockHeader.Number, subchainHash)
}
return batch.Flush()
}
func (bs *BlockState) setFirstSlotOnFinalisation() error {
header, err := bs.GetHeaderByNumber(1)
if err != nil {
return err
}
slot, err := types.GetSlotFromHeader(header)
if err != nil {
return err
}
return bs.baseState.storeFirstSlot(slot)
}