-
Notifications
You must be signed in to change notification settings - Fork 0
/
chain.go
358 lines (304 loc) · 8.54 KB
/
chain.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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package blockchain
import (
"encoding/binary"
"fmt"
"sync"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/dnerochain/dnero/common"
"github.com/dnerochain/dnero/core"
"github.com/dnerochain/dnero/store"
)
const maxDistance = 2000
var logger *log.Entry = log.WithFields(log.Fields{"prefix": "blockchain"})
// Chain represents the blockchain and also is the interface to underlying store.
type Chain struct {
store store.Store
ChainID string
root common.Hash
mu *sync.RWMutex
}
// NewChain creates a new Chain instance.
func NewChain(chainID string, store store.Store, root *core.Block) *Chain {
chain := &Chain{
ChainID: chainID,
store: store,
mu: &sync.RWMutex{},
}
rootBlock, err := chain.FindBlock(root.Hash())
if err != nil {
logger.WithFields(log.Fields{"Hash": root.Hash().Hex()}).Info("Root block is not found in chain. Adding block.")
rootBlock, err = chain.AddSnapshotRoot(root)
if err != nil {
logger.Panic(err)
}
}
chain.FinalizePreviousBlocks(rootBlock.Hash())
chain.root = rootBlock.Hash()
return chain
}
// Root returns the root block
func (ch *Chain) Root() *core.ExtendedBlock {
ret, _ := ch.FindBlock(ch.root)
return ret
}
// AddSnapshotRoot adds the root block of the chain
func (ch *Chain) AddSnapshotRoot(block *core.Block) (*core.ExtendedBlock, error) {
return ch.addBlock(block, true)
}
// AddBlock adds a block to the chain and underlying store
func (ch *Chain) AddBlock(block *core.Block) (*core.ExtendedBlock, error) {
return ch.addBlock(block, false)
}
func (ch *Chain) addBlock(block *core.Block, isSnapshotRoot bool) (*core.ExtendedBlock, error) {
ch.mu.Lock()
defer ch.mu.Unlock()
if block.ChainID != ch.ChainID {
return nil, errors.Errorf("ChainID mismatch: block.ChainID(%s) != %s", block.ChainID, ch.ChainID)
}
val := &core.ExtendedBlock{}
hash := block.Hash()
err := ch.store.Get(hash[:], val)
if err == nil {
// Block has already been added.
return val, fmt.Errorf("Block has already been added: %X", hash[:])
}
// Update parent if present.
if !block.Parent.IsEmpty() && !isSnapshotRoot {
parentBlock, err := ch.findBlock(block.Parent)
if err == nil {
parentBlock.Children = append(parentBlock.Children, hash)
err = ch.saveBlock(parentBlock)
if err != nil {
log.Panic(err)
}
}
}
extendedBlock := &core.ExtendedBlock{Block: block}
// Update children if present.
children := ch.findBlocksByHeight(block.Height + 1)
extendedBlock.Children = []common.Hash{}
for i := 0; i < len(children); i++ {
if children[i].Parent != block.Hash() {
continue
}
extendedBlock.Children = append(extendedBlock.Children, children[i].Hash())
}
err = ch.saveBlock(extendedBlock)
if err != nil {
logger.Panic(err)
}
ch.AddBlockByHeightIndex(extendedBlock.Height, extendedBlock.Hash())
ch.AddTxsToIndex(extendedBlock, false)
return extendedBlock, nil
}
// FixBlockIndex fixes index for given block.
func (ch *Chain) FixBlockIndex(block *core.ExtendedBlock) {
ch.mu.Lock()
defer ch.mu.Unlock()
ch.AddBlockByHeightIndex(block.Height, block.Hash())
ch.AddTxsToIndex(block, false)
}
// FixMissingChildren removes dead links to missing children blocks.
func (ch *Chain) FixMissingChildren(block *core.ExtendedBlock) {
ch.mu.Lock()
defer ch.mu.Unlock()
newChildren := []common.Hash{}
for _, hash := range block.Children {
_, err := ch.findBlock(hash)
if err != nil {
logger.Warningf("Removing dead link from block $v to block %v", block.Hash().Hex(), hash.Hex())
} else {
newChildren = append(newChildren, hash)
}
}
block.Children = newChildren
err := ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
}
// blockByHeightIndexKey constructs the DB key for the given block height.
func blockByHeightIndexKey(height uint64) common.Bytes {
// convert uint64 to []byte
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutUvarint(buf, height)
b := buf[:n]
return append(common.Bytes("bh/"), b...)
}
type BlockByHeightIndexEntry struct {
Blocks []common.Hash
}
func (ch *Chain) AddBlockByHeightIndex(height uint64, block common.Hash) {
key := blockByHeightIndexKey(height)
blockByHeightIndexEntry := BlockByHeightIndexEntry{
Blocks: []common.Hash{},
}
ch.store.Get(key, &blockByHeightIndexEntry)
// Check if block has already been added to index.
for _, b := range blockByHeightIndexEntry.Blocks {
if block == b {
return
}
}
blockByHeightIndexEntry.Blocks = append(blockByHeightIndexEntry.Blocks, block)
err := ch.store.Put(key, blockByHeightIndexEntry)
if err != nil {
logger.Panic(err)
}
}
// FindBlocksByHeight tries to retrieve blocks by height.
func (ch *Chain) FindBlocksByHeight(height uint64) []*core.ExtendedBlock {
ch.mu.RLock()
defer ch.mu.RUnlock()
return ch.findBlocksByHeight(height)
}
// findBlocksByHeight is the non-locking version of FindBlockByHeight.
func (ch *Chain) findBlocksByHeight(height uint64) []*core.ExtendedBlock {
key := blockByHeightIndexKey(height)
blockByHeightIndexEntry := BlockByHeightIndexEntry{
Blocks: []common.Hash{},
}
ch.store.Get(key, &blockByHeightIndexEntry)
ret := []*core.ExtendedBlock{}
for _, hash := range blockByHeightIndexEntry.Blocks {
block, err := ch.findBlock(hash)
if err == nil {
ret = append(ret, block)
}
}
return ret
}
func (ch *Chain) MarkBlockValid(hash common.Hash) *core.ExtendedBlock {
ch.mu.Lock()
defer ch.mu.Unlock()
block, err := ch.findBlock(hash)
if err != nil {
logger.Panic(err)
}
block.Status = core.BlockStatusValid
err = ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
return block
}
func (ch *Chain) MarkBlockInvalid(hash common.Hash) *core.ExtendedBlock {
ch.mu.Lock()
defer ch.mu.Unlock()
block, err := ch.findBlock(hash)
if err != nil {
logger.Panic(err)
}
block.Status = core.BlockStatusInvalid
err = ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
return block
}
func (ch *Chain) MarkBlockHasValidatorUpdate(hash common.Hash) *core.ExtendedBlock {
ch.mu.Lock()
defer ch.mu.Unlock()
block, err := ch.findBlock(hash)
if err != nil {
logger.Panic(err)
}
block.HasValidatorUpdate = true
err = ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
return block
}
func (ch *Chain) CommitBlock(hash common.Hash) {
ch.mu.Lock()
defer ch.mu.Unlock()
block, err := ch.findBlock(hash)
if err != nil {
logger.Panic(err)
}
block.Status = core.BlockStatusCommitted
err = ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
}
func (ch *Chain) FinalizePreviousBlocks(hash common.Hash) error {
ch.mu.Lock()
defer ch.mu.Unlock()
status := core.BlockStatusDirectlyFinalized
for !hash.IsEmpty() {
block, err := ch.findBlock(hash)
if err != nil || block.Status.IsFinalized() {
return nil
}
if block.Status == core.BlockStatusDisposed {
return errors.New("Cannot finalize disposed branch")
}
block.Status = status
status = core.BlockStatusIndirectlyFinalized // Only the first block is marked as directly finalized
err = ch.saveBlock(block)
if err != nil {
logger.Panic(err)
}
hash = block.Parent
}
return nil
}
func (ch *Chain) IsOrphan(block *core.Block) bool {
_, err := ch.FindBlock(block.Parent)
return err != nil
}
// saveBlock updates a previously stored block.
func (ch *Chain) saveBlock(block *core.ExtendedBlock) error {
hash := block.Hash()
return ch.store.Put(hash[:], block)
}
func (ch *Chain) SaveBlock(block *core.ExtendedBlock) error {
return ch.saveBlock(block)
}
// FindBlock tries to retrieve a block by hash.
func (ch *Chain) FindBlock(hash common.Hash) (*core.ExtendedBlock, error) {
ch.mu.RLock()
defer ch.mu.RUnlock()
return ch.findBlock(hash)
}
// findBlock is the non-locking version of FindBlock.
func (ch *Chain) findBlock(hash common.Hash) (*core.ExtendedBlock, error) {
var block core.ExtendedBlock
err := ch.store.Get(hash[:], &block)
if err != nil {
return nil, err
}
return &block, nil
}
// IsDescendant determines whether one block is the ascendant of another block.
func (ch *Chain) IsDescendant(ascendantHash common.Hash, descendantHash common.Hash) bool {
hash := descendantHash
for i := 0; i < maxDistance; i++ {
if hash == ascendantHash {
return true
}
currBlock, err := ch.FindBlock(hash)
if err != nil {
return false
}
hash = currBlock.Parent
}
return false
}
// PrintBranch return the string describing path from root to given leaf.
func (ch *Chain) PrintBranch(hash common.Hash) string {
ret := []string{}
for {
var currBlock core.ExtendedBlock
err := ch.store.Get(hash[:], &currBlock)
if err != nil {
break
}
ret = append(ret, hash.String())
hash = currBlock.Parent
}
return fmt.Sprintf("%v", ret)
}