forked from aergoio/aergo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chainservice.go
408 lines (365 loc) · 11.1 KB
/
chainservice.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
/**
* @file
* @copyright defined in aergo/LICENSE.txt
*/
package chain
import (
"errors"
"github.com/aergoio/aergo-actor/actor"
"github.com/aergoio/aergo-lib/log"
cfg "github.com/aergoio/aergo/config"
"github.com/aergoio/aergo/consensus"
"github.com/aergoio/aergo/contract"
"github.com/aergoio/aergo/contract/system"
"github.com/aergoio/aergo/internal/enc"
"github.com/aergoio/aergo/mempool"
"github.com/aergoio/aergo/message"
"github.com/aergoio/aergo/pkg/component"
"github.com/aergoio/aergo/state"
"github.com/aergoio/aergo/types"
"github.com/libp2p/go-libp2p-peer"
)
// ChainService manage connectivity of blocks
type ChainService struct {
*component.BaseComponent
consensus.ChainConsensus
cfg *cfg.Config
cdb *ChainDB
sdb *state.ChainStateDB
op *OrphanPool
validator *BlockValidator
}
var (
logger = log.NewLogger("chain")
genesisBlock *types.Block
initialBestBlock *types.Block
ErrBlockExist = errors.New("error! block already exist")
)
// NewChainService create instance of ChainService
func NewChainService(cfg *cfg.Config, cc consensus.ChainConsensus, pool *mempool.MemPool) *ChainService {
actor := &ChainService{
ChainConsensus: cc,
cfg: cfg,
cdb: NewChainDB(cc),
sdb: state.NewChainStateDB(),
op: NewOrphanPool(),
}
if err := Init(cfg.Blockchain.MaxBlockSize,
cfg.Blockchain.CoinbaseAccount,
types.DefaultCoinbaseFee,
cfg.Consensus.EnableBp,
cfg.Blockchain.MaxAnchorCount); err != nil {
logger.Error().Err(err).Msg("failed to init chainservice")
panic("invalid config: blockchain")
}
if cc != nil {
cc.SetStateDB(actor.sdb)
}
actor.validator = NewBlockValidator(actor.sdb)
if pool != nil {
pool.SetChainStateDB(actor.sdb)
}
actor.BaseComponent = component.NewBaseComponent(message.ChainSvc, actor, logger)
return actor
}
func (cs *ChainService) initDB(dbType string, dataDir string) error {
// init chaindb
if err := cs.cdb.Init(dbType, dataDir); err != nil {
logger.Fatal().Err(err).Msg("failed to initialize chaindb")
return err
}
// init statedb
bestBlock, err := cs.GetBestBlock()
if err != nil {
return err
}
if err := cs.sdb.Init(dbType, dataDir, bestBlock, cs.cfg.EnableTestmode); err != nil {
logger.Fatal().Err(err).Msg("failed to initialize statedb")
return err
}
contract.LoadDatabase(dataDir)
return nil
}
// BeforeStart initialize chain database and generate empty genesis block if necessary
func (cs *ChainService) BeforeStart() {
var err error
if err = cs.initDB(cs.cfg.DbType, cs.cfg.DataDir); err != nil {
logger.Fatal().Err(err).Msg("failed to initialize DB")
}
// init genesis block
if _, err := cs.initGenesis(nil); err != nil {
logger.Fatal().Err(err).Msg("failed to genesis block")
}
cs.ChainConsensus.Init(cs.cdb)
}
// AfterStart ... do nothing
func (cs *ChainService) AfterStart() {
}
// InitGenesisBlock initialize chain database and generate specified genesis block if necessary
func (cs *ChainService) InitGenesisBlock(gb *types.Genesis, dbType string, dataDir string) error {
if err := cs.initDB(dbType, dataDir); err != nil {
logger.Fatal().Err(err).Msg("failed to initialize DB")
return err
}
_, err := cs.initGenesis(gb)
if err != nil {
logger.Fatal().Err(err).Msg("cannot initialize genesis block")
return err
}
return nil
}
func (cs *ChainService) initGenesis(genesis *types.Genesis) (*types.Block, error) {
gh, _ := cs.cdb.getHashByNo(0)
if gh == nil || len(gh) == 0 {
logger.Info().Uint64("nom", cs.cdb.latest).Msg("current latest")
if cs.cdb.latest == 0 {
if genesis == nil {
genesis = types.GetDefaultGenesis()
}
genesisBlock := types.GenesisToBlock(genesis)
err := InitGenesisBPs(cs.sdb.GetStateDB(), genesis)
if err != nil {
logger.Fatal().Err(err).Msg("cannot set bp identifications")
return nil, err
}
err = cs.sdb.SetGenesis(genesis)
if err != nil {
logger.Fatal().Err(err).Msg("cannot set statedb of genesisblock")
return nil, err
}
err = cs.cdb.addGenesisBlock(genesisBlock)
if err != nil {
logger.Fatal().Err(err).Msg("cannot add genesisblock")
return nil, err
}
logger.Info().Msg("genesis block is generated")
}
}
genesisBlock, _ := cs.cdb.GetBlockByNo(0)
logger.Info().Str("genesis", enc.ToString(genesisBlock.Hash)).
Str("stateroot", enc.ToString(genesisBlock.GetHeader().GetBlocksRootHash())).Msg("chain initialized")
return genesisBlock, nil
}
// ChainSync synchronize with peer
func (cs *ChainService) ChainSync(peerID peer.ID, remoteBestHash []byte) {
// handlt it like normal block (orphan)
logger.Debug().Msg("Best Block Request")
anchors := cs.getAnchorsFromHash(remoteBestHash)
hashes := make([]message.BlockHash, 0)
for _, a := range anchors {
hashes = append(hashes, message.BlockHash(a))
logger.Debug().Str("hash", enc.ToString(a)).Msg("request blocks for sync")
}
cs.RequestTo(message.P2PSvc, &message.GetMissingBlocks{ToWhom: peerID, Hashes: hashes})
}
// BeforeStop close chain database and stop BlockValidator
func (cs *ChainService) BeforeStop() {
cs.CloseDB()
cs.validator.Stop()
}
// CloseDB close chain database
func (cs *ChainService) CloseDB() {
if cs.sdb != nil {
cs.sdb.Close()
}
if cs.cdb != nil {
cs.cdb.Close()
}
contract.CloseDatabase()
}
func (cs *ChainService) notifyBlock(block *types.Block) {
cs.BaseComponent.RequestTo(message.P2PSvc,
&message.NotifyNewBlock{
BlockNo: block.Header.BlockNo,
Block: block,
})
}
// Receive actor message
func (cs *ChainService) Receive(context actor.Context) {
switch msg := context.Message().(type) {
case *message.GetBestBlockNo:
context.Respond(message.GetBestBlockNoRsp{
BlockNo: cs.getBestBlockNo(),
})
case *message.GetBestBlock:
block, err := cs.GetBestBlock()
if err != nil {
logger.Error().Err(err).Msg("failed to get best block")
}
context.Respond(message.GetBestBlockRsp{
Block: block,
Err: err,
})
case *message.GetBlock:
bid := types.ToBlockID(msg.BlockHash)
block, err := cs.getBlock(bid[:])
if err != nil {
logger.Debug().Err(err).Str("hash", enc.ToString(msg.BlockHash)).Msg("block not found")
}
context.Respond(message.GetBlockRsp{
Block: block,
Err: err,
})
case *message.GetBlockByNo:
block, err := cs.getBlockByNo(msg.BlockNo)
if err != nil {
logger.Error().Err(err).Uint64("blockNo", msg.BlockNo).Msg("failed to get block by no")
}
context.Respond(message.GetBlockByNoRsp{
Block: block,
Err: err,
})
case *message.AddBlock:
bid := msg.Block.BlockID()
block := msg.Block
logger.Debug().Str("hash", msg.Block.ID()).
Uint64("blockNo", msg.Block.GetHeader().GetBlockNo()).Msg("add block chainservice")
_, err := cs.getBlock(bid[:])
if err == nil {
logger.Debug().Str("hash", msg.Block.ID()).Msg("already exist")
err = ErrBlockExist
} else {
var bstate *state.BlockState
if msg.Bstate != nil {
bstate = msg.Bstate.(*state.BlockState)
}
err := cs.addBlock(block, bstate, msg.PeerID)
if err != nil {
logger.Error().Err(err).Str("hash", msg.Block.ID()).Msg("failed add block")
}
}
context.Respond(message.AddBlockRsp{
BlockNo: block.GetHeader().GetBlockNo(),
BlockHash: block.BlockHash(),
Err: err,
})
cs.Hub().Tell(message.RPCSvc, block)
case *message.MemPoolDelRsp:
err := msg.Err
if err != nil {
logger.Error().Err(err).Msg("failed to remove txs from mempool")
}
case *message.GetState:
id := types.ToAccountID(msg.Account)
state, err := cs.sdb.GetStateDB().GetAccountState(id)
if err != nil {
logger.Error().Str("hash", enc.ToString(msg.Account)).Err(err).Msg("failed to get state for account")
}
context.Respond(message.GetStateRsp{
State: state,
Err: err,
})
case *message.GetStateAndProof:
id := types.ToAccountID(msg.Account)
stateProof, err := cs.sdb.GetStateDB().GetStateAndProof(id, msg.Root)
if err != nil {
logger.Error().Str("hash", enc.ToString(msg.Account)).Err(err).Msg("failed to get state for account")
}
context.Respond(message.GetStateAndProofRsp{
StateProof: stateProof,
Err: err,
})
case *message.GetMissing:
stopHash := msg.StopHash
hashes := msg.Hashes
topHash, topNo, stopNo := cs.handleMissing(stopHash, hashes)
context.Respond(message.GetMissingRsp{
TopMatched: topHash,
TopNumber: topNo,
StopNumber: stopNo,
})
case *message.GetTx:
tx, txIdx, err := cs.getTx(msg.TxHash)
context.Respond(message.GetTxRsp{
Tx: tx,
TxIds: txIdx,
Err: err,
})
case *message.GetReceipt:
receipt, err := cs.getReceipt(msg.TxHash)
context.Respond(message.GetReceiptRsp{
Receipt: receipt,
Err: err,
})
case *message.GetABI:
contractState, err := cs.sdb.GetStateDB().OpenContractStateAccount(types.ToAccountID(msg.Contract))
if err == nil {
abi, err := contract.GetABI(contractState)
context.Respond(message.GetABIRsp{
ABI: abi,
Err: err,
})
} else {
context.Respond(message.GetABIRsp{
ABI: nil,
Err: err,
})
}
case *message.GetQuery:
ctrState, err := cs.sdb.GetStateDB().OpenContractStateAccount(types.ToAccountID(msg.Contract))
if err != nil {
logger.Error().Str("hash", enc.ToString(msg.Contract)).Err(err).Msg("failed to get state for contract")
context.Respond(message.GetQueryRsp{Result: nil, Err: err})
} else {
bs := state.NewBlockState(cs.sdb.OpenNewStateDB(cs.sdb.GetRoot()))
ret, err := contract.Query(msg.Contract, bs, ctrState, msg.Queryinfo)
context.Respond(message.GetQueryRsp{Result: ret, Err: err})
}
case *message.SyncBlockState:
cs.checkBlockHandshake(msg.PeerID, msg.BlockNo, msg.BlockHash)
case *message.GetElected:
top, err := cs.getVotes(msg.N)
context.Respond(&message.GetVoteRsp{
Top: top,
Err: err,
})
case *message.GetVote:
top, err := cs.getVote(msg.Addr)
context.Respond(&message.GetVoteRsp{
Top: top,
Err: err,
})
case actor.SystemMessage,
actor.AutoReceiveMessage,
actor.NotInfluenceReceiveTimeout:
//logger.Debugf("Received message. (%v) %s", reflect.TypeOf(msg), msg)
default:
//logger.Debugf("Missed message. (%v) %s", reflect.TypeOf(msg), msg)
}
}
func (cs *ChainService) Statistics() *map[string]interface{} {
return &map[string]interface{}{
"orphan": cs.op.curCnt,
}
}
func (cs *ChainService) GetChainTree() ([]byte, error) {
return cs.cdb.GetChainTree()
}
func (cs *ChainService) getVotes(n int) (*types.VoteList, error) {
scs, err := cs.sdb.GetStateDB().OpenContractStateAccount(types.ToAccountID([]byte(types.AergoSystem)))
if err != nil {
return nil, err
}
return system.GetVoteResult(scs, n)
}
func (cs *ChainService) getVote(addr []byte) (*types.VoteList, error) {
scs, err := cs.sdb.GetStateDB().OpenContractStateAccount(types.ToAccountID([]byte(types.AergoSystem)))
if err != nil {
return nil, err
}
var voteList types.VoteList
var tmp []*types.Vote
voteList.Votes = tmp
amount, _, to, err := system.GetVote(scs, addr)
if err != nil {
return nil, err
}
for offset := 0; offset < len(to); offset += system.PeerIDLength {
vote := &types.Vote{
Candidate: to[offset : offset+system.PeerIDLength],
Amount: amount,
}
voteList.Votes = append(voteList.Votes, vote)
}
return &voteList, nil
}