forked from bitmark-inc/bitmarkd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.go
206 lines (168 loc) · 4.78 KB
/
setup.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// Copyright (c) 2014-2016 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package storage
import (
"bytes"
"fmt"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/util"
"reflect"
"sync"
)
// a binary data item
type Element struct {
Key []byte
Value []byte
}
// a pool handle
type PoolHandle struct {
prefix byte
limit []byte
}
// exported storage pools
//
// note all must be exported (i.e. initial capital) or initialisation will panic
type pools struct {
Blocks *PoolHandle `prefix:"B"`
BlockOwners *PoolHandle `prefix:"F"`
Assets *PoolHandle `prefix:"A"`
Transactions *PoolHandle `prefix:"T"`
OwnerCount *PoolHandle `prefix:"N"`
Ownership *PoolHandle `prefix:"K"`
OwnerDigest *PoolHandle `prefix:"D"`
TestData *PoolHandle `prefix:"Z"`
}
// the instance
var Pool pools
// for database version
var versionKey = []byte{0x00, 'V', 'E', 'R', 'S', 'I', 'O', 'N'}
var currentVersion = []byte{0x00, 0x00, 0x00, 0x02}
// holds the database handle
var poolData struct {
sync.Mutex
database *leveldb.DB
}
// open up the database connection
//
// this must be called before any pool.New() is created
func Initialise(database string) error {
poolData.Lock()
defer poolData.Unlock()
if nil != poolData.database {
return fault.ErrAlreadyInitialised
}
db, err := leveldb.RecoverFile(database, nil)
// db, err := leveldb.OpenFile(database, nil)
fault.PanicIfError("pool.Initialise", err)
poolData.database = db
// ensure that the database is compatible
versionValue, err := poolData.database.Get(versionKey, nil)
if leveldb.ErrNotFound == err {
err = poolData.database.Put(versionKey, currentVersion, nil)
if nil != err {
return err
}
} else if nil != err {
return err
} else if !bytes.Equal(versionValue, currentVersion) {
return fmt.Errorf("incompatible database version: expected: 0x%x actual: 0x%x", currentVersion, versionValue)
}
// this will be a struct type
poolType := reflect.TypeOf(Pool)
// get write acces by using pointer + Elem()
poolValue := reflect.ValueOf(&Pool).Elem()
// scan each field
for i := 0; i < poolType.NumField(); i += 1 {
fieldInfo := poolType.Field(i)
prefixTag := fieldInfo.Tag.Get("prefix")
if 1 != len(prefixTag) {
fault.Panicf("pool: %v has invalid prefix: %q", fieldInfo, prefixTag)
}
prefix := prefixTag[0]
limit := []byte(nil)
if prefix < 255 {
limit = []byte{prefix + 1}
}
p := &PoolHandle{
prefix: prefix,
limit: limit,
}
newPool := reflect.ValueOf(p)
poolValue.Field(i).Set(newPool)
}
return nil
}
// close the database connection
func Finalise() {
poolData.Lock()
defer poolData.Unlock()
// no need to stop if already stopped
if nil == poolData.database {
return
}
poolData.database.Close()
poolData.database = nil
return
}
// prepend the prefix onto the key
func (p *PoolHandle) prefixKey(key []byte) []byte {
prefixedKey := make([]byte, 1, len(key)+1)
prefixedKey[0] = p.prefix
return append(prefixedKey, key...)
}
// store a key/value bytes pair to the database
func (p *PoolHandle) Put(key []byte, value []byte) {
err := poolData.database.Put(p.prefixKey(key), value, nil)
fault.PanicIfError("pool.Add", err)
}
// remove a key from the database
func (p *PoolHandle) Delete(key []byte) {
err := poolData.database.Delete(p.prefixKey(key), nil)
fault.PanicIfError("pool.Remove", err)
}
// read a value for a given key
//
// this returns the actual element - copy the result if it must be preserved
func (p *PoolHandle) Get(key []byte) []byte {
value, err := poolData.database.Get(p.prefixKey(key), nil)
if leveldb.ErrNotFound == err {
return nil
}
fault.PanicIfError("pool.Get", err)
return value
}
// Check if a key exists
func (p *PoolHandle) Has(key []byte) bool {
value, err := poolData.database.Has(p.prefixKey(key), nil)
fault.PanicIfError("pool.Has", err)
return value
}
// get the last element in a pool
func (p *PoolHandle) LastElement() (Element, bool) {
maxRange := util.Range{
Start: []byte{p.prefix}, // Start of key range, included in the range
Limit: p.limit, // Limit of key range, excluded from the range
}
iter := poolData.database.NewIterator(&maxRange, nil)
found := false
result := Element{}
if iter.Last() {
// contents of the returned slice must not be modified, and are
// only valid until the next call to Next
key := iter.Key()
value := iter.Value()
dataKey := make([]byte, len(key)-1) // strip the prefix
copy(dataKey, key[1:]) // ...
dataValue := make([]byte, len(value))
copy(dataValue, value)
result.Key = dataKey
result.Value = dataValue
found = true
}
iter.Release()
err := iter.Error()
fault.PanicIfError("pool.LastElement", err)
return result, found
}