-
Notifications
You must be signed in to change notification settings - Fork 1
/
para.go
448 lines (387 loc) · 13.6 KB
/
para.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
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package para
import (
"encoding/hex"
"fmt"
"sort"
"sync"
log "github.com/assetcloud/chain/common/log/log15"
"sync/atomic"
"time"
"github.com/assetcloud/chain/client/api"
"github.com/assetcloud/chain/common/crypto"
"github.com/assetcloud/chain/common/merkle"
"github.com/assetcloud/chain/queue"
"github.com/assetcloud/chain/rpc/grpcclient"
drivers "github.com/assetcloud/chain/system/consensus"
cty "github.com/assetcloud/chain/system/dapp/coins/types"
"github.com/assetcloud/chain/types"
paracross "github.com/assetcloud/plugin/plugin/dapp/paracross/types"
pt "github.com/assetcloud/plugin/plugin/dapp/paracross/types"
)
const (
defaultWaitMinBlockNum = 100 //min block number startHeight before lastHeight in mainchain
defaultGenesisBlockTime int64 = 1514533390
//current miner tx take any privatekey for unify all nodes sign purpose, and para chain is free
minerPrivateKey = "6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b"
poolMainBlockMsec int64 = 5000
defaultEmptyBlockInterval int64 = 50 //write empty block every interval blocks in mainchain
defaultSearchMatchedBlockDepth int32 = 10000
)
var (
plog = log.New("module", "para")
zeroHash [32]byte
)
func init() {
drivers.Reg("para", New)
drivers.QueryData.Register("para", &client{})
}
type client struct {
*drivers.BaseClient
grpcClient types.ChainClient
execAPI api.ExecutorAPI
caughtUp int32
commitMsgClient *commitMsgClient
blockSyncClient *blockSyncClient
multiDldCli *multiDldClient
jumpDldCli *jumpDldClient
minerPrivateKey crypto.PrivKey
wg sync.WaitGroup
cfg *types.Consensus
subCfg *subConfig
dldCfg *downloadClient
blsSignCli *blsClient
isClosed int32
quit chan struct{}
}
type subConfig struct {
WriteBlockMsec int64 `json:"writeBlockMsec,omitempty"`
StartHeight int64 `json:"startHeight,omitempty"`
WaitMainBlockNum int64 `json:"waitMainBlockNum,omitempty"`
GenesisStartHeightSame bool `json:"genesisStartHeightSame,omitempty"`
EmptyBlockInterval []string `json:"emptyBlockInterval,omitempty"`
AuthAccount string `json:"authAccount,omitempty"`
WaitBlocks4CommitMsg int32 `json:"waitBlocks4CommitMsg,omitempty"`
GenesisAmount int64 `json:"genesisAmount,omitempty"`
MainBlockHashForkHeight int64 `json:"mainBlockHashForkHeight,omitempty"`
WaitConsensStopTimes uint32 `json:"waitConsensStopTimes,omitempty"`
MaxCacheCount int64 `json:"maxCacheCount,omitempty"`
MaxSyncErrCount int32 `json:"maxSyncErrCount,omitempty"`
BatchFetchBlockCount int64 `json:"batchFetchBlockCount,omitempty"`
ParaConsensStartHeight int64 `json:"paraConsensStartHeight,omitempty"`
MultiDownloadOpen bool `json:"multiDownloadOpen,omitempty"`
MultiDownInvNumPerJob int64 `json:"multiDownInvNumPerJob,omitempty"`
MultiDownJobBuffNum uint32 `json:"multiDownJobBuffNum,omitempty"`
MultiDownServerRspTime uint32 `json:"multiDownServerRspTime,omitempty"`
RmCommitParamMainHeight int64 `json:"rmCommitParamMainHeight,omitempty"`
JumpDownloadClose bool `json:"jumpDownloadClose,omitempty"`
Bls *blsConfig `json:"bls,omitempty"`
}
// New function to init paracross env
func New(cfg *types.Consensus, sub []byte) queue.Module {
c := drivers.NewBaseClient(cfg)
var subcfg subConfig
if sub != nil {
types.MustDecode(sub, &subcfg)
}
//支持创世精度为0
if subcfg.GenesisAmount < 0 {
panic(fmt.Sprintf("genesis amount <0"))
}
if subcfg.WriteBlockMsec <= 0 {
subcfg.WriteBlockMsec = poolMainBlockMsec
}
//WaitMainBlockNum 配置最小为1,因为genesis块是startHeight-1, wait=1和startHeight相等
if subcfg.WaitMainBlockNum <= 0 {
subcfg.WaitMainBlockNum = defaultWaitMinBlockNum
}
//最初平行链toml GenesisBlockTime=1514533394,但是未被使用,一直使用的内置的1514533390,最新版本开始适配cfg.GenesisBlockTime,并且
//时间也缺省改为1514533390,支持修改时间, 如果有以前的旧的配置未修改,panic强制修改
if cfg.GenesisBlockTime == 1514533394 {
panic("para chain GenesisBlockTime need be modified to 1514533390 or other")
}
emptyInterval, err := parseEmptyBlockInterval(subcfg.EmptyBlockInterval)
if err != nil {
panic("para EmptyBlockInterval config not correct")
}
err = checkEmptyBlockInterval(emptyInterval)
if err != nil {
panic("para EmptyBlockInterval config not correct")
}
if subcfg.BatchFetchBlockCount <= 0 {
subcfg.BatchFetchBlockCount = types.MaxBlockCountPerTime
}
if subcfg.BatchFetchBlockCount > types.MaxBlockCountPerTime {
panic(fmt.Sprintf("BatchFetchBlockCount=%d should be <= %d ", subcfg.BatchFetchBlockCount, types.MaxBlockCountPerTime))
}
pk, err := hex.DecodeString(minerPrivateKey)
if err != nil {
panic(err)
}
secp, err := crypto.Load(types.GetSignName("", types.SECP256K1), -1)
if err != nil {
panic(err)
}
priKey, err := secp.PrivKeyFromBytes(pk)
if err != nil {
panic(err)
}
para := &client{
BaseClient: c,
minerPrivateKey: priKey,
cfg: cfg,
subCfg: &subcfg,
quit: make(chan struct{}),
}
para.dldCfg = &downloadClient{}
para.dldCfg.emptyInterval = append(para.dldCfg.emptyInterval, emptyInterval...)
para.commitMsgClient = newCommitMsgCli(para, &subcfg)
para.blockSyncClient = newBlockSyncCli(para, &subcfg)
para.multiDldCli = newMultiDldCli(para, &subcfg)
para.jumpDldCli = newJumpDldCli(para, &subcfg)
para.blsSignCli = newBlsClient(para, &subcfg)
c.SetChild(para)
return para
}
//para 不检查任何的交易
func (client *client) CheckBlock(parent *types.Block, current *types.BlockDetail) error {
err := checkMinerTx(current)
return err
}
func (client *client) Close() {
atomic.StoreInt32(&client.isClosed, 1)
close(client.commitMsgClient.quit)
close(client.quit)
close(client.blockSyncClient.quitChan)
close(client.blsSignCli.quit)
client.wg.Wait()
client.BaseClient.Close()
plog.Info("consensus para closed")
}
func (client *client) isCancel() bool {
return atomic.LoadInt32(&client.isClosed) == 1
}
func (client *client) SetQueueClient(c queue.Client) {
plog.Info("Enter SetQueueClient method of Para consensus")
client.InitClient(c, func() {
client.InitBlock()
})
go client.EventLoop()
client.wg.Add(1)
go client.commitMsgClient.handler()
client.wg.Add(1)
go client.CreateBlock()
client.wg.Add(1)
go client.blockSyncClient.syncBlocks()
client.wg.Add(2)
go client.blsSignCli.procAggregateTxs()
go client.blsSignCli.procLeaderSync()
}
func (client *client) InitBlock() {
var err error
client.execAPI = api.New(client.BaseClient.GetAPI(), client.grpcClient)
cfg := client.GetAPI().GetConfig()
grpcCli, err := grpcclient.NewMainChainClient(cfg, "")
if err != nil {
panic(err)
}
client.grpcClient = grpcCli
err = client.commitMsgClient.setSelfConsEnable()
if err != nil {
panic(err)
}
block, err := client.RequestLastBlock()
if err != nil {
panic(err)
}
if block == nil {
if client.subCfg.StartHeight <= 0 {
panic(fmt.Sprintf("startHeight(%d) should be more than 0 in mainchain", client.subCfg.StartHeight))
}
//平行链创世区块对应主链hash为startHeight-1的那个block的hash
mainHash := client.GetStartMainHash(client.subCfg.StartHeight - 1)
// 创世区块
newblock := &types.Block{}
newblock.Height = 0
newblock.BlockTime = defaultGenesisBlockTime
if client.cfg.GenesisBlockTime > 0 {
newblock.BlockTime = client.cfg.GenesisBlockTime
}
newblock.ParentHash = zeroHash[:]
newblock.MainHash = mainHash
//缺省是减1,但有些特殊项目方6.2.0版本升级上来要求blockhash不变,则需与6.2.0保持一致,不减一
newblock.MainHeight = client.subCfg.StartHeight - 1
if client.subCfg.GenesisStartHeightSame {
newblock.MainHeight = client.subCfg.StartHeight
}
tx := client.CreateGenesisTx()
newblock.Txs = tx
newblock.TxHash = merkle.CalcMerkleRoot(cfg, newblock.GetMainHeight(), newblock.Txs)
err := client.blockSyncClient.createGenesisBlock(newblock)
if err != nil {
panic(fmt.Sprintf("para chain create genesis block,err=%s", err.Error()))
}
err = client.createLocalGenesisBlock(newblock)
if err != nil {
panic(fmt.Sprintf("para chain create local genesis block,err=%s", err.Error()))
}
} else {
client.SetCurrentBlock(block)
}
plog.Debug("para consensus init parameter", "mainBlockHashForkHeight", client.subCfg.MainBlockHashForkHeight)
}
// GetStartMainHash 获取start
func (client *client) GetStartMainHash(height int64) []byte {
lastHeight, err := client.GetLastHeightOnMainChain()
if err != nil {
panic(err)
}
if lastHeight < height {
panic(fmt.Sprintf("lastHeight(%d) less than startHeight(%d) in mainchain", lastHeight, height))
}
if height > 0 {
hint := time.NewTicker(time.Second)
for lastHeight < height+client.subCfg.WaitMainBlockNum {
select {
case <-hint.C:
plog.Info("Waiting lastHeight increase......", "lastHeight", lastHeight, "startHeight", height)
default:
lastHeight, err = client.GetLastHeightOnMainChain()
if err != nil {
panic(err)
}
time.Sleep(time.Second)
}
}
hint.Stop()
plog.Info(fmt.Sprintf("lastHeight more than %d blocks after startHeight", client.subCfg.WaitMainBlockNum), "lastHeight", lastHeight, "startHeight", height)
}
hash, err := client.GetHashByHeightOnMainChain(height)
if err != nil {
panic(err)
}
plog.Info("the start hash in mainchain", "height", height, "hash", hex.EncodeToString(hash))
return hash
}
func (client *client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction
cfg := client.GetAPI().GetConfig()
tx.Execer = []byte(cfg.ExecName(cfg.GetCoinExec()))
tx.To = client.Cfg.Genesis
//gen payload
g := &cty.CoinsAction_Genesis{}
g.Genesis = &types.AssetsGenesis{}
g.Genesis.Amount = client.subCfg.GenesisAmount * cfg.GetCoinPrecision()
tx.Payload = types.Encode(&cty.CoinsAction{Value: g, Ty: cty.CoinsActionGenesis})
ret = append(ret, &tx)
return
}
func (client *client) ProcEvent(msg *queue.Message) bool {
if msg.Ty == types.EventReceiveSubData {
if req, ok := msg.GetData().(*types.TopicData); ok {
var sub pt.ParaP2PSubMsg
err := types.Decode(req.Data, &sub)
if err != nil {
plog.Error("paracross ProcEvent decode", "ty", types.EventReceiveSubData)
return true
}
plog.Info("paracross ProcEvent", "from", req.GetFrom(), "topic:", req.GetTopic(), "ty", sub.GetTy())
if !client.blsSignCli.blsSignOn {
plog.Error("paracross ProcEvent bls is closed")
return true
}
switch sub.GetTy() {
case P2pSubCommitTx:
go client.blsSignCli.rcvCommitTx(sub.GetCommitTx())
case P2pSubLeaderSyncMsg:
err := client.blsSignCli.rcvLeaderSyncTx(sub.GetSyncMsg())
if err != nil {
plog.Error("bls.event.paracross ProcEvent leader sync msg", "err", err)
}
default:
plog.Error("paracross ProcEvent not support", "ty", sub.GetTy())
}
} else {
plog.Error("paracross ProcEvent topicData", "ty", types.EventReceiveSubData)
}
return true
}
return false
}
func (client *client) isCaughtUp() bool {
return atomic.LoadInt32(&client.caughtUp) == 1
}
func checkMinerTx(current *types.BlockDetail) error {
//检查第一个笔交易的execs, 以及执行状态
if len(current.Block.Txs) == 0 {
return types.ErrEmptyTx
}
baseTx := current.Block.Txs[0]
//判断交易类型和执行情况
var action paracross.ParacrossAction
err := types.Decode(baseTx.GetPayload(), &action)
if err != nil {
return err
}
if action.GetTy() != pt.ParacrossActionMiner {
return paracross.ErrParaMinerTxType
}
//判断交易执行是否OK
if action.GetMiner() == nil {
return paracross.ErrParaEmptyMinerTx
}
//判断exec 是否成功
if current.Receipts[0].Ty != types.ExecOk {
plog.Error("checkMinerTx", "receiptTy", current.Receipts[0].Ty)
return paracross.ErrParaMinerExecErr
}
return nil
}
//比较newBlock是不是最优区块
func (client *client) CmpBestBlock(newBlock *types.Block, cmpBlock *types.Block) bool {
return false
}
//["0:50","100:20","500:30"]
func parseEmptyBlockInterval(cfg []string) ([]*emptyBlockInterval, error) {
var emptyInter []*emptyBlockInterval
if len(cfg) == 0 {
interval := &emptyBlockInterval{startHeight: 0, interval: defaultEmptyBlockInterval}
emptyInter = append(emptyInter, interval)
return emptyInter, nil
}
list := make(map[int64]int64)
var seq []int64
for _, e := range cfg {
ret, err := divideStr2Int64s(e, ":")
if err != nil {
plog.Error("parse empty block inter config", "str", e)
return nil, err
}
seq = append(seq, ret[0])
list[ret[0]] = ret[1]
}
sort.Slice(seq, func(i, j int) bool { return seq[i] < seq[j] })
for _, h := range seq {
emptyInter = append(emptyInter, &emptyBlockInterval{startHeight: h, interval: list[h]})
}
return emptyInter, nil
}
func checkEmptyBlockInterval(in []*emptyBlockInterval) error {
for i := 0; i < len(in); i++ {
if i == 0 && in[i].startHeight != 0 {
plog.Error("EmptyBlockInterval,first blockHeight should be 0", "height", in[i].startHeight)
return types.ErrInvalidParam
}
if i > 0 && in[i].startHeight <= in[i-1].startHeight {
plog.Error("EmptyBlockInterval,blockHeight should be sequence", "preHeight", in[i-1].startHeight, "laterHeight", in[i].startHeight)
return types.ErrInvalidParam
}
if in[i].interval <= 0 {
plog.Error("EmptyBlockInterval,interval should > 0", "height", in[i].startHeight)
return types.ErrInvalidParam
}
}
return nil
}