forked from Onyx-Protocol/Onyx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
recover.go
74 lines (67 loc) · 2.18 KB
/
recover.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
package protocol
import (
"context"
"fmt"
"chain/errors"
"chain/protocol/bc"
"chain/protocol/state"
"chain/protocol/validation"
)
// Recover performs crash recovery, restoring the blockchain
// to a complete state. It returns the latest confirmed block
// and the corresponding state snapshot.
//
// If the blockchain is empty (missing initial block), this function
// returns a nil block and an empty snapshot.
func (c *Chain) Recover(ctx context.Context) (*bc.Block, *state.Snapshot, error) {
snapshot, snapshotHeight, err := c.store.LatestSnapshot(ctx)
if err != nil {
return nil, nil, errors.Wrap(err, "getting latest snapshot")
}
var b *bc.Block
if snapshotHeight > 0 {
b, err = c.store.GetBlock(ctx, snapshotHeight)
if err != nil {
return nil, nil, errors.Wrap(err, "getting snapshot block")
}
c.lastQueuedSnapshot = b.Time()
}
if snapshot == nil {
snapshot = state.Empty()
}
// The true height of the blockchain might be higher than the
// height at which the state snapshot was taken. Replay all
// existing blocks higher than the snapshot height.
height, err := c.store.Height(ctx)
if err != nil {
return nil, nil, errors.Wrap(err, "getting blockchain height")
}
// Bring the snapshot up to date with the latest block
for h := snapshotHeight + 1; h <= height; h++ {
b, err = c.store.GetBlock(ctx, h)
if err != nil {
return nil, nil, errors.Wrap(err, "getting block")
}
err = validation.ApplyBlock(snapshot, b)
if err != nil {
return nil, nil, errors.Wrap(err, "applying block")
}
if b.AssetsMerkleRoot != snapshot.Tree.RootHash() {
return nil, nil, fmt.Errorf("block %d has state root %s; snapshot has root %s",
b.Height, b.AssetsMerkleRoot, snapshot.Tree.RootHash())
}
}
if b != nil {
// All blocks before the latest one have been fully processed
// (saved in the db, callbacks invoked). The last one may have
// been too, but make sure just in case. Also "finalize" the last
// block (notifying other processes of the latest block height)
// and maybe persist the snapshot.
err = c.CommitBlock(ctx, b, snapshot)
if err != nil {
return nil, nil, errors.Wrap(err, "committing block")
}
}
close(c.ready)
return b, snapshot, nil
}