-
Notifications
You must be signed in to change notification settings - Fork 198
/
accountsDB.go
466 lines (384 loc) · 11.5 KB
/
accountsDB.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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
package state
import (
"bytes"
"errors"
"strconv"
"sync"
"github.com/ElrondNetwork/elrond-go/core/check"
"github.com/ElrondNetwork/elrond-go/data"
"github.com/ElrondNetwork/elrond-go/hashing"
"github.com/ElrondNetwork/elrond-go/marshal"
)
// AccountsDB is the struct used for accessing accounts
type AccountsDB struct {
mainTrie data.Trie
hasher hashing.Hasher
marshalizer marshal.Marshalizer
accountFactory AccountFactory
dataTries TriesHolder
entries []JournalEntry
mutEntries sync.RWMutex
}
// NewAccountsDB creates a new account manager
func NewAccountsDB(
trie data.Trie,
hasher hashing.Hasher,
marshalizer marshal.Marshalizer,
accountFactory AccountFactory,
) (*AccountsDB, error) {
if trie == nil || trie.IsInterfaceNil() {
return nil, ErrNilTrie
}
if hasher == nil || hasher.IsInterfaceNil() {
return nil, ErrNilHasher
}
if marshalizer == nil || marshalizer.IsInterfaceNil() {
return nil, ErrNilMarshalizer
}
if accountFactory == nil || accountFactory.IsInterfaceNil() {
return nil, ErrNilAccountFactory
}
return &AccountsDB{
mainTrie: trie,
hasher: hasher,
marshalizer: marshalizer,
accountFactory: accountFactory,
entries: make([]JournalEntry, 0),
mutEntries: sync.RWMutex{},
dataTries: NewDataTriesHolder(),
}, nil
}
// PutCode sets the SC plain code in AccountHandler object and trie, code hash in AccountState.
// Errors if something went wrong
func (adb *AccountsDB) PutCode(accountHandler AccountHandler, code []byte) error {
if code == nil {
return ErrNilCode
}
if accountHandler == nil || accountHandler.IsInterfaceNil() {
return ErrNilAccountHandler
}
codeHash := adb.hasher.Compute(string(code))
err := adb.addCodeToTrieIfMissing(codeHash, code)
if err != nil {
return err
}
err = accountHandler.SetCodeHashWithJournal(codeHash)
if err != nil {
return err
}
accountHandler.SetCode(code)
return nil
}
func (adb *AccountsDB) addCodeToTrieIfMissing(codeHash []byte, code []byte) error {
val, err := adb.mainTrie.Get(codeHash)
if err != nil {
return err
}
if val == nil {
//append a journal entry as the code needs to be inserted in the trie
entry, err := NewBaseJournalEntryCreation(codeHash, adb.mainTrie)
if err != nil {
return err
}
adb.Journalize(entry)
return adb.mainTrie.Update(codeHash, code)
}
return nil
}
// RemoveCode deletes the code from the trie. It writes an empty byte slice at codeHash "address"
func (adb *AccountsDB) RemoveCode(codeHash []byte) error {
return adb.mainTrie.Update(codeHash, make([]byte, 0))
}
// LoadDataTrie retrieves and saves the SC data inside accountHandler object.
// Errors if something went wrong
func (adb *AccountsDB) loadDataTrie(accountHandler AccountHandler) error {
if accountHandler.GetRootHash() == nil {
//do nothing, the account is either SC library or transfer account
return nil
}
if len(accountHandler.GetRootHash()) != HashLength {
return NewErrorTrieNotNormalized(HashLength, len(accountHandler.GetRootHash()))
}
dataTrie := adb.dataTries.Get(accountHandler.AddressContainer().Bytes())
if dataTrie != nil {
accountHandler.SetDataTrie(dataTrie)
return nil
}
dataTrie, err := adb.mainTrie.Recreate(accountHandler.GetRootHash())
if err != nil {
//error as there is an inconsistent state:
//account has data root hash but does not contain the actual trie
return NewErrMissingTrie(accountHandler.GetRootHash())
}
accountHandler.SetDataTrie(dataTrie)
adb.dataTries.Put(accountHandler.AddressContainer().Bytes(), dataTrie)
return nil
}
// SaveDataTrie is used to save the data trie (not committing it) and to recompute the new Root value
// If data is not dirtied, method will not create its JournalEntries to keep track of data modification
func (adb *AccountsDB) SaveDataTrie(accountHandler AccountHandler) error {
flagHasDirtyData := false
if check.IfNil(accountHandler.DataTrie()) {
newDataTrie, err := adb.mainTrie.Recreate(make([]byte, 0))
if err != nil {
return err
}
accountHandler.SetDataTrie(newDataTrie)
adb.dataTries.Put(accountHandler.AddressContainer().Bytes(), newDataTrie)
}
trackableDataTrie := accountHandler.DataTrieTracker()
if trackableDataTrie == nil {
return ErrNilTrackableDataTrie
}
dataTrie := trackableDataTrie.DataTrie()
oldValues := make(map[string][]byte)
for k, v := range trackableDataTrie.DirtyData() {
originalValue := trackableDataTrie.OriginalValue([]byte(k))
if !bytes.Equal(v, originalValue) {
flagHasDirtyData = true
val, err := dataTrie.Get([]byte(k))
if err != nil {
return err
}
oldValues[k] = val
err = dataTrie.Update([]byte(k), v)
if err != nil {
return err
}
}
}
if !flagHasDirtyData {
//do not need to save, return
return nil
}
entry, err := NewJournalEntryDataTrieUpdates(oldValues, accountHandler)
if err != nil {
return err
}
adb.Journalize(entry)
rootHash, err := trackableDataTrie.DataTrie().Root()
if err != nil {
return err
}
accountHandler.SetRootHash(rootHash)
trackableDataTrie.ClearDataCaches()
return adb.SaveAccount(accountHandler)
}
// HasAccount searches for an account based on the address. Errors if something went wrong and
// outputs if the account exists or not
func (adb *AccountsDB) HasAccount(addressContainer AddressContainer) (bool, error) {
val, err := adb.mainTrie.Get(addressContainer.Bytes())
if err != nil {
return false, err
}
return val != nil, nil
}
func (adb *AccountsDB) getAccount(addressContainer AddressContainer) (AccountHandler, error) {
addrBytes := addressContainer.Bytes()
val, err := adb.mainTrie.Get(addrBytes)
if err != nil {
return nil, err
}
if val == nil {
return nil, nil
}
acnt, err := adb.accountFactory.CreateAccount(addressContainer, adb)
if err != nil {
return nil, err
}
err = adb.marshalizer.Unmarshal(acnt, val)
if err != nil {
return nil, err
}
return acnt, nil
}
// SaveAccount saves the account WITHOUT data trie inside main trie. Errors if something went wrong
func (adb *AccountsDB) SaveAccount(accountHandler AccountHandler) error {
if accountHandler == nil || accountHandler.IsInterfaceNil() {
return errors.New("can not save nil account state")
}
//pass the reference to marshalizer, otherwise it will fail marshalizing balance
buff, err := adb.marshalizer.Marshal(accountHandler)
if err != nil {
return err
}
return adb.mainTrie.Update(accountHandler.AddressContainer().Bytes(), buff)
}
// RemoveAccount removes the account data from underlying trie.
// It basically calls Update with empty slice
func (adb *AccountsDB) RemoveAccount(addressContainer AddressContainer) error {
return adb.mainTrie.Update(addressContainer.Bytes(), make([]byte, 0))
}
// GetAccountWithJournal fetches the account based on the address. Creates an empty account if the account is missing.
func (adb *AccountsDB) GetAccountWithJournal(addressContainer AddressContainer) (AccountHandler, error) {
acnt, err := adb.getAccount(addressContainer)
if err != nil {
return nil, err
}
if acnt != nil {
return adb.loadAccountHandler(acnt)
}
return adb.newAccountHandler(addressContainer)
}
// GetExistingAccount returns an existing account if exists or nil if missing
func (adb *AccountsDB) GetExistingAccount(addressContainer AddressContainer) (AccountHandler, error) {
acnt, err := adb.getAccount(addressContainer)
if err != nil {
return nil, err
}
if acnt == nil {
return nil, ErrAccNotFound
}
err = adb.loadCodeAndDataIntoAccountHandler(acnt)
if err != nil {
return nil, err
}
return acnt, nil
}
func (adb *AccountsDB) loadAccountHandler(accountHandler AccountHandler) (AccountHandler, error) {
err := adb.loadCodeAndDataIntoAccountHandler(accountHandler)
if err != nil {
return nil, err
}
return accountHandler, nil
}
func (adb *AccountsDB) loadCodeAndDataIntoAccountHandler(accountHandler AccountHandler) error {
err := adb.loadCode(accountHandler)
if err != nil {
return err
}
err = adb.loadDataTrie(accountHandler)
if err != nil {
return err
}
return nil
}
func (adb *AccountsDB) newAccountHandler(address AddressContainer) (AccountHandler, error) {
acnt, err := adb.accountFactory.CreateAccount(address, adb)
if err != nil {
return nil, err
}
entry, err := NewBaseJournalEntryCreation(address.Bytes(), adb.mainTrie)
if err != nil {
return nil, err
}
adb.Journalize(entry)
err = adb.SaveAccount(acnt)
if err != nil {
return nil, err
}
return acnt, nil
}
// RevertToSnapshot apply Revert method over accounts object and removes entries from the list
// If snapshot > len(entries) will do nothing, return will be nil
// 0 index based. Calling this method with negative value will do nothing. Calling with 0 revert everything.
// Concurrent safe.
func (adb *AccountsDB) RevertToSnapshot(snapshot int) error {
if snapshot > len(adb.entries) || snapshot < 0 {
//outside of bounds array, not quite error, just return
return nil
}
adb.mutEntries.Lock()
defer adb.mutEntries.Unlock()
for i := len(adb.entries) - 1; i >= snapshot; i-- {
account, err := adb.entries[i].Revert()
if err != nil {
return err
}
if account != nil {
err = adb.SaveAccount(account)
}
}
adb.entries = adb.entries[:snapshot]
return nil
}
// JournalLen will return the number of entries
// Concurrent safe.
func (adb *AccountsDB) JournalLen() int {
adb.mutEntries.RLock()
length := len(adb.entries)
adb.mutEntries.RUnlock()
return length
}
// Commit will persist all data inside the trie
func (adb *AccountsDB) Commit() ([]byte, error) {
adb.mutEntries.RLock()
jEntries := make([]JournalEntry, len(adb.entries))
copy(jEntries, adb.entries)
adb.mutEntries.RUnlock()
//Step 1. commit all data tries
dataTries := adb.dataTries.GetAll()
for i := 0; i < len(dataTries); i++ {
err := dataTries[i].Commit()
if err != nil {
return nil, err
}
}
adb.dataTries.Reset()
//step 2. clean the journal
adb.clearJournal()
//Step 3. commit main trie
err := adb.mainTrie.Commit()
if err != nil {
return nil, err
}
root, err := adb.mainTrie.Root()
if err != nil {
return nil, err
}
return root, nil
}
// loadCode retrieves and saves the SC code inside AccountState object. Errors if something went wrong
func (adb *AccountsDB) loadCode(accountHandler AccountHandler) error {
if accountHandler.GetCodeHash() == nil || len(accountHandler.GetCodeHash()) == 0 {
return nil
}
if len(accountHandler.GetCodeHash()) != HashLength {
return errors.New("attempt to search a hash not normalized to" +
strconv.Itoa(HashLength) + "bytes")
}
val, err := adb.mainTrie.Get(accountHandler.GetCodeHash())
if err != nil {
return err
}
accountHandler.SetCode(val)
return nil
}
// RootHash returns the main trie's root hash
func (adb *AccountsDB) RootHash() ([]byte, error) {
return adb.mainTrie.Root()
}
// RecreateTrie is used to reload the trie based on an existing rootHash
func (adb *AccountsDB) RecreateTrie(rootHash []byte) error {
newTrie, err := adb.mainTrie.Recreate(rootHash)
if err != nil {
return err
}
if newTrie == nil {
return ErrNilTrie
}
adb.mainTrie = newTrie
return nil
}
// Journalize adds a new object to entries list. Concurrent safe.
func (adb *AccountsDB) Journalize(entry JournalEntry) {
if entry == nil || entry.IsInterfaceNil() {
return
}
adb.mutEntries.Lock()
adb.entries = append(adb.entries, entry)
adb.mutEntries.Unlock()
}
// Clear clears the data from this journal.
func (adb *AccountsDB) clearJournal() {
adb.mutEntries.Lock()
adb.entries = make([]JournalEntry, 0)
adb.mutEntries.Unlock()
}
// IsInterfaceNil returns true if there is no value under the interface
func (adb *AccountsDB) IsInterfaceNil() bool {
if adb == nil {
return true
}
return false
}