forked from Fantom-foundation/Substate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update_db.go
330 lines (280 loc) · 8.05 KB
/
update_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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
package substate
import (
"encoding/binary"
"fmt"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/rawdb"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/rlp"
)
type UpdateSetRLP struct {
SubstateAlloc SubstateAllocRLP
DeletedAccounts []common.Address
}
func NewUpdateSetRLP(updateset SubstateAlloc, deletedAccounts []common.Address) UpdateSetRLP {
var rlp UpdateSetRLP
rlp.SubstateAlloc = NewSubstateAllocRLP(updateset)
rlp.DeletedAccounts = deletedAccounts
return rlp
}
const (
SubstateAllocPrefix = "2s" // SubstateAllocPrefix + block (64-bit) + tx (64-bit) -> substateRLP
)
func SubstateAllocKey(block uint64) []byte {
prefix := []byte(SubstateAllocPrefix)
blockTx := make([]byte, 8)
binary.BigEndian.PutUint64(blockTx[0:8], block)
return append(prefix, blockTx...)
}
func DecodeUpdateSetKey(key []byte) (block uint64, err error) {
prefix := SubstateAllocPrefix
if len(key) != len(prefix)+8 {
err = fmt.Errorf("invalid length of updateset key: %v", len(key))
return
}
if p := string(key[:len(prefix)]); p != prefix {
err = fmt.Errorf("invalid prefix of updateset key: %#x", p)
return
}
blockTx := key[len(prefix):]
block = binary.BigEndian.Uint64(blockTx[0:8])
return
}
type UpdateDB struct {
backend BackendDatabase
}
func NewUpdateDB(backend BackendDatabase) *UpdateDB {
return &UpdateDB{backend: backend}
}
func OpenUpdateDB(updateSetDir string) (*UpdateDB, error) {
fmt.Println("substate: OpenUpdateSetDB")
backend, err := rawdb.NewLevelDBDatabase(updateSetDir, 1024, 100, "updatesetdir", false)
if err != nil {
return nil, fmt.Errorf("error opening update-set leveldb %s: %v", updateSetDir, err)
}
return NewUpdateDB(backend), nil
}
func OpenUpdateDBReadOnly(updateSetDir string) (*UpdateDB, error) {
fmt.Println("substate: OpenUpdateSetDB")
backend, err := rawdb.NewLevelDBDatabase(updateSetDir, 1024, 100, "updatesetdir", true)
if err != nil {
return nil, fmt.Errorf("error opening update-set leveldb %s: %v", updateSetDir, err)
}
return NewUpdateDB(backend), nil
}
func (db *UpdateDB) Compact(start []byte, limit []byte) error {
return db.backend.Compact(start, limit)
}
func (db *UpdateDB) Close() error {
return db.backend.Close()
}
// GetFirstKey returns the first block number in the update-set DB
func (db *UpdateDB) GetFirstKey() (uint64, error) {
iter := db.backend.NewIterator([]byte(SubstateAllocPrefix), nil)
defer iter.Release()
for iter.Next() {
firstBlock, err := DecodeUpdateSetKey(iter.Key())
if err != nil {
return 0, fmt.Errorf("cannot decode updateset key; %v", err)
}
return firstBlock, nil
}
return 0, fmt.Errorf("no updateset found")
}
// GetLastKey returns the last block number in the update-set DB
// if not found then returns 0
func (db *UpdateDB) GetLastKey() (uint64, error) {
var block uint64
var err error
iter := db.backend.NewIterator([]byte(SubstateAllocPrefix), nil)
for iter.Next() {
block, err = DecodeUpdateSetKey(iter.Key())
if err != nil {
return 0, fmt.Errorf("error iterating updateDB: %v", err)
}
}
iter.Release()
return block, nil
}
func (db *UpdateDB) HasCode(codeHash common.Hash) bool {
if codeHash == EmptyCodeHash {
return false
}
key := Stage1CodeKey(codeHash)
has, err := db.backend.Has(key)
if err != nil {
panic(fmt.Errorf("substate: error checking bytecode for codeHash %s: %v", codeHash.Hex(), err))
}
return has
}
func (db *UpdateDB) GetCode(codeHash common.Hash) []byte {
if codeHash == EmptyCodeHash {
return nil
}
key := Stage1CodeKey(codeHash)
code, err := db.backend.Get(key)
if err != nil {
panic(fmt.Errorf("substate: error getting code %s: %v", codeHash.Hex(), err))
}
return code
}
func (db *UpdateDB) PutCode(code []byte) {
if len(code) == 0 {
return
}
codeHash := crypto.Keccak256Hash(code)
key := Stage1CodeKey(codeHash)
err := db.backend.Put(key, code)
if err != nil {
panic(fmt.Errorf("substate: error putting code %s: %v", codeHash.Hex(), err))
}
}
func (db *UpdateDB) HasUpdateSet(block uint64) bool {
key := SubstateAllocKey(block)
has, _ := db.backend.Has(key)
return has
}
func (up *UpdateSetRLP) GetSubstateAlloc(db *UpdateDB) *SubstateAlloc {
alloc := make(SubstateAlloc)
for i, addr := range up.SubstateAlloc.Addresses {
var sa SubstateAccount
saRLP := up.SubstateAlloc.Accounts[i]
sa.Balance = saRLP.Balance
sa.Nonce = saRLP.Nonce
sa.Code = db.GetCode(saRLP.CodeHash)
sa.Storage = make(map[common.Hash]common.Hash)
for i := range saRLP.Storage {
sa.Storage[saRLP.Storage[i][0]] = saRLP.Storage[i][1]
}
alloc[addr] = &sa
}
return &alloc
}
func (db *UpdateDB) GetUpdateSet(block uint64) *SubstateAlloc {
var err error
key := SubstateAllocKey(block)
value, err := db.backend.Get(key)
if err != nil {
panic(fmt.Errorf("substate: error getting substate %v from substate DB: %v,", block, err))
}
// decode value
updateSetRLP := UpdateSetRLP{}
if err := rlp.DecodeBytes(value, &updateSetRLP); err != nil {
panic(fmt.Errorf("substate: failed to decode updateset value at block %v, key %v", block, key))
}
updateSet := updateSetRLP.GetSubstateAlloc(db)
return updateSet
}
func (db *UpdateDB) PutUpdateSet(block uint64, updateSet *SubstateAlloc, deletedAccounts []common.Address) {
var err error
// put deployed/creation code
for _, account := range *updateSet {
db.PutCode(account.Code)
}
key := SubstateAllocKey(block)
defer func() {
if err != nil {
panic(fmt.Errorf("substate: error putting update-set %v into substate DB: %v", block, err))
}
}()
updateSetRLP := NewUpdateSetRLP(*updateSet, deletedAccounts)
value, err := rlp.EncodeToBytes(updateSetRLP)
if err != nil {
panic(err)
}
err = db.backend.Put(key, value)
if err != nil {
panic(err)
}
}
func (db *UpdateDB) DeleteSubstateAlloc(block uint64) {
key := SubstateAllocKey(block)
err := db.backend.Delete(key)
if err != nil {
panic(err)
}
}
type UpdateBlock struct {
Block uint64
UpdateSet *SubstateAlloc
DeletedAccounts []common.Address
}
func parseUpdateSet(db *UpdateDB, data rawEntry) *UpdateBlock {
key := data.key
value := data.value
block, err := DecodeUpdateSetKey(data.key)
if err != nil {
panic(fmt.Errorf("substate: invalid update-set key found: %v - issue: %v", key, err))
}
updateSetRLP := UpdateSetRLP{}
rlp.DecodeBytes(value, &updateSetRLP)
updateSet := updateSetRLP.GetSubstateAlloc(db)
return &UpdateBlock{
Block: block,
UpdateSet: updateSet,
DeletedAccounts: updateSetRLP.DeletedAccounts,
}
}
type UpdateSetIterator struct {
db *UpdateDB
iter ethdb.Iterator
cur *UpdateBlock
// Connections to parsing pipeline
source <-chan *UpdateBlock
done chan<- int
}
func NewUpdateSetIterator(db *UpdateDB, startBlock, endBlock uint64) UpdateSetIterator {
start := BlockToBytes(startBlock)
// updateset prefix is already in start
iter := db.backend.NewIterator([]byte(SubstateAllocPrefix), start)
done := make(chan int)
result := make(chan *UpdateBlock, 1)
go func() {
defer close(result)
for iter.Next() {
key := make([]byte, len(iter.Key()))
copy(key, iter.Key())
// Decode key, if past the end block, stop here.
// This avoids filling channels which huge data objects that are not consumed.
block, err := DecodeUpdateSetKey(key)
if err != nil {
panic(fmt.Errorf("worldstate-upate: invalid update-set key found: %v - issue: %v", key, err))
}
if block > endBlock {
return
}
value := make([]byte, len(iter.Value()))
copy(value, iter.Value())
raw := rawEntry{key, value}
select {
case <-done:
return
case result <- parseUpdateSet(db, raw): //fall-through
}
}
}()
return UpdateSetIterator{
db: db,
iter: iter,
source: result,
done: done,
}
}
func (i *UpdateSetIterator) Release() {
close(i.done)
// drain pipeline until the result channel is closed
for open := true; open; _, open = <-i.source {
}
i.iter.Release()
}
func (i *UpdateSetIterator) Next() bool {
if i.iter == nil {
return false
}
i.cur = <-i.source
return i.cur != nil
}
func (i *UpdateSetIterator) Value() *UpdateBlock {
return i.cur
}