Commit b24eac06 authored by mdj33's avatar mdj33 Committed by vipwzw

correct linter err of golint govet ineffasign

parent 71f4916a
...@@ -29,43 +29,44 @@ import ( ...@@ -29,43 +29,44 @@ import (
) )
const ( const (
AddAct int64 = 1 addAct int64 = 1 //add para block action
DelAct int64 = 2 //reference blockstore.go delAct int64 = 2 //reference blockstore.go, del para block action
ParaCrossTxCount = 2 //current only support 2 txs for cross paraCrossTxCount = 2 //current only support 2 txs for cross
) )
var ( var (
plog = log.New("module", "para") plog = log.New("module", "para")
grpcSite = "localhost:8802" grpcSite = "localhost:8802"
genesisBlockTime int64 = 1514533390 genesisBlockTime int64 = 1514533390
startHeight int64 = 0 //parachain sync from startHeight in mainchain startHeight int64 //parachain sync from startHeight in mainchain
searchSeq int64 = 0 //start sequence to search startHeight in mainchain searchSeq int64 //start sequence to search startHeight in mainchain
blockSec int64 = 5 //write block interval, second blockSec int64 = 5 //write block interval, second
emptyBlockInterval int64 = 4 //write empty block every interval blocks in mainchain emptyBlockInterval int64 = 4 //write empty block every interval blocks in mainchain
zeroHash [32]byte zeroHash [32]byte
grpcRecSize int = 30 * 1024 * 1024 //the size should be limited in server grpcRecSize = 30 * 1024 * 1024 //the size should be limited in server
//current miner tx take any privatekey for unify all nodes sign purpose, and para chain is free //current miner tx take any privatekey for unify all nodes sign purpose, and para chain is free
minerPrivateKey string = "6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b" minerPrivateKey = "6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b"
) )
func init() { func init() {
drivers.Reg("para", New) drivers.Reg("para", New)
drivers.QueryData.Register("para", &ParaClient{}) drivers.QueryData.Register("para", &client{})
} }
type ParaClient struct { type client struct {
*drivers.BaseClient *drivers.BaseClient
conn *grpc.ClientConn conn *grpc.ClientConn
grpcClient types.Chain33Client grpcClient types.Chain33Client
paraClient paracross.ParacrossClient paraClient paracross.ParacrossClient
isCatchingUp bool isCatchingUp bool
commitMsgClient *CommitMsgClient commitMsgClient *commitMsgClient
authAccount string authAccount string
privateKey crypto.PrivKey privateKey crypto.PrivKey
wg sync.WaitGroup wg sync.WaitGroup
} }
// New function to init paracross env
func New(cfg *types.Consensus, sub []byte) queue.Module { func New(cfg *types.Consensus, sub []byte) queue.Module {
c := drivers.NewBaseClient(cfg) c := drivers.NewBaseClient(cfg)
if cfg.ParaRemoteGrpcClient != "" { if cfg.ParaRemoteGrpcClient != "" {
...@@ -106,7 +107,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { ...@@ -106,7 +107,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module {
grpcClient := types.NewChain33Client(conn) grpcClient := types.NewChain33Client(conn)
paraCli := paracross.NewParacrossClient(conn) paraCli := paracross.NewParacrossClient(conn)
para := &ParaClient{ para := &client{
BaseClient: c, BaseClient: c,
conn: conn, conn: conn,
grpcClient: grpcClient, grpcClient: grpcClient,
...@@ -118,7 +119,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { ...@@ -118,7 +119,7 @@ func New(cfg *types.Consensus, sub []byte) queue.Module {
if cfg.WaitBlocks4CommitMsg < 2 { if cfg.WaitBlocks4CommitMsg < 2 {
panic("config WaitBlocks4CommitMsg should not less 2") panic("config WaitBlocks4CommitMsg should not less 2")
} }
para.commitMsgClient = &CommitMsgClient{ para.commitMsgClient = &commitMsgClient{
paraClient: para, paraClient: para,
waitMainBlocks: cfg.WaitBlocks4CommitMsg, waitMainBlocks: cfg.WaitBlocks4CommitMsg,
commitMsgNotify: make(chan int64, 1), commitMsgNotify: make(chan int64, 1),
...@@ -132,22 +133,20 @@ func New(cfg *types.Consensus, sub []byte) queue.Module { ...@@ -132,22 +133,20 @@ func New(cfg *types.Consensus, sub []byte) queue.Module {
return para return para
} }
func calcSearchseq(height int64) (seq int64) { func calcSearchseq(height int64) int64 {
if height < 1000 { if height < 1000 {
return 0 return 0
} else {
seq = height - 1000
} }
return seq return height - 1000
} }
//para 不检查任何的交易 //para 不检查任何的交易
func (client *ParaClient) CheckBlock(parent *types.Block, current *types.BlockDetail) error { func (client *client) CheckBlock(parent *types.Block, current *types.BlockDetail) error {
err := CheckMinerTx(current) err := checkMinerTx(current)
return err return err
} }
func (client *ParaClient) Close() { func (client *client) Close() {
client.BaseClient.Close() client.BaseClient.Close()
close(client.commitMsgClient.quit) close(client.commitMsgClient.quit)
client.wg.Wait() client.wg.Wait()
...@@ -155,7 +154,7 @@ func (client *ParaClient) Close() { ...@@ -155,7 +154,7 @@ func (client *ParaClient) Close() {
plog.Info("consensus para closed") plog.Info("consensus para closed")
} }
func (client *ParaClient) SetQueueClient(c queue.Client) { func (client *client) SetQueueClient(c queue.Client) {
plog.Info("Enter SetQueueClient method of Para consensus") plog.Info("Enter SetQueueClient method of Para consensus")
client.InitClient(c, func() { client.InitClient(c, func() {
client.InitBlock() client.InitBlock()
...@@ -167,7 +166,7 @@ func (client *ParaClient) SetQueueClient(c queue.Client) { ...@@ -167,7 +166,7 @@ func (client *ParaClient) SetQueueClient(c queue.Client) {
go client.CreateBlock() go client.CreateBlock()
} }
func (client *ParaClient) InitBlock() { func (client *client) InitBlock() {
block, err := client.RequestLastBlock() block, err := client.RequestLastBlock()
if err != nil { if err != nil {
panic(err) panic(err)
...@@ -192,7 +191,7 @@ func (client *ParaClient) InitBlock() { ...@@ -192,7 +191,7 @@ func (client *ParaClient) InitBlock() {
} }
} }
func (client *ParaClient) GetSeqByHeightOnMain(height int64, originSeq int64) int64 { func (client *client) GetSeqByHeightOnMain(height int64, originSeq int64) int64 {
lastSeq, err := client.GetLastSeqOnMainChain() lastSeq, err := client.GetLastSeqOnMainChain()
plog.Info("Searching for the sequence", "heightOnMain", height, "searchSeq", searchSeq, "lastSeq", lastSeq) plog.Info("Searching for the sequence", "heightOnMain", height, "searchSeq", searchSeq, "lastSeq", lastSeq)
if err != nil { if err != nil {
...@@ -209,7 +208,7 @@ func (client *ParaClient) GetSeqByHeightOnMain(height int64, originSeq int64) in ...@@ -209,7 +208,7 @@ func (client *ParaClient) GetSeqByHeightOnMain(height int64, originSeq int64) in
if err != nil { if err != nil {
panic(err) panic(err)
} }
if blockDetail.Block.Height == height && seqTy == AddAct { if blockDetail.Block.Height == height && seqTy == addAct {
plog.Info("the target sequence in mainchain", "heightOnMain", height, "targetSeq", originSeq) plog.Info("the target sequence in mainchain", "heightOnMain", height, "targetSeq", originSeq)
return originSeq return originSeq
} }
...@@ -219,7 +218,7 @@ func (client *ParaClient) GetSeqByHeightOnMain(height int64, originSeq int64) in ...@@ -219,7 +218,7 @@ func (client *ParaClient) GetSeqByHeightOnMain(height int64, originSeq int64) in
panic("Main chain has not reached the height currently") panic("Main chain has not reached the height currently")
} }
func (client *ParaClient) CreateGenesisTx() (ret []*types.Transaction) { func (client *client) CreateGenesisTx() (ret []*types.Transaction) {
var tx types.Transaction var tx types.Transaction
tx.Execer = []byte(types.ExecName(cty.CoinsX)) tx.Execer = []byte(types.ExecName(cty.CoinsX))
tx.To = client.Cfg.Genesis tx.To = client.Cfg.Genesis
...@@ -232,7 +231,7 @@ func (client *ParaClient) CreateGenesisTx() (ret []*types.Transaction) { ...@@ -232,7 +231,7 @@ func (client *ParaClient) CreateGenesisTx() (ret []*types.Transaction) {
return return
} }
func (client *ParaClient) ProcEvent(msg queue.Message) bool { func (client *client) ProcEvent(msg queue.Message) bool {
return false return false
} }
...@@ -257,24 +256,24 @@ func calcParaCrossTxGroup(tx *types.Transaction, main *types.BlockDetail, index ...@@ -257,24 +256,24 @@ func calcParaCrossTxGroup(tx *types.Transaction, main *types.BlockDetail, index
} }
if main.Receipts[i].Ty == types.ExecOk { if main.Receipts[i].Ty == types.ExecOk {
return main.Block.Txs[headIdx:endIdx], endIdx return main.Block.Txs[headIdx:endIdx], endIdx
} else { }
for _, log := range main.Receipts[i].Logs { for _, log := range main.Receipts[i].Logs {
if log.Ty == types.TyLogErr { if log.Ty == types.TyLogErr {
return nil, endIdx return nil, endIdx
} }
} }
} }
}
//全部是平行链交易 或主链执行非失败的tx //全部是平行链交易 或主链执行非失败的tx
return main.Block.Txs[headIdx:endIdx], endIdx return main.Block.Txs[headIdx:endIdx], endIdx
} }
func (client *ParaClient) FilterTxsForPara(main *types.BlockDetail) []*types.Transaction { func (client *client) FilterTxsForPara(main *types.BlockDetail) []*types.Transaction {
var txs []*types.Transaction var txs []*types.Transaction
for i := 0; i < len(main.Block.Txs); i++ { for i := 0; i < len(main.Block.Txs); i++ {
tx := main.Block.Txs[i] tx := main.Block.Txs[i]
if types.IsParaExecName(string(tx.Execer)) { if types.IsParaExecName(string(tx.Execer)) {
if tx.GroupCount >= ParaCrossTxCount { if tx.GroupCount >= paraCrossTxCount {
mainTxs, endIdx := calcParaCrossTxGroup(tx, main, i) mainTxs, endIdx := calcParaCrossTxGroup(tx, main, i)
txs = append(txs, mainTxs...) txs = append(txs, mainTxs...)
i = endIdx - 1 i = endIdx - 1
...@@ -287,7 +286,7 @@ func (client *ParaClient) FilterTxsForPara(main *types.BlockDetail) []*types.Tra ...@@ -287,7 +286,7 @@ func (client *ParaClient) FilterTxsForPara(main *types.BlockDetail) []*types.Tra
} }
//get the last sequence in parachain //get the last sequence in parachain
func (client *ParaClient) GetLastSeq() (int64, error) { func (client *client) GetLastSeq() (int64, error) {
msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetLastBlockSequence, "") msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetLastBlockSequence, "")
client.GetQueueClient().Send(msg, true) client.GetQueueClient().Send(msg, true)
resp, err := client.GetQueueClient().Wait(msg) resp, err := client.GetQueueClient().Wait(msg)
...@@ -300,9 +299,9 @@ func (client *ParaClient) GetLastSeq() (int64, error) { ...@@ -300,9 +299,9 @@ func (client *ParaClient) GetLastSeq() (int64, error) {
return -2, errors.New("Not an int64 data") return -2, errors.New("Not an int64 data")
} }
func (client *ParaClient) GetBlockedSeq(hash []byte) (int64, error) { func (client *client) GetBlockedSeq(hash []byte) (int64, error) {
//from blockchain db //from blockchain db
msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetSeqByHash, &types.ReqHash{hash}) msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetSeqByHash, &types.ReqHash{Hash: hash})
client.GetQueueClient().Send(msg, true) client.GetQueueClient().Send(msg, true)
resp, _ := client.GetQueueClient().Wait(msg) resp, _ := client.GetQueueClient().Wait(msg)
if blockedSeq, ok := resp.GetData().(*types.Int64); ok { if blockedSeq, ok := resp.GetData().(*types.Int64); ok {
...@@ -311,7 +310,7 @@ func (client *ParaClient) GetBlockedSeq(hash []byte) (int64, error) { ...@@ -311,7 +310,7 @@ func (client *ParaClient) GetBlockedSeq(hash []byte) (int64, error) {
return -2, errors.New("Not an int64 data") return -2, errors.New("Not an int64 data")
} }
func (client *ParaClient) GetLastSeqOnMainChain() (int64, error) { func (client *client) GetLastSeqOnMainChain() (int64, error) {
seq, err := client.grpcClient.GetLastBlockSequence(context.Background(), &types.ReqNil{}) seq, err := client.grpcClient.GetLastBlockSequence(context.Background(), &types.ReqNil{})
if err != nil { if err != nil {
plog.Error("GetLastSeqOnMainChain", "Error", err.Error()) plog.Error("GetLastSeqOnMainChain", "Error", err.Error())
...@@ -321,8 +320,8 @@ func (client *ParaClient) GetLastSeqOnMainChain() (int64, error) { ...@@ -321,8 +320,8 @@ func (client *ParaClient) GetLastSeqOnMainChain() (int64, error) {
return seq.Data, nil return seq.Data, nil
} }
func (client *ParaClient) GetBlocksByHashesFromMainChain(hashes [][]byte) (*types.BlockDetails, error) { func (client *client) GetBlocksByHashesFromMainChain(hashes [][]byte) (*types.BlockDetails, error) {
req := &types.ReqHashes{hashes} req := &types.ReqHashes{Hashes: hashes}
blocks, err := client.grpcClient.GetBlockByHashes(context.Background(), req) blocks, err := client.grpcClient.GetBlockByHashes(context.Background(), req)
if err != nil { if err != nil {
plog.Error("GetBlocksByHashesFromMainChain", "Error", err.Error()) plog.Error("GetBlocksByHashesFromMainChain", "Error", err.Error())
...@@ -331,8 +330,8 @@ func (client *ParaClient) GetBlocksByHashesFromMainChain(hashes [][]byte) (*type ...@@ -331,8 +330,8 @@ func (client *ParaClient) GetBlocksByHashesFromMainChain(hashes [][]byte) (*type
return blocks, nil return blocks, nil
} }
func (client *ParaClient) GetBlockHashFromMainChain(start int64, end int64) (*types.BlockSequences, error) { func (client *client) GetBlockHashFromMainChain(start int64, end int64) (*types.BlockSequences, error) {
req := &types.ReqBlocks{start, end, true, []string{}} req := &types.ReqBlocks{Start: start, End: end, IsDetail: true, Pid: []string{}}
blockSeqs, err := client.grpcClient.GetBlockSequences(context.Background(), req) blockSeqs, err := client.grpcClient.GetBlockSequences(context.Background(), req)
if err != nil { if err != nil {
plog.Error("GetBlockHashFromMainChain", "Error", err.Error()) plog.Error("GetBlockHashFromMainChain", "Error", err.Error())
...@@ -341,7 +340,7 @@ func (client *ParaClient) GetBlockHashFromMainChain(start int64, end int64) (*ty ...@@ -341,7 +340,7 @@ func (client *ParaClient) GetBlockHashFromMainChain(start int64, end int64) (*ty
return blockSeqs, nil return blockSeqs, nil
} }
func (client *ParaClient) GetBlockOnMainBySeq(seq int64) (*types.BlockDetail, int64, error) { func (client *client) GetBlockOnMainBySeq(seq int64) (*types.BlockDetail, int64, error) {
blockSeqs, err := client.GetBlockHashFromMainChain(seq, seq) blockSeqs, err := client.GetBlockHashFromMainChain(seq, seq)
if err != nil { if err != nil {
plog.Error("Not found block hash on seq", "start", seq, "end", seq) plog.Error("Not found block hash on seq", "start", seq, "end", seq)
...@@ -366,7 +365,7 @@ func (client *ParaClient) GetBlockOnMainBySeq(seq int64) (*types.BlockDetail, in ...@@ -366,7 +365,7 @@ func (client *ParaClient) GetBlockOnMainBySeq(seq int64) (*types.BlockDetail, in
return blockDetails.Items[0], blockSeqs.Items[0].Type, nil return blockDetails.Items[0], blockSeqs.Items[0].Type, nil
} }
func (client *ParaClient) RequestTx(currSeq int64) ([]*types.Transaction, *types.Block, int64, error) { func (client *client) RequestTx(currSeq int64) ([]*types.Transaction, *types.Block, int64, error) {
plog.Debug("Para consensus RequestTx") plog.Debug("Para consensus RequestTx")
lastSeq, err := client.GetLastSeqOnMainChain() lastSeq, err := client.GetLastSeqOnMainChain()
...@@ -399,7 +398,7 @@ func (client *ParaClient) RequestTx(currSeq int64) ([]*types.Transaction, *types ...@@ -399,7 +398,7 @@ func (client *ParaClient) RequestTx(currSeq int64) ([]*types.Transaction, *types
} }
//正常情况下,打包交易 //正常情况下,打包交易
func (client *ParaClient) CreateBlock() { func (client *client) CreateBlock() {
incSeqFlag := true incSeqFlag := true
currSeq, err := client.GetLastSeq() currSeq, err := client.GetLastSeq()
if err != nil { if err != nil {
...@@ -451,7 +450,7 @@ func (client *ParaClient) CreateBlock() { ...@@ -451,7 +450,7 @@ func (client *ParaClient) CreateBlock() {
} }
plog.Info("Parachain process block", "blockedSeq", blockedSeq, "blockOnMain.Height", blockOnMain.Height, "savedBlockOnMain.Height", savedBlockOnMain.Block.Height) plog.Info("Parachain process block", "blockedSeq", blockedSeq, "blockOnMain.Height", blockOnMain.Height, "savedBlockOnMain.Height", savedBlockOnMain.Block.Height)
if seqTy == DelAct { if seqTy == delAct {
if len(txs) == 0 { if len(txs) == 0 {
if blockOnMain.Height > savedBlockOnMain.Block.Height { if blockOnMain.Height > savedBlockOnMain.Block.Height {
incSeqFlag = true incSeqFlag = true
...@@ -464,7 +463,7 @@ func (client *ParaClient) CreateBlock() { ...@@ -464,7 +463,7 @@ func (client *ParaClient) CreateBlock() {
if err != nil { if err != nil {
plog.Error(fmt.Sprintf("********************err:%v", err.Error())) plog.Error(fmt.Sprintf("********************err:%v", err.Error()))
} }
} else if seqTy == AddAct { } else if seqTy == addAct {
if len(txs) == 0 { if len(txs) == 0 {
if blockOnMain.Height-savedBlockOnMain.Block.Height < emptyBlockInterval { if blockOnMain.Height-savedBlockOnMain.Block.Height < emptyBlockInterval {
incSeqFlag = true incSeqFlag = true
...@@ -488,7 +487,7 @@ func (client *ParaClient) CreateBlock() { ...@@ -488,7 +487,7 @@ func (client *ParaClient) CreateBlock() {
} }
// miner tx need all para node create, but not all node has auth account, here just not sign to keep align // miner tx need all para node create, but not all node has auth account, here just not sign to keep align
func (client *ParaClient) addMinerTx(preStateHash []byte, block *types.Block, main *types.Block) error { func (client *client) addMinerTx(preStateHash []byte, block *types.Block, main *types.Block) error {
status := &pt.ParacrossNodeStatus{ status := &pt.ParacrossNodeStatus{
Title: types.GetTitle(), Title: types.GetTitle(),
Height: block.Height, Height: block.Height,
...@@ -509,7 +508,7 @@ func (client *ParaClient) addMinerTx(preStateHash []byte, block *types.Block, ma ...@@ -509,7 +508,7 @@ func (client *ParaClient) addMinerTx(preStateHash []byte, block *types.Block, ma
} }
func (client *ParaClient) createBlock(lastBlock *types.Block, txs []*types.Transaction, seq int64, mainBlock *types.Block) error { func (client *client) createBlock(lastBlock *types.Block, txs []*types.Transaction, seq int64, mainBlock *types.Block) error {
var newblock types.Block var newblock types.Block
plog.Debug(fmt.Sprintf("the len txs is: %v", len(txs))) plog.Debug(fmt.Sprintf("the len txs is: %v", len(txs)))
newblock.ParentHash = lastBlock.Hash() newblock.ParentHash = lastBlock.Hash()
...@@ -534,11 +533,11 @@ func (client *ParaClient) createBlock(lastBlock *types.Block, txs []*types.Trans ...@@ -534,11 +533,11 @@ func (client *ParaClient) createBlock(lastBlock *types.Block, txs []*types.Trans
} }
// 向blockchain写区块 // 向blockchain写区块
func (client *ParaClient) WriteBlock(prev []byte, paraBlock *types.Block, seq int64) error { func (client *client) WriteBlock(prev []byte, paraBlock *types.Block, seq int64) error {
//共识模块不执行block,统一由blockchain模块执行block并做去重的处理,返回执行后的blockdetail //共识模块不执行block,统一由blockchain模块执行block并做去重的处理,返回执行后的blockdetail
blockDetail := &types.BlockDetail{Block: paraBlock} blockDetail := &types.BlockDetail{Block: paraBlock}
parablockDetail := &types.ParaChainBlockDetail{blockDetail, seq} parablockDetail := &types.ParaChainBlockDetail{Blockdetail: blockDetail, Sequence: seq}
msg := client.GetQueueClient().NewMessage("blockchain", types.EventAddParaChainBlockDetail, parablockDetail) msg := client.GetQueueClient().NewMessage("blockchain", types.EventAddParaChainBlockDetail, parablockDetail)
client.GetQueueClient().Send(msg, true) client.GetQueueClient().Send(msg, true)
resp, err := client.GetQueueClient().Wait(msg) resp, err := client.GetQueueClient().Wait(msg)
...@@ -560,13 +559,13 @@ func (client *ParaClient) WriteBlock(prev []byte, paraBlock *types.Block, seq in ...@@ -560,13 +559,13 @@ func (client *ParaClient) WriteBlock(prev []byte, paraBlock *types.Block, seq in
} }
// 向blockchain删区块 // 向blockchain删区块
func (client *ParaClient) DelBlock(block *types.Block, seq int64) error { func (client *client) DelBlock(block *types.Block, seq int64) error {
plog.Debug("delete block in parachain") plog.Debug("delete block in parachain")
start := block.Height start := block.Height
if start == 0 { if start == 0 {
panic("Parachain attempt to Delete GenesisBlock !") panic("Parachain attempt to Delete GenesisBlock !")
} }
msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetBlocks, &types.ReqBlocks{start, start, true, []string{""}}) msg := client.GetQueueClient().NewMessage("blockchain", types.EventGetBlocks, &types.ReqBlocks{Start: start, End: start, IsDetail: true, Pid: []string{""}})
client.GetQueueClient().Send(msg, true) client.GetQueueClient().Send(msg, true)
resp, err := client.GetQueueClient().Wait(msg) resp, err := client.GetQueueClient().Wait(msg)
if err != nil { if err != nil {
...@@ -574,7 +573,7 @@ func (client *ParaClient) DelBlock(block *types.Block, seq int64) error { ...@@ -574,7 +573,7 @@ func (client *ParaClient) DelBlock(block *types.Block, seq int64) error {
} }
blocks := resp.GetData().(*types.BlockDetails) blocks := resp.GetData().(*types.BlockDetails)
parablockDetail := &types.ParaChainBlockDetail{blocks.Items[0], seq} parablockDetail := &types.ParaChainBlockDetail{Blockdetail: blocks.Items[0], Sequence: seq}
msg = client.GetQueueClient().NewMessage("blockchain", types.EventDelParaChainBlockDetail, parablockDetail) msg = client.GetQueueClient().NewMessage("blockchain", types.EventDelParaChainBlockDetail, parablockDetail)
client.GetQueueClient().Send(msg, true) client.GetQueueClient().Send(msg, true)
resp, err = client.GetQueueClient().Wait(msg) resp, err = client.GetQueueClient().Wait(msg)
......
...@@ -112,7 +112,7 @@ func TestFilterTxsForPara(t *testing.T) { ...@@ -112,7 +112,7 @@ func TestFilterTxsForPara(t *testing.T) {
Receipts: receipts, Receipts: receipts,
} }
para := &ParaClient{} para := &client{}
rst := para.FilterTxsForPara(detail) rst := para.FilterTxsForPara(detail)
filterTxs := []*types.Transaction{tx3, tx4, tx5, tx6, txA, txB, txC} filterTxs := []*types.Transaction{tx3, tx4, tx5, tx6, txA, txB, txC}
assert.Equal(t, filterTxs, rst) assert.Equal(t, filterTxs, rst)
......
...@@ -21,8 +21,8 @@ var ( ...@@ -21,8 +21,8 @@ var (
consensusInterval = 16 //about 1 new block interval consensusInterval = 16 //about 1 new block interval
) )
type CommitMsgClient struct { type commitMsgClient struct {
paraClient *ParaClient paraClient *client
waitMainBlocks int32 waitMainBlocks int32
commitMsgNotify chan int64 commitMsgNotify chan int64
delMsgNotify chan int64 delMsgNotify chan int64
...@@ -33,7 +33,7 @@ type CommitMsgClient struct { ...@@ -33,7 +33,7 @@ type CommitMsgClient struct {
quit chan struct{} quit chan struct{}
} }
func (client *CommitMsgClient) handler() { func (client *commitMsgClient) handler() {
var isSync bool var isSync bool
var notification []int64 //记录每次系统重启后 min and current height var notification []int64 //记录每次系统重启后 min and current height
var finishHeight int64 var finishHeight int64
...@@ -185,7 +185,7 @@ out: ...@@ -185,7 +185,7 @@ out:
client.paraClient.wg.Done() client.paraClient.wg.Done()
} }
func (client *CommitMsgClient) calcCommitMsgTxs(notifications []*pt.ParacrossNodeStatus) (*types.Transaction, int64, error) { func (client *commitMsgClient) calcCommitMsgTxs(notifications []*pt.ParacrossNodeStatus) (*types.Transaction, int64, error) {
txs, count, err := client.batchCalcTxGroup(notifications) txs, count, err := client.batchCalcTxGroup(notifications)
if err != nil { if err != nil {
txs, err = client.singleCalcTx((notifications)[0]) txs, err = client.singleCalcTx((notifications)[0])
...@@ -199,7 +199,7 @@ func (client *CommitMsgClient) calcCommitMsgTxs(notifications []*pt.ParacrossNod ...@@ -199,7 +199,7 @@ func (client *CommitMsgClient) calcCommitMsgTxs(notifications []*pt.ParacrossNod
return txs, int64(count), nil return txs, int64(count), nil
} }
func (client *CommitMsgClient) getTxsGroup(txsArr *types.Transactions) (*types.Transaction, error) { func (client *commitMsgClient) getTxsGroup(txsArr *types.Transactions) (*types.Transaction, error) {
if len(txsArr.Txs) < 2 { if len(txsArr.Txs) < 2 {
tx := txsArr.Txs[0] tx := txsArr.Txs[0]
tx.Sign(types.SECP256K1, client.privateKey) tx.Sign(types.SECP256K1, client.privateKey)
...@@ -224,7 +224,7 @@ func (client *CommitMsgClient) getTxsGroup(txsArr *types.Transactions) (*types.T ...@@ -224,7 +224,7 @@ func (client *CommitMsgClient) getTxsGroup(txsArr *types.Transactions) (*types.T
return newtx, nil return newtx, nil
} }
func (client *CommitMsgClient) batchCalcTxGroup(notifications []*pt.ParacrossNodeStatus) (*types.Transaction, int, error) { func (client *commitMsgClient) batchCalcTxGroup(notifications []*pt.ParacrossNodeStatus) (*types.Transaction, int, error) {
var rawTxs types.Transactions var rawTxs types.Transactions
for _, status := range notifications { for _, status := range notifications {
tx, err := paracross.CreateRawCommitTx4MainChain(status, pt.ParaX, 0) tx, err := paracross.CreateRawCommitTx4MainChain(status, pt.ParaX, 0)
...@@ -242,7 +242,7 @@ func (client *CommitMsgClient) batchCalcTxGroup(notifications []*pt.ParacrossNod ...@@ -242,7 +242,7 @@ func (client *CommitMsgClient) batchCalcTxGroup(notifications []*pt.ParacrossNod
return txs, len(notifications), nil return txs, len(notifications), nil
} }
func (client *CommitMsgClient) singleCalcTx(status *pt.ParacrossNodeStatus) (*types.Transaction, error) { func (client *commitMsgClient) singleCalcTx(status *pt.ParacrossNodeStatus) (*types.Transaction, error) {
tx, err := paracross.CreateRawCommitTx4MainChain(status, pt.ParaX, 0) tx, err := paracross.CreateRawCommitTx4MainChain(status, pt.ParaX, 0)
if err != nil { if err != nil {
plog.Error("para get commit tx", "block height", status.Height) plog.Error("para get commit tx", "block height", status.Height)
...@@ -258,7 +258,7 @@ func (client *CommitMsgClient) singleCalcTx(status *pt.ParacrossNodeStatus) (*ty ...@@ -258,7 +258,7 @@ func (client *CommitMsgClient) singleCalcTx(status *pt.ParacrossNodeStatus) (*ty
// if sendCommitMsgTx block quite long, write channel will be block in handle(), addBlock will not send new msg until rpc send over // if sendCommitMsgTx block quite long, write channel will be block in handle(), addBlock will not send new msg until rpc send over
// if sendCommitMsgTx block quite long, if delMsg occur, after send over, ignore previous tx succ or fail, new msg will be rcv and sent // if sendCommitMsgTx block quite long, if delMsg occur, after send over, ignore previous tx succ or fail, new msg will be rcv and sent
// if sendCommitMsgTx fail, wait 1s resend the failed tx, if new tx rcv from ch, send the new one. // if sendCommitMsgTx fail, wait 1s resend the failed tx, if new tx rcv from ch, send the new one.
func (client *CommitMsgClient) sendCommitMsg(ch chan *types.Transaction) { func (client *commitMsgClient) sendCommitMsg(ch chan *types.Transaction) {
var err error var err error
var tx *types.Transaction var tx *types.Transaction
resendTimer := time.After(time.Second * 1) resendTimer := time.After(time.Second * 1)
...@@ -286,7 +286,7 @@ out: ...@@ -286,7 +286,7 @@ out:
client.paraClient.wg.Done() client.paraClient.wg.Done()
} }
func (client *CommitMsgClient) sendCommitMsgTx(tx *types.Transaction) error { func (client *commitMsgClient) sendCommitMsgTx(tx *types.Transaction) error {
if tx == nil { if tx == nil {
return nil return nil
} }
...@@ -319,7 +319,7 @@ func checkTxInMainBlock(targetTx *types.Transaction, detail *types.BlockDetail) ...@@ -319,7 +319,7 @@ func checkTxInMainBlock(targetTx *types.Transaction, detail *types.BlockDetail)
//当前未考虑获取key非常多失败的场景, 如果获取height非常多,block模块会比较大,但是使用完了就释放了 //当前未考虑获取key非常多失败的场景, 如果获取height非常多,block模块会比较大,但是使用完了就释放了
//如果有必要也可以考虑每次最多取20个一个txgroup,发送共识部分循环获取发送也没问题 //如果有必要也可以考虑每次最多取20个一个txgroup,发送共识部分循环获取发送也没问题
func (client *CommitMsgClient) getNodeStatus(start, end int64) ([]*pt.ParacrossNodeStatus, error) { func (client *commitMsgClient) getNodeStatus(start, end int64) ([]*pt.ParacrossNodeStatus, error) {
var ret []*pt.ParacrossNodeStatus var ret []*pt.ParacrossNodeStatus
if start == 0 { if start == 0 {
geneStatus, err := client.getGenesisNodeStatus() geneStatus, err := client.getGenesisNodeStatus()
...@@ -402,7 +402,7 @@ func (client *CommitMsgClient) getNodeStatus(start, end int64) ([]*pt.ParacrossN ...@@ -402,7 +402,7 @@ func (client *CommitMsgClient) getNodeStatus(start, end int64) ([]*pt.ParacrossN
} }
func (client *CommitMsgClient) getGenesisNodeStatus() (*pt.ParacrossNodeStatus, error) { func (client *commitMsgClient) getGenesisNodeStatus() (*pt.ParacrossNodeStatus, error) {
var status pt.ParacrossNodeStatus var status pt.ParacrossNodeStatus
req := &types.ReqBlocks{Start: 0, End: 0} req := &types.ReqBlocks{Start: 0, End: 0}
msg := client.paraClient.GetQueueClient().NewMessage("blockchain", types.EventGetBlocks, req) msg := client.paraClient.GetQueueClient().NewMessage("blockchain", types.EventGetBlocks, req)
...@@ -425,7 +425,7 @@ func (client *CommitMsgClient) getGenesisNodeStatus() (*pt.ParacrossNodeStatus, ...@@ -425,7 +425,7 @@ func (client *CommitMsgClient) getGenesisNodeStatus() (*pt.ParacrossNodeStatus,
return &status, nil return &status, nil
} }
func (client *CommitMsgClient) onBlockAdded(height int64) error { func (client *commitMsgClient) onBlockAdded(height int64) error {
select { select {
case client.commitMsgNotify <- height: case client.commitMsgNotify <- height:
case <-client.quit: case <-client.quit:
...@@ -434,14 +434,14 @@ func (client *CommitMsgClient) onBlockAdded(height int64) error { ...@@ -434,14 +434,14 @@ func (client *CommitMsgClient) onBlockAdded(height int64) error {
return nil return nil
} }
func (client *CommitMsgClient) onBlockDeleted(height int64) { func (client *commitMsgClient) onBlockDeleted(height int64) {
select { select {
case client.delMsgNotify <- height: case client.delMsgNotify <- height:
case <-client.quit: case <-client.quit:
} }
} }
func (client *CommitMsgClient) onMainBlockAdded(block *types.BlockDetail) { func (client *commitMsgClient) onMainBlockAdded(block *types.BlockDetail) {
select { select {
case client.mainBlockAdd <- block: case client.mainBlockAdd <- block:
case <-client.quit: case <-client.quit:
...@@ -449,7 +449,7 @@ func (client *CommitMsgClient) onMainBlockAdded(block *types.BlockDetail) { ...@@ -449,7 +449,7 @@ func (client *CommitMsgClient) onMainBlockAdded(block *types.BlockDetail) {
} }
//only sync once, as main usually sync, here just need the first sync status after start up //only sync once, as main usually sync, here just need the first sync status after start up
func (client *CommitMsgClient) mainSync() error { func (client *commitMsgClient) mainSync() error {
req := &types.ReqNil{} req := &types.ReqNil{}
reply, err := client.paraClient.grpcClient.IsSync(context.Background(), req) reply, err := client.paraClient.grpcClient.IsSync(context.Background(), req)
if err != nil { if err != nil {
...@@ -466,7 +466,7 @@ func (client *CommitMsgClient) mainSync() error { ...@@ -466,7 +466,7 @@ func (client *CommitMsgClient) mainSync() error {
} }
func (client *CommitMsgClient) getConsensusHeight(consensusRst chan *pt.ParacrossStatus) { func (client *commitMsgClient) getConsensusHeight(consensusRst chan *pt.ParacrossStatus) {
ticker := time.NewTicker(time.Second * time.Duration(consensusInterval)) ticker := time.NewTicker(time.Second * time.Duration(consensusInterval))
isSync := false isSync := false
defer ticker.Stop() defer ticker.Stop()
...@@ -486,7 +486,7 @@ out: ...@@ -486,7 +486,7 @@ out:
} }
ret, err := client.paraClient.paraClient.GetTitle(context.Background(), ret, err := client.paraClient.paraClient.GetTitle(context.Background(),
&types.ReqString{types.GetTitle()}) &types.ReqString{Data: types.GetTitle()})
if err != nil { if err != nil {
plog.Error("getConsensusHeight ", "err", err.Error()) plog.Error("getConsensusHeight ", "err", err.Error())
continue continue
...@@ -499,7 +499,7 @@ out: ...@@ -499,7 +499,7 @@ out:
client.paraClient.wg.Done() client.paraClient.wg.Done()
} }
func (client *CommitMsgClient) fetchPrivacyKey(ch chan crypto.PrivKey) { func (client *commitMsgClient) fetchPrivacyKey(ch chan crypto.PrivKey) {
defer client.paraClient.wg.Done() defer client.paraClient.wg.Done()
if client.paraClient.authAccount == "" { if client.paraClient.authAccount == "" {
close(ch) close(ch)
...@@ -544,7 +544,7 @@ out: ...@@ -544,7 +544,7 @@ out:
} }
func CheckMinerTx(current *types.BlockDetail) error { func checkMinerTx(current *types.BlockDetail) error {
//检查第一个笔交易的execs, 以及执行状态 //检查第一个笔交易的execs, 以及执行状态
if len(current.Block.Txs) == 0 { if len(current.Block.Txs) == 0 {
return types.ErrEmptyTx return types.ErrEmptyTx
......
...@@ -42,7 +42,7 @@ func init() { ...@@ -42,7 +42,7 @@ func init() {
type suiteParaCommitMsg struct { type suiteParaCommitMsg struct {
// Include our basic suite logic. // Include our basic suite logic.
suite.Suite suite.Suite
para *ParaClient para *client
grpcCli *typesmocks.Chain33Client grpcCli *typesmocks.Chain33Client
q queue.Queue q queue.Queue
block *blockchain.BlockChain block *blockchain.BlockChain
...@@ -70,7 +70,7 @@ func (s *suiteParaCommitMsg) initEnv(cfg *types.Config, sub *types.ConfigSubModu ...@@ -70,7 +70,7 @@ func (s *suiteParaCommitMsg) initEnv(cfg *types.Config, sub *types.ConfigSubModu
s.store = store.New(cfg.Store, sub.Store) s.store = store.New(cfg.Store, sub.Store)
s.store.SetQueueClient(q.Client()) s.store.SetQueueClient(q.Client())
s.para = New(cfg.Consensus, sub.Consensus["para"]).(*ParaClient) s.para = New(cfg.Consensus, sub.Consensus["para"]).(*client)
s.grpcCli = &typesmocks.Chain33Client{} s.grpcCli = &typesmocks.Chain33Client{}
//data := &types.Int64{1} //data := &types.Int64{1}
s.grpcCli.On("GetLastBlockSequence", mock.Anything, mock.Anything).Return(nil, errors.New("nil")) s.grpcCli.On("GetLastBlockSequence", mock.Anything, mock.Anything).Return(nil, errors.New("nil"))
...@@ -97,7 +97,7 @@ func (s *suiteParaCommitMsg) initEnv(cfg *types.Config, sub *types.ConfigSubModu ...@@ -97,7 +97,7 @@ func (s *suiteParaCommitMsg) initEnv(cfg *types.Config, sub *types.ConfigSubModu
} }
func walletProcess(q queue.Queue, para *ParaClient) { func walletProcess(q queue.Queue, para *client) {
defer para.wg.Done() defer para.wg.Done()
client := q.Client() client := q.Client()
...@@ -109,7 +109,7 @@ func walletProcess(q queue.Queue, para *ParaClient) { ...@@ -109,7 +109,7 @@ func walletProcess(q queue.Queue, para *ParaClient) {
return return
case msg := <-client.Recv(): case msg := <-client.Recv():
if msg.Ty == types.EventDumpPrivkey { if msg.Ty == types.EventDumpPrivkey {
msg.Reply(client.NewMessage("", types.EventHeader, &types.ReplyString{"6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b"})) msg.Reply(client.NewMessage("", types.EventHeader, &types.ReplyString{Data: "6da92a632ab7deb67d38c0f6560bcfed28167998f6496db64c258d5e8393a81b"}))
} }
} }
} }
......
...@@ -36,6 +36,7 @@ func init() { ...@@ -36,6 +36,7 @@ func init() {
drivers.QueryData.Register("ticket", &Client{}) drivers.QueryData.Register("ticket", &Client{})
} }
// Client export ticket client struct
type Client struct { type Client struct {
*drivers.BaseClient *drivers.BaseClient
//ticket list for miner //ticket list for miner
...@@ -57,6 +58,7 @@ type subConfig struct { ...@@ -57,6 +58,7 @@ type subConfig struct {
Genesis []*genesisTicket `json:"genesis"` Genesis []*genesisTicket `json:"genesis"`
} }
// New ticket's init env
func New(cfg *types.Consensus, sub []byte) queue.Module { func New(cfg *types.Consensus, sub []byte) queue.Module {
c := drivers.NewBaseClient(cfg) c := drivers.NewBaseClient(cfg)
var subcfg subConfig var subcfg subConfig
...@@ -86,12 +88,14 @@ Loop: ...@@ -86,12 +88,14 @@ Loop:
} }
} }
// Close ticket close
func (client *Client) Close() { func (client *Client) Close() {
close(client.done) close(client.done)
client.BaseClient.Close() client.BaseClient.Close()
tlog.Info("consensus ticket closed") tlog.Info("consensus ticket closed")
} }
// CreateGenesisTx ticket create genesis tx
func (client *Client) CreateGenesisTx() (ret []*types.Transaction) { func (client *Client) CreateGenesisTx() (ret []*types.Transaction) {
for _, genesis := range client.subcfg.Genesis { for _, genesis := range client.subcfg.Genesis {
tx1 := createTicket(genesis.MinerAddr, genesis.ReturnAddr, genesis.Count, 0) tx1 := createTicket(genesis.MinerAddr, genesis.ReturnAddr, genesis.Count, 0)
...@@ -119,7 +123,7 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret ...@@ -119,7 +123,7 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret
tx2.To = driver.ExecAddress("ticket") tx2.To = driver.ExecAddress("ticket")
//gen payload //gen payload
g = &cty.CoinsAction_Genesis{} g = &cty.CoinsAction_Genesis{}
g.Genesis = &types.AssetsGenesis{int64(count) * types.GetP(height).TicketPrice, returnAddr} g.Genesis = &types.AssetsGenesis{Amount: int64(count) * types.GetP(height).TicketPrice, ReturnAddress: returnAddr}
tx2.Payload = types.Encode(&cty.CoinsAction{Value: g, Ty: cty.CoinsActionGenesis}) tx2.Payload = types.Encode(&cty.CoinsAction{Value: g, Ty: cty.CoinsActionGenesis})
ret = append(ret, &tx2) ret = append(ret, &tx2)
...@@ -127,26 +131,29 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret ...@@ -127,26 +131,29 @@ func createTicket(minerAddr, returnAddr string, count int32, height int64) (ret
tx3.Execer = []byte("ticket") tx3.Execer = []byte("ticket")
tx3.To = driver.ExecAddress("ticket") tx3.To = driver.ExecAddress("ticket")
gticket := &ty.TicketAction_Genesis{} gticket := &ty.TicketAction_Genesis{}
gticket.Genesis = &ty.TicketGenesis{minerAddr, returnAddr, count} gticket.Genesis = &ty.TicketGenesis{MinerAddress: minerAddr, ReturnAddress: returnAddr, Count: count}
tx3.Payload = types.Encode(&ty.TicketAction{Value: gticket, Ty: ty.TicketActionGenesis}) tx3.Payload = types.Encode(&ty.TicketAction{Value: gticket, Ty: ty.TicketActionGenesis})
ret = append(ret, &tx3) ret = append(ret, &tx3)
return ret return ret
} }
// Query_GetTicketCount ticket query ticket count function
func (client *Client) Query_GetTicketCount(req *types.ReqNil) (types.Message, error) { func (client *Client) Query_GetTicketCount(req *types.ReqNil) (types.Message, error) {
var ret types.Int64 var ret types.Int64
ret.Data = client.getTicketCount() ret.Data = client.getTicketCount()
return &ret, nil return &ret, nil
} }
// Query_FlushTicket ticket query flush ticket function
func (client *Client) Query_FlushTicket(req *types.ReqNil) (types.Message, error) { func (client *Client) Query_FlushTicket(req *types.ReqNil) (types.Message, error) {
err := client.flushTicket() err := client.flushTicket()
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &types.Reply{true, []byte("OK")}, nil return &types.Reply{IsOk: true, Msg: []byte("OK")}, nil
} }
// ProcEvent ticket reply not support action err
func (client *Client) ProcEvent(msg queue.Message) bool { func (client *Client) ProcEvent(msg queue.Message) bool {
msg.ReplyErr("Client", types.ErrActionNotSupport) msg.ReplyErr("Client", types.ErrActionNotSupport)
return true return true
...@@ -207,7 +214,7 @@ func (client *Client) flushTicket() error { ...@@ -207,7 +214,7 @@ func (client *Client) flushTicket() error {
tlog.Error("flushTicket error", "err", err) tlog.Error("flushTicket error", "err", err)
return err return err
} }
client.setTicket(&ty.ReplyTicketList{tickets}, getPrivMap(privs)) client.setTicket(&ty.ReplyTicketList{Tickets: tickets}, getPrivMap(privs))
return nil return nil
} }
...@@ -242,7 +249,7 @@ func (client *Client) getMinerTx(current *types.Block) (*ty.TicketAction, error) ...@@ -242,7 +249,7 @@ func (client *Client) getMinerTx(current *types.Block) (*ty.TicketAction, error)
return &ticketAction, nil return &ticketAction, nil
} }
func (client *Client) getModify(block *types.Block) ([]byte, error) { func (client *Client) getMinerModify(block *types.Block) ([]byte, error) {
ticketAction, err := client.getMinerTx(block) ticketAction, err := client.getMinerTx(block)
if err != nil { if err != nil {
return defaultModify, err return defaultModify, err
...@@ -250,7 +257,7 @@ func (client *Client) getModify(block *types.Block) ([]byte, error) { ...@@ -250,7 +257,7 @@ func (client *Client) getModify(block *types.Block) ([]byte, error) {
return ticketAction.GetMiner().GetModify(), nil return ticketAction.GetMiner().GetModify(), nil
} }
func (client *Client) GetModify(beg, end int64) ([]byte, error) { func (client *Client) getModify(beg, end int64) ([]byte, error) {
//通过某个区间计算modify //通过某个区间计算modify
timeSource := int64(0) timeSource := int64(0)
total := int64(0) total := int64(0)
...@@ -280,6 +287,7 @@ func (client *Client) GetModify(beg, end int64) ([]byte, error) { ...@@ -280,6 +287,7 @@ func (client *Client) GetModify(beg, end int64) ([]byte, error) {
return []byte(modify), nil return []byte(modify), nil
} }
// CheckBlock ticket implete checkblock func
func (client *Client) CheckBlock(parent *types.Block, current *types.BlockDetail) error { func (client *Client) CheckBlock(parent *types.Block, current *types.BlockDetail) error {
cfg := types.GetP(current.Block.Height) cfg := types.GetP(current.Block.Height)
if current.Block.BlockTime-types.Now().Unix() > cfg.FutureBlockTime { if current.Block.BlockTime-types.Now().Unix() > cfg.FutureBlockTime {
...@@ -348,7 +356,7 @@ func (client *Client) getNextTarget(block *types.Block, bits uint32) (*big.Int, ...@@ -348,7 +356,7 @@ func (client *Client) getNextTarget(block *types.Block, bits uint32) (*big.Int,
powLimit := difficulty.CompactToBig(types.GetP(0).PowLimitBits) powLimit := difficulty.CompactToBig(types.GetP(0).PowLimitBits)
return powLimit, defaultModify, nil return powLimit, defaultModify, nil
} }
targetBits, modify, err := client.GetNextRequiredDifficulty(block, bits) targetBits, modify, err := client.getNextRequiredDifficulty(block, bits)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
...@@ -370,7 +378,7 @@ func (client *Client) getCurrentTarget(blocktime int64, id string, modify []byte ...@@ -370,7 +378,7 @@ func (client *Client) getCurrentTarget(blocktime int64, id string, modify []byte
// This function differs from the exported CalcNextRequiredDifficulty in that // This function differs from the exported CalcNextRequiredDifficulty in that
// the exported version uses the current best chain as the previous block node // the exported version uses the current best chain as the previous block node
// while this function accepts any block node. // while this function accepts any block node.
func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32) (uint32, []byte, error) { func (client *Client) getNextRequiredDifficulty(block *types.Block, bits uint32) (uint32, []byte, error) {
// Genesis block. // Genesis block.
if block == nil { if block == nil {
return types.GetP(0).PowLimitBits, defaultModify, nil return types.GetP(0).PowLimitBits, defaultModify, nil
...@@ -382,7 +390,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32) ...@@ -382,7 +390,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32)
if (block.Height+1) <= blocksPerRetarget || (block.Height+1)%blocksPerRetarget != 0 { if (block.Height+1) <= blocksPerRetarget || (block.Height+1)%blocksPerRetarget != 0 {
// For the main network (or any unrecognized networks), simply // For the main network (or any unrecognized networks), simply
// return the previous block's difficulty requirements. // return the previous block's difficulty requirements.
modify, err := client.getModify(block) modify, err := client.getMinerModify(block)
if err != nil { if err != nil {
return bits, defaultModify, err return bits, defaultModify, err
} }
...@@ -399,7 +407,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32) ...@@ -399,7 +407,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32)
return cfg.PowLimitBits, defaultModify, types.ErrBlockNotFound return cfg.PowLimitBits, defaultModify, types.ErrBlockNotFound
} }
modify, err := client.GetModify(block.Height+1-blocksPerRetarget, block.Height) modify, err := client.getModify(block.Height+1-blocksPerRetarget, block.Height)
if err != nil { if err != nil {
return cfg.PowLimitBits, defaultModify, err return cfg.PowLimitBits, defaultModify, err
} }
...@@ -443,7 +451,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32) ...@@ -443,7 +451,7 @@ func (client *Client) GetNextRequiredDifficulty(block *types.Block, bits uint32)
tlog.Info("Timespan", "Actual timespan", time.Duration(actualTimespan)*time.Second, tlog.Info("Timespan", "Actual timespan", time.Duration(actualTimespan)*time.Second,
"adjusted timespan", time.Duration(adjustedTimespan)*time.Second, "adjusted timespan", time.Duration(adjustedTimespan)*time.Second,
"target timespan", cfg.TargetTimespan) "target timespan", cfg.TargetTimespan)
prevmodify, err := client.getModify(block) prevmodify, err := client.getMinerModify(block)
if err != nil { if err != nil {
panic(err) panic(err)
} }
...@@ -511,6 +519,7 @@ func (client *Client) delTicket(ticket *ty.Ticket, index int) { ...@@ -511,6 +519,7 @@ func (client *Client) delTicket(ticket *ty.Ticket, index int) {
} }
} }
// Miner ticket miner function
func (client *Client) Miner(parent, block *types.Block) bool { func (client *Client) Miner(parent, block *types.Block) bool {
//add miner address //add miner address
ticket, priv, diff, modify, index, err := client.searchTargetTicket(parent, block) ticket, priv, diff, modify, index, err := client.searchTargetTicket(parent, block)
...@@ -577,7 +586,7 @@ func (client *Client) addMinerTx(parent, block *types.Block, diff *big.Int, priv ...@@ -577,7 +586,7 @@ func (client *Client) addMinerTx(parent, block *types.Block, diff *big.Int, priv
return err return err
} }
miner.PrivHash = privHash miner.PrivHash = privHash
ticketAction.Value = &ty.TicketAction_Miner{miner} ticketAction.Value = &ty.TicketAction_Miner{Miner: miner}
ticketAction.Ty = ty.TicketActionMiner ticketAction.Ty = ty.TicketActionMiner
//构造transaction //构造transaction
tx := client.createMinerTx(&ticketAction, priv) tx := client.createMinerTx(&ticketAction, priv)
...@@ -648,6 +657,7 @@ func (client *Client) updateBlock(newblock *types.Block, txHashList [][]byte) (* ...@@ -648,6 +657,7 @@ func (client *Client) updateBlock(newblock *types.Block, txHashList [][]byte) (*
return lastBlock, txHashList return lastBlock, txHashList
} }
// CreateBlock ticket create block func
func (client *Client) CreateBlock() { func (client *Client) CreateBlock() {
for { for {
if !client.IsMining() || !(client.IsCaughtUp() || client.Cfg.ForceMining) { if !client.IsMining() || !(client.IsCaughtUp() || client.Cfg.ForceMining) {
......
...@@ -226,11 +226,11 @@ func commitOnce(suite *CommitTestSuite, privkeyStr string) (receipt *types.Recei ...@@ -226,11 +226,11 @@ func commitOnce(suite *CommitTestSuite, privkeyStr string) (receipt *types.Recei
} }
func commitOnceImpl(suite suite.Suite, exec *Paracross, privkeyStr string) (receipt *types.Receipt) { func commitOnceImpl(suite suite.Suite, exec *Paracross, privkeyStr string) (receipt *types.Receipt) {
tx, err := fillRawCommitTx(suite) tx, _ := fillRawCommitTx(suite)
tx, err = signTx(suite, tx, privkeyStr) tx, _ = signTx(suite, tx, privkeyStr)
suite.T().Log(tx.From()) suite.T().Log(tx.From())
receipt, err = exec.Exec(tx, 0) receipt, err := exec.Exec(tx, 0)
suite.T().Log(receipt) suite.T().Log(receipt)
assert.NotNil(suite.T(), receipt) assert.NotNil(suite.T(), receipt)
assert.Nil(suite.T(), err) assert.Nil(suite.T(), err)
...@@ -526,7 +526,7 @@ func createTxsGroup(s suite.Suite, txs []*types.Transaction) ([]*types.Transacti ...@@ -526,7 +526,7 @@ func createTxsGroup(s suite.Suite, txs []*types.Transaction) ([]*types.Transacti
if err != nil { if err != nil {
return nil, err return nil, err
} }
privKey, err := getPrivKey(s, PrivKeyA) privKey, _ := getPrivKey(s, PrivKeyA)
for i := range group.Txs { for i := range group.Txs {
group.SignN(i, int32(types.SECP256K1), privKey) group.SignN(i, int32(types.SECP256K1), privKey)
} }
......
...@@ -67,9 +67,12 @@ func NewRelayd(config *Config) *Relayd { ...@@ -67,9 +67,12 @@ func NewRelayd(config *Config) *Relayd {
} }
currentHeight, err := db.Get(currentBtcBlockheightKey[:]) currentHeight, err := db.Get(currentBtcBlockheightKey[:])
if err != nil {
log.Warn("NewRelayd", "db get error: ", err.Error())
}
height, err := strconv.Atoi(string(currentHeight)) height, err := strconv.Atoi(string(currentHeight))
if err != nil { if err != nil {
log.Warn("NewRelayd", "atoi height error: ", err) log.Warn("NewRelayd", "atoi height error: ", err.Error())
} }
if height < firstHeight || isResetBtcHeight { if height < firstHeight || isResetBtcHeight {
......
...@@ -80,7 +80,7 @@ func (s *suiteBtcStore) TestSaveBlockHead() { ...@@ -80,7 +80,7 @@ func (s *suiteBtcStore) TestSaveBlockHead() {
Time: 1231731025, Time: 1231731025,
Height: 2, Height: 2,
} }
val, err := proto.Marshal(head) val, _ := proto.Marshal(head)
key := calcBtcHeaderKeyHash(head.Hash) key := calcBtcHeaderKeyHash(head.Hash)
kv = append(kv, &types.KeyValue{key, val}) kv = append(kv, &types.KeyValue{key, val})
key = calcBtcHeaderKeyHeight(int64(head.Height)) key = calcBtcHeaderKeyHeight(int64(head.Height))
......
...@@ -451,6 +451,10 @@ func (action *relayDB) confirmTx(confirm *ty.RelayConfirmTx) (*types.Receipt, er ...@@ -451,6 +451,10 @@ func (action *relayDB) confirmTx(confirm *ty.RelayConfirmTx) (*types.Receipt, er
//report Error if coinTxHash has been used and not same orderId, if same orderId, means to modify the txHash //report Error if coinTxHash has been used and not same orderId, if same orderId, means to modify the txHash
coinTxOrder, err := action.getOrderByCoinHash([]byte(calcCoinHash(confirm.TxHash))) coinTxOrder, err := action.getOrderByCoinHash([]byte(calcCoinHash(confirm.TxHash)))
if err != nil {
relaylog.Error("confirmTx getOrderByCoinHash", "orderid", confirm.OrderId, "err", err.Error())
return nil, err
}
if coinTxOrder != nil { if coinTxOrder != nil {
if coinTxOrder.Id != confirm.OrderId { if coinTxOrder.Id != confirm.OrderId {
relaylog.Error("confirmTx", "coinTxHash", confirm.TxHash, "has been used in other order", coinTxOrder.Id) relaylog.Error("confirmTx", "coinTxHash", confirm.TxHash, "has been used in other order", coinTxOrder.Id)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment