-
Notifications
You must be signed in to change notification settings - Fork 5
/
chain.go
394 lines (331 loc) · 11.7 KB
/
chain.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
package chain
import (
"encoding/json"
"fmt"
"math/big"
"sync"
"github.com/drep-project/DREP-Chain/chain/block"
"github.com/drep-project/DREP-Chain/chain/store"
"github.com/drep-project/DREP-Chain/app"
"github.com/drep-project/DREP-Chain/params"
"gopkg.in/urfave/cli.v1"
"github.com/drep-project/DREP-Chain/common"
"github.com/drep-project/DREP-Chain/common/event"
"github.com/drep-project/DREP-Chain/crypto"
"github.com/drep-project/DREP-Chain/crypto/sha3"
"github.com/drep-project/DREP-Chain/database"
"github.com/drep-project/binary"
rpc2 "github.com/drep-project/DREP-Chain/pkgs/rpc"
"github.com/drep-project/DREP-Chain/types"
)
var (
DefaultChainConfigMainnet = &ChainConfig{
RemotePort: params.RemotePortMainnet,
ChainId: types.ChainIdType(params.RootChain),
GenesisAddr: params.HoleAddress,
}
DefaultChainConfigTestnet = &ChainConfig{
RemotePort: params.RemotePortTestnet,
ChainId: types.ChainIdType(params.RootChain),
GenesisAddr: params.HoleAddress,
}
span = uint64(params.MaxGasLimit / 360)
)
type ChainServiceInterface interface {
app.Service
ChainID() types.ChainIdType
DeriveMerkleRoot(txs []*types.Transaction) []byte
DeriveReceiptRoot(receipts []*types.Receipt) crypto.Hash
GetBlockByHash(hash *crypto.Hash) (*types.Block, error)
GetBlockByHeight(number uint64) (*types.Block, error)
//DefaultChainConfig
GetBlockHeaderByHash(hash *crypto.Hash) (*types.BlockHeader, error)
GetBlockHeaderByHeight(number uint64) (*types.BlockHeader, error)
GetHeader(hash crypto.Hash, number uint64) *types.BlockHeader
GetCurrentHeader() *types.BlockHeader
GetHighestBlock() (*types.Block, error)
RootChain() types.ChainIdType
BestChain() *ChainView
CalcGasLimit(parent *types.BlockHeader, gasFloor, gasCeil uint64) *big.Int
ProcessBlock(block *types.Block) (bool, bool, error)
NewBlockFeed() *event.Feed
GetLogsFeed() *event.Feed
GetRMLogsFeed() *event.Feed
BlockExists(blockHash *crypto.Hash) bool
Index() *block.BlockIndex
BlockValidator() BlockValidators
AddBlockValidator(validator IBlockValidator)
//TransactionValidators() map[ITransactionSelector]ITransactionValidator
//AddTransactionValidator(selector ITransactionSelector, validator ITransactionValidator)
AddGenesisProcess(validator IGenesisProcess)
GetConfig() *ChainConfig
DetachBlockFeed() *event.Feed
}
var cs ChainServiceInterface = &ChainService{}
//xxx
type ChainService struct {
RpcService *rpc2.RpcService `service:"rpc"`
DatabaseService *database.DatabaseService `service:"database"`
apis []app.API
chainID types.ChainIdType
lock sync.RWMutex
addBlockSync sync.Mutex
// These fields are related to handling of orphan blocks. They are
// protected by a combination of the chain lock and the orphan lock.
orphanLock sync.RWMutex
orphans map[crypto.Hash]*types.OrphanBlock
prevOrphans map[crypto.Hash][]*types.OrphanBlock
oldestOrphan *types.OrphanBlock
blockIndex *block.BlockIndex
bestChain *ChainView
Config *ChainConfig
genesisBlock *types.Block
//Provide a new block subscription
newBlockFeed event.Feed
detachBlockFeed event.Feed
logsFeed event.Feed
rmLogsFeed event.Feed
blockValidator BlockValidators
//transactionValidator map[ITransactionSelector]ITransactionValidator
genesisProcess []IGenesisProcess
chainStore *store.ChainStore
genesisConfig json.RawMessage
}
type ChainState struct {
types.BestState
db *store.StoreInterface
}
func (chainService *ChainService) Init(executeContext *app.ExecuteContext) error {
chainService.blockIndex = block.NewBlockIndex()
chainService.bestChain = NewChainView(nil)
chainService.chainStore = &store.ChainStore{chainService.DatabaseService.LevelDb()}
chainService.orphans = make(map[crypto.Hash]*types.OrphanBlock)
chainService.prevOrphans = make(map[crypto.Hash][]*types.OrphanBlock)
chainService.blockValidator = []IBlockValidator{NewChainBlockValidator(chainService)}
chainService.genesisProcess = []IGenesisProcess{NewPreminerGenesisProcessor()}
//chainService.transactionValidator = map[ITransactionSelector]ITransactionValidator{
//&TransferTxSelector{}: &TransferTransactionProcessor{},
//&AliasTxSelector{}: &AliasTransactionProcessor{},
//&StakeTxSelector{}: &StakeTransactionProcessor{},
//&CancelVoteTxSelector{}: &CancelVoteTransactionProcessor{},
//&CandidateTxSelector{}: &CandidateTransactionProcessor{},
//&CancelCandidateTxSelector{}: &CancelCandidateTransactionProcessor{},
//}
if _, ok := executeContext.PhaseConfig["genesis"]; ok {
chainService.genesisConfig = executeContext.PhaseConfig["genesis"]
} else if executeContext.NetConfigType == params.MainnetType {
chainService.genesisConfig = []byte(params.DefaultGenesisParamMainnet)
} else if executeContext.NetConfigType == params.TestnetType {
chainService.genesisConfig = []byte(params.DefaultGenesisParamTestnet)
} else {
return fmt.Errorf("net type err,type:%s", executeContext.NetConfigType)
}
var err error
chainService.genesisBlock, err = chainService.GetGenisiBlock(chainService.Config.GenesisAddr)
if err != nil {
return err
}
hash := chainService.genesisBlock.Header.Hash()
if !chainService.chainStore.HasBlock(hash) {
chainService.genesisBlock, err = chainService.ProcessGenesisBlock(chainService.Config.GenesisAddr)
err = chainService.createChainState()
if err != nil {
log.Error("createChainState err", err)
return err
}
_, err = store.TrieStoreFromStore(chainService.DatabaseService.LevelDb(), chainService.genesisBlock.Header.StateRoot)
if err != nil {
return err
}
}
err = chainService.InitStates()
if err != nil {
log.Error("InitStates err:", err)
return err
}
chainService.apis = []app.API{
{
Namespace: MODULENAME,
Version: "1.0",
Service: NewChainApi(chainService.DatabaseService.LevelDb(), chainService.BestChain(), chainService.chainStore),
Public: true,
},
}
return nil
}
func (chainService *ChainService) Start(executeContext *app.ExecuteContext) error {
return nil
}
func (chainService *ChainService) Stop(executeContext *app.ExecuteContext) error {
return nil
}
func (chainService *ChainService) BlockExists(blockHash *crypto.Hash) bool {
return chainService.blockIndex.HaveBlock(blockHash)
}
func (chainService *ChainService) RootChain() types.ChainIdType {
return types.ChainIdType(params.RootChain)
}
func (chainService *ChainService) GetCurrentHeader() *types.BlockHeader {
heighestBlockBode := chainService.bestChain.Tip()
if heighestBlockBode == nil {
return nil
}
block, err := chainService.chainStore.GetBlock(heighestBlockBode.Hash)
if err != nil {
return nil
}
return block.Header
}
func (chainService *ChainService) GetHighestBlock() (*types.Block, error) {
heighestBlockBode := chainService.bestChain.Tip()
if heighestBlockBode == nil {
return nil, fmt.Errorf("chain not init")
}
block, err := chainService.chainStore.GetBlock(heighestBlockBode.Hash)
if err != nil {
return nil, err
}
return block, nil
}
func (chainService *ChainService) GetBlockByHash(hash *crypto.Hash) (*types.Block, error) {
block, err := chainService.chainStore.GetBlock(hash)
if err != nil {
return nil, err
}
return block, nil
}
func (chainService *ChainService) GetBlockHeaderByHash(hash *crypto.Hash) (*types.BlockHeader, error) {
blockNode, ok := chainService.blockIndex.Index[*hash]
if !ok {
return nil, ErrBlockNotFound
}
blockHeader := blockNode.Header()
return &blockHeader, nil
}
func (chainService *ChainService) GetHeader(hash crypto.Hash, number uint64) *types.BlockHeader {
header, _ := chainService.GetBlockHeaderByHash(&hash)
return header
}
func (chainService *ChainService) GetBlockByHeight(number uint64) (*types.Block, error) {
blockNode := chainService.bestChain.NodeByHeight(number)
return chainService.GetBlockByHash(blockNode.Hash)
}
func (chainService *ChainService) GetBlockHeaderByHeight(number uint64) (*types.BlockHeader, error) {
blockNode := chainService.bestChain.NodeByHeight(number)
if blockNode == nil {
return nil, ErrBlockNotFound
}
header := blockNode.Header()
return &header, nil
}
func (chainService *ChainService) getTxHashes(ts []*types.Transaction) ([][]byte, error) {
txHashes := make([][]byte, len(ts))
for i, tx := range ts {
b, err := binary.Marshal(tx.Data)
if err != nil {
return nil, err
}
txHashes[i] = sha3.Keccak256(b)
}
return txHashes, nil
}
func (chainService *ChainService) DeriveMerkleRoot(txs []*types.Transaction) []byte {
if len(txs) == 0 {
return []byte{}
}
ts, _ := chainService.getTxHashes(txs)
merkle := common.NewMerkle(ts)
return merkle.Root.Hash
}
func (chainService *ChainService) DeriveReceiptRoot(receipts []*types.Receipt) crypto.Hash {
if len(receipts) == 0 {
return crypto.Hash{}
}
receiptsHashes := make([][]byte, len(receipts))
for i, receipt := range receipts {
b, _ := binary.Marshal(receipt)
receiptsHashes[i] = sha3.Keccak256(b)
}
merkle := common.NewMerkle(receiptsHashes)
receiptRoot := crypto.Hash{}
receiptRoot.SetBytes(merkle.Root.Hash)
return receiptRoot
}
func (chainService *ChainService) createChainState() error {
node := types.NewBlockNode(chainService.genesisBlock.Header, nil)
node.Status = types.StatusDataStored | types.StatusValid
chainService.bestChain.SetTip(node)
// Add the new node to the index which is used for faster lookups.
chainService.blockIndex.AddNode(node)
// Save the genesis block to the block index database.
err := chainService.chainStore.PutBlockNode(node)
if err != nil {
return err
}
err = chainService.chainStore.PutBlock(chainService.genesisBlock)
if err != nil {
return err
}
return nil
}
//GETTER
func (chainService *ChainService) GetDatabaseService() *database.DatabaseService {
return chainService.DatabaseService
}
func (chainService *ChainService) DetachBlockFeed() *event.Feed {
return &chainService.detachBlockFeed
}
func (chainService *ChainService) GetConfig() *ChainConfig {
return chainService.Config
}
func (chainService *ChainService) BlockValidator() BlockValidators {
return chainService.blockValidator
}
//func (chainService *ChainService) TransactionValidators() map[ITransactionSelector]ITransactionValidator {
// return chainService.transactionValidator
//}
func (chainService *ChainService) AddBlockValidator(validator IBlockValidator) {
chainService.blockValidator = append(chainService.blockValidator, validator)
}
//func (chainService *ChainService) AddTransactionValidator(selector ITransactionSelector, validator ITransactionValidator) {
// chainService.transactionValidator[selector] = validator
//}
func (chainService *ChainService) AddGenesisProcess(validator IGenesisProcess) {
chainService.genesisProcess = append(chainService.genesisProcess, validator)
}
func (chainService *ChainService) Index() *block.BlockIndex {
return chainService.blockIndex
}
func (chainService *ChainService) NewBlockFeed() *event.Feed {
return &chainService.newBlockFeed
}
func (chainService *ChainService) GetLogsFeed() *event.Feed {
return &chainService.logsFeed
}
func (chainService *ChainService) GetRMLogsFeed() *event.Feed {
return &chainService.rmLogsFeed
}
func (chainService *ChainService) BestChain() *ChainView {
return chainService.bestChain
}
func (chainService *ChainService) ChainID() types.ChainIdType {
return chainService.chainID
}
func (chainService *ChainService) Name() string {
return MODULENAME
}
func (chainService *ChainService) Api() []app.API {
return chainService.apis
}
func (chainService *ChainService) CommandFlags() ([]cli.Command, []cli.Flag) {
return nil, []cli.Flag{}
}
// DefaultConfig -> config
func (chainService *ChainService) DefaultConfig(netType params.NetType) *ChainConfig {
switch netType {
case params.MainnetType:
return DefaultChainConfigMainnet
default:
return DefaultChainConfigTestnet
}
}