-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathchain.go
More file actions
50 lines (43 loc) · 1.78 KB
/
chain.go
File metadata and controls
50 lines (43 loc) · 1.78 KB
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
package toolslib
import (
"github.com/deso-protocol/core/lib"
"github.com/dgraph-io/badger/v3"
"github.com/pkg/errors"
)
// Returns the badgerDB handler associated with a dataDir path.
func OpenDataDir(dataDir string) (*badger.DB, error) {
dir := lib.GetBadgerDbPath(dataDir)
opts := lib.PerformanceBadgerOptions(dir)
opts.ValueDir = lib.GetBadgerDbPath(dataDir)
db, err := badger.Open(opts)
if err != nil {
return nil, errors.Wrap(err, "OpenBadgerDB() failed to open badger")
}
return db, nil
}
// TODO: This utility function needs to be updated to account for not having the entire chain in
// memory (no more BEST CHAIN representing the entire history of the blockchain).
// Returns the best chain associated with a badgerDB handle.
func GetBestChainFromBadger(syncedDBHandle *badger.DB, params *lib.DeSoParams) ([]*lib.BlockNode, error) {
bestBlockHash := lib.DbGetBestHash(syncedDBHandle, nil, lib.ChainTypeDeSoBlock)
if bestBlockHash == nil {
return nil, errors.Errorf("GetBestChainFromBadger() could not find a blockchain in the provided db")
}
// Fetch the block index.
blockIndex, err := lib.GetBlockIndex(syncedDBHandle, false /*bitcoinNodes*/, params)
if err != nil {
return nil, errors.Errorf("GetBestChainFromBadger() could not get blockIndex")
}
// Find the tip node with the best node hash.
tipNode, _ := blockIndex.Get(*bestBlockHash)
if tipNode == nil {
return nil, errors.Errorf("GetBestChainFromBadger() bestBlockHash not found in blockIndex")
}
// Walk back from the best node to the genesis block and store them all in bestChain.
bi := lib.NewBlockIndex(syncedDBHandle, nil, tipNode)
bestChain, err := lib.GetBestChain(tipNode, bi)
if err != nil {
return nil, errors.Wrap(err, "GetBestChainFromBadger() failed to GetBestChain")
}
return bestChain, nil
}