-
Notifications
You must be signed in to change notification settings - Fork 2
/
blockchain.go
413 lines (366 loc) · 14.5 KB
/
blockchain.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
package blockchain
import (
"fmt"
"github.com/DSiSc/blockchain/config"
"github.com/DSiSc/blockstore"
blkconf "github.com/DSiSc/blockstore/config"
"github.com/DSiSc/craft/log"
"github.com/DSiSc/craft/monitor"
"github.com/DSiSc/craft/types"
"github.com/DSiSc/statedb-NG"
"github.com/DSiSc/statedb-NG/ethdb"
"github.com/DSiSc/statedb-NG/ethdb/leveldb"
"github.com/DSiSc/statedb-NG/ethdb/memorydb"
"math/big"
"sync"
)
// global disk database instance
var (
lock sync.RWMutex
initialized bool
stateDiskDB ethdb.Database = nil
globalBlockStore *blockstore.BlockStore = nil
globalEventCenter types.EventCenter = nil
)
// blockchain module constant value.
const (
// DB plugin
PLUGIN_LEVELDB = "leveldb"
// memory plugin
PLUGIN_MEMDB = "memorydb"
)
// InitBlockChain init blockchain module config.
func InitBlockChain(chainConfig config.BlockChainConfig, eventCenter types.EventCenter) error {
lock.Lock()
defer lock.Unlock()
if initialized {
log.Warn("BlockChain has been initialized")
}
log.Info("Start initializing block chain")
switch chainConfig.PluginName {
case PLUGIN_LEVELDB:
if chainConfig.StateDataPath == chainConfig.BlockDataPath {
log.Error("Statedb path should be different with Blockdb path")
return fmt.Errorf("statedb path should be different with blockdb path")
}
// create statedb low level database.
levelDB, err := leveldb.New(chainConfig.StateDataPath, 0, 0, "")
if err != nil {
log.Error("Failed to create levelDB for Statedb, as: %v", err)
return err
}
// create blockstore
bstore, err := blockstore.NewBlockStore(&blkconf.BlockStoreConfig{
PluginName: PLUGIN_LEVELDB,
DataPath: chainConfig.BlockDataPath,
})
if err != nil {
log.Error("Failed to create file-based block store, as: %v", err)
return err
}
stateDiskDB = levelDB
globalBlockStore = bstore
case PLUGIN_MEMDB:
stateDiskDB = memorydb.New()
// create blockstore
bstore, err := blockstore.NewBlockStore(&blkconf.BlockStoreConfig{
PluginName: PLUGIN_MEMDB,
DataPath: "",
})
if err != nil {
log.Error("Failed to create memory-based block store, as: %v", err)
return err
}
globalBlockStore = bstore
default:
log.Error("Unsupported plugin type: %s ", chainConfig.PluginName)
return fmt.Errorf("Unsupported plugin type: %s ", chainConfig.PluginName)
}
globalEventCenter = eventCenter
initialized = true
return nil
}
// BlockChain is the chain manager.
//
// The BlockChain is used to write block to chain, get block from chain, and get the block state.
type BlockChain struct {
blockStore blockstore.BlockStoreAPI
state *statedb.StateDB
mu sync.RWMutex
eventCenter types.EventCenter
currentBlock *types.Block
}
// NewLatestStateBlockChain create a blockchain with latest state hash.
func NewLatestStateBlockChain() (*BlockChain, error) {
log.Debug("Create block chain at the latest height")
if stateDiskDB == nil || globalBlockStore == nil {
log.Error("BlockChain have not been initialized")
return nil, fmt.Errorf("BlockChain have not been initialized")
}
currentBlock := globalBlockStore.GetCurrentBlock()
if currentBlock == nil {
log.Info("There are no blocks in block store, create block chain with init state")
return NewBlockChainByHash(types.Hash{})
} else {
return NewBlockChainByHash(currentBlock.Header.StateRoot)
}
}
// NewLatestStateBlockChain create a blockchain with specified block hash.
func NewBlockChainByBlockHash(blockHash types.Hash) (*BlockChain, error) {
log.Info("Create block chain with block hash: %x", blockHash)
if stateDiskDB == nil || globalBlockStore == nil {
log.Error("BlockChain have not been initialized")
return nil, fmt.Errorf("BlockChain have not been initialized")
}
block, err := globalBlockStore.GetBlockByHash(blockHash)
if err != nil {
log.Error("Can not find block from block store with hash: %x", blockHash)
return nil, fmt.Errorf("Can not find block from block store with hash: %x ", blockHash)
}
return NewBlockChainByHash(block.Header.StateRoot)
}
// NewBlockChain returns a blockchain instance with specified hash.
func NewBlockChainByHash(root types.Hash) (*BlockChain, error) {
log.Debug("Create block chain with hash root: %x", root)
if stateDiskDB == nil || globalBlockStore == nil {
log.Error("BlockChain have not been initialized")
return nil, fmt.Errorf("BlockChain have not been initialized")
}
stateDB, err := statedb.New(root, statedb.NewDatabase(stateDiskDB))
if err != nil {
log.Error("Failed to create statedb, as: %v ", err)
return nil, fmt.Errorf("Failed to create statedb, as: %v ", err)
}
lock.RLock()
defer lock.RUnlock()
return &BlockChain{
state: stateDB,
blockStore: globalBlockStore,
eventCenter: globalEventCenter,
}, nil
}
// WriteBlockWithState writes the block to the database.
func (blockChain *BlockChain) WriteBlock(block *types.Block) error {
return blockChain.WriteBlockWithReceipts(block, nil)
}
// GetTransactionByHash get transaction by hash
func (blockChain *BlockChain) GetTransactionByHash(hash types.Hash) (*types.Transaction, types.Hash, uint64, uint64, error) {
return blockChain.blockStore.GetTransactionByHash(hash)
}
// WriteBlock write the block and relative receipts to database. return error if write failed.
func (blockChain *BlockChain) WriteBlockWithReceipts(block *types.Block, receipts []*types.Receipt) error {
log.Debug("write block %x with receipt.", block.HeaderHash)
return blockChain.EventWriteBlockWithReceipts(block, receipts, true)
}
// WriteBlock write the block and relative receipts to database. return error if write failed.
func (blockChain *BlockChain) EventWriteBlockWithReceipts(block *types.Block, receipts []*types.Receipt, emitCommitEvent bool) error {
log.Info("Start Writing block: %x, height: %d", block.HeaderHash, block.Header.Height)
// write state to database
stateRoot, err := blockChain.Commit(false)
if err != nil {
log.Error("Failed to Commit block %x's state root, block height %d, failed reason: %v", block.HeaderHash, block.Header.Height, err)
if block.Header.Height == blockstore.INIT_BLOCK_HEIGHT || !emitCommitEvent {
blockChain.eventCenter.Notify(types.EventBlockWriteFailed, err)
} else {
blockChain.eventCenter.Notify(types.EventBlockCommitFailed, err)
}
return err
} else {
log.Info("Commit state %x to database, current block height: %d", stateRoot, block.Header.Height)
}
// write block to block store
if receipts == nil || len(receipts) == 0 {
err = blockChain.blockStore.WriteBlock(block)
} else {
err = blockChain.blockStore.WriteBlockWithReceipts(block, receipts)
}
if err != nil {
log.Error("Failed to write block to block store, as: %v", err)
if block.Header.Height == blockstore.INIT_BLOCK_HEIGHT || !emitCommitEvent {
blockChain.eventCenter.Notify(types.EventBlockWriteFailed, err)
} else {
blockChain.eventCenter.Notify(types.EventBlockCommitFailed, err)
}
return err
}
// send block Commit event if it is not the genesis block.
if block.Header.Height == blockstore.INIT_BLOCK_HEIGHT || !emitCommitEvent {
blockChain.eventCenter.Notify(types.EventBlockWritten, block)
} else {
blockChain.eventCenter.Notify(types.EventBlockCommitted, block)
}
log.Info("Write block %x height %d successfully", block.HeaderHash, block.Header.Height)
monitor.JTMetrics.BlockTxNum.Set(float64(len(block.Transactions)))
monitor.JTMetrics.CommittedTx.Add(float64(len(block.Transactions)))
monitor.JTMetrics.BlockHeight.Set(float64(block.Header.Height))
return nil
}
// GetReceiptByHash get receipt by relative tx's hash
func (blockChain *BlockChain) GetReceiptByTxHash(txHash types.Hash) (*types.Receipt, types.Hash, uint64, uint64, error) {
return blockChain.blockStore.GetReceiptByTxHash(txHash)
}
// GetReceiptByHash get receipt by relative block's hash
func (blockChain *BlockChain) GetReceiptByBlockHash(blockHash types.Hash) []*types.Receipt {
return blockChain.blockStore.GetReceiptByBlockHash(blockHash)
}
// GetLogs get transaction's execution log
func (blockChain *BlockChain) GetLogs(txHash types.Hash) []*types.Log {
log.Debug("Get Tx[%x]'s execution log", txHash)
return blockChain.state.GetLogs(txHash)
}
// GetBlockByHash retrieves a block from the local chain.
func (blockChain *BlockChain) GetBlockByHash(hash types.Hash) (*types.Block, error) {
log.Debug("Get block by hash %x.", hash)
return blockChain.blockStore.GetBlockByHash(hash)
}
// GetBlockByHeight get block by height.
func (blockChain *BlockChain) GetBlockByHeight(height uint64) (*types.Block, error) {
log.Debug("Get block by height %d.", height)
return blockChain.blockStore.GetBlockByHeight(height)
}
// GetCurrentBlock get current block.
func (blockChain *BlockChain) GetCurrentBlock() *types.Block {
log.Debug("get current block.")
return blockChain.blockStore.GetCurrentBlock()
}
// GetCurrentBlockHeight get current block height.
func (blockChain *BlockChain) GetCurrentBlockHeight() uint64 {
log.Debug("get current block height.")
return blockChain.blockStore.GetCurrentBlockHeight()
}
func (blockChain *BlockChain) SetBalance(addr types.Address, amount *big.Int) {
blockChain.state.SetBalance(addr, amount)
}
// CreateAccount create an account
func (blockChain *BlockChain) CreateAccount(address types.Address) {
blockChain.state.CreateAccount(address)
}
func (blockChain *BlockChain) SubBalance(address types.Address, value *big.Int) {
blockChain.state.SubBalance(address, value)
}
func (blockChain *BlockChain) AddBalance(address types.Address, value *big.Int) {
blockChain.state.AddBalance(address, value)
}
func (blockChain *BlockChain) GetBalance(address types.Address) *big.Int {
return blockChain.state.GetBalance(address)
}
// GetNonce get account's nounce
func (blockChain *BlockChain) GetNonce(address types.Address) uint64 {
return blockChain.state.GetNonce(address)
}
func (blockChain *BlockChain) SetNonce(address types.Address, value uint64) {
blockChain.state.SetNonce(address, value)
}
func (blockChain *BlockChain) GetCodeHash(address types.Address) types.Hash {
return blockChain.state.GetCodeHash(address)
}
func (blockChain *BlockChain) GetCode(address types.Address) []byte {
log.Debug("get code by address %x.", address)
return blockChain.state.GetCode(address)
}
func (blockChain *BlockChain) SetCode(address types.Address, code []byte) {
blockChain.state.SetCode(address, code)
}
func (blockChain *BlockChain) GetCodeSize(address types.Address) int {
return blockChain.state.GetCodeSize(address)
}
func (blockChain *BlockChain) AddRefund(value uint64) {
blockChain.state.AddRefund(value)
}
func (blockChain *BlockChain) GetRefund() uint64 {
return blockChain.state.GetRefund()
}
func (blockChain *BlockChain) GetState(address types.Address, bhash types.Hash) types.Hash {
return blockChain.state.GetState(address, bhash)
}
func (blockChain *BlockChain) SetState(address types.Address, key, value types.Hash) {
blockChain.state.SetState(address, key, value)
}
func (blockChain *BlockChain) Suicide(address types.Address) bool {
return blockChain.state.Suicide(address)
}
func (blockChain *BlockChain) HasSuicided(address types.Address) bool {
return blockChain.state.HasSuicided(address)
}
// Exist reports whether the given account exists in state.
// Notably this should also return true for suicided accounts.
func (blockChain *BlockChain) Exist(address types.Address) bool {
return blockChain.state.Exist(address)
}
// Empty returns whether the given account is empty. Empty
// is defined according to EIP161 (balance = nonce = code = 0).
func (blockChain *BlockChain) Empty(address types.Address) bool {
return blockChain.state.Empty(address)
}
func (blockChain *BlockChain) RevertToSnapshot(revid int) {
blockChain.state.RevertToSnapshot(revid)
}
func (blockChain *BlockChain) Snapshot() int {
return blockChain.state.Snapshot()
}
func (blockChain *BlockChain) AddPreimage(hash types.Hash, preimage []byte) {
blockChain.state.AddPreimage(hash, preimage)
}
func (blockChain *BlockChain) ForEachStorage(addr types.Address, cb func(key, value types.Hash) bool) {
blockChain.state.ForEachStorage(addr, cb)
}
// Reset clears out all ephemeral state objects from the state db, but keeps
// the underlying state trie to avoid reloading data for the next operations.
func (blockChain *BlockChain) Reset(root types.Hash) error {
return blockChain.state.Reset(root)
}
// Finalise finalises the state by removing the self destructed objects
// and clears the journal as well as the refunds.
func (blockChain *BlockChain) Finalise(deleteEmptyObjects bool) {
blockChain.state.Finalise(deleteEmptyObjects)
}
// IntermediateRoot computes the current root hash of the state trie.
// It is called in between transactions to get the root hash that
// goes into transaction receipts.
func (blockChain *BlockChain) IntermediateRoot(deleteEmptyObjects bool) types.Hash {
log.Debug("get intermediate root.")
return blockChain.state.IntermediateRoot(deleteEmptyObjects)
}
// Prepare sets the current transaction hash and index and block hash which is
// used when the EVM emits new state logs.
func (blockChain *BlockChain) Prepare(thash, bhash types.Hash, ti int) {
blockChain.state.Prepare(thash, bhash, ti)
}
// AddLog add contract execute log.
func (blockChain *BlockChain) AddLog(log *types.Log) {
blockChain.state.AddLog(log)
}
// Commit writes the state to the underlying in-memory trie database.
func (blockChain *BlockChain) Commit(deleteEmptyObjects bool) (root types.Hash, err error) {
log.Info("Start committing statedb state to database")
//Commit statedb
stateRoot, err := blockChain.state.Commit(false)
if err != nil {
log.Info("failed to Commit statedb to MPT tree, as: %v", err)
return types.Hash{}, err
}
// Commit statedb to low level disk database
err = blockChain.state.Database().TrieDB().Commit(stateRoot, false)
if err != nil {
log.Info("failed to Commit MPT tree database, as: %v", err)
return types.Hash{}, err
}
return stateRoot, nil
}
// Put add a record to database
func (blockChain *BlockChain) Put(key []byte, value []byte) error {
return blockChain.blockStore.Put(key, value)
}
// Get get a record by key
func (blockChain *BlockChain) Get(key []byte) ([]byte, error) {
return blockChain.blockStore.Get(key)
}
// GetCommittedState retrieves a value from the given account's committed storage trie.
func (blockChain *BlockChain) GetCommittedState(addr types.Address, hash types.Hash) types.Hash {
return blockChain.state.GetCommittedState(addr, hash)
}
// SubRefund removes gas from the refund counter.
// This method will panic if the refund counter goes below zero
func (blockChain *BlockChain) SubRefund(gas uint64) {
blockChain.state.SubRefund(gas)
}