-
Notifications
You must be signed in to change notification settings - Fork 2
/
chain.go
47 lines (40 loc) · 1.52 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
package toolslib
import (
"github.com/deso-smart/deso-core/v3/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
}
// Returns the best chain associated with a badgerDB handle.
func GetBestChainFromBadger(syncedDBHandle *badger.DB) ([]*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*/)
if err != nil {
return nil, errors.Errorf("GetBestChainFromBadger() could not get blockIndex")
}
// Find the tip node with the best node hash.
tipNode := blockIndex[*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.
bestChain, err := lib.GetBestChain(tipNode, blockIndex)
if err != nil {
return nil, errors.Wrap(err, "GetBestChainFromBadger() failed to GetBestChain")
}
return bestChain, nil
}