-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
294 lines (246 loc) · 6.21 KB
/
store.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package store
import (
"bytes"
"encoding/gob"
"errors"
"log"
"sync"
"github.com/paw-digital/nano/address"
"github.com/paw-digital/nano/blocks"
"github.com/paw-digital/nano/types"
"github.com/paw-digital/nano/uint128"
"github.com/dgraph-io/badger"
)
type Config struct {
Path string
GenesisBlock *blocks.OpenBlock
}
const (
MetaOpen byte = iota
MetaReceive
MetaSend
MetaChange
)
type BlockItem struct {
badger.Item
}
func (i *BlockItem) ToBlock() blocks.Block {
meta := i.UserMeta()
value, _ := i.ValueCopy(nil)
dec := gob.NewDecoder(bytes.NewBuffer(value))
var result blocks.Block
switch meta {
case MetaOpen:
var b blocks.OpenBlock
dec.Decode(&b)
result = &b
case MetaReceive:
var b blocks.ReceiveBlock
dec.Decode(&b)
result = &b
case MetaSend:
var b blocks.SendBlock
dec.Decode(&b)
result = &b
case MetaChange:
var b blocks.ChangeBlock
dec.Decode(&b)
result = &b
}
return result
}
var LiveConfig = Config{
"DATA",
blocks.LiveGenesisBlock,
}
var TestConfig = Config{
"TESTDATA",
blocks.TestGenesisBlock,
}
var TestConfigLive = Config{
"TESTDATA",
blocks.LiveGenesisBlock,
}
// Blocks that we cannot store due to not having their parent
// block stored
var unconnectedBlockPool map[types.BlockHash]blocks.Block
var Conf *Config
var globalConn *badger.DB
var currentTxn *badger.Txn
var connLock sync.Mutex
func getConn() *badger.Txn {
connLock.Lock()
if currentTxn != nil {
return currentTxn
}
if globalConn == nil {
opts := badger.DefaultOptions(Conf.Path)
conn, err := badger.Open(opts)
if err != nil {
panic(err)
}
globalConn = conn
}
currentTxn = globalConn.NewTransaction(true)
return currentTxn
}
func releaseConn(conn *badger.Txn) {
currentTxn.Commit()
currentTxn = nil
connLock.Unlock()
}
func Init(config Config) {
var err error
unconnectedBlockPool = make(map[types.BlockHash]blocks.Block)
if globalConn != nil {
globalConn.Close()
globalConn = nil
}
Conf = &config
conn := getConn()
defer releaseConn(conn)
_, err = conn.Get(blocks.LiveGenesisBlockHash.ToBytes())
if err != nil {
uncheckedStoreBlock(conn, config.GenesisBlock)
}
}
func FetchOpen(account types.Account) (b *blocks.OpenBlock) {
conn := getConn()
defer releaseConn(conn)
return fetchOpen(conn, account)
}
func fetchOpen(conn *badger.Txn, account types.Account) (b *blocks.OpenBlock) {
account_bytes, err := address.AddressToPub(account)
if err != nil {
return nil
}
item, err := conn.Get(account_bytes)
if err != nil {
return nil
}
blockItem := BlockItem{*item}
return blockItem.ToBlock().(*blocks.OpenBlock)
}
func FetchBlock(hash types.BlockHash) (b blocks.Block) {
conn := getConn()
defer releaseConn(conn)
return fetchBlock(conn, hash)
}
func fetchBlock(conn *badger.Txn, hash types.BlockHash) (b blocks.Block) {
item, err := conn.Get(hash.ToBytes())
if err != nil {
return nil
}
blockItem := BlockItem{*item}
return blockItem.ToBlock()
}
func GetBalance(block blocks.Block) uint128.Uint128 {
conn := getConn()
defer releaseConn(conn)
return getBalance(conn, block)
}
func getSendAmount(conn *badger.Txn, block *blocks.SendBlock) uint128.Uint128 {
prev := fetchBlock(conn, block.PreviousHash)
return getBalance(conn, prev).Sub(getBalance(conn, block))
}
func getBalance(conn *badger.Txn, block blocks.Block) uint128.Uint128 {
switch block.Type() {
case blocks.Open:
b := block.(*blocks.OpenBlock)
if b.SourceHash == Conf.GenesisBlock.SourceHash {
return blocks.GenesisAmount
}
source := fetchBlock(conn, b.SourceHash).(*blocks.SendBlock)
return getSendAmount(conn, source)
case blocks.Send:
b := block.(*blocks.SendBlock)
return b.Balance
case blocks.Receive:
b := block.(*blocks.ReceiveBlock)
prev := fetchBlock(conn, b.PreviousHash)
source := fetchBlock(conn, b.SourceHash).(*blocks.SendBlock)
received := getSendAmount(conn, source)
return getBalance(conn, prev).Add(received)
case blocks.Change:
b := block.(*blocks.ChangeBlock)
return getBalance(conn, fetchBlock(conn, b.PreviousHash))
default:
panic("Unknown block type")
}
}
// Validate and store a block
// TODO: Validate signature and balance
func StoreBlock(block blocks.Block) error {
conn := getConn()
defer releaseConn(conn)
return storeBlock(conn, block)
}
func storeBlock(conn *badger.Txn, block blocks.Block) error {
if !blocks.ValidateBlockWork(block) {
return errors.New("Invalid work for block")
}
if block.Type() != blocks.Open && block.Type() != blocks.Change && block.Type() != blocks.Send && block.Type() != blocks.Receive {
return errors.New("Unknown block type")
}
if fetchBlock(conn, block.PreviousBlockHash()) == nil {
if unconnectedBlockPool[block.PreviousBlockHash()] == nil {
unconnectedBlockPool[block.PreviousBlockHash()] = block
log.Printf("Added block to unconnected pool, now %d", len(unconnectedBlockPool))
}
return errors.New("Cannot find parent block")
}
uncheckedStoreBlock(conn, block)
dependentBlock := unconnectedBlockPool[block.Hash()]
if dependentBlock != nil {
// We have an unconnected block dependent on this: Store it now that
// it's connected
delete(unconnectedBlockPool, block.Hash())
storeBlock(conn, dependentBlock)
}
return nil
}
// Store a block without checking whether it's valid
// The block should be pre-checked to ensure it has a valid signature,
// parent block, balance, etc.
func uncheckedStoreBlock(conn *badger.Txn, block blocks.Block) {
var buf bytes.Buffer
enc := gob.NewEncoder(&buf)
switch block.Type() {
case blocks.Open:
b := block.(*blocks.OpenBlock)
err := enc.Encode(b)
if err != nil {
panic(err)
}
// Open blocks need to be stored twice, once keyed on account,
// once keyed on hash.
err = conn.Set(b.RootHash().ToBytes(), buf.Bytes())
if err != nil {
panic(err)
}
case blocks.Send:
b := block.(*blocks.SendBlock)
err := enc.Encode(b)
if err != nil {
panic(err)
}
case blocks.Receive:
b := block.(*blocks.ReceiveBlock)
err := enc.Encode(b)
if err != nil {
panic(err)
}
case blocks.Change:
b := block.(*blocks.ChangeBlock)
err := enc.Encode(b)
if err != nil {
panic(err)
}
default:
panic("Unknown block type")
}
err := conn.Set(block.Hash().ToBytes(), buf.Bytes())
if err != nil {
panic("Failed to store block")
}
}