-
Notifications
You must be signed in to change notification settings - Fork 291
/
state_store.go
578 lines (516 loc) · 16.3 KB
/
state_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
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology 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 ontology 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 ontology. If not, see <http://www.gnu.org/licenses/>.
*/
package ledgerstore
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
common2 "github.com/ethereum/go-ethereum/common"
"github.com/ontio/ontology/common"
"github.com/ontio/ontology/common/log"
"github.com/ontio/ontology/common/serialization"
"github.com/ontio/ontology/core/payload"
"github.com/ontio/ontology/core/states"
scom "github.com/ontio/ontology/core/store/common"
"github.com/ontio/ontology/core/store/leveldbstore"
"github.com/ontio/ontology/core/store/overlaydb"
"github.com/ontio/ontology/merkle"
"github.com/ontio/ontology/smartcontract/service/native/ontid"
"github.com/ontio/ontology/smartcontract/service/native/utils"
"github.com/ontio/ontology/smartcontract/storage"
)
var (
BOOKKEEPER = []byte("Bookkeeper") //Bookkeeper store key
)
//StateStore saving the data of ledger states. Like balance of account, and the execution result of smart contract
type StateStore struct {
dbDir string //Store file path
store scom.PersistStore //Store handler
merklePath string //Merkle tree store path
merkleTree *merkle.CompactMerkleTree //Merkle tree of block root
deltaMerkleTree *merkle.CompactMerkleTree //Merkle tree of delta state root
merkleHashStore merkle.HashStore
stateHashCheckHeight uint32
}
//NewStateStore return state store instance
func NewStateStore(dbDir, merklePath string, stateHashCheckHeight uint32) (*StateStore, error) {
var err error
store, err := leveldbstore.NewLevelDBStore(dbDir)
if err != nil {
return nil, err
}
stateStore := &StateStore{
dbDir: dbDir,
store: store,
merklePath: merklePath,
stateHashCheckHeight: stateHashCheckHeight,
}
_, height, err := stateStore.GetCurrentBlock()
if err != nil && err != scom.ErrNotFound {
return nil, fmt.Errorf("GetCurrentBlock error %s", err)
}
err = stateStore.init(height)
if err != nil {
return nil, fmt.Errorf("init error %s", err)
}
return stateStore, nil
}
// for test
func NewMemStateStore(stateHashHeight uint32) *StateStore {
store := leveldbstore.NewMemLevelDBStore()
stateStore := &StateStore{
store: store,
merkleTree: merkle.NewTree(0, nil, nil),
deltaMerkleTree: merkle.NewTree(0, nil, nil),
stateHashCheckHeight: stateHashHeight,
}
return stateStore
}
//NewBatch start new commit batch
func (self *StateStore) NewBatch() {
self.store.NewBatch()
}
func (self *StateStore) BatchPutRawKeyVal(key, val []byte) {
self.store.BatchPut(key, val)
}
func (self *StateStore) BatchDeleteRawKey(key []byte) {
self.store.BatchDelete(key)
}
func (self *StateStore) init(currBlockHeight uint32) error {
treeSize, hashes, err := self.GetBlockMerkleTree()
if err != nil && err != scom.ErrNotFound {
return err
}
if treeSize > 0 && treeSize != currBlockHeight+1 {
return fmt.Errorf("merkle tree size is inconsistent with blockheight: %d", currBlockHeight+1)
}
self.merkleHashStore, err = merkle.NewFileHashStore(self.merklePath, treeSize)
if err != nil {
log.Warn("merkle store is inconsistent with ChainStore. persistence will be disabled")
}
self.merkleTree = merkle.NewTree(treeSize, hashes, self.merkleHashStore)
if currBlockHeight >= self.stateHashCheckHeight {
treeSize, hashes, err := self.GetStateMerkleTree()
if err != nil && err != scom.ErrNotFound {
return err
}
if treeSize > 0 && treeSize != currBlockHeight-self.stateHashCheckHeight+1 {
return fmt.Errorf("merkle tree size is inconsistent with blockheight: %d", currBlockHeight+1)
}
self.deltaMerkleTree = merkle.NewTree(treeSize, hashes, nil)
}
return nil
}
//GetStateMerkleTree return merkle tree size an tree node
func (self *StateStore) GetStateMerkleTree() (uint32, []common.Uint256, error) {
key := self.genStateMerkleTreeKey()
return self.getMerkleTree(key)
}
//GetBlockMerkleTree return merkle tree size an tree node
func (self *StateStore) GetBlockMerkleTree() (uint32, []common.Uint256, error) {
key := self.genBlockMerkleTreeKey()
return self.getMerkleTree(key)
}
func (self *StateStore) getMerkleTree(key []byte) (uint32, []common.Uint256, error) {
data, err := self.store.Get(key)
if err != nil {
return 0, nil, err
}
value := bytes.NewBuffer(data)
treeSize, err := serialization.ReadUint32(value)
if err != nil {
return 0, nil, err
}
hashCount := (len(data) - 4) / common.UINT256_SIZE
hashes := make([]common.Uint256, 0, hashCount)
for i := 0; i < hashCount; i++ {
var hash = new(common.Uint256)
err = hash.Deserialize(value)
if err != nil {
return 0, nil, err
}
hashes = append(hashes, *hash)
}
return treeSize, hashes, nil
}
func (self *StateStore) GetStateMerkleRoot(height uint32) (result common.Uint256, err error) {
if height < self.stateHashCheckHeight {
return
}
key := self.genStateMerkleRootKey(height)
var value []byte
value, err = self.store.Get(key)
if err != nil {
return
}
source := common.NewZeroCopySource(value)
_, eof := source.NextHash()
if eof {
err = io.ErrUnexpectedEOF
}
result, eof = source.NextHash()
if eof {
err = io.ErrUnexpectedEOF
}
return
}
func (self *StateStore) AddStateMerkleTreeRoot(blockHeight uint32, writeSetHash common.Uint256) error {
if blockHeight < self.stateHashCheckHeight {
return nil
} else if blockHeight == self.stateHashCheckHeight {
self.deltaMerkleTree = merkle.NewTree(0, nil, nil)
}
key := self.genStateMerkleTreeKey()
self.deltaMerkleTree.AppendHash(writeSetHash)
treeSize := self.deltaMerkleTree.TreeSize()
hashes := self.deltaMerkleTree.Hashes()
value := common.NewZeroCopySink(make([]byte, 0, 4+len(hashes)*common.UINT256_SIZE))
value.WriteUint32(treeSize)
for _, hash := range hashes {
value.WriteHash(hash)
}
self.store.BatchPut(key, value.Bytes())
key = self.genStateMerkleRootKey(blockHeight)
value.Reset()
value.WriteHash(writeSetHash)
value.WriteHash(self.deltaMerkleTree.Root())
self.store.BatchPut(key, value.Bytes())
return nil
}
//AddBlockMerkleTreeRoot add a new tree root
func (self *StateStore) AddBlockMerkleTreeRoot(txRoot common.Uint256) error {
key := self.genBlockMerkleTreeKey()
self.merkleTree.AppendHash(txRoot)
treeSize := self.merkleTree.TreeSize()
hashes := self.merkleTree.Hashes()
value := common.NewZeroCopySink(make([]byte, 0, 4+len(hashes)*common.UINT256_SIZE))
value.WriteUint32(treeSize)
for _, hash := range hashes {
value.WriteHash(hash)
}
self.store.BatchPut(key, value.Bytes())
return nil
}
//GetMerkleProof return merkle proof of block
func (self *StateStore) GetMerkleProof(proofHeight, rootHeight uint32) ([]common.Uint256, error) {
return self.merkleTree.InclusionProof(proofHeight, rootHeight+1)
}
func (self *StateStore) NewOverlayDB() *overlaydb.OverlayDB {
return overlaydb.NewOverlayDB(self.store)
}
//CommitTo commit state batch to state store
func (self *StateStore) CommitTo() error {
return self.store.BatchCommit()
}
//GetContractState return contract by contract address
func (self *StateStore) GetContractState(contractHash common.Address) (*payload.DeployCode, error) {
key, err := self.getContractStateKey(contractHash)
if err != nil {
return nil, err
}
value, err := self.store.Get(key)
if err != nil {
return nil, err
}
source := common.NewZeroCopySource(value)
contractState := new(payload.DeployCode)
err = contractState.Deserialization(source)
if err != nil {
return nil, err
}
return contractState, nil
}
//GetBookkeeperState return current book keeper states
func (self *StateStore) GetBookkeeperState() (*states.BookkeeperState, error) {
key, err := self.getBookkeeperKey()
if err != nil {
return nil, err
}
value, err := self.store.Get(key)
if err != nil {
return nil, err
}
reader := common.NewZeroCopySource(value)
bookkeeperState := new(states.BookkeeperState)
err = bookkeeperState.Deserialization(reader)
if err != nil {
return nil, err
}
return bookkeeperState, nil
}
//SaveBookkeeperState persist book keeper state to store
func (self *StateStore) SaveBookkeeperState(bookkeeperState *states.BookkeeperState) error {
key, err := self.getBookkeeperKey()
if err != nil {
return err
}
value := common.NewZeroCopySink(nil)
bookkeeperState.Serialization(value)
return self.store.Put(key, value.Bytes())
}
func (self *StateStore) GetEthCode(codeHash common2.Hash) ([]byte, error) {
key := genEthCodeKey(codeHash)
value, err := self.store.Get(key)
if err != nil {
return nil, err
}
return value, nil
}
func (self *StateStore) GetEthAccount(address common2.Address) (*storage.EthAccount, error) {
key := genEthAccountKey(address)
value, err := self.store.Get(key)
if err != nil {
if err == scom.ErrNotFound {
return &storage.EthAccount{}, nil
}
return nil, err
}
reader := common.NewZeroCopySource(value)
account := new(storage.EthAccount)
err = account.Deserialization(reader)
if err != nil {
return nil, err
}
return account, nil
}
func (self *StateStore) GetEthState(addr common2.Address, stateKey common2.Hash) ([]byte, error) {
key := genStateKey(addr, stateKey)
value, err := self.store.Get(key)
if err != nil {
if err == scom.ErrNotFound {
return nil, nil
}
return nil, err
}
return value, nil
}
func genEthCodeKey(codeHash common2.Hash) []byte {
key := make([]byte, 1+len(codeHash))
key[0] = byte(scom.ST_ETH_CODE)
copy(key[1:], codeHash[:])
return key
}
func genStateKey(contract common2.Address, stateKey common2.Hash) []byte {
suffixKey := genKey(contract, stateKey)
key := make([]byte, 1+len(suffixKey))
key[0] = byte(scom.ST_STORAGE)
copy(key[1:], suffixKey)
return key
}
func genKey(contract common2.Address, key common2.Hash) []byte {
var result []byte
result = append(result, contract.Bytes()...)
result = append(result, key.Bytes()...)
return result
}
func genEthAccountKey(addr common2.Address) []byte {
key := make([]byte, 1+len(addr))
key[0] = byte(scom.ST_ETH_ACCOUNT)
copy(key[1:], addr[:])
return key
}
//GetStorageItem return the storage value of the key in smart contract.
func (self *StateStore) GetStorageState(key *states.StorageKey) (*states.StorageItem, error) {
storeKey := self.genStorageKey(key)
data, err := self.store.Get(storeKey)
if err != nil {
return nil, err
}
reader := common.NewZeroCopySource(data)
storageState := new(states.StorageItem)
err = storageState.Deserialization(reader)
if err != nil {
return nil, err
}
return storageState, nil
}
//GetCurrentBlock return current block height and current hash in state store
func (self *StateStore) GetCurrentBlock() (common.Uint256, uint32, error) {
key := self.getCurrentBlockKey()
data, err := self.store.Get(key)
if err != nil {
return common.Uint256{}, 0, err
}
reader := bytes.NewReader(data)
blockHash := common.Uint256{}
err = blockHash.Deserialize(reader)
if err != nil {
return common.Uint256{}, 0, err
}
height, err := serialization.ReadUint32(reader)
if err != nil {
return common.Uint256{}, 0, err
}
return blockHash, height, nil
}
//SaveCurrentBlock persist current block to state store
func (self *StateStore) SaveCurrentBlock(height uint32, blockHash common.Uint256) error {
key := self.getCurrentBlockKey()
value := bytes.NewBuffer(nil)
blockHash.Serialize(value)
serialization.WriteUint32(value, height)
self.store.BatchPut(key, value.Bytes())
return nil
}
func (self *StateStore) GetCrossStates(height uint32) ([]common.Uint256, error) {
key := self.genCrossStatesKey(height)
data, err := self.store.Get(key)
if err != nil {
return []common.Uint256{}, err
}
source := common.NewZeroCopySource(data)
l := len(data) / common.UINT256_SIZE
hashes := make([]common.Uint256, 0, l)
for i := 0; i < l; i++ {
u256, eof := source.NextHash()
if eof {
return []common.Uint256{}, fmt.Errorf("%s", "Get states hash error!")
}
hashes = append(hashes, u256)
}
return hashes, nil
}
func (self *StateStore) GetCrossStatesRoot(height uint32) (common.Uint256, error) {
states, err := self.GetCrossStates(height)
if err != nil && err != scom.ErrNotFound {
return common.UINT256_EMPTY, err
}
if err == scom.ErrNotFound {
return common.UINT256_EMPTY, nil
}
return merkle.TreeHasher{}.HashFullTreeWithLeafHash(states), nil
}
func (self *StateStore) SaveCrossStates(height uint32, crossStates []common.Uint256) error {
//save cross states hash
if len(crossStates) == 0 {
return nil
}
key := self.genCrossStatesKey(height)
sink := common.NewZeroCopySink(make([]byte, 0, len(crossStates)*common.UINT256_SIZE))
for _, v := range crossStates {
sink.WriteHash(v)
}
self.store.BatchPut(key, sink.Bytes())
return nil
}
func (self *StateStore) genCrossStatesKey(height uint32) []byte {
key := make([]byte, 5)
key[0] = byte(scom.SYS_CURRENT_CROSS_STATES)
binary.LittleEndian.PutUint32(key[1:], height)
return key
}
func (self *StateStore) getCurrentBlockKey() []byte {
return []byte{byte(scom.SYS_CURRENT_BLOCK)}
}
func (self *StateStore) getBookkeeperKey() ([]byte, error) {
key := make([]byte, 1+len(BOOKKEEPER))
key[0] = byte(scom.ST_BOOKKEEPER)
copy(key[1:], BOOKKEEPER)
return key, nil
}
func (self *StateStore) getContractStateKey(contractHash common.Address) ([]byte, error) {
data := contractHash[:]
key := make([]byte, 1+len(data))
key[0] = byte(scom.ST_CONTRACT)
copy(key[1:], data)
return key, nil
}
func (self *StateStore) genStorageKey(key *states.StorageKey) []byte {
buf := bytes.NewBuffer(nil)
buf.WriteByte(byte(scom.ST_STORAGE))
buf.Write(key.ContractAddress[:])
buf.Write(key.Key)
return buf.Bytes()
}
func (self *StateStore) GetStateMerkleRootWithNewHash(writeSetHash common.Uint256) common.Uint256 {
return self.deltaMerkleTree.GetRootWithNewLeaf(writeSetHash)
}
func (self *StateStore) GetBlockRootWithNewTxRoots(txRoots []common.Uint256) common.Uint256 {
return self.merkleTree.GetRootWithNewLeaves(txRoots)
}
func (self *StateStore) genBlockMerkleTreeKey() []byte {
return []byte{byte(scom.SYS_BLOCK_MERKLE_TREE)}
}
func (self *StateStore) genStateMerkleTreeKey() []byte {
return []byte{byte(scom.SYS_STATE_MERKLE_TREE)}
}
func (self *StateStore) genStateMerkleRootKey(height uint32) []byte {
key := make([]byte, 5, 5)
key[0] = byte(scom.DATA_STATE_MERKLE_ROOT)
binary.LittleEndian.PutUint32(key[1:], height)
return key
}
//ClearAll clear all data in state store
func (self *StateStore) ClearAll() error {
self.store.NewBatch()
iter := self.store.NewIterator(nil)
for iter.Next() {
self.store.BatchDelete(iter.Key())
}
iter.Release()
if err := iter.Error(); err != nil {
self.store.NewBatch() // reset the batch
return err
}
return self.store.BatchCommit()
}
//Close state store
func (self *StateStore) Close() error {
self.merkleHashStore.Close()
return self.store.Close()
}
func (self *StateStore) CheckStorage() error {
db := self.store
prefix := append([]byte{byte(scom.ST_STORAGE)}, utils.OntIDContractAddress[:]...) //prefix of new storage key
flag := append(prefix, ontid.FIELD_VERSION)
val, err := db.Get(flag)
if err == nil {
item := &states.StorageItem{}
source := common.NewZeroCopySource(val)
err := item.Deserialization(source)
if err == nil && item.Value[0] == ontid.FLAG_VERSION {
return nil
} else if err == nil {
return errors.New("check ontid storage: invalid version flag")
} else {
return err
}
}
prefix1 := []byte{byte(scom.ST_STORAGE), 0x2a, 0x64, 0x69, 0x64} //prefix of old storage key
iter := db.NewIterator(prefix1)
db.NewBatch()
for ok := iter.First(); ok; ok = iter.Next() {
key := append(prefix, iter.Key()[1:]...)
db.BatchPut(key, iter.Value())
db.BatchDelete(iter.Key())
}
iter.Release()
err = iter.Error()
if err != nil {
return err
}
tag := states.StorageItem{}
tag.Value = []byte{ontid.FLAG_VERSION}
buf := common.NewZeroCopySink(nil)
tag.Serialization(buf)
db.BatchPut(flag, buf.Bytes())
err = db.BatchCommit()
return err
}