/
database.go
92 lines (79 loc) · 2.4 KB
/
database.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
// Copyright 2019 ChainSafe Systems (ON) Corp.
// This file is part of gossamer.
//
// The gossamer library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The gossamer library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the gossamer library. If not, see <http://www.gnu.org/licenses/>.
package trie
import (
"github.com/ChainSafe/gossamer/polkadb"
"sync"
)
// Database is a wrapper around a polkadb
type Database struct {
db polkadb.Database
batch polkadb.Batch
lock sync.RWMutex
hasher *Hasher
}
// WriteToDB writes the trie to the underlying database batch writer
// Stores the merkle value of the node as the key and the encoded node as the value
// This does not actually write to the db, just to the batch writer
// Commit must be called afterwards to finish writing to the db
func (t *Trie) WriteToDB() error {
t.db.batch = t.db.db.NewBatch()
return t.writeToDB(t.root)
}
// writeToDB recursively attempts to write each node in the trie to the db batch writer
func (t *Trie) writeToDB(n node) error {
_, err := t.writeNodeToDB(n)
if err != nil {
return err
}
switch n := n.(type) {
case *branch:
for _, child := range n.children {
if child != nil {
err = t.writeToDB(child)
if err != nil {
return err
}
}
}
}
return nil
}
// writeNodeToDB returns true if node is written to db batch writer, false otherwise
// if node is clean, it will not attempt to be written to the db
// otherwise if it's dirty, try to write it to db
func (t *Trie) writeNodeToDB(n node) (bool, error) {
if !n.isDirty() {
return false, nil
}
encRoot, err := Encode(n)
if err != nil {
return false, err
}
hash, err := t.db.hasher.Hash(n)
if err != nil {
return false, err
}
t.db.lock.Lock()
err = t.db.batch.Put(hash, encRoot)
t.db.lock.Unlock()
n.setDirty(false)
return true, err
}
// Commit writes the contents of the db's batch writer to the db
func (t *Trie) Commit() error {
return t.db.batch.Write()
}