forked from kaspanet/kaspad
-
Notifications
You must be signed in to change notification settings - Fork 8
/
db.go
95 lines (75 loc) · 2.09 KB
/
db.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
package mine
import (
"path/filepath"
"github.com/Hoosat-Oy/HTND/domain/consensus/model/externalapi"
"github.com/Hoosat-Oy/HTND/infrastructure/db/database"
"github.com/Hoosat-Oy/HTND/infrastructure/db/database/ldb"
)
const leveldbCacheSizeMiB = 256
var blockIDToHashBucket = database.MakeBucket([]byte("id-to-block-hash"))
var lastMinedBlockKey = database.MakeBucket(nil).Key([]byte("last-sent-block"))
type miningDB struct {
idToBlockHash map[string]*externalapi.DomainHash
hashToBlockID map[externalapi.DomainHash]string
db *ldb.LevelDB
}
func (mdb *miningDB) hashByID(id string) *externalapi.DomainHash {
return mdb.idToBlockHash[id]
}
func (mdb *miningDB) putID(id string, hash *externalapi.DomainHash) error {
mdb.idToBlockHash[id] = hash
mdb.hashToBlockID[*hash] = id
return mdb.db.Put(blockIDToHashBucket.Key([]byte(id)), hash.ByteSlice())
}
func (mdb *miningDB) updateLastMinedBlock(id string) error {
return mdb.db.Put(lastMinedBlockKey, []byte(id))
}
func (mdb *miningDB) lastMinedBlock() (string, error) {
has, err := mdb.db.Has(lastMinedBlockKey)
if err != nil {
return "", err
}
if !has {
return "0", nil
}
blockID, err := mdb.db.Get(lastMinedBlockKey)
if err != nil {
return "", err
}
return string(blockID), nil
}
func newMiningDB(dataDir string) (*miningDB, error) {
idToBlockHash := make(map[string]*externalapi.DomainHash)
hashToBlockID := make(map[externalapi.DomainHash]string)
dbPath := filepath.Join(dataDir, "minedb")
db, err := ldb.NewLevelDB(dbPath, leveldbCacheSizeMiB)
if err != nil {
return nil, err
}
cursor, err := db.Cursor(blockIDToHashBucket)
if err != nil {
return nil, err
}
for cursor.Next() {
key, err := cursor.Key()
if err != nil {
return nil, err
}
value, err := cursor.Value()
if err != nil {
return nil, err
}
hash, err := externalapi.NewDomainHashFromByteSlice(value)
if err != nil {
return nil, err
}
id := string(key.Suffix())
idToBlockHash[id] = hash
hashToBlockID[*hash] = id
}
return &miningDB{
idToBlockHash: idToBlockHash,
hashToBlockID: hashToBlockID,
db: db,
}, nil
}